diff --git a/.github/workflows/alpine_linux_musl_test.yml b/.github/workflows/alpine_linux_musl_test.yml index e78d1ba71..145221760 100644 --- a/.github/workflows/alpine_linux_musl_test.yml +++ b/.github/workflows/alpine_linux_musl_test.yml @@ -44,15 +44,19 @@ jobs: git config --global user.email 'action@github.com' && \ make && \ make release && \ - _build/dist/linux/kclvm/bin/kclvm_cli version" + _build/dist/linux/core/libkcl version" - name: Read VERSION file id: read_version run: | - VERSION=$(cat VERSION) + VERSION=$(cargo pkgid -p kcl-api | cut -d'@' -f2) echo "VERSION=v${VERSION}" >> $GITHUB_ENV + + - name: Rename artifact name with version + run: sudo mv -f _build/dist/linux/kcl-latest-linux-amd64.tar.gz _build/dist/linux/kcl-$VERSION-linux-amd64.tar.gz + - name: Upload Artifact uses: actions/upload-artifact@v4 with: name: kcl-${{ env.VERSION }}-linux-musl if-no-files-found: error - path: _build/kclvm-${{ env.VERSION }}-linux-amd64.tar.gz + path: _build/dist/linux/kcl-${{ env.VERSION }}-linux-amd64.tar.gz diff --git a/.github/workflows/centos7_test.yaml b/.github/workflows/centos7_test.yaml deleted file mode 100644 index d5eaadbad..000000000 --- a/.github/workflows/centos7_test.yaml +++ /dev/null @@ -1,53 +0,0 @@ -name: Build and Test on centos7 amd64 -on: - pull_request: - branches: - - main - push: - branches: - - main -jobs: - build-and-test-centos7: - name: Build and Test on centos7 amd64 - runs-on: ubuntu-latest - steps: - - name: Check out code - uses: actions/checkout@v3 - with: - submodules: "true" - - - name: Set up QEMU - uses: docker/setup-qemu-action@v2 - with: - platforms: linux/amd64 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 - - - name: Pull custom centos7 Docker image - run: | - docker pull kcllang/kcl-builder:centos7 - - # Use llvm7 to build kcl in centos7 - - name: Release - run: | - docker run --rm \ - -v ${{ github.workspace }}:/workspace -w /workspace \ - kcllang/kcl-builder:centos7 \ - /bin/bash -c "export KCL_BUILD_GIT_SHA=$(git rev-parse HEAD) && source ~/.bash_profile && export PATH=$PATH:/opt/build/bin/ && sed -i 's/llvm12/llvm7/g' kclvm/compiler/Cargo.toml && git config --global --add safe.directory /workspace && git config --global user.name 'GitHub Action' && git config --global user.email 'action@github.com' && git add . && git commit -m 'chore: bump llvm version to 7.0' && make && make release" - - - name: Show Artifact Version - run: _build/dist/linux/kclvm/bin/kclvm_cli version - - - name: Read VERSION file - id: read_version - run: | - VERSION=$(cat VERSION) - echo "VERSION=v${VERSION}" >> $GITHUB_ENV - - - name: Upload Artifact - uses: actions/upload-artifact@v4 - with: - name: kcl-${{ env.VERSION }}-linux-amd64 - if-no-files-found: error - path: _build/kclvm-${{ env.VERSION }}-linux-amd64.tar.gz diff --git a/.github/workflows/compiler_base_test.yaml b/.github/workflows/compiler_base_test.yaml index cab4fe12d..fbdc00b82 100644 --- a/.github/workflows/compiler_base_test.yaml +++ b/.github/workflows/compiler_base_test.yaml @@ -22,13 +22,10 @@ jobs: - name: Install rust nightly toolchain uses: actions-rs/toolchain@v1 with: - toolchain: 1.84.1 + toolchain: 1.88 override: true components: clippy, rustfmt - - name: Rust code format check - working-directory: ./compiler_base - run: cargo fmt --check - shell: bash + test-codecov-lcov: name: Test strategy: @@ -43,15 +40,10 @@ jobs: - name: Install rust nightly toolchain uses: actions-rs/toolchain@v1 with: - toolchain: 1.84.1 + toolchain: 1.88 override: true components: clippy, rustfmt - name: Compiler_base rust unit test working-directory: ./compiler_base - run: make codecov-lcov + run: make test shell: bash - - name: Coveralls upload - uses: coverallsapp/github-action@master - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - path-to-lcov: ./compiler_base/.compiler_base/lcov.info diff --git a/.github/workflows/macos_arm_test.yaml b/.github/workflows/macos_arm_test.yaml index 1bda0dcc1..a843322f9 100644 --- a/.github/workflows/macos_arm_test.yaml +++ b/.github/workflows/macos_arm_test.yaml @@ -33,7 +33,7 @@ jobs: - name: Install rust nightly toolchain uses: actions-rs/toolchain@v1 with: - toolchain: 1.84.1 + toolchain: 1.88 override: true components: clippy, rustfmt - name: Set up python @@ -41,27 +41,24 @@ jobs: with: python-version: '3.11' - name: Grammar test - working-directory: ./kclvm - run: export PATH=$PATH:$PWD/../_build/dist/darwin/kclvm/bin && make && make test-grammar - shell: bash - - name: Evaluator Grammar test - working-directory: ./kclvm - run: export PATH=$PATH:$PWD/../_build/dist/darwin/kclvm/bin && make test-grammar-evaluator + run: export PATH=$PATH:$PWD/_build/dist/darwin/core && make && make test-grammar shell: bash - name: Release - run: export PATH=$PATH:$PWD/../_build/dist/darwin/kclvm/bin && make release + run: export PATH=$PATH:$PWD/_build/dist/darwin/core && make release shell: bash - name: Read VERSION file - id: read_version run: | - VERSION=$(cat VERSION) + VERSION=$(cargo pkgid -p kcl-api | cut -d'@' -f2) echo "VERSION=v${VERSION}" >> $GITHUB_ENV + - name: Rename artifact name with version + run: sudo mv -f _build/dist/darwin/kcl-latest-darwin-arm64.tar.gz _build/dist/darwin/kcl-${{ env.VERSION }}-darwin-arm64.tar.gz + - uses: actions/upload-artifact@v4 if: "contains(matrix.os, 'macos-13-xlarge')" with: name: kcl-${{ env.VERSION }}-darwin-arm64 if-no-files-found: error - path: _build/kclvm-${{ env.VERSION }}-darwin-arm64.tar.gz + path: _build/dist/darwin/kcl-${{ env.VERSION }}-darwin-arm64.tar.gz diff --git a/.github/workflows/macos_test.yaml b/.github/workflows/macos_test.yaml index b5ff67b08..fe558f75f 100644 --- a/.github/workflows/macos_test.yaml +++ b/.github/workflows/macos_test.yaml @@ -47,49 +47,37 @@ jobs: - name: Install rust nightly toolchain uses: actions-rs/toolchain@v1 with: - toolchain: 1.84.1 + toolchain: 1.88 override: true components: clippy, rustfmt - name: Code format check - working-directory: ./kclvm run: cargo fmt --check shell: bash - name: Grammar test - working-directory: ./kclvm - run: export PATH=$PATH:$PWD/../_build/dist/darwin/kclvm/bin && make && make test-grammar - shell: bash - - name: Evaluator Grammar test - working-directory: ./kclvm - run: export PATH=$PATH:$PWD/../_build/dist/darwin/kclvm/bin && make test-grammar-evaluator + run: export PATH=$PATH:$PWD/_build/dist/darwin/core && make && make test-grammar shell: bash - name: Runtime test - working-directory: ./kclvm - run: export PATH=$PATH:$PWD/../_build/dist/darwin/kclvm/bin && make test-runtime + run: export PATH=$PATH:$PWD/_build/dist/darwin/core && make test-runtime shell: bash - - name: Unit test - working-directory: ./kclvm - run: export PATH=$PATH:$PWD/../_build/dist/darwin/kclvm/bin && make codecov-lcov + run: export PATH=$PATH:$PWD/_build/dist/darwin/core && make test shell: bash - - name: Coveralls upload - uses: coverallsapp/github-action@master - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - path-to-lcov: ./kclvm/.kclvm_cov/lcov.info - - name: Release - run: export PATH=$PATH:$PWD/../_build/dist/darwin/kclvm/bin && make release + run: export PATH=$PATH:$PWD/../_build/dist/darwin/core && make release shell: bash - name: Read VERSION file id: read_version run: | - VERSION=$(cat VERSION) + VERSION=$(cargo pkgid -p kcl-api | cut -d'@' -f2) echo "VERSION=v${VERSION}" >> $GITHUB_ENV + - name: Rename artifact name with version + run: sudo mv -f _build/dist/darwin/kcl-latest-darwin-amd64.tar.gz _build/dist/darwin/kcl-${{ env.VERSION }}-darwin-amd64.tar.gz + - uses: actions/upload-artifact@v4 with: name: kcl-${{ env.VERSION }}-darwin-amd64 if-no-files-found: error - path: _build/kclvm-${{ env.VERSION }}-darwin-amd64.tar.gz + path: _build/dist/darwin/kcl-${{ env.VERSION }}-darwin-amd64.tar.gz diff --git a/.github/workflows/ubuntu_arm_test.yaml b/.github/workflows/ubuntu_arm_test.yaml index d74645bd7..6b441018c 100644 --- a/.github/workflows/ubuntu_arm_test.yaml +++ b/.github/workflows/ubuntu_arm_test.yaml @@ -32,31 +32,23 @@ jobs: - name: Install rust nightly toolchain uses: actions-rs/toolchain@v1 with: - toolchain: 1.84.1 + toolchain: 1.88 override: true components: clippy, rustfmt - name: Code format check - working-directory: ./kclvm run: cargo fmt --check shell: bash - name: chmod run: | - chmod -R 777 kclvm + chmod -R 777 crates - name: Code clippy check - working-directory: ./kclvm run: cargo clippy --no-deps -r shell: bash - name: Grammar test - working-directory: ./kclvm - run: export PATH=$PATH:$PWD/../_build/dist/linux/kclvm/bin && make && make test-grammar - shell: bash - - name: Evaluator Grammar test - working-directory: ./kclvm - run: export PATH=$PATH:$PWD/../_build/dist/linux/kclvm/bin && make test-grammar-evaluator + run: export PATH=$PATH:$PWD/_build/dist/linux/core && make && make test-grammar shell: bash - name: Runtime test - working-directory: ./kclvm - run: export PATH=$PATH:$PWD/../_build/dist/linux/kclvm/bin && make test-runtime + run: export PATH=$PATH:$PWD/_build/dist/linux/core && make test-runtime shell: bash - name: Install KCL CLI run: | @@ -64,23 +56,24 @@ jobs: echo "$(go env GOPATH)/bin" >> $GITHUB_PATH echo "${{ github.workspace }}/go/bin" >> $GITHUB_PATH - name: Unit test - working-directory: ./kclvm - run: export PATH=$PATH:$PWD/../_build/dist/linux/kclvm/bin && make test + run: export PATH=$PATH:$PWD/_build/dist/linux/core && make test shell: bash - name: Release - run: export PATH=$PATH:$PWD/../_build/dist/linux/kclvm/bin && make release + run: export PATH=$PATH:$PWD/_build/dist/linux/core && make release shell: bash - name: Read VERSION file id: read_version run: | - VERSION=$(cat VERSION) + VERSION=$(cargo pkgid -p kcl-api | cut -d'@' -f2) echo "VERSION=v${VERSION}" >> $GITHUB_ENV + - name: Rename artifact name with version + run: sudo mv -f _build/dist/linux/kcl-latest-linux-arm64.tar.gz _build/dist/linux/kcl-${{ env.VERSION }}-linux-arm64.tar.gz + - uses: actions/upload-artifact@v4 with: name: kcl-${{ env.VERSION }}-linux-arm64 if-no-files-found: error - path: _build/kclvm-${{ env.VERSION }}-linux-arm64.tar.gz - + path: _build/dist/linux/kcl-${{ env.VERSION }}-linux-arm64.tar.gz diff --git a/.github/workflows/ubuntu_test.yaml b/.github/workflows/ubuntu_test.yaml index b58806489..460cb77d8 100644 --- a/.github/workflows/ubuntu_test.yaml +++ b/.github/workflows/ubuntu_test.yaml @@ -32,28 +32,20 @@ jobs: - name: Install rust nightly toolchain uses: actions-rs/toolchain@v1 with: - toolchain: 1.84.1 + toolchain: 1.88 override: true components: clippy, rustfmt - name: Code format check - working-directory: ./kclvm run: cargo fmt --check shell: bash - name: Code clippy check - working-directory: ./kclvm run: cargo clippy --no-deps -r shell: bash - name: Grammar test - working-directory: ./kclvm - run: export PATH=$PATH:$PWD/../_build/dist/linux/kclvm/bin && make && make test-grammar - shell: bash - - name: Evaluator Grammar test - working-directory: ./kclvm - run: export PATH=$PATH:$PWD/../_build/dist/linux/kclvm/bin && make test-grammar-evaluator + run: export PATH=$PATH:$PWD/_build/dist/linux/core && make && make test-grammar shell: bash - name: Runtime test - working-directory: ./kclvm - run: export PATH=$PATH:$PWD/../_build/dist/linux/kclvm/bin && make test-runtime + run: export PATH=$PATH:$PWD/_build/dist/linux/core && make test-runtime shell: bash - name: Install KCL CLI run: | @@ -61,7 +53,5 @@ jobs: echo "$(go env GOPATH)/bin" >> $GITHUB_PATH echo "${{ github.workspace }}/go/bin" >> $GITHUB_PATH - name: Unit test - working-directory: ./kclvm - run: export PATH=$PATH:$PWD/../_build/dist/linux/kclvm/bin && make test + run: export PATH=$PATH:$PWD/_build/dist/linux/core && make test shell: bash - diff --git a/.github/workflows/wasm_test.yaml b/.github/workflows/wasm_test.yaml index b95ec300c..24b9368c8 100644 --- a/.github/workflows/wasm_test.yaml +++ b/.github/workflows/wasm_test.yaml @@ -20,19 +20,18 @@ jobs: - name: Install rust nightly toolchain uses: actions-rs/toolchain@v1 with: - toolchain: 1.83 + toolchain: 1.88 override: true components: clippy, rustfmt - - name: Unit test - working-directory: ./kclvm - run: | - rustup target add wasm32-wasip1 && make build-wasm - mv target/wasm32-wasip1/release/kclvm_cli_cdylib.wasm target/wasm32-wasip1/release/kcl.wasm - shell: bash + # - name: Build WASM + # run: | + # rustup target add wasm32-wasip1 && make build-wasm + # mv target/wasm32-wasip1/release/kcl.wasm target/wasm32-wasip1/release/kcl.wasm + # shell: bash - - uses: actions/upload-artifact@v4 - with: - name: kcl-wasm - if-no-files-found: error - path: kclvm/target/wasm32-wasip1/release/kcl.wasm + # - uses: actions/upload-artifact@v4 + # with: + # name: kcl-wasm + # if-no-files-found: error + # path: target/wasm32-wasip1/release/kcl.wasm diff --git a/.github/workflows/windows_mingw_test.yaml b/.github/workflows/windows_mingw_test.yaml index ebd38babd..777447df5 100644 --- a/.github/workflows/windows_mingw_test.yaml +++ b/.github/workflows/windows_mingw_test.yaml @@ -19,7 +19,7 @@ jobs: - name: Install rust nightly toolchain uses: actions-rs/toolchain@v1 with: - toolchain: 1.84.1 + toolchain: 1.88 override: true components: clippy, rustfmt @@ -27,22 +27,22 @@ jobs: - shell: pwsh run: echo "C:\msys64\mingw64\bin" >> $Env:GITHUB_PATH - - working-directory: ./kclvm - run: | + - run: | rustup target add x86_64-pc-windows-gnu cargo build -r --target x86_64-pc-windows-gnu - name: Read VERSION file id: read_version run: | - $version = Get-Content VERSION + $pkgId = cargo pkgid -p kcl-api + $version = ($pkgId -split '@')[1] echo "VERSION=v$version" >> $env:GITHUB_ENV - uses: actions/upload-artifact@v4 with: - name: kclvm-${{ env.VERSION }}-windows-mingw + name: kcl-${{ env.VERSION }}-windows-mingw if-no-files-found: error path: | - kclvm/target/x86_64-pc-windows-gnu/release/libkclvm_cli_cdylib.a - kclvm/target/x86_64-pc-windows-gnu/release/libkclvm_cli_cdylib.dll.a - kclvm/target/x86_64-pc-windows-gnu/release/kclvm_cli_cdylib.dll + target/x86_64-pc-windows-gnu/release/libkcl.a + target/x86_64-pc-windows-gnu/release/libkcl.dll.a + target/x86_64-pc-windows-gnu/release/kcl.dll diff --git a/.github/workflows/windows_test.yaml b/.github/workflows/windows_test.yaml index cc34af67f..74808c0cf 100644 --- a/.github/workflows/windows_test.yaml +++ b/.github/workflows/windows_test.yaml @@ -10,9 +10,6 @@ jobs: build-and-test: name: build and test on windows runs-on: windows-latest - env: - LLVM_SYS_120_PREFIX: "C:/LLVM" - KCLVM_CLANG: "C:/LLVM/bin/clang.exe" steps: - name: Git checkout uses: actions/checkout@v2 @@ -22,7 +19,7 @@ jobs: - name: Install rust nightly toolchain uses: actions-rs/toolchain@v1 with: - toolchain: 1.84.1 + toolchain: 1.88 override: true components: clippy, rustfmt @@ -45,38 +42,29 @@ jobs: - run: clang --version - run: cargo --version - # Install LLVM-12 - - run: Invoke-WebRequest -Uri https://github.com/kcl-lang/llvm-package-windows/releases/download/v12.0.1/LLVM-12.0.1-win64.7z -OutFile C:/LLVM-12.0.1-win64.7z - - run: Get-FileHash -Algorithm MD5 C:/LLVM-12.0.1-win64.7z # md5: 3fcf77f82c6c3ee650711439b20aebe5 - - run: 7z x -y C:/LLVM-12.0.1-win64.7z -o"C:/LLVM" - - run: Remove-Item C:/LLVM-12.0.1-win64.7z + # Build + - run: .\scripts\build.ps1 - - run: echo "C:/LLVM/bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append - - # Build kclvm CLI - - run: .\scripts\build-windows\build.ps1 - - # Set kclvm CLI into PATH - - run: echo ";$(pwd)\scripts\build-windows\_output\kclvm-windows\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append - working-directory: . + # Set KCL Lib CLI into PATH + - run: echo ";$(pwd)\scripts\_output\core" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append # Rust unit test - run: cargo test --workspace -r -- --nocapture - working-directory: ./kclvm - name: Read VERSION file id: read_version run: | - $version = Get-Content VERSION + $pkgId = cargo pkgid -p kcl-api + $version = ($pkgId -split '@')[1] echo "VERSION=v$version" >> $env:GITHUB_ENV - - name: Rename kclvm-windows folder + - name: Rename core folder run: | $version = "${{ env.VERSION }}" - Rename-Item -Path ".\scripts\build-windows\_output\kclvm-windows" -NewName "kclvm-$version-windows" + Rename-Item -Path ".\scripts\_output\core" -NewName "kcl-$version-windows" - uses: actions/upload-artifact@v4 with: - name: kclvm-${{ env.VERSION }}-windows + name: kcl-${{ env.VERSION }}-windows if-no-files-found: error - path: scripts/build-windows/_output/kclvm-${{ env.VERSION }}-windows + path: scripts/_output/kcl-${{ env.VERSION }}-windows diff --git a/.gitignore b/.gitignore index 5af2a7fca..6758478a8 100644 --- a/.gitignore +++ b/.gitignore @@ -9,7 +9,6 @@ __pycache__ __kclcache__/ build-result/ dist/ -kclvm.egg-info/ .eggs/ # Mac OS X files @@ -20,8 +19,8 @@ _site-packages __kcl_test_main.k -# kclvm bundles -/kclvm-*.zip +# kcl bundles +/kcl-*.zip /kcl-go* /_build_dist .kusion @@ -38,7 +37,6 @@ __kcl_test_main.k /result coverage.xml -TEST-kclvm.xml /go-test-coverprofile.* @@ -69,16 +67,9 @@ lark_parser.pickle /*/*/target /**/target -/kclvm/vendor -/scripts/docker/kclvm-builder/vendor* -/scripts/docker/kclvm-builder/crates.io-index -/scripts/docker/kclvm-builder-centos7/crates.io-index -/scripts/docker/kclvm-builder-ubuntu/crates.io-index *.tar.gz # KCL cache and temp output -.kclvm -.kclvm_cov *.dylib *.so *.dll diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 431e3bb6d..000000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "test/integration/konfig"] - path = test/integration/konfig - url = https://github.com/KusionStack/konfig.git diff --git a/CLAUDE.md b/CLAUDE.md index d6ed3fad2..ed247891d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -29,13 +29,12 @@ Ant Group, Youzan, and Huawei are notable production users managing large-scale ### Top-Level Organization ``` -/kclvm/ Core KCL VM and compiler implementation (main codebase) +/crates/ Core KCL VM and compiler implementation (main codebase) /compiler_base/ Base compiler libraries and utilities (WIP, rustc-derived) /cli/ Command-line interface binary wrapper /test/ Integration and grammar tests /grammar/ Extensive grammar test cases /integration/ Integration test suites -/samples/ Example KCL programs (hello.k, kubernetes.k, fib.k, etc.) /docs/ Developer guides and documentation /dev_guide/ Development guide (architecture, quick start, etc.) /design/ Design documents @@ -45,8 +44,6 @@ Ant Group, Youzan, and Huawei are notable production users managing large-scale ### Key Files - `Makefile` - Top-level build orchestration -- `run.sh` - Build and release automation script -- `VERSION` - Current version: **0.11.2** - `LICENSE` - Apache License 2.0 - `README.md` - Project documentation @@ -55,8 +52,8 @@ Ant Group, Youzan, and Huawei are notable production users managing large-scale ### Primary Language: Rust - 362+ Rust source files - ~32,673 lines of Rust code in core modules -- **Requires Rust 1.84+** for building -- Rust 2021 edition +- **Requires Rust 1.88+** for building +- Rust 2024 edition ### Secondary Languages - **KCL** - The language itself (.k files for examples and tests) @@ -65,7 +62,6 @@ Ant Group, Youzan, and Huawei are notable production users managing large-scale - **C/C++** - Runtime interop and FFI interfaces ### Key Dependencies -- **LLVM 12** - Compiler backend (optional, for high-performance compilation) - **Protobuf** - API definitions and RPC communication - **WASM** - WebAssembly compilation target support - **tokio** - Async runtime (for LSP and server) @@ -84,55 +80,52 @@ Source Code (.k files) ↓ [Resolver/Sema] → Semantic Analysis & Type Checking ↓ -[Compiler] → IR (LLVM IR or AST-based) - ↓ [Evaluator/Runner] → Execution ↓ Output (YAML/JSON) ``` -### Key Components (/kclvm crates) +### Key Components (/crates) **Frontend (Parsing & Analysis):** -- `kclvm-lexer` - Lexical analysis and tokenization -- `kclvm-parser` - Parse KCL source into AST -- `kclvm-ast` - Abstract Syntax Tree definitions and walker -- `kclvm-ast-pretty` - AST formatting and pretty-printing -- `kclvm-span` - Source code span/position tracking -- `kclvm-error` - Error handling and diagnostics +- `kcl-lexer` - Lexical analysis and tokenization +- `kcl-parser` - Parse KCL source into AST +- `kcl-ast` - Abstract Syntax Tree definitions and walker +- `kcl-ast-pretty` - AST formatting and pretty-printing +- `kcl-span` - Source code span/position tracking +- `kcl-error` - Error handling and diagnostics **Semantic Analysis:** -- `kclvm-sema` - Semantic analysis, type checking, and validation -- `kclvm-loader` - Module loading and dependency management -- `kclvm-query` - Code query and information retrieval +- `kcl-sema` - Semantic analysis, type checking, and validation +- `kcl-loader` - Module loading and dependency management +- `kcl-query` - Code query and information retrieval **Compilation & Execution:** -- `kclvm-compiler` - Main compilation logic with optional LLVM backend -- `kclvm-evaluator` - Expression evaluation engine -- `kclvm-runner` - Program execution environment -- `kclvm-driver` - Compilation driver and orchestration +- `kcl-evaluator` - Expression evaluation engine +- `kcl-runner` - Program execution environment +- `kcl-driver` - Compilation driver and orchestration **Runtime:** -- `kclvm-runtime` - Runtime support libraries with extensive standard library +- `kcl-runtime` - Runtime support libraries with extensive standard library - Value representation and type system - Standard library modules: json, yaml, base64, regex, crypto, datetime, math, net, etc. - Template rendering (handlebars) - File I/O and manifests **Tooling:** -- `kclvm-tools` - Development tools +- `kcl-tools` - Development tools - Format, Lint, Fix, Vet - Testing infrastructure - **LSP** (Language Server) - Full IDE support with autocomplete, goto-definition, diagnostics -- `kclvm-api` - Public API layer for multi-language SDKs -- `kclvm-cmd` - CLI command implementation +- `kcl-api` - Public API layer for multi-language SDKs +- `kcl-cmd` - CLI command implementation **Utilities:** -- `kclvm-config` - Configuration parsing -- `kclvm-version` - Version management -- `kclvm-utils` - Common utilities -- `kclvm-primitives` - Primitive type definitions -- `kclvm-macros` - Procedural macros +- `kcl-config` - Configuration parsing +- `kcl-version` - Version management +- `kcl-utils` - Common utilities +- `kcl-primitives` - Primitive type definitions +- `kcl-macros` - Procedural macros ### Language Server Architecture - Salsa-based incremental compilation for performance @@ -140,7 +133,7 @@ Output (YAML/JSON) - Thread pool for concurrent request handling - Event-driven architecture (Tasks + LSP Messages) - Compile unit discovery for projects without explicit config -- Located at: `/kclvm/tools/src/LSP` +- Located at: `/crates/tools/src/LSP` ## Build System @@ -161,13 +154,11 @@ make build-wasm # WASM target ### Build Features - Workspace with 20+ member crates -- Optional `llvm` feature flag for high-performance backend - Support for multiple targets: native, WASM (wasm32-wasip1), WASM-unknown - Cross-platform: Linux (AMD64, ARM64), macOS (AMD64, ARM64), Windows (MinGW) - Release profile optimized for size (opt-level = "z", LTO enabled) ### Major Dependencies -- **inkwell** - LLVM bindings (optional) - **serde/serde_json** - Serialization - **serde_yaml_ng** - YAML support (note: migrated from serde_yaml) - **prost/protobuf** - Protocol buffers @@ -185,7 +176,6 @@ make build-wasm # WASM target **1. Unit Tests:** - Cargo-based unit tests across all crates - Command: `make test` or `cargo test --workspace` -- Code coverage via `cargo llvm-cov` **2. Grammar Tests:** - Extensive grammar test suite in `/test/grammar` @@ -195,15 +185,9 @@ make build-wasm # WASM target - Command: `make test-grammar` **3. Integration Tests:** -- `/kclvm/tests/integration` - Rust integration tests -- `/test/integration` - Python integration tests -- Konfig tests for real-world scenarios - -**4. Fuzz Testing:** -- Parser fuzzing in `/kclvm/tests/fuzz` -- Command: `make fuzz-parser` +- `tests/grammar` - Python integration tests -**5. Runtime Tests:** +**4. Runtime Tests:** - Python-based runtime library tests - Command: `make test-runtime` @@ -248,10 +232,9 @@ Comprehensive GitHub Actions workflows (11 pipelines) for: 1. **Spec-driven**: Independent syntax and semantics specification 2. **Functional**: Low side-effects, no system-level operations (no threads/IO) 3. **Constraint-based**: Schema + Rule + Lambda for configuration validation -4. **High Performance**: Rust + LLVM compilation, WASM support -5. **API-first**: Multi-language SDKs (Rust, Go, Python, .NET, Java, Node.js) -6. **Cloud-native**: Native support for OpenAPI, K8s CRD, KRM spec -7. **Type Safety**: Static type system with constraints and validation rules +4. **API-first**: Multi-language SDKs (Rust, Go, Python, .NET, Java, Node.js) +5. **Cloud-native**: Native support for OpenAPI, K8s CRD, KRM spec +6. **Type Safety**: Static type system with constraints and validation rules ## Development Workflow @@ -262,8 +245,7 @@ Comprehensive GitHub Actions workflows (11 pipelines) for: docker pull kcllang/kcl-builder # Or install dependencies locally -# - Rust 1.84+ -# - LLVM 12 (optional, for high-performance backend) +# - Rust 1.88+ # - Python 3.x (for tests) # - Protobuf compiler @@ -294,32 +276,9 @@ make test-grammar - Comprehensive tooling (format, lint, test, vet) - Extensive test coverage and fuzzing 5. **Performance Focus:** - - Optional LLVM backend for native code compilation - WASM compilation target - Size-optimized release builds -## Common Development Tasks - -### Working with the Compiler -- Main compiler logic: `/kclvm/compiler/src/` -- LLVM codegen: `/kclvm/compiler/src/codegen/llvm/` -- Semantic analysis: `/kclvm/sema/src/` - -### Working with the Runtime -- Runtime implementation: `/kclvm/runtime/src/` -- Standard library: `/kclvm/runtime/src/_kclvm_main.ll` and various modules -- Value system: `/kclvm/runtime/src/value/` - -### Working with the Language Server -- LSP implementation: `/kclvm/tools/src/LSP/` -- Entry point: `/kclvm/tools/src/LSP/src/main.rs` -- Key components: state management, completion, goto-definition, diagnostics - -### Working with Tests -- Grammar tests: `/test/grammar/` (Python-based) -- Integration tests: `/kclvm/tests/integration/` (Rust) -- Add new test cases by following existing patterns - ## Git Workflow - **Main branch:** `main` (use this for PRs) @@ -335,8 +294,7 @@ make test-grammar 4. **Cross-platform support** - Consider multiple platforms when making changes 5. **Documentation** - Keep docs in sync with code changes 6. **The codebase uses workspaces** - Changes may affect multiple crates -7. **LLVM backend is optional** - Code should work with or without it -8. **Recent migration from serde_yaml to serde_yaml_ng** - Use the new library +7. **Recent migration from serde_yaml to serde_yaml_ng** - Use the new library ## Quick Reference diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 000000000..95905ba6e --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,46 @@ +[workspace] +members = ["crates/*"] +default-members = ["crates/lib"] +resolver = "2" + +[workspace.dependencies] +compiler_base = { path = "crates/compiler_base" } + +kcl-api = { path = "crates/api" } +kcl-ast = { path = "crates/ast" } +kcl-ast-pretty = { path = "crates/ast_pretty" } +kcl-cli = { path = "crates/cli" } +kcl-cmd = { path = "crates/cmd" } +kcl-compiler = { path = "crates/compiler" } +kcl-config = { path = "crates/config" } +kcl-driver = { path = "crates/driver" } +kcl-error = { path = "crates/error" } +kcl-evaluator = { path = "crates/evaluator" } +kcl-lexer = { path = "crates/lexer" } +kcl-lib = { path = "crates/lib" } +kcl-loader = { path = "crates/loader" } +kcl-macros = { path = "crates/macros" } +kcl-parser = { path = "crates/parser" } +kcl-primitives = { path = "crates/primitives" } +kcl-query = { path = "crates/query" } +kcl-runner = { path = "crates/runner" } +kcl-runtime = { path = "crates/runtime" } +kcl-sema = { path = "crates/sema" } +kcl-span = { path = "crates/span" } +kcl-tools = { path = "crates/tools" } +kcl-utils = { path = "crates/utils" } +kcl-version = { path = "crates/version" } + +[workspace.package] +version = "0.12.0" +edition = "2024" +rust-version = "1.83" +exclude = [".github/"] +license = "Apache-2.0" +readme = "README.md" + +[profile.release] +rpath = true +panic = "unwind" +opt-level = "z" # Optimize for size. +lto = true diff --git a/Makefile b/Makefile index 32541693d..35dce9b69 100644 --- a/Makefile +++ b/Makefile @@ -1,61 +1,80 @@ # Copyright The KCL Authors. All rights reserved. PROJECT_NAME = kcl - PWD:=$(shell pwd) -VERSION := $(shell cat VERSION) -BUILD_IMAGE:=kcllang/kcl-builder - -# export DOCKER_DEFAULT_PLATFORM=linux/amd64 -# or -# --platform linux/amd64 - -RUN_IN_DOCKER:=docker run -it --rm -RUN_IN_DOCKER+=-v ~/.ssh:/root/.ssh -RUN_IN_DOCKER+=-v ~/.gitconfig:/root/.gitconfig -RUN_IN_DOCKER+=-v ${PWD}:/root/kclvm -RUN_IN_DOCKER+=-w /root/kclvm ${BUILD_IMAGE} - # ---------------- # Build # ---------------- .PHONY: build build: - ${PWD}/run.sh -a build + ${PWD}/scripts/build.sh + +.PHONY: build-wasm +build-wasm: + cargo build --target=wasm32-wasip1 --release .PHONY: build-lsp build-lsp: - make -C ./kclvm build-lsp + cargo build --release --manifest-path crates/tools/src/LSP/Cargo.toml + +.PHONY: build-cli +build-cli: + cargo build --release --manifest-path crates/cli/Cargo.toml .PHONY: release release: - ${PWD}/run.sh -a release + ${PWD}/scripts/release.sh .PHONY: check check: - make -C ./kclvm check - -.PHONY: test -test: - make -C ./kclvm test - -.PHONY: test-grammar -test-grammar: - make -C ./kclvm test-grammar + cargo check -r --all .PHONY: fmt fmt: - make -C ./kclvm fmt + cargo fmt --all -.PHONY: tag -tag: - scripts/tag.sh v$(VERSION) +# Cargo clippy all packages +.PHONY: lint +lint: + cargo clippy -# ---------------- -# Docker -# ---------------- +# Cargo clippy all packages +.PHONY: lint-all +lint-all: + cargo clippy --workspace --all-features --benches --examples --tests + +# Cargo clippy all packages witj auto fix +.PHONY: fix +fix: + cargo clippy --fix --allow-dirty + +# Generate runtime libraries when the runtime code is changed. +gen-runtime-api: + make -C crates/runtime gen-api-spec + make fmt + +# Install the wasm-wasi target +install-rustc-wasm-wasi: + rustup target add wasm32-wasip1 + +# Install python3 pytest +install-test-deps: + python3 -m pip install --user -U pytest pytest-html pytest-xdist ruamel.yaml + +# ------------------------ +# Tests +# ------------------------ + +# Unit tests without code cov +test: + cargo test --workspace -r -- --nocapture + +# Test runtime libaries using python functions +test-runtime: install-test-deps + cd tests/runtime && PYTHONPATH=. python3 -m pytest -vv || { echo 'runtime test failed' ; exit 1; } -sh-in-docker: - ${RUN_IN_DOCKER} bash +# E2E grammar tests with the fast evaluator +test-grammar: install-test-deps + cd tests/grammar && python3 -m pytest -v -n 5 diff --git a/README-zh.md b/README-zh.md index 2e495f686..92019d8fa 100644 --- a/README-zh.md +++ b/README-zh.md @@ -47,7 +47,7 @@ KCL 是一个开源的基于约束的记录及函数语言并通过成熟的编 + **可靠稳定**:依赖[静态类型系统](https://kcl-lang.io/docs/reference/lang/tour/#type-system)、[约束](https://kcl-lang.io/docs/reference/lang/tour/#validation)和[自定义规则](https://kcl-lang.io/docs/reference/lang/tour#rule)的配置稳定性 + **强可扩展**:通过独立配置块[自动合并机制](https://kcl-lang.io/docs/reference/lang/tour/#-operators-1)保证配置编写的高可扩展性 + **易自动化**:[CRUD APIs](https://kcl-lang.io/docs/reference/lang/tour/#kcl-cli-variable-override),[多语言 SDK](https://kcl-lang.io/docs/reference/xlang-api/overview),[语言插件](https://github.com/kcl-lang/kcl-plugin) 构成的梯度自动化方案 -+ **极致性能**:使用 Rust & C,[LLVM](https://llvm.org/) 实现,支持编译到本地代码和 [WASM](https://webassembly.org/) 的高性能编译时和运行时 ++ **极致性能**:使用 Rust & C,支持编译到本地代码和 [WASM](https://webassembly.org/) 的高性能编译时和运行时 + **API 亲和**:原生支持 [OpenAPI](https://github.com/kcl-lang/kcl-openapi)、 Kubernetes CRD, Kubernetes Resource Model (KRM) 等 API 生态规范 + **开发友好**:[语言工具](https://kcl-lang.io/docs/tools/cli/kcl/) (Format,Lint,Test,Vet,Doc, 包管理工具等) 和 [IDE 插件](https://kcl-lang.io/docs/tools/Ide/) 构建良好的研发体验 + **安全可控**:面向领域,不原生提供线程、IO 等系统级功能,低噪音,低安全风险,易维护,易治理 diff --git a/README.md b/README.md index 8bab05b10..6985193ea 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ You can use KCL to + **Stability**: Configuration stability is achieved through a [static type system](https://kcl-lang.io/docs/reference/lang/tour/#type-system), [constraints](https://kcl-lang.io/docs/reference/lang/tour/#validation), and [rules](https://kcl-lang.io/docs/reference/lang/tour#rule). + **Scalability**: High scalability is assured with an [automatic merge mechanism](https://kcl-lang.io/docs/reference/lang/tour/#-operators-1) of isolated config blocks. + **Fast automation**: Gradient automation scheme of [CRUD APIs](https://kcl-lang.io/docs/reference/lang/tour/#kcl-cli-variable-override), [multilingual SDKs](https://kcl-lang.io/docs/reference/xlang-api/overview), and [language plugin](https://github.com/kcl-lang/kcl-plugin) -+ **High performance**: High compile-time and runtime performance using Rust & C and [LLVM](https://llvm.org/), and support compilation to native code and [WASM](https://webassembly.org/). ++ **High performance**: High compile-time and runtime performance using Rust & C, and support compilation to native code and [WASM](https://webassembly.org/). + **API affinity**: Native support for ecological API specifications such as [OpenAPI](https://github.com/kcl-lang/kcl-openapi), Kubernetes CRD, Kubernetes Resource Model (KRM) spec. + **Developer-friendly**: Friendly development experiences with rich [language tools](https://kcl-lang.io/docs/tools/cli/kcl/) (Format, Lint, Test, Vet, Doc, package management tools etc.), and multiple [IDE extensions](https://kcl-lang.io/docs/tools/Ide/). + **Safety & maintainable**: Domain-oriented, no system-level functions such as native threads and IO, low noise and security risk, easy maintenance and governance. diff --git a/VERSION b/VERSION deleted file mode 100644 index a8839f70d..000000000 --- a/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.11.2 \ No newline at end of file diff --git a/build.ps1 b/build.ps1 deleted file mode 100644 index a3e5a058b..000000000 --- a/build.ps1 +++ /dev/null @@ -1,14 +0,0 @@ -Set-Location $PSScriptRoot -. '.\scripts\build-windows\build.ps1' -$bin_path = Join-Path $PSScriptRoot 'scripts\build-windows\_output\kclvm-windows\bin' -$env:Path += ";$bin_path" -# rust unit test -Set-Location .\kclvm -cargo test --workspace -r -- --nocapture -Set-Location $PSScriptRoot -# rust runtime test -Set-Location .\kclvm\tests\test_units -python3 -m pytest -vv -Set-Location $PSScriptRoot -# konfig test -Invoke-Expression -Command '.\test\integration\test_konfig.bat' diff --git a/cli/Cargo.toml b/cli/Cargo.toml deleted file mode 100644 index d7ddfd771..000000000 --- a/cli/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "kclvm_cli" -version = "0.11.2" -edition = "2021" - -[[bin]] -path = "src/main.rs" -name = "kclvm_cli" - -[profile.release] -rpath = true -panic = "unwind" -opt-level = "z" # Optimize for size. -lto = true diff --git a/cli/build.rs b/cli/build.rs deleted file mode 100644 index bb7623caf..000000000 --- a/cli/build.rs +++ /dev/null @@ -1,13 +0,0 @@ -fn main() { - if cfg!(target_os = "windows") { - println!("cargo:rustc-link-search=..\\kclvm\\target\\release"); - } else { - println!("cargo:rustc-link-search=../kclvm/target/release"); - } - println!("cargo:rustc-link-lib=dylib=kclvm_cli_cdylib"); - if cfg!(target_os = "macos") { - println!("cargo:rustc-link-arg=-Wl,-rpath,@loader_path"); - } else if cfg!(target_os = "linux") { - println!("cargo:rustc-link-arg=-Wl,-rpath,$ORIGIN"); - } -} diff --git a/cli/src/main.rs b/cli/src/main.rs deleted file mode 100644 index 421ccf5bf..000000000 --- a/cli/src/main.rs +++ /dev/null @@ -1,30 +0,0 @@ -//! The `kclvm` command-line interface. - -use std::{ - ffi::{c_char, c_int, CString}, - process::ExitCode, -}; - -#[link(name = "kclvm_cli_cdylib")] -#[allow(improper_ctypes)] -extern "C-unwind" { - fn kclvm_cli_main(argc: c_int, argv: *const *const c_char) -> *mut ExitCode; -} - -fn main() -> ExitCode { - // create a vector of zero terminated strings - let args = std::env::args() - .map(|arg| CString::new(arg).unwrap()) - .collect::>(); - // convert the strings to raw pointers - let c_args = args - .iter() - .map(|arg| arg.as_ptr()) - .collect::>(); - unsafe { - // pass the pointer of the vector's internal buffer to a C function - let result = kclvm_cli_main(c_args.len() as c_int, c_args.as_ptr()); - let result = Box::from_raw(result); - *result - } -} diff --git a/compiler_base/3rdparty/rustc_span/src/README.md b/compiler_base/3rdparty/rustc_span/src/README.md index 045516fbd..d898daa5f 100644 --- a/compiler_base/3rdparty/rustc_span/src/README.md +++ b/compiler_base/3rdparty/rustc_span/src/README.md @@ -1,5 +1,5 @@ Porting ['rustc_span'] code here to enable code reuse due to the unstable and unreusable of the ['rustc_span'] crate now. -We mainly reuse helper structs and functions like `rustc_span::span`, `rustc_span::spandata`, `rustc_span::sourcemap` to manage source positions in KCLVM. +We mainly reuse helper structs and functions like `rustc_span::span`, `rustc_span::spandata`, `rustc_span::sourcemap` to manage source positions in KCL. Note: the structs and functions here exist as implementations and will not be exposed to other crates directly. diff --git a/compiler_base/Cargo.toml b/compiler_base/Cargo.toml index e0aeca2e1..84fd7aa75 100644 --- a/compiler_base/Cargo.toml +++ b/compiler_base/Cargo.toml @@ -25,4 +25,4 @@ members = [ "3rdparty/rustc_errors", "3rdparty/rustc_data_structures", "3rdparty/rustc_span", -] \ No newline at end of file +] diff --git a/compiler_base/macros/src/bug.rs b/compiler_base/macros/src/bug.rs index 2a0a027c6..6497338e7 100644 --- a/compiler_base/macros/src/bug.rs +++ b/compiler_base/macros/src/bug.rs @@ -1,7 +1,7 @@ use std::{error, fmt, panic}; /// `bug!` macro is used to report compiler internal bug. -/// You can use bug! macros directly by adding `#[macro_use]extern crate kclvm_error;` +/// You can use bug! macros directly by adding `#[macro_use]extern crate kcl_error;` /// in the lib.rs, and then call as follows: /// ```no_check /// bug!(); diff --git a/compiler_base/makefile b/compiler_base/makefile index 3a111b224..18641723b 100644 --- a/compiler_base/makefile +++ b/compiler_base/makefile @@ -1,5 +1,4 @@ PWD:=$(shell pwd) -COVER_REPORT_FILE_PATH:=$(PWD)/target/llvm-cov/html/index.html # ------------------------ # Compile and run @@ -24,16 +23,3 @@ lint: # Unit tests without code cov test: cargo test -p compiler_base_* - -# Unit tests with code cov (Requires rust 1.60+) -codecov: - rustup component add llvm-tools-preview - cargo install cargo-llvm-cov@0.6.15 - cargo llvm-cov --workspace --ignore-filename-regex gpyrpc.rs --html --open - -# Unit tests with code cov and output the lcov file (Requires rust 1.60+) -codecov-lcov: - rustup component add llvm-tools-preview - cargo install cargo-llvm-cov@0.6.15 - mkdir $(PWD)/.compiler_base - cargo llvm-cov --lcov --output-path $(PWD)/.compiler_base/lcov.info --workspace --ignore-filename-regex gpyrpc.rs diff --git a/kclvm/rustfmt.toml b/compiler_base/rustfmt.toml similarity index 100% rename from kclvm/rustfmt.toml rename to compiler_base/rustfmt.toml diff --git a/crates/api/Cargo.toml b/crates/api/Cargo.toml new file mode 100644 index 000000000..e89a9b563 --- /dev/null +++ b/crates/api/Cargo.toml @@ -0,0 +1,48 @@ +[package] +name = "kcl-api" +version.workspace = true +edition.workspace = true + +[dependencies] +futures = "0.3.28" +tempfile = "3.5.0" +maplit = "1.0.2" + +serde_json = "1.0" +serde_yaml_ng = "0.10.0" +anyhow = "1.0.70" +serde = { version = "1", features = ["derive"] } +once_cell = "1.5.2" + +prost = "0.14.1" +prost-wkt = "0.7.0" +prost-types = "0.14.1" + +kcl-runner = { path = "../runner" } +kcl-config = { path = "../config" } +kcl-driver = { path = "../driver" } +kcl-error = { path = "../error" } +kcl-parser = { path = "../parser" } +kcl-loader = { path = "../loader" } +kcl-sema = { path = "../sema" } +kcl-ast = { path = "../ast" } +kcl-ast-pretty = { path = "../ast_pretty" } +kcl-runtime = { path = "../runtime" } +kcl-tools = { path = "../tools" } +kcl-query = { path = "../query" } +kcl-version = { path = "../version" } +kcl-language-server = { path = "../tools/src/LSP" } +kcl-primitives = { path = "../primitives" } +kcl-utils = { path = "../utils" } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +jsonrpc-stdio-server = "18.0.0" +tokio = { version = "1.37.0", features = ["full"] } + +[dev-dependencies] +criterion = "0.5" + +[build-dependencies] +protoc-bin-vendored = "3.2.0" +prost-build = "0.14.1" +prost-wkt-build = "0.7.0" diff --git a/crates/api/build.rs b/crates/api/build.rs new file mode 100644 index 000000000..086e4f9e9 --- /dev/null +++ b/crates/api/build.rs @@ -0,0 +1,35 @@ +use std::{env, path::PathBuf}; + +use prost_wkt_build::{FileDescriptorSet, Message}; + +/// According to the file spec.proto, automatically generate +/// the corresponding rust source file to the directory src/model +fn main() { + unsafe { + if env::var("PROTOC").is_err() { + env::set_var( + "PROTOC", + protoc_bin_vendored::protoc_bin_path().unwrap().as_os_str(), + ); + } + } + let out = PathBuf::from(env::var("OUT_DIR").unwrap()); + let descriptor_file = out.join("kcl_service_descriptor.bin"); + + let mut prost_build = prost_build::Config::new(); + prost_build + .type_attribute(".", "#[derive(serde::Serialize,serde::Deserialize)]") + .field_attribute(".", "#[serde(default)]") + .extern_path(".google.protobuf.Any", "::prost_wkt_types::Any") + .extern_path(".google.protobuf.Timestamp", "::prost_wkt_types::Timestamp") + .extern_path(".google.protobuf.Value", "::prost_wkt_types::Value") + .file_descriptor_set_path(&descriptor_file) + .compile_protos(&["spec.proto"], &["."]) + .expect("Running prost build failed."); + + let descriptor_bytes = std::fs::read(descriptor_file).unwrap(); + + let descriptor = FileDescriptorSet::decode(&descriptor_bytes[..]).unwrap(); + + prost_wkt_build::add_serde(out, descriptor); +} diff --git a/crates/api/spec.proto b/crates/api/spec.proto new file mode 100644 index 000000000..5fef6d714 --- /dev/null +++ b/crates/api/spec.proto @@ -0,0 +1,1479 @@ +// Copyright The KCL Authors. All rights reserved. +// +// This file defines the request parameters and return structure of the KCL RPC server. + +syntax = "proto3"; + +package gpyrpc; + +// Message representing an external package for KCL. +// kcl main.k -E pkg_name=pkg_path +message ExternalPkg { + // Name of the package. + string pkg_name = 1; + // Path of the package. + string pkg_path = 2; +} + +// Message representing a key-value argument for KCL. +// kcl main.k -D name=value +message Argument { + // Name of the argument. + string name = 1; + // Value of the argument. + string value = 2; +} + +// ---------------------------------------------------------------------------- +// Error types +// ---------------------------------------------------------------------------- + +// Message representing an error. +message Error { + // Level of the error (e.g., "Error", "Warning"). + string level = 1; + // Error code. (e.g., "E1001") + string code = 2; + // List of error messages. + repeated Message messages = 3; +} + +// Message representing a detailed error message with a position. +message Message { + // The error message text. + string msg = 1; + // The position in the source code where the error occurred. + Position pos = 2; +} + +// ---------------------------------------------------------------------------- +// service request/response +// ---------------------------------------------------------------------------- + +// Service for built-in functionality. +service BuiltinService { + // Sends a ping request. + rpc Ping(Ping_Args) returns (Ping_Result); + // Lists available methods. + rpc ListMethod(ListMethod_Args) returns (ListMethod_Result); +} + +// Service for KCL VM interactions. +service KclService { + /// Ping KclService, return the same value as the parameter + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "Ping", + /// "params": { + /// "value": "hello" + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "value": "hello" + /// }, + /// "id": 1 + /// } + /// ``` + rpc Ping(Ping_Args) returns (Ping_Result); + + /// GetVersion KclService, return the kcl service version information + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "GetVersion", + /// "params": {}, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "version": "0.9.1", + /// "checksum": "c020ab3eb4b9179219d6837a57f5d323", + /// "git_sha": "1a9a72942fffc9f62cb8f1ae4e1d5ca32aa1f399", + /// "version_info": "Version: 0.9.1-c020ab3eb4b9179219d6837a57f5d323\nPlatform: aarch64-apple-darwin\nGitCommit: 1a9a72942fffc9f62cb8f1ae4e1d5ca32aa1f399" + /// }, + /// "id": 1 + /// } + /// ``` + rpc GetVersion(GetVersion_Args) returns (GetVersion_Result); + + /// Parse KCL program with entry files. + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "ParseProgram", + /// "params": { + /// "paths": ["./src/testdata/test.k"] + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "ast_json": "{...}", + /// "paths": ["./src/testdata/test.k"], + /// "errors": [] + /// }, + /// "id": 1 + /// } + /// ``` + rpc ParseProgram(ParseProgram_Args) returns (ParseProgram_Result); + + /// Parse KCL single file to Module AST JSON string with import dependencies + /// and parse errors. + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "ParseFile", + /// "params": { + /// "path": "./src/testdata/parse/main.k" + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "ast_json": "{...}", + /// "deps": ["./dep1", "./dep2"], + /// "errors": [] + /// }, + /// "id": 1 + /// } + /// ``` + rpc ParseFile(ParseFile_Args) returns (ParseFile_Result); + + /// load_package provides users with the ability to parse kcl program and semantic model + /// information including symbols, types, definitions, etc. + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "LoadPackage", + /// "params": { + /// "parse_args": { + /// "paths": ["./src/testdata/parse/main.k"] + /// }, + /// "resolve_ast": true + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "program": "{...}", + /// "paths": ["./src/testdata/parse/main.k"], + /// "parse_errors": [], + /// "type_errors": [], + /// "symbols": { ... }, + /// "scopes": { ... }, + /// "node_symbol_map": { ... }, + /// "symbol_node_map": { ... }, + /// "fully_qualified_name_map": { ... }, + /// "pkg_scope_map": { ... } + /// }, + /// "id": 1 + /// } + /// ``` + rpc LoadPackage(LoadPackage_Args) returns (LoadPackage_Result); + + /// list_options provides users with the ability to parse kcl program and get all option information. + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "ListOptions", + /// "params": { + /// "paths": ["./src/testdata/option/main.k"] + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "options": [ + /// { "name": "option1", "type": "str", "required": true, "default_value": "", "help": "option 1 help" }, + /// { "name": "option2", "type": "int", "required": false, "default_value": "0", "help": "option 2 help" }, + /// { "name": "option3", "type": "bool", "required": false, "default_value": "false", "help": "option 3 help" } + /// ] + /// }, + /// "id": 1 + /// } + /// ``` + rpc ListOptions(ParseProgram_Args) returns (ListOptions_Result); + + /// list_variables provides users with the ability to parse kcl program and get all variables by specs. + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "ListVariables", + /// "params": { + /// "files": ["./src/testdata/variables/main.k"], + /// "specs": ["a"] + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "variables": { + /// "a": { + /// "variables": [ + /// { "value": "1", "type_name": "int", "op_sym": "", "list_items": [], "dict_entries": [] } + /// ] + /// } + /// }, + /// "unsupported_codes": [], + /// "parse_errors": [] + /// }, + /// "id": 1 + /// } + /// ``` + rpc ListVariables(ListVariables_Args) returns (ListVariables_Result); + + /// Execute KCL file with args. **Note that it is not thread safe.** + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "ExecProgram", + /// "params": { + /// "work_dir": "./src/testdata", + /// "k_filename_list": ["test.k"] + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "json_result": "{\"alice\": {\"age\": 18}}", + /// "yaml_result": "alice:\n age: 18", + /// "log_message": "", + /// "err_message": "" + /// }, + /// "id": 1 + /// } + /// + /// // Request with code + /// { + /// "jsonrpc": "2.0", + /// "method": "ExecProgram", + /// "params": { + /// "k_filename_list": ["file.k"], + /// "k_code_list": ["alice = {age = 18}"] + /// }, + /// "id": 2 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "json_result": "{\"alice\": {\"age\": 18}}", + /// "yaml_result": "alice:\n age: 18", + /// "log_message": "", + /// "err_message": "" + /// }, + /// "id": 2 + /// } + /// + /// // Error case - cannot find file + /// { + /// "jsonrpc": "2.0", + /// "method": "ExecProgram", + /// "params": { + /// "k_filename_list": ["invalid_file.k"] + /// }, + /// "id": 3 + /// } + /// + /// // Error Response + /// { + /// "jsonrpc": "2.0", + /// "error": { + /// "code": -32602, + /// "message": "Cannot find the kcl file" + /// }, + /// "id": 3 + /// } + /// + /// // Error case - no input files + /// { + /// "jsonrpc": "2.0", + /// "method": "ExecProgram", + /// "params": { + /// "k_filename_list": [] + /// }, + /// "id": 4 + /// } + /// + /// // Error Response + /// { + /// "jsonrpc": "2.0", + /// "error": { + /// "code": -32602, + /// "message": "No input KCL files or paths" + /// }, + /// "id": 4 + /// } + /// ``` + rpc ExecProgram(ExecProgram_Args) returns (ExecProgram_Result); + + /// Build the KCL program to an artifact. + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "BuildProgram", + /// "params": { + /// "exec_args": { + /// "work_dir": "./src/testdata", + /// "k_filename_list": ["test.k"] + /// }, + /// "output": "./build" + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "path": "./build/test.k" + /// }, + /// "id": 1 + /// } + /// ``` + rpc BuildProgram(BuildProgram_Args) returns (BuildProgram_Result); + + /// Execute the KCL artifact with args. **Note that it is not thread safe.** + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "ExecArtifact", + /// "params": { + /// "path": "./artifact_path", + /// "exec_args": { + /// "work_dir": "./src/testdata", + /// "k_filename_list": ["test.k"] + /// } + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "json_result": "{\"alice\": {\"age\": 18}}", + /// "yaml_result": "alice:\n age: 18", + /// "log_message": "", + /// "err_message": "" + /// }, + /// "id": 1 + /// } + /// ``` + rpc ExecArtifact(ExecArtifact_Args) returns (ExecProgram_Result); + + /// Override KCL file with args. + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "OverrideFile", + /// "params": { + /// "file": "./src/testdata/test.k", + /// "specs": ["alice.age=18"] + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "result": true, + /// "parse_errors": [] + /// }, + /// "id": 1 + /// } + /// ``` + rpc OverrideFile(OverrideFile_Args) returns (OverrideFile_Result); + + /// Get schema type mapping. + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "GetSchemaTypeMapping", + /// "params": { + /// "exec_args": { + /// "work_dir": "./src/testdata", + /// "k_filename_list": ["main.k"], + /// "external_pkgs": [ + /// { + /// "pkg_name":"pkg", + /// "pkg_path": "./src/testdata/pkg" + /// } + /// ] + /// }, + /// "schema_name": "Person" + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "schema_type_mapping": { + /// "Person": { + /// "type": "schema", + /// "schema_name": "Person", + /// "properties": { + /// "name": { "type": "str" }, + /// "age": { "type": "int" } + /// }, + /// "required": ["name", "age"], + /// "decorators": [] + /// } + /// } + /// }, + /// "id": 1 + /// } + /// ``` + rpc GetSchemaTypeMapping(GetSchemaTypeMapping_Args) returns (GetSchemaTypeMapping_Result); + + /// Format code source. + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "FormatCode", + /// "params": { + /// "source": "schema Person {\n name: str\n age: int\n}\nperson = Person {\n name = \"Alice\"\n age = 18\n}\n" + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "formatted": "schema Person {\n name: str\n age: int\n}\nperson = Person {\n name = \"Alice\"\n age = 18\n}\n" + /// }, + /// "id": 1 + /// } + /// ``` + rpc FormatCode(FormatCode_Args) returns (FormatCode_Result); + + /// Format KCL file or directory path contains KCL files and returns the changed file paths. + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "FormatPath", + /// "params": { + /// "path": "./src/testdata/test.k" + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "changed_paths": [] + /// }, + /// "id": 1 + /// } + /// ``` + rpc FormatPath(FormatPath_Args) returns (FormatPath_Result); + + /// Lint files and return error messages including errors and warnings. + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "LintPath", + /// "params": { + /// "paths": ["./src/testdata/test-lint.k"] + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "results": ["Module 'math' imported but unused"] + /// }, + /// "id": 1 + /// } + /// ``` + rpc LintPath(LintPath_Args) returns (LintPath_Result); + + /// Validate code using schema and data strings. + /// + /// **Note that it is not thread safe.** + /// + /// # Examples + /// + /// ```jsonrpc + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "ValidateCode", + /// "params": { + /// "code": "schema Person {\n name: str\n age: int\n check: 0 < age < 120\n}", + /// "data": "{\"name\": \"Alice\", \"age\": 10}" + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "success": true, + /// "err_message": "" + /// }, + /// "id": 1 + /// } + /// ``` + rpc ValidateCode(ValidateCode_Args) returns (ValidateCode_Result); + + rpc ListDepFiles(ListDepFiles_Args) returns (ListDepFiles_Result); + /// Build setting file config from args. + /// + /// # Examples + /// + /// + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "LoadSettingsFiles", + /// "params": { + /// "work_dir": "./src/testdata/settings", + /// "files": ["./src/testdata/settings/kcl.yaml"] + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "kcl_cli_configs": { + /// "files": ["./src/testdata/settings/kcl.yaml"], + /// "output": "", + /// "overrides": [], + /// "path_selector": [], + /// "strict_range_check": false, + /// "disable_none": false, + /// "verbose": 0, + /// "debug": false, + /// "sort_keys": false, + /// "show_hidden": false, + /// "include_schema_type_path": false, + /// "fast_eval": false + /// }, + /// "kcl_options": [] + /// }, + /// "id": 1 + /// } + /// ``` + rpc LoadSettingsFiles(LoadSettingsFiles_Args) returns (LoadSettingsFiles_Result); + + /// Rename all the occurrences of the target symbol in the files. This API will rewrite files if they contain symbols to be renamed. + /// Return the file paths that got changed. + /// + /// # Examples + /// + /// + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "Rename", + /// "params": { + /// "package_root": "./src/testdata/rename_doc", + /// "symbol_path": "a", + /// "file_paths": ["./src/testdata/rename_doc/main.k"], + /// "new_name": "a2" + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "changed_files": ["./src/testdata/rename_doc/main.k"] + /// }, + /// "id": 1 + /// } + /// ``` + rpc Rename(Rename_Args) returns (Rename_Result); + + /// Rename all the occurrences of the target symbol and return the modified code if any code has been changed. This API won't rewrite files but return the changed code. + /// + /// # Examples + /// + /// + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "RenameCode", + /// "params": { + /// "package_root": "/mock/path", + /// "symbol_path": "a", + /// "source_codes": { + /// "/mock/path/main.k": "a = 1\nb = a" + /// }, + /// "new_name": "a2" + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "changed_codes": { + /// "/mock/path/main.k": "a2 = 1\nb = a2" + /// } + /// }, + /// "id": 1 + /// } + /// ``` + rpc RenameCode(RenameCode_Args) returns (RenameCode_Result); + + /// Test KCL packages with test arguments. + /// + /// # Examples + /// + /// + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "Test", + /// "params": { + /// "exec_args": { + /// "work_dir": "./src/testdata/testing/module", + /// "k_filename_list": ["main.k"] + /// }, + /// "pkg_list": ["./src/testdata/testing/module/..."] + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "info": [ + /// {"name": "test_case_1", "error": "", "duration": 1000, "log_message": ""}, + /// {"name": "test_case_2", "error": "some error", "duration": 2000, "log_message": ""} + /// ] + /// }, + /// "id": 1 + /// } + /// ``` + rpc Test(Test_Args) returns (Test_Result); + + /// Download and update dependencies defined in the kcl.mod file. + /// + /// # Examples + /// + /// + /// // Request + /// { + /// "jsonrpc": "2.0", + /// "method": "UpdateDependencies", + /// "params": { + /// "manifest_path": "./src/testdata/update_dependencies" + /// }, + /// "id": 1 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "external_pkgs": [ + /// {"pkg_name": "pkg1", "pkg_path": "./src/testdata/update_dependencies/pkg1"} + /// ] + /// }, + /// "id": 1 + /// } + /// + /// // Request with vendor flag + /// { + /// "jsonrpc": "2.0", + /// "method": "UpdateDependencies", + /// "params": { + /// "manifest_path": "./src/testdata/update_dependencies", + /// "vendor": true + /// }, + /// "id": 2 + /// } + /// + /// // Response + /// { + /// "jsonrpc": "2.0", + /// "result": { + /// "external_pkgs": [ + /// {"pkg_name": "pkg1", "pkg_path": "./src/testdata/update_dependencies/pkg1"} + /// ] + /// }, + /// "id": 2 + /// } + /// ``` + rpc UpdateDependencies(UpdateDependencies_Args) returns (UpdateDependencies_Result); +} + +// Message for ping request arguments. +message Ping_Args { + // Value to be sent in the ping request. + string value = 1; +} + +// Message for ping response. +message Ping_Result { + // Value received in the ping response. + string value = 1; +} + +// Message for version request arguments. Empty message. +message GetVersion_Args { + // empty +} + +// Message for version response. +message GetVersion_Result { + // KCL version. + string version = 1; + // Checksum of the KCL version. + string checksum = 2; + // Git Git SHA of the KCL code repo. + string git_sha = 3; + // Detailed version information as a string. + string version_info = 4; +} + +// Message for list method request arguments. Empty message. +message ListMethod_Args { + // empty +} + +// Message for list method response. +message ListMethod_Result { + // List of available method names. + repeated string method_name_list = 1; +} + +// Message for parse file request arguments. +message ParseFile_Args { + // Path of the file to be parsed. + string path = 1; + // Source code to be parsed. + string source = 2; + // External packages path. + repeated ExternalPkg external_pkgs = 3; +} + +// Message for parse file response. +message ParseFile_Result { + // Abstract Syntax Tree (AST) in JSON format. + string ast_json = 1; + // File dependency paths. + repeated string deps = 2; + // List of parse errors. + repeated Error errors = 3; +} + +// Message for parse program request arguments. +message ParseProgram_Args { + // Paths of the program files to be parsed. + repeated string paths = 1; + // Source codes to be parsed. + repeated string sources = 2; + // External packages path. + repeated ExternalPkg external_pkgs = 3; +} + +// Message for parse program response. +message ParseProgram_Result { + // Abstract Syntax Tree (AST) in JSON format. + string ast_json = 1; + // Returns the files in the order they should be compiled. + repeated string paths = 2; + // List of parse errors. + repeated Error errors = 3; +} + +// Message for load package request arguments. +message LoadPackage_Args { + // Arguments for parsing the program. + ParseProgram_Args parse_args = 1; + // Flag indicating whether to resolve AST. + bool resolve_ast = 2; + // Flag indicating whether to load built-in modules. + bool load_builtin = 3; + // Flag indicating whether to include AST index. + bool with_ast_index = 4; +} + +// Message for load package response. +message LoadPackage_Result { + // Program Abstract Syntax Tree (AST) in JSON format. + string program = 1; + // Returns the files in the order they should be compiled. + repeated string paths = 2; + // List of parse errors. + repeated Error parse_errors = 3; + // List of type errors. + repeated Error type_errors = 4; + // Map of scopes with scope index as key. + map scopes = 5; + // Map of symbols with symbol index as key. + map symbols = 6; + // Map of node-symbol associations with AST index UUID as key. + map node_symbol_map = 7; + // Map of symbol-node associations with symbol index as key. + map symbol_node_map = 8; + // Map of fully qualified names with symbol index as key. + map fully_qualified_name_map = 9; + // Map of package scope with package path as key. + map pkg_scope_map = 10; +} + +// Message for list options response. +message ListOptions_Result { + // List of available options. + repeated OptionHelp options = 2; +} + +// Message representing a help option. +message OptionHelp { + // Name of the option. + string name = 1; + // Type of the option. + string type = 2; + // Flag indicating if the option is required. + bool required = 3; + // Default value of the option. + string default_value = 4; + // Help text for the option. + string help = 5; +} + +// Message representing a symbol in KCL. +message Symbol { + // Type of the symbol. + KclType ty = 1; + // Name of the symbol. + string name = 2; + // Owner of the symbol. + SymbolIndex owner = 3; + // Definition of the symbol. + SymbolIndex def = 4; + // Attributes of the symbol. + repeated SymbolIndex attrs = 5; + // Flag indicating if the symbol is global. + bool is_global = 6; +} + +// Message representing a scope in KCL. +message Scope { + // Type of the scope. + string kind = 1; + // Parent scope. + ScopeIndex parent = 2; + // Owner of the scope. + SymbolIndex owner = 3; + // Children of the scope. + repeated ScopeIndex children = 4; + // Definitions in the scope. + repeated SymbolIndex defs = 5; +} + +// Message representing a symbol index. +message SymbolIndex { + // Index identifier. + uint64 i = 1; + // Global identifier. + uint64 g = 2; + // Type of the symbol or scope. + string kind = 3; +} + +// Message representing a scope index. +message ScopeIndex { + // Index identifier. + uint64 i = 1; + // Global identifier. + uint64 g = 2; + // Type of the scope. + string kind = 3; +} + +// Message for execute program request arguments. +message ExecProgram_Args { + // Working directory. + string work_dir = 1; + // List of KCL filenames. + repeated string k_filename_list = 2; + // List of KCL codes. + repeated string k_code_list = 3; + // Arguments for the program. + repeated Argument args = 4; + // Override configurations. + repeated string overrides = 5; + // Flag to disable YAML result. + bool disable_yaml_result = 6; + // Flag to print override AST. + bool print_override_ast = 7; + // Flag for strict range check. + bool strict_range_check = 8; + // Flag to disable none values. + bool disable_none = 9; + // Verbose level. + int32 verbose = 10; + // Debug level. + int32 debug = 11; + // Flag to sort keys in YAML/JSON results. + bool sort_keys = 12; + // External packages path. + repeated ExternalPkg external_pkgs = 13; + // Flag to include schema type path in results. + bool include_schema_type_path = 14; + // Flag to compile only without execution. + bool compile_only = 15; + // Flag to show hidden attributes. + bool show_hidden = 16; + // Path selectors for results. + repeated string path_selector = 17; + // Flag for fast evaluation. + bool fast_eval = 18; +} + +// Message for execute program response. +message ExecProgram_Result { + // Result in JSON format. + string json_result = 1; + // Result in YAML format. + string yaml_result = 2; + // Log message from execution. + string log_message = 3; + // Error message from execution. + string err_message = 4; +} + +// Message for build program request arguments. +message BuildProgram_Args { + // Arguments for executing the program. + ExecProgram_Args exec_args = 1; + // Output path. + string output = 2; +} + +// Message for build program response. +message BuildProgram_Result { + // Path of the built program. + string path = 1; +} + +// Message for execute artifact request arguments. +message ExecArtifact_Args { + // Path of the artifact. + string path = 1; + // Arguments for executing the program. + ExecProgram_Args exec_args = 2; +} + +// Message for format code request arguments. +message FormatCode_Args { + // Source code to be formatted. + string source = 1; +} + +// Message for format code response. +message FormatCode_Result { + // Formatted code as bytes. + bytes formatted = 1; +} + +// Message for format file path request arguments. +message FormatPath_Args { + // Path of the file to format. + string path = 1; +} + +// Message for format file path response. +message FormatPath_Result { + // List of changed file paths. + repeated string changed_paths = 1; +} + +// Message for lint file path request arguments. +message LintPath_Args { + // Paths of the files to lint. + repeated string paths = 1; +} + +// Message for lint file path response. +message LintPath_Result { + // List of lint results. + repeated string results = 1; +} + +// Message for override file request arguments. +message OverrideFile_Args { + // Path of the file to override. + string file = 1; + // List of override specifications. + repeated string specs = 2; + // List of import paths. + repeated string import_paths = 3; +} + +// Message for override file response. +message OverrideFile_Result { + // Result of the override operation. + bool result = 1; + // List of parse errors encountered. + repeated Error parse_errors = 2; +} + +// Message for list variables options. +message ListVariables_Options { + // Flag to merge program configuration. + bool merge_program = 1; +} + +// Message representing a list of variables. +message VariableList { + // List of variables. + repeated Variable variables = 1; +} + +// Message for list variables request arguments. +message ListVariables_Args { + // Files to be processed. + repeated string files = 1; + // Specifications for variables. + repeated string specs = 2; + // Options for listing variables. + ListVariables_Options options = 3; +} + +// Message for list variables response. +message ListVariables_Result { + // Map of variable lists by file. + map variables = 1; + // List of unsupported codes. + repeated string unsupported_codes = 2; + // List of parse errors encountered. + repeated Error parse_errors = 3; +} + +// Message representing a variable. +message Variable { + // Value of the variable. + string value = 1; + // Type name of the variable. + string type_name = 2; + // Operation symbol associated with the variable. + string op_sym = 3; + // List items if the variable is a list. + repeated Variable list_items = 4; + // Dictionary entries if the variable is a dictionary. + repeated MapEntry dict_entries = 5; +} + +// Message representing a map entry. +message MapEntry { + // Key of the map entry. + string key = 1; + // Value of the map entry. + Variable value = 2; +} + +// Message for get schema type mapping request arguments. +message GetSchemaTypeMapping_Args { + // Arguments for executing the program. + ExecProgram_Args exec_args = 1; + // Name of the schema. + string schema_name = 2; +} + +// Message for get schema type mapping response. +message GetSchemaTypeMapping_Result { + // Map of schema type mappings. + map schema_type_mapping = 1; +} + +// Message for get schema type mapping response. +message GetSchemaTypeMappingUnderPath_Result { + // Map of pkg and schema types mappings. + map schema_type_mapping = 1; +} + +message SchemaTypes { + // List of schema type mappings. + repeated KclType schema_type = 1; +} + +// Message for validate code request arguments. +message ValidateCode_Args { + // Path to the data file. + string datafile = 1; + // Data content. + string data = 2; + // Path to the code file. + string file = 3; + // Source code content. + string code = 4; + // Name of the schema. + string schema = 5; + // Name of the attribute. + string attribute_name = 6; + // Format of the validation (e.g., "json", "yaml"). + string format = 7; + // List of external packages updated. + repeated ExternalPkg external_pkgs = 8; +} + +// Message for validate code response. +message ValidateCode_Result { + // Flag indicating if validation was successful. + bool success = 1; + // Error message from validation. + string err_message = 2; +} + +// Message representing a position in the source code. +message Position { + // Line number. + int64 line = 1; + // Column number. + int64 column = 2; + // Filename the position refers to. + string filename = 3; +} + +// Message for list dependency files request arguments. +message ListDepFiles_Args { + // Working directory. + string work_dir = 1; + // Flag to use absolute paths. + bool use_abs_path = 2; + // Flag to include all files. + bool include_all = 3; + // Flag to use fast parser. + bool use_fast_parser = 4; +} + +// Message for list dependency files response. +message ListDepFiles_Result { + // Root package path. + string pkgroot = 1; + // Package path. + string pkgpath = 2; + // List of file paths in the package. + repeated string files = 3; +} + +// --------------------------------------------------------------------------------- +// LoadSettingsFiles API +// Input work dir and setting files and return the merged kcl singleton config. +// --------------------------------------------------------------------------------- + +// Message for load settings files request arguments. +message LoadSettingsFiles_Args { + // Working directory. + string work_dir = 1; + // Setting files to load. + repeated string files = 2; +} + +// Message for load settings files response. +message LoadSettingsFiles_Result { + // KCL CLI configuration. + CliConfig kcl_cli_configs = 1; + // List of KCL options as key-value pairs. + repeated KeyValuePair kcl_options = 2; +} + +// Message representing KCL CLI configuration. +message CliConfig { + // List of files. + repeated string files = 1; + // Output path. + string output = 2; + // List of overrides. + repeated string overrides = 3; + // Path selectors. + repeated string path_selector = 4; + // Flag for strict range check. + bool strict_range_check = 5; + // Flag to disable none values. + bool disable_none = 6; + // Verbose level. + int64 verbose = 7; + // Debug flag. + bool debug = 8; + // Flag to sort keys in YAML/JSON results. + bool sort_keys = 9; + // Flag to show hidden attributes. + bool show_hidden = 10; + // Flag to include schema type path in results. + bool include_schema_type_path = 11; + // Flag for fast evaluation. + bool fast_eval = 12; +} + +// Message representing a key-value pair. +message KeyValuePair { + // Key of the pair. + string key = 1; + // Value of the pair. + string value = 2; +} + +// --------------------------------------------------------------------------------- +// Rename API +// Find all the occurrences of the target symbol and rename them. +// This API will rewrite files if they contain symbols to be renamed. +// --------------------------------------------------------------------------------- + +// Message for rename request arguments. +message Rename_Args { + // File path to the package root. + string package_root = 1; + // Path to the target symbol to be renamed. + string symbol_path = 2; + // Paths to the source code files. + repeated string file_paths = 3; + // New name of the symbol. + string new_name = 4; +} + +// Message for rename response. +message Rename_Result { + // List of file paths that got changed. + repeated string changed_files = 1; +} + +// --------------------------------------------------------------------------------- +// RenameCode API +// Find all the occurrences of the target symbol and rename them. +// This API won't rewrite files but return the modified code if any code has been changed. +// --------------------------------------------------------------------------------- + +// Message for rename code request arguments. +message RenameCode_Args { + // File path to the package root. + string package_root = 1; + // Path to the target symbol to be renamed. + string symbol_path = 2; + // Map of source code with filename as key and code as value. + map source_codes = 3; + // New name of the symbol. + string new_name = 4; +} + +// Message for rename code response. +message RenameCode_Result { + // Map of changed code with filename as key and modified code as value. + map changed_codes = 1; +} + +// --------------------------------------------------------------------------------- +// Test API +// Test KCL packages with test arguments. +// --------------------------------------------------------------------------------- + +// Message for test request arguments. +message Test_Args { + // Execution program arguments. + ExecProgram_Args exec_args = 1; + // List of KCL package paths to be tested. + repeated string pkg_list = 2; + // Regular expression for filtering tests to run. + string run_regexp = 3; + // Flag to stop the test run on the first failure. + bool fail_fast = 4; +} + +// Message for test response. +message Test_Result { + // List of test case information. + repeated TestCaseInfo info = 2; +} + +// Message representing information about a single test case. +message TestCaseInfo { + // Name of the test case. + string name = 1; + // Error message if any. + string error = 2; + // Duration of the test case in microseconds. + uint64 duration = 3; + // Log message from the test case. + string log_message = 4; +} + +// --------------------------------------------------------------------------------- +// UpdateDependencies API +// Download and update dependencies defined in the kcl.mod file. +// --------------------------------------------------------------------------------- + +// Message for update dependencies request arguments. +message UpdateDependencies_Args { + // Path to the manifest file. + string manifest_path = 1; + // Flag to vendor dependencies locally. + bool vendor = 2; +} + +// Message for update dependencies response. +message UpdateDependencies_Result { + // List of external packages updated. + repeated ExternalPkg external_pkgs = 3; +} + +// ---------------------------------------------------------------------------- +// KCL Type Structure +// ---------------------------------------------------------------------------- + +// Message representing a KCL type. +message KclType { + // Type name (e.g., schema, dict, list, str, int, float, bool, any, union, number_multiplier). + string type = 1; + // Union types if applicable. + repeated KclType union_types = 2; + // Default value of the type. + string default = 3; + // Name of the schema if applicable. + string schema_name = 4; + // Documentation for the schema. + string schema_doc = 5; + // Properties of the schema as a map with property name as key. + map properties = 6; + // List of required schema properties. + repeated string required = 7; + // Key type if the KclType is a dictionary. + KclType key = 8; + // Item type if the KclType is a list or dictionary. + KclType item = 9; + // Line number where the type is defined. + int32 line = 10; + // List of decorators for the schema. + repeated Decorator decorators = 11; + // Absolute path of the file where the attribute is located. + string filename = 12; + // Path of the package where the attribute is located. + string pkg_path = 13; + // Documentation for the attribute. + string description = 14; + // Map of examples with example name as key. + map examples = 15; + // Base schema if applicable. + KclType base_schema = 16; +} + +// Message representing a decorator in KCL. +message Decorator { + // Name of the decorator. + string name = 1; + // Arguments for the decorator. + repeated string arguments = 2; + // Keyword arguments for the decorator as a map with keyword name as key. + map keywords = 3; +} + +// Message representing an example in KCL. +message Example { + // Short description for the example. + string summary = 1; + // Long description for the example. + string description = 2; + // Embedded literal example. + string value = 3; +} + +// ---------------------------------------------------------------------------- +// END +// ---------------------------------------------------------------------------- diff --git a/kclvm/api/src/capi_test.rs b/crates/api/src/capi_test.rs similarity index 89% rename from kclvm/api/src/capi_test.rs rename to crates/api/src/capi_test.rs index d3a05d1e0..a130c919a 100644 --- a/kclvm/api/src/capi_test.rs +++ b/crates/api/src/capi_test.rs @@ -1,6 +1,6 @@ use crate::service::capi::*; use crate::{call, gpyrpc::*}; -use kclvm_utils::path::PathPrefix; +use kcl_utils::path::PathPrefix; use once_cell::sync::Lazy; use prost::Message; use serde::de::DeserializeOwned; @@ -16,7 +16,7 @@ static TEST_MUTEX: Lazy> = Lazy::new(|| Mutex::new(0i32)); #[test] fn test_c_api_call_exec_program() { test_c_api::( - "KclvmService.ExecProgram", + "KclService.ExecProgram", "exec-program.json", "exec-program.response.json", |_| {}, @@ -26,7 +26,7 @@ fn test_c_api_call_exec_program() { #[test] fn test_c_api_call_exec_program_with_external_pkg() { test_c_api::( - "KclvmService.ExecProgram", + "KclService.ExecProgram", "exec-program-with-external-pkg.json", "exec-program-with-external-pkg.response.json", |_| {}, @@ -36,7 +36,7 @@ fn test_c_api_call_exec_program_with_external_pkg() { #[test] fn test_c_api_call_exec_program_with_include_schema_type_path() { test_c_api::( - "KclvmService.ExecProgram", + "KclService.ExecProgram", "exec-program-with-include-schema-type-path.json", "exec-program-with-include-schema-type-path.response.json", |_| {}, @@ -46,7 +46,7 @@ fn test_c_api_call_exec_program_with_include_schema_type_path() { #[test] fn test_c_api_call_exec_program_with_path_selector() { test_c_api::( - "KclvmService.ExecProgram", + "KclService.ExecProgram", "exec-program-with-path-selector.json", "exec-program-with-path-selector.response.json", |_| {}, @@ -56,7 +56,7 @@ fn test_c_api_call_exec_program_with_path_selector() { #[test] fn test_c_api_call_exec_program_with_print() { test_c_api::( - "KclvmService.ExecProgram", + "KclService.ExecProgram", "exec-program-with-print.json", "exec-program-with-print.response.json", |_| {}, @@ -87,7 +87,7 @@ fn test_c_api_call_override_file() { for (input, output) in &test_cases { test_c_api_without_wrapper::( - "KclvmService.OverrideFile", + "KclService.OverrideFile", input, output, ); @@ -97,7 +97,7 @@ fn test_c_api_call_override_file() { #[test] fn test_c_api_get_schema_type_mapping() { test_c_api::( - "KclvmService.GetSchemaTypeMapping", + "KclService.GetSchemaTypeMapping", "get-schema-type-mapping.json", "get-schema-type-mapping.response.json", |r| { @@ -120,7 +120,7 @@ fn test_c_api_get_schema_type_mapping() { #[test] fn test_c_api_format_code() { test_c_api_without_wrapper::( - "KclvmService.FormatCode", + "KclService.FormatCode", "format-code.json", "format-code.response.json", ); @@ -129,7 +129,7 @@ fn test_c_api_format_code() { #[test] fn test_c_api_format_path() { test_c_api_without_wrapper::( - "KclvmService.FormatPath", + "KclService.FormatPath", "format-path.json", "format-path.response.json", ); @@ -138,7 +138,7 @@ fn test_c_api_format_path() { #[test] fn test_c_api_lint_path() { test_c_api_without_wrapper::( - "KclvmService.LintPath", + "KclService.LintPath", "lint-path.json", "lint-path.response.json", ); @@ -147,7 +147,7 @@ fn test_c_api_lint_path() { #[test] fn test_c_api_call_exec_program_with_compile_only() { test_c_api_panic::( - "KclvmService.ExecProgram", + "KclService.ExecProgram", "exec-program-with-compile-only.json", "exec-program-with-compile-only.response.panic", ); @@ -156,7 +156,7 @@ fn test_c_api_call_exec_program_with_compile_only() { #[test] fn test_c_api_validate_code_with_dep() { test_c_api_without_wrapper::( - "KclvmService.ValidateCode", + "KclService.ValidateCode", "validate-code-file-with-dep.json", "validate-code-file-with-dep.response.json", ); @@ -165,7 +165,7 @@ fn test_c_api_validate_code_with_dep() { #[test] fn test_c_api_validate_code() { test_c_api_without_wrapper::( - "KclvmService.ValidateCode", + "KclService.ValidateCode", "validate-code.json", "validate-code.response.json", ); @@ -174,7 +174,7 @@ fn test_c_api_validate_code() { #[test] fn test_c_api_validate_code_file() { test_c_api_without_wrapper::( - "KclvmService.ValidateCode", + "KclService.ValidateCode", "validate-code-file.json", "validate-code-file.response.json", ); @@ -183,7 +183,7 @@ fn test_c_api_validate_code_file() { #[test] fn test_c_api_load_settings_files() { test_c_api_without_wrapper::( - "KclvmService.LoadSettingsFiles", + "KclService.LoadSettingsFiles", "load-settings-files.json", "load-settings-files.response.json", ); @@ -198,7 +198,7 @@ fn test_c_api_rename() { fs::write(path.clone(), content).unwrap(); test_c_api::( - "KclvmService.Rename", + "KclService.Rename", "rename.json", "rename.response.json", |r| { @@ -223,7 +223,7 @@ fn test_c_api_rename() { #[test] fn test_c_api_rename_code() { test_c_api_without_wrapper::( - "KclvmService.RenameCode", + "KclService.RenameCode", "rename-code.json", "rename-code.response.json", ); @@ -232,7 +232,7 @@ fn test_c_api_rename_code() { #[test] fn test_c_api_list_options() { test_c_api_without_wrapper::( - "KclvmService.ListOptions", + "KclService.ListOptions", "list-options.json", "list-options.response.json", ); @@ -241,7 +241,7 @@ fn test_c_api_list_options() { #[test] fn test_c_api_list_variables() { test_c_api_without_wrapper::( - "KclvmService.ListVariables", + "KclService.ListVariables", "list-variables.json", "list-variables.response.json", ); @@ -250,7 +250,7 @@ fn test_c_api_list_variables() { #[test] fn test_c_api_parse_file() { test_c_api_without_wrapper::( - "KclvmService.ParseFile", + "KclService.ParseFile", "parse-file.json", "parse-file.response.json", ); @@ -259,7 +259,7 @@ fn test_c_api_parse_file() { #[test] fn test_c_api_testing() { test_c_api::( - "KclvmService.Test", + "KclService.Test", "test.json", "test.response.json", |r| { @@ -291,7 +291,7 @@ where F: Fn(&mut R), { let _test_lock = TEST_MUTEX.lock().unwrap(); - let serv = kclvm_service_new(0); + let serv = kcl_service_new(0); let input_path = Path::new(TEST_DATA_PATH).join(input); let input = fs::read_to_string(&input_path) @@ -300,7 +300,7 @@ where let args = unsafe { CString::from_vec_unchecked(args_vec.clone()) }; let call = CString::new(svc_name).unwrap(); let mut result_len: usize = 0; - let src_ptr = kclvm_service_call_with_length( + let src_ptr = kcl_service_call_with_length( serv, call.as_ptr(), args.as_ptr(), @@ -330,8 +330,8 @@ where wrapper(&mut except_result); assert_eq!(result, except_result, "\nresult json is {result_json}"); unsafe { - kclvm_service_delete(serv); - kclvm_service_free_string(src_ptr as *mut c_char); + kcl_service_delete(serv); + kcl_service_free_string(src_ptr as *mut c_char); } } @@ -340,7 +340,7 @@ where A: Message + DeserializeOwned, { let _test_lock = TEST_MUTEX.lock().unwrap(); - let serv = kclvm_service_new(0); + let serv = kcl_service_new(0); let prev_hook = std::panic::take_hook(); // disable print panic info std::panic::set_hook(Box::new(|_info| {})); @@ -351,7 +351,7 @@ where let args_vec = serde_json::from_str::(&input).unwrap().encode_to_vec(); let args = unsafe { CString::from_vec_unchecked(args_vec.clone()) }; let call = CString::new(svc_name).unwrap(); - kclvm_service_call(serv, call.as_ptr(), args.as_ptr(), args_vec.len()) + kcl_service_call(serv, call.as_ptr(), args.as_ptr(), args_vec.len()) }); std::panic::set_hook(prev_hook); match result { @@ -371,8 +371,8 @@ where result.to_string_lossy() ); unsafe { - kclvm_service_delete(serv); - kclvm_service_free_string(result_ptr as *mut c_char); + kcl_service_delete(serv); + kcl_service_free_string(result_ptr as *mut c_char); } } Err(_) => { @@ -383,7 +383,7 @@ where #[test] fn test_call_exec_program() { - let name = b"KclvmService.ExecProgram"; + let name = b"KclService.ExecProgram"; let args = b"\x12\x1a./src/testdata/test_call.k"; let result = call(name, args).unwrap(); assert!( @@ -395,7 +395,7 @@ fn test_call_exec_program() { #[test] fn test_call_get_version() { - let name = b"KclvmService.GetVersion"; + let name = b"KclService.GetVersion"; let args = b""; let result = call(name, args).unwrap(); assert!(!result.starts_with(b"ERROR")) diff --git a/crates/api/src/lib.rs b/crates/api/src/lib.rs new file mode 100644 index 000000000..9217a36d8 --- /dev/null +++ b/crates/api/src/lib.rs @@ -0,0 +1,104 @@ +//! # KCL Rust SDK +//! +//! ## How to Use +//! +//! ```no_check,no_run +//! cargo add --git https://github.com/kcl-lang/kcl kcl_api +//! ``` +//! +//! Write the Code +//! +//! ```no_run +//! use kcl_api::*; +//! use std::path::Path; +//! use anyhow::Result; +//! +//! fn main() -> Result<()> { +//! let api = API::default(); +//! let args = &ExecProgramArgs { +//! work_dir: Path::new(".").join("testdata").canonicalize().unwrap().display().to_string(), +//! k_filename_list: vec!["test.k".to_string()], +//! ..Default::default() +//! }; +//! let exec_result = api.exec_program(args)?; +//! assert_eq!(exec_result.yaml_result, "alice:\n age: 18"); +//! Ok(()) +//! } +//! ``` +#[cfg(test)] +pub mod capi_test; +pub mod service; + +pub mod gpyrpc { + include!(concat!(env!("OUT_DIR"), "/gpyrpc.rs")); +} + +pub use crate::gpyrpc::*; +use crate::service::capi::{kcl_service_call_with_length, kcl_service_new}; +use crate::service::service_impl::KclServiceImpl; +use anyhow::Result; +use std::ffi::{CString, c_char}; + +pub type API = KclServiceImpl; + +/// Call KCL API with the API name and argument protobuf bytes. +#[inline] +pub fn call<'a>(name: &'a [u8], args: &'a [u8]) -> Result> { + call_with_plugin_agent(name, args, 0) +} + +/// Call KCL API with the API name, argument protobuf bytes and the plugin agent pointer address. +pub fn call_with_plugin_agent<'a>( + name: &'a [u8], + args: &'a [u8], + plugin_agent: u64, +) -> Result> { + let mut result_len: usize = 0; + let result_ptr = { + let serv = kcl_service_new(plugin_agent); + let args_len = args.len(); + let name = unsafe { CString::from_vec_unchecked(name.to_vec()) }; + let args = unsafe { CString::from_vec_unchecked(args.to_vec()) }; + kcl_service_call_with_length( + serv, + name.as_ptr(), + args.as_ptr() as *const c_char, + args_len, + &mut result_len, + ) + }; + let result = unsafe { + let mut dest_data: Vec = Vec::with_capacity(result_len); + let dest_ptr: *mut u8 = dest_data.as_mut_ptr(); + std::ptr::copy_nonoverlapping(result_ptr as *const u8, dest_ptr, result_len); + dest_data.set_len(result_len); + dest_data + }; + + Ok(result) +} + +/// call_native is a universal KCL API interface that is consistent with the methods and parameters defined in Protobuf. +/// The first two parameters represent the name and length of the calling method, the middle two parameters represent +/// the Protobuf byte sequence and length of the calling parameter, and the return parameter is the byte sequence and +/// length of Protobuf. +#[unsafe(no_mangle)] +pub extern "C-unwind" fn call_native( + name_ptr: *const u8, + name_len: usize, + args_ptr: *const u8, + args_len: usize, + result_ptr: *mut u8, +) -> usize { + let name = unsafe { std::slice::from_raw_parts(name_ptr, name_len) }; + let args = unsafe { std::slice::from_raw_parts(args_ptr, args_len) }; + let res = call(name, args); + let result = match res { + Ok(res) => res, + Err(err) => err.to_string().into_bytes(), + }; + unsafe { + std::ptr::copy_nonoverlapping(result.as_ptr(), result_ptr, result.len()); + } + result.len() +} diff --git a/crates/api/src/service/capi.rs b/crates/api/src/service/capi.rs new file mode 100644 index 000000000..c4d687831 --- /dev/null +++ b/crates/api/src/service/capi.rs @@ -0,0 +1,636 @@ +use prost::Message; + +use crate::gpyrpc::*; +use crate::service::service_impl::KclServiceImpl; +use std::ffi::CString; +use std::os::raw::c_char; +use std::slice; + +#[allow(non_camel_case_types)] +type kcl_service = KclServiceImpl; + +fn c_char_to_vec(args: *const c_char, args_len: usize) -> Vec { + if args.is_null() { + return Vec::new(); + } + // Create a slice from the raw pointer + let slice = unsafe { slice::from_raw_parts(args as *const u8, args_len) }; + // Convert slice to Vec + slice.to_vec() +} + +/// Create an instance of kcl_service and return its pointer +#[unsafe(no_mangle)] +pub extern "C-unwind" fn kcl_service_new(plugin_agent: u64) -> *mut kcl_service { + let serv = kcl_service { plugin_agent }; + Box::into_raw(Box::new(serv)) +} + +/// # Safety +/// +/// This function should not be called twice on the same ptr. +/// Delete KclService +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_service_delete(serv: *mut kcl_service) { + if !serv.is_null() { + unsafe { + drop(Box::from_raw(serv)); + } + } +} + +/// # Safety +/// +/// This function should not be called twice on the same ptr. +/// Free memory for string returned to the outside +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_service_free_string(res: *mut c_char) { + if !res.is_null() { + unsafe { + let _ = CString::from_raw(res); + }; + } +} + +macro_rules! call { + ($serv:expr, $args:expr, $args_len:expr, $result_len:expr, $arg_name:ident, $serv_name:ident) => {{ + unsafe { + let serv_ref = &mut *$serv; + let args = c_char_to_vec($args, $args_len); + let args = args.as_slice(); + let args = $arg_name::decode(args).unwrap(); + let res = serv_ref.$serv_name(&args); + let result_byte = match res { + Ok(res) => res.encode_to_vec(), + Err(err) => format!("ERROR:{}", err.to_string()).into_bytes(), + }; + *$result_len = result_byte.len(); + CString::from_vec_unchecked(result_byte).into_raw() + } + }}; +} + +/// Call kcl service by C API. **Note that it is not thread safe.** +/// +/// # Parameters +/// +/// `serv`: [*mut kcl_service] +/// The pointer of &\[[KclServiceImpl]] +/// +/// `call`: [*const c_char] +/// The C str of the name of the called service, +/// with the format "KclService.{MethodName}" +/// +/// `args`: [*const c_char] +/// Arguments of the call serialized as protobuf byte sequence, +/// refer to kcl/spec/gpyrpc/gpyrpc.proto for the specific definitions of arguments +/// +/// # Returns +/// +/// result: [*const c_char] +/// Result of the call serialized as protobuf byte sequence +#[unsafe(no_mangle)] +pub extern "C-unwind" fn kcl_service_call( + serv: *mut kcl_service, + name: *const c_char, + args: *const c_char, + args_len: usize, +) -> *const c_char { + let mut _result_len = 0; + kcl_service_call_with_length(serv, name, args, args_len, &mut _result_len) +} + +/// Call kcl service by C API. **Note that it is not thread safe.** +/// +/// # Parameters +/// +/// `serv`: [*mut kcl_service] +/// The pointer of &\[[KclServiceImpl]] +/// +/// `call`: [*const c_char] +/// The C str of the name of the called service, +/// with the format "KclService.{MethodName}" +/// +/// `args`: [*const c_char] +/// Arguments of the call serialized as protobuf byte sequence, +/// refer to kcl/spec/gpyrpc/gpyrpc.proto for the specific definitions of arguments +/// +/// # Returns +/// +/// result: [*const c_char] +/// Result of the call serialized as protobuf byte sequence +#[unsafe(no_mangle)] +pub extern "C-unwind" fn kcl_service_call_with_length( + serv: *mut kcl_service, + name: *const c_char, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + let result = std::panic::catch_unwind(|| { + let name = unsafe { std::ffi::CStr::from_ptr(name) }.to_str().unwrap(); + let call = kcl_get_service_fn_ptr_by_name(name); + if call == 0 { + panic!("null fn ptr"); + } + let call = (&call as *const u64) as *const () + as *const fn( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, + ) -> *const c_char; + unsafe { (*call)(serv, args, args_len, result_len) } + }); + match result { + Ok(result) => result, + Err(panic_err) => { + let err_message = kcl_error::err_to_str(panic_err); + + let c_string = std::ffi::CString::new(format!("ERROR:{}", err_message.as_str())) + .expect("CString::new failed"); + let ptr = c_string.into_raw(); + ptr as *const c_char + } + } +} + +pub(crate) fn kcl_get_service_fn_ptr_by_name(name: &str) -> u64 { + match name { + "KclService.Ping" => ping as *const () as u64, + "KclService.GetVersion" => get_version as *const () as u64, + "KclService.ParseFile" => parse_file as *const () as u64, + "KclService.ParseProgram" => parse_program as *const () as u64, + "KclService.LoadPackage" => load_package as *const () as u64, + "KclService.ListOptions" => list_options as *const () as u64, + "KclService.ListVariables" => list_variables as *const () as u64, + "KclService.ExecProgram" => exec_program as *const () as u64, + "KclService.OverrideFile" => override_file as *const () as u64, + "KclService.GetSchemaTypeMapping" => get_schema_type_mapping as *const () as u64, + "KclService.GetSchemaTypeMappingUnderPath" => { + get_schema_type_mapping_under_path as *const () as u64 + } + "KclService.FormatCode" => format_code as *const () as u64, + "KclService.FormatPath" => format_path as *const () as u64, + "KclService.LintPath" => lint_path as *const () as u64, + "KclService.ValidateCode" => validate_code as *const () as u64, + "KclService.LoadSettingsFiles" => load_settings_files as *const () as u64, + "KclService.Rename" => rename as *const () as u64, + "KclService.RenameCode" => rename_code as *const () as u64, + "KclService.Test" => test as *const () as u64, + #[cfg(not(target_arch = "wasm32"))] + "KclService.UpdateDependencies" => update_dependencies as *const () as u64, + _ => panic!("unknown method name : {name}"), + } +} + +/// ping is used to test whether kcl service is successfully imported +/// arguments and return results should be consistent +pub(crate) fn ping( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!(serv, args, args_len, result_len, PingArgs, ping) +} + +/// get_version is used to get kcl service version +pub(crate) fn get_version( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + GetVersionArgs, + get_version + ) +} + +/// parse_file provides users with the ability to parse kcl single file +/// +/// # Parameters +/// +/// `serv`: [*mut kcl_service] +/// The pointer of &\[[KclServiceImpl]] +/// +/// +/// `args`: [*const c_char] +/// the items and compile parameters selected by the user in the KCL CLI +/// serialized as protobuf byte sequence +/// +/// # Returns +/// +/// result: [*const c_char] +/// Result of the call serialized as protobuf byte sequence +pub(crate) fn parse_file( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!(serv, args, args_len, result_len, ParseFileArgs, parse_file) +} + +/// parse_program provides users with the ability to parse kcl program +/// +/// # Parameters +/// +/// `serv`: [*mut kcl_service] +/// The pointer of &\[[KclServiceImpl]] +/// +/// +/// `args`: [*const c_char] +/// the items and compile parameters selected by the user in the KCL CLI +/// serialized as protobuf byte sequence +/// +/// # Returns +/// +/// result: [*const c_char] +/// Result of the call serialized as protobuf byte sequence +pub(crate) fn parse_program( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + ParseProgramArgs, + parse_program + ) +} + +/// load_package provides users with the ability to parse kcl program and sematic model +/// information including symbols, types, definitions, etc, +/// +/// # Parameters +/// +/// `serv`: [*mut kcl_service] +/// The pointer of &\[[KclServiceImpl]] +/// +/// +/// `args`: [*const c_char] +/// the items and compile parameters selected by the user in the KCL CLI +/// serialized as protobuf byte sequence +/// +/// # Returns +/// +/// result: [*const c_char] +/// Result of the call serialized as protobuf byte sequence +pub(crate) fn load_package( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + LoadPackageArgs, + load_package + ) +} + +/// list_options provides users with the ability to parse kcl program and get all option +/// calling information. +/// +/// # Parameters +/// +/// `serv`: [*mut kcl_service] +/// The pointer of &\[[KclServiceImpl]] +/// +/// +/// `args`: [*const c_char] +/// the items and compile parameters selected by the user in the KCL CLI +/// serialized as protobuf byte sequence +/// +/// # Returns +/// +/// result: [*const c_char] +/// Result of the call serialized as protobuf byte sequence +pub(crate) fn list_options( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + ParseProgramArgs, + list_options + ) +} + +/// list_variables provides users with the ability to parse kcl program and get all variables +/// calling information. +/// +/// # Parameters +/// +/// `serv`: [*mut kcl_service] +/// The pointer of &\[[KclServiceImpl]] +/// +/// +/// `args`: [*const c_char] +/// the items and compile parameters selected by the user in the KCL CLI +/// serialized as protobuf byte sequence +/// +/// # Returns +/// +/// result: [*const c_char] +/// Result of the call serialized as protobuf byte sequence +pub(crate) fn list_variables( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + ListVariablesArgs, + list_variables + ) +} + +/// exec_program provides users with the ability to execute KCL code +/// +/// # Parameters +/// +/// `serv`: [*mut kcl_service] +/// The pointer of &\[[KclServiceImpl]] +/// +/// +/// `args`: [*const c_char] +/// the items and compile parameters selected by the user in the KCL CLI +/// serialized as protobuf byte sequence +/// +/// # Returns +/// +/// result: [*const c_char] +/// Result of the call serialized as protobuf byte sequence +pub(crate) fn exec_program( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + ExecProgramArgs, + exec_program + ) +} + +/// override_file enable users override existing KCL file with specific KCl code +/// +/// # Parameters +/// +/// `serv`: [*mut kcl_service] +/// The pointer of &\[[KclServiceImpl]] +/// +/// +/// `args`: [*const c_char] +/// kcl file , override specs and import paths selected by the user in the KCL CLI +/// serialized as protobuf byte sequence +/// +/// # Returns +/// +/// result: [*const c_char] +/// Result of the call serialized as protobuf byte sequence +pub(crate) fn override_file( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + OverrideFileArgs, + override_file + ) +} + +/// Get schema types from a kcl file or code. +/// +/// # Parameters +/// file: [&str]. The kcl filename. +/// +/// code: [Option<&str>]. The kcl code string +/// +/// schema_name: [Option<&str>]. The schema name, when the schema name is empty, all schemas are returned. +pub(crate) fn get_schema_type_mapping( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + GetSchemaTypeMappingArgs, + get_schema_type_mapping + ) +} + +/// Get schema types under path +/// +/// # Parameters +/// file: [&str]. The kcl filename. +/// +/// code: [Option<&str>]. The kcl code string +/// +/// schema_name: [Option<&str>]. The schema name, when the schema name is empty, all schemas are returned. +pub(crate) fn get_schema_type_mapping_under_path( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + GetSchemaTypeMappingArgs, + get_schema_type_mapping_under_path + ) +} + +/// Service for formatting a code source and returns the formatted source and +/// whether the source is changed. +pub(crate) fn format_code( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + FormatCodeArgs, + format_code + ) +} + +/// Service for formatting kcl file or directory path contains kcl files and +/// returns the changed file paths. +pub(crate) fn format_path( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + FormatPathArgs, + format_path + ) +} + +/// Service for KCL Lint API, check a set of files, skips execute, +/// returns error message including errors and warnings. +pub(crate) fn lint_path( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!(serv, args, args_len, result_len, LintPathArgs, lint_path) +} + +/// Service for validating the data string using the schema code string, when the parameter +/// `schema` is omitted, use the first schema appeared in the kcl code. +pub(crate) fn validate_code( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + ValidateCodeArgs, + validate_code + ) +} + +/// Service for building setting file config from args. +pub(crate) fn load_settings_files( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + LoadSettingsFilesArgs, + load_settings_files + ) +} + +/// Service for renaming all the occurrences of the target symbol in the files. This API will rewrite files if they contain symbols to be renamed. +/// return the file paths got changed. +pub(crate) fn rename( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!(serv, args, args_len, result_len, RenameArgs, rename) +} + +/// Service for renaming all the occurrences of the target symbol in the code. This API won't rewrite files but return the modified code if any code has been changed. +/// return the changed code. +pub(crate) fn rename_code( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + RenameCodeArgs, + rename_code + ) +} + +/// Service for the testing tool. +pub(crate) fn test( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!(serv, args, args_len, result_len, TestArgs, test) +} + +#[cfg(not(target_arch = "wasm32"))] +/// Service for the dependencies updating +/// calling information. +/// +/// # Parameters +/// +/// `serv`: [*mut kcl_service] +/// The pointer of &\[[KclServiceImpl]] +/// +/// +/// `args`: [*const c_char] +/// the items and compile parameters selected by the user in the KCL CLI +/// serialized as protobuf byte sequence +/// +/// # Returns +/// +/// result: [*const c_char] +/// Result of the call serialized as protobuf byte sequence +pub(crate) fn update_dependencies( + serv: *mut kcl_service, + args: *const c_char, + args_len: usize, + result_len: *mut usize, +) -> *const c_char { + call!( + serv, + args, + args_len, + result_len, + UpdateDependenciesArgs, + update_dependencies + ) +} diff --git a/crates/api/src/service/into.rs b/crates/api/src/service/into.rs new file mode 100644 index 000000000..d661d8f92 --- /dev/null +++ b/crates/api/src/service/into.rs @@ -0,0 +1,138 @@ +use crate::gpyrpc::{ + CliConfig, Error, KeyValuePair, LoadSettingsFilesResult, Message, Position, Scope, ScopeIndex, + Symbol, SymbolIndex, +}; +use crate::service::ty::kcl_ty_to_pb_ty; +use kcl_config::settings::SettingsFile; +use kcl_error::Diagnostic; +use kcl_loader::{ScopeInfo, SymbolInfo}; +use kcl_sema::core::{scope::ScopeRef, symbol::SymbolRef}; + +pub(crate) trait IntoLoadSettingsFiles { + /// Convert self into the LoadSettingsFiles structure. + fn into_load_settings_files(self, files: &[String]) -> LoadSettingsFilesResult; +} + +pub(crate) trait IntoError { + fn into_error(self) -> Error; +} + +pub(crate) trait IntoSymbolIndex { + fn into_symbol_index(self) -> SymbolIndex; +} + +pub(crate) trait IntoSymbol { + fn into_symbol(self) -> Symbol; +} + +pub(crate) trait IntoScope { + fn into_scope(self) -> Scope; +} + +pub(crate) trait IntoScopeIndex { + fn into_scope_index(self) -> ScopeIndex; +} + +impl IntoLoadSettingsFiles for SettingsFile { + fn into_load_settings_files(self, files: &[String]) -> LoadSettingsFilesResult { + LoadSettingsFilesResult { + kcl_cli_configs: self.kcl_cli_configs.map(|config| CliConfig { + files: files.to_vec(), + output: config.output.unwrap_or_default(), + overrides: config.overrides.unwrap_or_default(), + path_selector: config.path_selector.unwrap_or_default(), + strict_range_check: config.strict_range_check.unwrap_or_default(), + disable_none: config.disable_none.unwrap_or_default(), + verbose: config.verbose.unwrap_or_default() as i64, + debug: config.debug.unwrap_or_default(), + sort_keys: config.sort_keys.unwrap_or_default(), + show_hidden: config.show_hidden.unwrap_or_default(), + fast_eval: config.fast_eval.unwrap_or_default(), + include_schema_type_path: config.include_schema_type_path.unwrap_or_default(), + }), + kcl_options: match self.kcl_options { + Some(opts) => opts + .iter() + .map(|o| KeyValuePair { + key: o.key.to_string(), + value: o.value.to_string(), + }) + .collect(), + None => vec![], + }, + } + } +} + +impl IntoError for Diagnostic { + fn into_error(self) -> Error { + Error { + level: self.level.to_string(), + code: format!( + "{:?}", + self.code.unwrap_or(kcl_error::DiagnosticId::Error( + kcl_error::ErrorKind::InvalidSyntax, + )) + ), + messages: self + .messages + .iter() + .map(|m| Message { + msg: m.message.clone(), + pos: Some(Position { + filename: m.range.0.filename.clone(), + line: m.range.0.line as i64, + column: m.range.0.column.unwrap_or_default() as i64, + }), + }) + .collect(), + } + } +} + +impl IntoSymbolIndex for SymbolRef { + fn into_symbol_index(self) -> SymbolIndex { + let (index, generation) = self.get_id().into_raw_parts(); + SymbolIndex { + i: index as u64, + g: generation, + kind: format!("{:?}", self.get_kind()), + } + } +} + +impl IntoScopeIndex for ScopeRef { + fn into_scope_index(self) -> ScopeIndex { + let (index, generation) = self.get_id().into_raw_parts(); + ScopeIndex { + i: index as u64, + g: generation, + kind: format!("{:?}", self.get_kind()), + } + } +} + +impl IntoSymbol for SymbolInfo { + fn into_symbol(self) -> Symbol { + Symbol { + ty: Some(kcl_ty_to_pb_ty(&self.ty)), + name: self.name, + owner: self.owner.map(|o| o.into_symbol_index()), + def: self.def.map(|d| d.into_symbol_index()), + attrs: self.attrs.iter().map(|a| a.into_symbol_index()).collect(), + is_global: self.is_global, + } + } +} + +impl IntoScope for ScopeInfo { + fn into_scope(self) -> Scope { + Scope { + kind: format!("{:?}", self.kind), + parent: self.parent.map(|o| o.into_scope_index()), + owner: self.owner.map(|o| o.into_symbol_index()), + children: self.children.iter().map(|a| a.into_scope_index()).collect(), + defs: self.defs.iter().map(|a| a.into_symbol_index()).collect(), + } + } +} diff --git a/crates/api/src/service/jsonrpc.rs b/crates/api/src/service/jsonrpc.rs new file mode 100644 index 000000000..94098557f --- /dev/null +++ b/crates/api/src/service/jsonrpc.rs @@ -0,0 +1,266 @@ +use crate::gpyrpc::*; +use crate::service::service_impl::KclServiceImpl; +use core::fmt::Display; +use jsonrpc_stdio_server::ServerBuilder; +use jsonrpc_stdio_server::jsonrpc_core::{Error, ErrorCode, IoHandler, Params}; +use serde::Serialize; +const KCL_SERVER_ERROR_CODE: i64 = 0x4B434C; // the ASCII code of "KCL" + +/// Start a json rpc server via Stdin/Stdout +#[tokio::main] +pub async fn start_stdio_server() -> Result<(), anyhow::Error> { + let mut io = IoHandler::default(); + // KclService + register_kcl_service(&mut io); + // BuiltinService + register_builtin_service(&mut io); + let server = ServerBuilder::new(io).build(); + server.await; + Ok(()) +} + +macro_rules! catch { + ($serv:expr, $args:expr, $serv_name:ident) => {{ + let prev_hook = std::panic::take_hook(); + + // disable print panic info + std::panic::set_hook(Box::new(|_info| {})); + let result = std::panic::catch_unwind(|| to_json_result(&$serv.$serv_name(&$args))); + std::panic::set_hook(prev_hook); + match result { + Ok(result) => result, + Err(panic_err) => { + let err_message = kcl_error::err_to_str(panic_err); + Err(Error { + code: ErrorCode::from(KCL_SERVER_ERROR_CODE), + message: err_message, + data: None, + }) + } + } + }}; +} + +/// Transform the [`Result`] into [`Result`] +#[inline] +fn to_json_result(val: &Result) -> Result +where + V: Serialize, + E: Display, +{ + match val { + Ok(val) => Ok(serde_json::to_value(val).unwrap()), + Err(err) => Err(Error { + code: ErrorCode::from(KCL_SERVER_ERROR_CODE), + message: err.to_string(), + data: None, + }), + } +} + +fn register_kcl_service(io: &mut IoHandler) { + io.add_method("KclService.Ping", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: PingArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, ping)) + }); + io.add_method("KclService.GetVersion", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: GetVersionArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, get_version)) + }); + io.add_method("KclService.ParseFile", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: ParseFileArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, parse_file)) + }); + io.add_method("KclService.ParseProgram", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: ParseProgramArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, parse_program)) + }); + io.add_method("KclService.LoadPackage", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: LoadPackageArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, load_package)) + }); + io.add_method("KclService.ListOptions", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: ParseProgramArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, list_options)) + }); + io.add_method("KclService.ListVariables", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: ListVariablesArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, list_variables)) + }); + io.add_method("KclService.ExecProgram", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: ExecProgramArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, exec_program)) + }); + io.add_method("KclService.OverrideFile", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: OverrideFileArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, override_file)) + }); + io.add_method("KclService.GetSchemaTypeMapping", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: GetSchemaTypeMappingArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, get_schema_type_mapping)) + }); + io.add_method( + "KclService.GetSchemaTypeMappingUnderPath", + |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: GetSchemaTypeMappingArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!( + kcl_service_impl, + args, + get_schema_type_mapping_under_path + )) + }, + ); + io.add_method("KclService.FormatCode", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: FormatCodeArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, format_code)) + }); + io.add_method("KclService.FormatPath", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: FormatPathArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, format_path)) + }); + io.add_method("KclService.LintPath", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: LintPathArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, lint_path)) + }); + io.add_method("KclService.ValidateCode", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: ValidateCodeArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, validate_code)) + }); + io.add_method("KclService.LoadSettingsFiles", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: LoadSettingsFilesArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, load_settings_files)) + }); + io.add_method("KclService.Rename", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: RenameArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, rename)) + }); + io.add_method("KclService.RenameCode", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: RenameCodeArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, rename_code)) + }); + io.add_method("KclService.Test", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: TestArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, test)) + }); + io.add_method("KclService.UpdateDependencies", |params: Params| { + let kcl_service_impl = KclServiceImpl::default(); + let args: UpdateDependenciesArgs = match params.parse() { + Ok(val) => val, + Err(err) => return futures::future::ready(Err(err)), + }; + futures::future::ready(catch!(kcl_service_impl, args, update_dependencies)) + }); +} + +fn register_builtin_service(io: &mut IoHandler) { + io.add_sync_method("BuiltinService.Ping", |params: Params| { + let args: PingArgs = params.parse()?; + let result = PingResult { value: args.value }; + Ok(serde_json::to_value(result).unwrap()) + }); + io.add_sync_method("BuiltinService.ListMethod", |_params: Params| { + let result = ListMethodResult { + method_name_list: vec![ + "KclService.Ping".to_owned(), + "KclService.GetVersion".to_owned(), + "KclService.ParseFile".to_owned(), + "KclService.ParseProgram".to_owned(), + "KclService.ExecProgram".to_owned(), + "KclService.BuildProgram".to_owned(), + "KclService.ExecArtifact".to_owned(), + "KclService.OverrideFile".to_owned(), + "KclService.GetSchemaType".to_owned(), + "KclService.GetFullSchemaType".to_owned(), + "KclService.GetSchemaTypeMapping".to_owned(), + "KclService.FormatCode".to_owned(), + "KclService.FormatPath".to_owned(), + "KclService.LintPath".to_owned(), + "KclService.ValidateCode".to_owned(), + "KclService.LoadSettingsFiles".to_owned(), + "KclService.Rename".to_owned(), + "KclService.RenameCode".to_owned(), + "KclService.Test".to_owned(), + "KclService.UpdateDependencies".to_owned(), + "BuiltinService.Ping".to_owned(), + "BuiltinService.PingListMethod".to_owned(), + ], + }; + Ok(serde_json::to_value(result).unwrap()) + }); +} diff --git a/crates/api/src/service/mod.rs b/crates/api/src/service/mod.rs new file mode 100644 index 000000000..43c10530e --- /dev/null +++ b/crates/api/src/service/mod.rs @@ -0,0 +1,9 @@ +pub mod capi; +pub(crate) mod into; +#[cfg(not(target_arch = "wasm32"))] +pub mod jsonrpc; +pub mod service_impl; +pub(crate) mod ty; +pub(crate) mod util; + +pub use service_impl::KclServiceImpl; diff --git a/kclvm/api/src/service/service_impl.rs b/crates/api/src/service/service_impl.rs similarity index 81% rename from kclvm/api/src/service/service_impl.rs rename to crates/api/src/service/service_impl.rs index 30a997620..b03144e0c 100644 --- a/kclvm/api/src/service/service_impl.rs +++ b/crates/api/src/service/service_impl.rs @@ -5,35 +5,33 @@ use std::string::String; use crate::gpyrpc::{self, *}; +use kcl_ast::ast::SerializeProgram; +use kcl_config::settings::build_settings_pathbuf; use kcl_language_server::rename; -use kclvm_ast::ast::SerializeProgram; -use kclvm_config::settings::build_settings_pathbuf; -use kclvm_loader::option::list_options; -use kclvm_loader::{load_packages_with_cache, LoadPackageOptions}; -use kclvm_parser::entry::{canonicalize_input_file, get_normalized_k_files_from_paths}; -use kclvm_parser::load_program; -use kclvm_parser::parse_single_file; -use kclvm_parser::KCLModuleCache; -use kclvm_parser::LoadProgramOptions; -use kclvm_parser::ParseSessionRef; -use kclvm_query::override_file; -use kclvm_query::query::CompilationOptions; -use kclvm_query::query::{get_full_schema_type, get_full_schema_type_under_path}; -use kclvm_query::selector::{list_variables, ListOptions}; -use kclvm_query::GetSchemaOption; -use kclvm_runner::exec_program; -#[cfg(feature = "llvm")] -use kclvm_runner::{build_program, exec_artifact}; -use kclvm_sema::core::global_state::GlobalState; -use kclvm_sema::resolver::scope::KCLScopeCache; -use kclvm_sema::resolver::Options; -use kclvm_tools::format::{format, format_source, FormatOptions}; -use kclvm_tools::lint::lint_files; -use kclvm_tools::testing; -use kclvm_tools::testing::TestRun; -use kclvm_tools::vet::validator::validate; -use kclvm_tools::vet::validator::LoaderKind; -use kclvm_tools::vet::validator::ValidateOption; +use kcl_loader::option::list_options; +use kcl_loader::{LoadPackageOptions, load_packages_with_cache}; +use kcl_parser::KCLModuleCache; +use kcl_parser::LoadProgramOptions; +use kcl_parser::ParseSessionRef; +use kcl_parser::entry::{canonicalize_input_file, get_normalized_k_files_from_paths}; +use kcl_parser::load_program; +use kcl_parser::parse_single_file; +use kcl_query::GetSchemaOption; +use kcl_query::override_file; +use kcl_query::query::CompilationOptions; +use kcl_query::query::{get_full_schema_type, get_full_schema_type_under_path}; +use kcl_query::selector::{ListOptions, list_variables}; +use kcl_runner::exec_program; +use kcl_sema::core::global_state::GlobalState; +use kcl_sema::resolver::Options; +use kcl_sema::resolver::scope::KCLScopeCache; +use kcl_tools::format::{FormatOptions, format, format_source}; +use kcl_tools::lint::lint_files; +use kcl_tools::testing; +use kcl_tools::testing::TestRun; +use kcl_tools::vet::validator::LoaderKind; +use kcl_tools::vet::validator::ValidateOption; +use kcl_tools::vet::validator::validate; use tempfile::NamedTempFile; use super::into::*; @@ -42,12 +40,12 @@ use super::util::{transform_exec_para, transform_str_para}; /// Specific implementation of calling service #[derive(Debug, Clone, Default)] -pub struct KclvmServiceImpl { +pub struct KclServiceImpl { pub plugin_agent: u64, } -impl From<&kclvm_query::selector::Variable> for Variable { - fn from(var: &kclvm_query::selector::Variable) -> Self { +impl From<&kcl_query::selector::Variable> for Variable { + fn from(var: &kcl_query::selector::Variable) -> Self { Variable { value: var.value.to_string(), type_name: var.type_name.to_string(), @@ -65,15 +63,15 @@ impl From<&kclvm_query::selector::Variable> for Variable { } } -impl KclvmServiceImpl { - /// Ping KclvmService, return the same value as the parameter +impl KclServiceImpl { + /// Ping KclService, return the same value as the parameter /// /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; - /// let serv = KclvmServiceImpl::default(); + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; + /// let serv = KclServiceImpl::default(); /// let args = &PingArgs { /// value: "hello".to_string(), /// ..Default::default() @@ -88,14 +86,14 @@ impl KclvmServiceImpl { }) } - /// GetVersion KclvmService, return the kclvm service version information + /// GetVersion KclService, return the kcl service version information /// /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; - /// let serv = KclvmServiceImpl::default(); + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; + /// let serv = KclServiceImpl::default(); /// let args = &GetVersionArgs { /// ..Default::default() /// }; @@ -105,10 +103,10 @@ impl KclvmServiceImpl { /// pub fn get_version(&self, _args: &GetVersionArgs) -> anyhow::Result { Ok(GetVersionResult { - version: kclvm_version::VERSION.to_string(), - checksum: kclvm_version::CHECK_SUM.to_string(), - git_sha: kclvm_version::GIT_SHA.to_string(), - version_info: kclvm_version::get_version_info(), + version: kcl_version::VERSION.to_string(), + checksum: kcl_version::CHECK_SUM.to_string(), + git_sha: kcl_version::GIT_SHA.to_string(), + version_info: kcl_version::get_version_info(), }) } @@ -117,11 +115,11 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// use std::path::Path; /// // File case - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let args = &ParseProgramArgs { /// paths: vec![Path::new(".").join("src").join("testdata").join("test.k").canonicalize().unwrap().display().to_string()], /// ..Default::default() @@ -168,11 +166,11 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// use std::path::Path; /// // File case - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let args = &ParseFileArgs { /// path: Path::new(".").join("src").join("testdata").join("parse").join("main.k").canonicalize().unwrap().display().to_string(), /// ..Default::default() @@ -203,12 +201,12 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// use std::path::Path; - /// use kclvm_utils::path::PathPrefix; + /// use kcl_utils::path::PathPrefix; /// - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let args = &LoadPackageArgs { /// parse_args: Some(ParseProgramArgs { /// paths: vec![Path::new(".").join("src").join("testdata").join("parse").join("main.k").canonicalize().unwrap().display().to_string().adjust_canonicalization()], @@ -264,7 +262,7 @@ impl KclvmServiceImpl { )?; if args.with_ast_index { // Thread local options - kclvm_ast::ast::set_should_serialize_id(true); + kcl_ast::ast::set_should_serialize_id(true); } let serialize_program: SerializeProgram = packages.program.into(); let program_json = serde_json::to_string(&serialize_program)?; @@ -328,11 +326,11 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// use std::path::Path; /// - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let args = &ParseProgramArgs { /// paths: vec![Path::new(".").join("src").join("testdata").join("option").join("main.k").canonicalize().unwrap().display().to_string()], /// ..Default::default() @@ -375,11 +373,11 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// use std::path::Path; /// - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let args = &ListVariablesArgs { /// files: vec![Path::new(".").join("src").join("testdata").join("variables").join("main.k").canonicalize().unwrap().display().to_string()], /// specs: vec!["a".to_string()], @@ -436,16 +434,14 @@ impl KclvmServiceImpl { /// Execute KCL file with arguments and return the JSON/YAML result. /// - /// **Note that it is not thread safe when the llvm feature is enabled.** - /// /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// use std::path::Path; /// // File case - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let args = &ExecProgramArgs { /// work_dir: Path::new(".").join("src").join("testdata").canonicalize().unwrap().display().to_string(), /// k_filename_list: vec!["test.k".to_string()], @@ -492,90 +488,15 @@ impl KclvmServiceImpl { }) } - /// Build the KCL program to an artifact. - /// - /// # Examples - /// - /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; - /// use std::path::Path; - /// // File case - /// let serv = KclvmServiceImpl::default(); - /// let exec_args = ExecProgramArgs { - /// work_dir: Path::new(".").join("src").join("testdata").canonicalize().unwrap().display().to_string(), - /// k_filename_list: vec!["test.k".to_string()], - /// ..Default::default() - /// }; - /// let artifact = serv.build_program(&BuildProgramArgs { - /// exec_args: Some(exec_args), - /// output: "".to_string(), - /// }).unwrap(); - /// assert!(!artifact.path.is_empty()); - /// ``` - #[cfg(feature = "llvm")] - pub fn build_program(&self, args: &BuildProgramArgs) -> anyhow::Result { - let exec_args = transform_exec_para(&args.exec_args, self.plugin_agent)?; - let artifact = build_program( - ParseSessionRef::default(), - &exec_args, - transform_str_para(&args.output), - )?; - Ok(BuildProgramResult { - path: artifact.get_path().to_string(), - }) - } - - /// Execute the KCL artifact with arguments and return the JSON/YAML result. - /// - /// ***Note that it is not thread safe when the llvm feature is enabled.* - /// - /// # Examples - /// - /// ```no_run - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; - /// use std::path::Path; - /// // File case - /// let serv = KclvmServiceImpl::default(); - /// let exec_args = ExecProgramArgs { - /// work_dir: Path::new(".").join("src").join("testdata").canonicalize().unwrap().display().to_string(), - /// k_filename_list: vec!["test.k".to_string()], - /// ..Default::default() - /// }; - /// let artifact = serv.build_program(&BuildProgramArgs { - /// exec_args: Some(exec_args.clone()), - /// output: "./lib".to_string(), - /// }).unwrap(); - /// assert!(!artifact.path.is_empty()); - /// let exec_result = serv.exec_artifact(&ExecArtifactArgs { - /// exec_args: Some(exec_args), - /// path: artifact.path, - /// }).unwrap(); - /// assert_eq!(exec_result.err_message, ""); - /// assert_eq!(exec_result.yaml_result, "alice:\n age: 18"); - /// ``` - #[cfg(feature = "llvm")] - pub fn exec_artifact(&self, args: &ExecArtifactArgs) -> anyhow::Result { - let exec_args = transform_exec_para(&args.exec_args, self.plugin_agent)?; - let result = exec_artifact(&args.path, &exec_args)?; - Ok(ExecProgramResult { - json_result: result.json_result, - yaml_result: result.yaml_result, - log_message: result.log_message, - err_message: result.err_message, - }) - } - /// Override KCL file with args /// /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let args = &OverrideFileArgs { /// file: "./src/testdata/test.k".to_string(), /// specs: vec!["alice.age=18".to_string()], @@ -614,11 +535,11 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// use std::path::Path; /// - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let work_dir_parent = Path::new(".").join("src").join("testdata").join("get_schema_ty"); /// let args = ExecProgramArgs { /// work_dir: work_dir_parent.join("aaa").canonicalize().unwrap().display().to_string(), @@ -671,12 +592,12 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// use std::path::Path; - /// use kclvm_ast::MAIN_PKG; + /// use kcl_ast::MAIN_PKG; /// - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let work_dir_parent = Path::new(".").join("src").join("testdata").join("get_schema_ty_under_path"); /// let args = ExecProgramArgs { /// k_filename_list: vec![ @@ -740,10 +661,10 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let source = r#"schema Person: /// name: str /// age: int @@ -780,10 +701,10 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let result = serv.format_path(&FormatPathArgs { /// path: "./src/testdata/test.k".to_string(), /// ..Default::default() @@ -815,10 +736,10 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let result = serv.lint_path(&LintPathArgs { /// paths: vec!["./src/testdata/test-lint.k".to_string()], /// ..Default::default() @@ -854,10 +775,10 @@ impl KclvmServiceImpl { /// # Examples /// /// ```no_run - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let code = r#" /// schema Person: /// name: str @@ -922,10 +843,10 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let result = serv.load_settings_files(&LoadSettingsFilesArgs { /// files: vec!["./src/testdata/settings/kcl.yaml".to_string()], /// work_dir: "./src/testdata/settings".to_string(), @@ -962,12 +883,12 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// # use std::path::PathBuf; /// # use std::fs; /// # - /// # let serv = KclvmServiceImpl::default(); + /// # let serv = KclServiceImpl::default(); /// # // before test, load template from .bak /// # let path = PathBuf::from(".").join("src").join("testdata").join("rename_doc").join("main.k"); /// # let backup_path = path.with_extension("bak"); @@ -1012,10 +933,10 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let result = serv.rename_code(&RenameCodeArgs { /// package_root: "/mock/path".to_string(), /// symbol_path: "a".to_string(), @@ -1041,10 +962,10 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let result = serv.test(&TestArgs { /// pkg_list: vec!["./src/testdata/testing/module/...".to_string()], /// ..TestArgs::default() @@ -1090,12 +1011,12 @@ impl KclvmServiceImpl { /// # Examples /// /// ``` - /// use kclvm_api::service::service_impl::KclvmServiceImpl; - /// use kclvm_api::gpyrpc::*; + /// use kcl_api::service::service_impl::KclServiceImpl; + /// use kcl_api::gpyrpc::*; /// use std::path::Path; /// use std::fs::remove_dir_all; /// - /// let serv = KclvmServiceImpl::default(); + /// let serv = KclServiceImpl::default(); /// let result = serv.update_dependencies(&UpdateDependenciesArgs { /// manifest_path: "./src/testdata/update_dependencies".to_string(), /// ..Default::default() @@ -1114,7 +1035,7 @@ impl KclvmServiceImpl { &self, args: &UpdateDependenciesArgs, ) -> anyhow::Result { - use kclvm_driver::client::ModClient; + use kcl_driver::client::ModClient; use std::path::Path; let mut client = ModClient::new(&args.manifest_path)?; if args.vendor { diff --git a/crates/api/src/service/ty.rs b/crates/api/src/service/ty.rs new file mode 100644 index 000000000..36bc6bf25 --- /dev/null +++ b/crates/api/src/service/ty.rs @@ -0,0 +1,121 @@ +use crate::gpyrpc::{Decorator, Example, KclType}; +use kcl_primitives::IndexSet; +use kcl_sema::ty::{DictType, SchemaType, Type}; +use std::collections::HashMap; + +/// Convert the kcl sematic type to the kcl protobuf type. +pub(crate) fn kcl_ty_to_pb_ty(ty: &Type) -> KclType { + match &ty.kind { + kcl_sema::ty::TypeKind::List(item_ty) => KclType { + r#type: "list".to_string(), + item: Some(Box::new(kcl_ty_to_pb_ty(item_ty))), + ..Default::default() + }, + kcl_sema::ty::TypeKind::Dict(DictType { key_ty, val_ty, .. }) => KclType { + r#type: "dict".to_string(), + key: Some(Box::new(kcl_ty_to_pb_ty(key_ty))), + item: Some(Box::new(kcl_ty_to_pb_ty(val_ty))), + ..Default::default() + }, + kcl_sema::ty::TypeKind::Union(types) => KclType { + r#type: "union".to_string(), + union_types: types.iter().map(|ty| kcl_ty_to_pb_ty(ty)).collect(), + ..Default::default() + }, + kcl_sema::ty::TypeKind::Schema(schema_ty) => kcl_schema_ty_to_pb_ty(schema_ty), + _ => KclType { + r#type: ty.ty_str(), + ..Default::default() + }, + } +} + +/// Convert the kcl sematic type to the kcl protobuf type. +pub(crate) fn kcl_schema_ty_to_pb_ty(schema_ty: &SchemaType) -> KclType { + KclType { + r#type: "schema".to_string(), + schema_name: schema_ty.name.clone(), + schema_doc: schema_ty.doc.clone(), + examples: get_schema_ty_examples(schema_ty), + properties: get_schema_ty_attributes(schema_ty, &mut 1), + required: get_schema_ty_required_attributes(schema_ty), + decorators: schema_ty + .decorators + .iter() + .map(|d| Decorator { + name: d.name.clone(), + arguments: d.arguments.clone(), + keywords: d.keywords.clone(), + }) + .collect(), + filename: schema_ty.filename.clone(), + pkg_path: schema_ty.pkgpath.clone(), + description: schema_ty.doc.clone(), + base_schema: schema_ty + .base + .as_ref() + .map(|base| Box::new(kcl_schema_ty_to_pb_ty(&**base))), + ..Default::default() + } +} + +fn get_schema_ty_examples(schema_ty: &SchemaType) -> HashMap { + let mut examples = HashMap::new(); + for (key, example) in &schema_ty.examples { + let exa = Example { + summary: example.summary.clone(), + description: example.description.clone(), + value: example.value.clone(), + }; + examples.insert(key.clone(), exa); + } + examples +} + +fn get_schema_ty_attributes(schema_ty: &SchemaType, line: &mut i32) -> HashMap { + let mut base_type_mapping = if let Some(base) = &schema_ty.base { + get_schema_ty_attributes(base, line) + } else { + HashMap::new() + }; + let mut type_mapping = HashMap::new(); + for (key, attr) in &schema_ty.attrs { + let mut ty = kcl_ty_to_pb_ty(&attr.ty); + ty.line = *line; + ty.description = attr.doc.clone().unwrap_or_default(); + ty.decorators = attr + .decorators + .iter() + .map(|d| Decorator { + name: d.name.clone(), + arguments: d.arguments.clone(), + keywords: d.keywords.clone(), + }) + .collect(); + ty.default = attr.default.clone().unwrap_or_default(); + type_mapping.insert(key.to_string(), ty); + *line += 1 + } + for (k, ty) in type_mapping { + base_type_mapping.insert(k, ty); + } + base_type_mapping +} + +fn get_schema_ty_required_attributes(schema_ty: &SchemaType) -> Vec { + let base_attr_set = if let Some(base) = &schema_ty.base { + get_schema_ty_required_attributes(base) + } else { + Vec::new() + }; + let mut attr_set = IndexSet::new(); + for (key, attr) in &schema_ty.attrs { + if !attr.is_optional { + attr_set.insert(key.to_string()); + } + } + for k in base_attr_set { + attr_set.insert(k); + } + attr_set.iter().cloned().collect() +} diff --git a/crates/api/src/service/util.rs b/crates/api/src/service/util.rs new file mode 100644 index 000000000..0c33a7c60 --- /dev/null +++ b/crates/api/src/service/util.rs @@ -0,0 +1,27 @@ +use crate::gpyrpc::ExecProgramArgs; + +/// Transform the str with zero value into [`Option`] +#[inline] +pub(crate) fn transform_str_para(para: &str) -> Option { + if para.is_empty() { + None + } else { + Some(para.to_string()) + } +} + +#[inline] +pub(crate) fn transform_exec_para( + exec_args: &Option, + plugin_agent: u64, +) -> anyhow::Result { + let mut args = match exec_args { + Some(exec_args) => { + let args_json = serde_json::to_string(exec_args)?; + kcl_runner::ExecProgramArgs::from_str(args_json.as_str()) + } + None => kcl_runner::ExecProgramArgs::default(), + }; + args.plugin_agent = plugin_agent; + Ok(args) +} diff --git a/kclvm/api/src/testdata/compile_recursive/kcl1/main.k b/crates/api/src/testdata/compile_recursive/kcl1/main.k similarity index 100% rename from kclvm/api/src/testdata/compile_recursive/kcl1/main.k rename to crates/api/src/testdata/compile_recursive/kcl1/main.k diff --git a/kclvm/api/src/testdata/compile_recursive/kcl2/main.k b/crates/api/src/testdata/compile_recursive/kcl2/main.k similarity index 100% rename from kclvm/api/src/testdata/compile_recursive/kcl2/main.k rename to crates/api/src/testdata/compile_recursive/kcl2/main.k diff --git a/kclvm/api/src/testdata/compile_recursive/main.k b/crates/api/src/testdata/compile_recursive/main.k similarity index 100% rename from kclvm/api/src/testdata/compile_recursive/main.k rename to crates/api/src/testdata/compile_recursive/main.k diff --git a/kclvm/api/src/testdata/dep/sub_dep/kcl.mod b/crates/api/src/testdata/dep/sub_dep/kcl.mod similarity index 100% rename from kclvm/api/src/testdata/dep/sub_dep/kcl.mod rename to crates/api/src/testdata/dep/sub_dep/kcl.mod diff --git a/kclvm/api/src/testdata/dep/sub_dep/main.k b/crates/api/src/testdata/dep/sub_dep/main.k similarity index 100% rename from kclvm/api/src/testdata/dep/sub_dep/main.k rename to crates/api/src/testdata/dep/sub_dep/main.k diff --git a/kclvm/api/src/testdata/exec-program-with-compile-only.json b/crates/api/src/testdata/exec-program-with-compile-only.json similarity index 100% rename from kclvm/api/src/testdata/exec-program-with-compile-only.json rename to crates/api/src/testdata/exec-program-with-compile-only.json diff --git a/kclvm/api/src/testdata/exec-program-with-compile-only.response.panic b/crates/api/src/testdata/exec-program-with-compile-only.response.panic similarity index 100% rename from kclvm/api/src/testdata/exec-program-with-compile-only.response.panic rename to crates/api/src/testdata/exec-program-with-compile-only.response.panic diff --git a/kclvm/api/src/testdata/exec-program-with-external-pkg.json b/crates/api/src/testdata/exec-program-with-external-pkg.json similarity index 100% rename from kclvm/api/src/testdata/exec-program-with-external-pkg.json rename to crates/api/src/testdata/exec-program-with-external-pkg.json diff --git a/kclvm/api/src/testdata/exec-program-with-external-pkg.response.json b/crates/api/src/testdata/exec-program-with-external-pkg.response.json similarity index 100% rename from kclvm/api/src/testdata/exec-program-with-external-pkg.response.json rename to crates/api/src/testdata/exec-program-with-external-pkg.response.json diff --git a/kclvm/api/src/testdata/exec-program-with-include-schema-type-path.json b/crates/api/src/testdata/exec-program-with-include-schema-type-path.json similarity index 100% rename from kclvm/api/src/testdata/exec-program-with-include-schema-type-path.json rename to crates/api/src/testdata/exec-program-with-include-schema-type-path.json diff --git a/kclvm/api/src/testdata/exec-program-with-include-schema-type-path.response.json b/crates/api/src/testdata/exec-program-with-include-schema-type-path.response.json similarity index 100% rename from kclvm/api/src/testdata/exec-program-with-include-schema-type-path.response.json rename to crates/api/src/testdata/exec-program-with-include-schema-type-path.response.json diff --git a/kclvm/api/src/testdata/exec-program-with-path-selector.json b/crates/api/src/testdata/exec-program-with-path-selector.json similarity index 100% rename from kclvm/api/src/testdata/exec-program-with-path-selector.json rename to crates/api/src/testdata/exec-program-with-path-selector.json diff --git a/kclvm/api/src/testdata/exec-program-with-path-selector.response.json b/crates/api/src/testdata/exec-program-with-path-selector.response.json similarity index 100% rename from kclvm/api/src/testdata/exec-program-with-path-selector.response.json rename to crates/api/src/testdata/exec-program-with-path-selector.response.json diff --git a/kclvm/api/src/testdata/exec-program-with-print.json b/crates/api/src/testdata/exec-program-with-print.json similarity index 100% rename from kclvm/api/src/testdata/exec-program-with-print.json rename to crates/api/src/testdata/exec-program-with-print.json diff --git a/kclvm/api/src/testdata/exec-program-with-print.response.json b/crates/api/src/testdata/exec-program-with-print.response.json similarity index 100% rename from kclvm/api/src/testdata/exec-program-with-print.response.json rename to crates/api/src/testdata/exec-program-with-print.response.json diff --git a/kclvm/api/src/testdata/exec-program.json b/crates/api/src/testdata/exec-program.json similarity index 100% rename from kclvm/api/src/testdata/exec-program.json rename to crates/api/src/testdata/exec-program.json diff --git a/kclvm/api/src/testdata/exec-program.response.json b/crates/api/src/testdata/exec-program.response.json similarity index 100% rename from kclvm/api/src/testdata/exec-program.response.json rename to crates/api/src/testdata/exec-program.response.json diff --git a/kclvm/api/src/testdata/format-code.json b/crates/api/src/testdata/format-code.json similarity index 100% rename from kclvm/api/src/testdata/format-code.json rename to crates/api/src/testdata/format-code.json diff --git a/kclvm/api/src/testdata/format-code.response.json b/crates/api/src/testdata/format-code.response.json similarity index 100% rename from kclvm/api/src/testdata/format-code.response.json rename to crates/api/src/testdata/format-code.response.json diff --git a/kclvm/api/src/testdata/format-path.json b/crates/api/src/testdata/format-path.json similarity index 100% rename from kclvm/api/src/testdata/format-path.json rename to crates/api/src/testdata/format-path.json diff --git a/kclvm/api/src/testdata/format-path.response.json b/crates/api/src/testdata/format-path.response.json similarity index 100% rename from kclvm/api/src/testdata/format-path.response.json rename to crates/api/src/testdata/format-path.response.json diff --git a/kclvm/api/src/testdata/get-schema-type-mapping.json b/crates/api/src/testdata/get-schema-type-mapping.json similarity index 100% rename from kclvm/api/src/testdata/get-schema-type-mapping.json rename to crates/api/src/testdata/get-schema-type-mapping.json diff --git a/kclvm/api/src/testdata/get-schema-type-mapping.response.json b/crates/api/src/testdata/get-schema-type-mapping.response.json similarity index 100% rename from kclvm/api/src/testdata/get-schema-type-mapping.response.json rename to crates/api/src/testdata/get-schema-type-mapping.response.json diff --git a/kclvm/api/src/testdata/get_schema_ty/aaa/kcl.mod b/crates/api/src/testdata/get_schema_ty/aaa/kcl.mod similarity index 100% rename from kclvm/api/src/testdata/get_schema_ty/aaa/kcl.mod rename to crates/api/src/testdata/get_schema_ty/aaa/kcl.mod diff --git a/kclvm/api/src/testdata/get_schema_ty/aaa/main.k b/crates/api/src/testdata/get_schema_ty/aaa/main.k similarity index 100% rename from kclvm/api/src/testdata/get_schema_ty/aaa/main.k rename to crates/api/src/testdata/get_schema_ty/aaa/main.k diff --git a/kclvm/api/src/testdata/get_schema_ty/bbb/kcl.mod b/crates/api/src/testdata/get_schema_ty/bbb/kcl.mod similarity index 100% rename from kclvm/api/src/testdata/get_schema_ty/bbb/kcl.mod rename to crates/api/src/testdata/get_schema_ty/bbb/kcl.mod diff --git a/kclvm/api/src/testdata/get_schema_ty/bbb/main.k b/crates/api/src/testdata/get_schema_ty/bbb/main.k similarity index 100% rename from kclvm/api/src/testdata/get_schema_ty/bbb/main.k rename to crates/api/src/testdata/get_schema_ty/bbb/main.k diff --git a/kclvm/api/src/testdata/get_schema_ty/ccc/kcl.mod b/crates/api/src/testdata/get_schema_ty/ccc/kcl.mod similarity index 100% rename from kclvm/api/src/testdata/get_schema_ty/ccc/kcl.mod rename to crates/api/src/testdata/get_schema_ty/ccc/kcl.mod diff --git a/kclvm/api/src/testdata/get_schema_ty/ccc/main.k b/crates/api/src/testdata/get_schema_ty/ccc/main.k similarity index 100% rename from kclvm/api/src/testdata/get_schema_ty/ccc/main.k rename to crates/api/src/testdata/get_schema_ty/ccc/main.k diff --git a/kclvm/api/src/testdata/get_schema_ty_under_path/aaa/kcl.mod b/crates/api/src/testdata/get_schema_ty_under_path/aaa/kcl.mod similarity index 100% rename from kclvm/api/src/testdata/get_schema_ty_under_path/aaa/kcl.mod rename to crates/api/src/testdata/get_schema_ty_under_path/aaa/kcl.mod diff --git a/kclvm/api/src/testdata/get_schema_ty_under_path/aaa/main.k b/crates/api/src/testdata/get_schema_ty_under_path/aaa/main.k similarity index 100% rename from kclvm/api/src/testdata/get_schema_ty_under_path/aaa/main.k rename to crates/api/src/testdata/get_schema_ty_under_path/aaa/main.k diff --git a/kclvm/api/src/testdata/get_schema_ty_under_path/aaa/sub/sub.k b/crates/api/src/testdata/get_schema_ty_under_path/aaa/sub/sub.k similarity index 100% rename from kclvm/api/src/testdata/get_schema_ty_under_path/aaa/sub/sub.k rename to crates/api/src/testdata/get_schema_ty_under_path/aaa/sub/sub.k diff --git a/kclvm/api/src/testdata/get_schema_ty_under_path/bbb/kcl.mod b/crates/api/src/testdata/get_schema_ty_under_path/bbb/kcl.mod similarity index 100% rename from kclvm/api/src/testdata/get_schema_ty_under_path/bbb/kcl.mod rename to crates/api/src/testdata/get_schema_ty_under_path/bbb/kcl.mod diff --git a/kclvm/api/src/testdata/get_schema_ty_under_path/bbb/main.k b/crates/api/src/testdata/get_schema_ty_under_path/bbb/main.k similarity index 100% rename from kclvm/api/src/testdata/get_schema_ty_under_path/bbb/main.k rename to crates/api/src/testdata/get_schema_ty_under_path/bbb/main.k diff --git a/kclvm/api/src/testdata/get_schema_ty_under_path/helloworld_0.0.1/README.md b/crates/api/src/testdata/get_schema_ty_under_path/helloworld_0.0.1/README.md similarity index 100% rename from kclvm/api/src/testdata/get_schema_ty_under_path/helloworld_0.0.1/README.md rename to crates/api/src/testdata/get_schema_ty_under_path/helloworld_0.0.1/README.md diff --git a/kclvm/api/src/testdata/get_schema_ty_under_path/helloworld_0.0.1/kcl.mod b/crates/api/src/testdata/get_schema_ty_under_path/helloworld_0.0.1/kcl.mod similarity index 100% rename from kclvm/api/src/testdata/get_schema_ty_under_path/helloworld_0.0.1/kcl.mod rename to crates/api/src/testdata/get_schema_ty_under_path/helloworld_0.0.1/kcl.mod diff --git a/kclvm/api/src/testdata/get_schema_ty_under_path/helloworld_0.0.1/main.k b/crates/api/src/testdata/get_schema_ty_under_path/helloworld_0.0.1/main.k similarity index 100% rename from kclvm/api/src/testdata/get_schema_ty_under_path/helloworld_0.0.1/main.k rename to crates/api/src/testdata/get_schema_ty_under_path/helloworld_0.0.1/main.k diff --git a/kclvm/api/src/testdata/hello.k b/crates/api/src/testdata/hello.k similarity index 100% rename from kclvm/api/src/testdata/hello.k rename to crates/api/src/testdata/hello.k diff --git a/kclvm/api/src/testdata/hello_import.k b/crates/api/src/testdata/hello_import.k similarity index 100% rename from kclvm/api/src/testdata/hello_import.k rename to crates/api/src/testdata/hello_import.k diff --git a/kclvm/api/src/testdata/hello_with_print.k b/crates/api/src/testdata/hello_with_print.k similarity index 100% rename from kclvm/api/src/testdata/hello_with_print.k rename to crates/api/src/testdata/hello_with_print.k diff --git a/kclvm/api/src/testdata/lint-path.json b/crates/api/src/testdata/lint-path.json similarity index 100% rename from kclvm/api/src/testdata/lint-path.json rename to crates/api/src/testdata/lint-path.json diff --git a/kclvm/api/src/testdata/lint-path.response.json b/crates/api/src/testdata/lint-path.response.json similarity index 100% rename from kclvm/api/src/testdata/lint-path.response.json rename to crates/api/src/testdata/lint-path.response.json diff --git a/kclvm/api/src/testdata/list-options.json b/crates/api/src/testdata/list-options.json similarity index 100% rename from kclvm/api/src/testdata/list-options.json rename to crates/api/src/testdata/list-options.json diff --git a/kclvm/api/src/testdata/list-options.response.json b/crates/api/src/testdata/list-options.response.json similarity index 100% rename from kclvm/api/src/testdata/list-options.response.json rename to crates/api/src/testdata/list-options.response.json diff --git a/kclvm/api/src/testdata/list-variables.json b/crates/api/src/testdata/list-variables.json similarity index 100% rename from kclvm/api/src/testdata/list-variables.json rename to crates/api/src/testdata/list-variables.json diff --git a/kclvm/api/src/testdata/list-variables.response.json b/crates/api/src/testdata/list-variables.response.json similarity index 100% rename from kclvm/api/src/testdata/list-variables.response.json rename to crates/api/src/testdata/list-variables.response.json diff --git a/kclvm/api/src/testdata/load-settings-files.json b/crates/api/src/testdata/load-settings-files.json similarity index 100% rename from kclvm/api/src/testdata/load-settings-files.json rename to crates/api/src/testdata/load-settings-files.json diff --git a/kclvm/api/src/testdata/load-settings-files.response.json b/crates/api/src/testdata/load-settings-files.response.json similarity index 100% rename from kclvm/api/src/testdata/load-settings-files.response.json rename to crates/api/src/testdata/load-settings-files.response.json diff --git a/kclvm/api/src/testdata/option/main.k b/crates/api/src/testdata/option/main.k similarity index 100% rename from kclvm/api/src/testdata/option/main.k rename to crates/api/src/testdata/option/main.k diff --git a/kclvm/api/src/testdata/override-file-bool.json b/crates/api/src/testdata/override-file-bool.json similarity index 100% rename from kclvm/api/src/testdata/override-file-bool.json rename to crates/api/src/testdata/override-file-bool.json diff --git a/kclvm/api/src/testdata/override-file-bool.response.json b/crates/api/src/testdata/override-file-bool.response.json similarity index 100% rename from kclvm/api/src/testdata/override-file-bool.response.json rename to crates/api/src/testdata/override-file-bool.response.json diff --git a/kclvm/api/src/testdata/override-file-dict.json b/crates/api/src/testdata/override-file-dict.json similarity index 100% rename from kclvm/api/src/testdata/override-file-dict.json rename to crates/api/src/testdata/override-file-dict.json diff --git a/kclvm/api/src/testdata/override-file-dict.response.json b/crates/api/src/testdata/override-file-dict.response.json similarity index 100% rename from kclvm/api/src/testdata/override-file-dict.response.json rename to crates/api/src/testdata/override-file-dict.response.json diff --git a/kclvm/api/src/testdata/override-file-dict_0.json b/crates/api/src/testdata/override-file-dict_0.json similarity index 100% rename from kclvm/api/src/testdata/override-file-dict_0.json rename to crates/api/src/testdata/override-file-dict_0.json diff --git a/kclvm/api/src/testdata/override-file-dict_0.response.json b/crates/api/src/testdata/override-file-dict_0.response.json similarity index 100% rename from kclvm/api/src/testdata/override-file-dict_0.response.json rename to crates/api/src/testdata/override-file-dict_0.response.json diff --git a/kclvm/api/src/testdata/override-file-list.json b/crates/api/src/testdata/override-file-list.json similarity index 100% rename from kclvm/api/src/testdata/override-file-list.json rename to crates/api/src/testdata/override-file-list.json diff --git a/kclvm/api/src/testdata/override-file-list.response.json b/crates/api/src/testdata/override-file-list.response.json similarity index 100% rename from kclvm/api/src/testdata/override-file-list.response.json rename to crates/api/src/testdata/override-file-list.response.json diff --git a/kclvm/api/src/testdata/override-file.json b/crates/api/src/testdata/override-file.json similarity index 100% rename from kclvm/api/src/testdata/override-file.json rename to crates/api/src/testdata/override-file.json diff --git a/kclvm/api/src/testdata/override-file.response.json b/crates/api/src/testdata/override-file.response.json similarity index 100% rename from kclvm/api/src/testdata/override-file.response.json rename to crates/api/src/testdata/override-file.response.json diff --git a/kclvm/api/src/testdata/override_bool.k b/crates/api/src/testdata/override_bool.k similarity index 100% rename from kclvm/api/src/testdata/override_bool.k rename to crates/api/src/testdata/override_bool.k diff --git a/kclvm/api/src/testdata/override_dict.k b/crates/api/src/testdata/override_dict.k similarity index 100% rename from kclvm/api/src/testdata/override_dict.k rename to crates/api/src/testdata/override_dict.k diff --git a/kclvm/api/src/testdata/override_dict_0.k b/crates/api/src/testdata/override_dict_0.k similarity index 100% rename from kclvm/api/src/testdata/override_dict_0.k rename to crates/api/src/testdata/override_dict_0.k diff --git a/kclvm/api/src/testdata/override_list.k b/crates/api/src/testdata/override_list.k similarity index 100% rename from kclvm/api/src/testdata/override_list.k rename to crates/api/src/testdata/override_list.k diff --git a/kclvm/api/src/testdata/parse-file.json b/crates/api/src/testdata/parse-file.json similarity index 100% rename from kclvm/api/src/testdata/parse-file.json rename to crates/api/src/testdata/parse-file.json diff --git a/kclvm/api/src/testdata/parse-file.response.json b/crates/api/src/testdata/parse-file.response.json similarity index 100% rename from kclvm/api/src/testdata/parse-file.response.json rename to crates/api/src/testdata/parse-file.response.json diff --git a/kclvm/api/src/testdata/parse/kcl.mod b/crates/api/src/testdata/parse/kcl.mod similarity index 100% rename from kclvm/api/src/testdata/parse/kcl.mod rename to crates/api/src/testdata/parse/kcl.mod diff --git a/kclvm/api/src/testdata/parse/main.k b/crates/api/src/testdata/parse/main.k similarity index 100% rename from kclvm/api/src/testdata/parse/main.k rename to crates/api/src/testdata/parse/main.k diff --git a/kclvm/api/src/testdata/parse/pkg1/pkg.k b/crates/api/src/testdata/parse/pkg1/pkg.k similarity index 100% rename from kclvm/api/src/testdata/parse/pkg1/pkg.k rename to crates/api/src/testdata/parse/pkg1/pkg.k diff --git a/kclvm/api/src/testdata/parse/pkg2/pkg.k b/crates/api/src/testdata/parse/pkg2/pkg.k similarity index 100% rename from kclvm/api/src/testdata/parse/pkg2/pkg.k rename to crates/api/src/testdata/parse/pkg2/pkg.k diff --git a/kclvm/api/src/testdata/rename-code.json b/crates/api/src/testdata/rename-code.json similarity index 100% rename from kclvm/api/src/testdata/rename-code.json rename to crates/api/src/testdata/rename-code.json diff --git a/kclvm/api/src/testdata/rename-code.response.json b/crates/api/src/testdata/rename-code.response.json similarity index 100% rename from kclvm/api/src/testdata/rename-code.response.json rename to crates/api/src/testdata/rename-code.response.json diff --git a/kclvm/api/src/testdata/rename.json b/crates/api/src/testdata/rename.json similarity index 100% rename from kclvm/api/src/testdata/rename.json rename to crates/api/src/testdata/rename.json diff --git a/kclvm/api/src/testdata/rename.response.json b/crates/api/src/testdata/rename.response.json similarity index 100% rename from kclvm/api/src/testdata/rename.response.json rename to crates/api/src/testdata/rename.response.json diff --git a/kclvm/api/src/testdata/rename/main.bak b/crates/api/src/testdata/rename/main.bak similarity index 100% rename from kclvm/api/src/testdata/rename/main.bak rename to crates/api/src/testdata/rename/main.bak diff --git a/kclvm/api/src/testdata/rename_doc/main.bak b/crates/api/src/testdata/rename_doc/main.bak similarity index 100% rename from kclvm/api/src/testdata/rename_doc/main.bak rename to crates/api/src/testdata/rename_doc/main.bak diff --git a/kclvm/api/src/testdata/settings/kcl.yaml b/crates/api/src/testdata/settings/kcl.yaml similarity index 100% rename from kclvm/api/src/testdata/settings/kcl.yaml rename to crates/api/src/testdata/settings/kcl.yaml diff --git a/kclvm/api/src/testdata/test-lint-import.k b/crates/api/src/testdata/test-lint-import.k similarity index 100% rename from kclvm/api/src/testdata/test-lint-import.k rename to crates/api/src/testdata/test-lint-import.k diff --git a/kclvm/api/src/testdata/test-lint.k b/crates/api/src/testdata/test-lint.k similarity index 100% rename from kclvm/api/src/testdata/test-lint.k rename to crates/api/src/testdata/test-lint.k diff --git a/kclvm/api/src/testdata/test-validate-with-dep.json b/crates/api/src/testdata/test-validate-with-dep.json similarity index 100% rename from kclvm/api/src/testdata/test-validate-with-dep.json rename to crates/api/src/testdata/test-validate-with-dep.json diff --git a/kclvm/api/src/testdata/test-validate.json b/crates/api/src/testdata/test-validate.json similarity index 100% rename from kclvm/api/src/testdata/test-validate.json rename to crates/api/src/testdata/test-validate.json diff --git a/kclvm/api/src/testdata/test.json b/crates/api/src/testdata/test.json similarity index 100% rename from kclvm/api/src/testdata/test.json rename to crates/api/src/testdata/test.json diff --git a/kclvm/api/src/testdata/test.k b/crates/api/src/testdata/test.k similarity index 100% rename from kclvm/api/src/testdata/test.k rename to crates/api/src/testdata/test.k diff --git a/kclvm/api/src/testdata/test.response.json b/crates/api/src/testdata/test.response.json similarity index 100% rename from kclvm/api/src/testdata/test.response.json rename to crates/api/src/testdata/test.response.json diff --git a/kclvm/api/src/testdata/test_call.k b/crates/api/src/testdata/test_call.k similarity index 100% rename from kclvm/api/src/testdata/test_call.k rename to crates/api/src/testdata/test_call.k diff --git a/kclvm/api/src/testdata/testing/module/kcl.mod b/crates/api/src/testdata/testing/module/kcl.mod similarity index 100% rename from kclvm/api/src/testdata/testing/module/kcl.mod rename to crates/api/src/testdata/testing/module/kcl.mod diff --git a/kclvm/api/src/testdata/testing/module/pkg/func.k b/crates/api/src/testdata/testing/module/pkg/func.k similarity index 100% rename from kclvm/api/src/testdata/testing/module/pkg/func.k rename to crates/api/src/testdata/testing/module/pkg/func.k diff --git a/kclvm/api/src/testdata/testing/module/pkg/func_test.k b/crates/api/src/testdata/testing/module/pkg/func_test.k similarity index 100% rename from kclvm/api/src/testdata/testing/module/pkg/func_test.k rename to crates/api/src/testdata/testing/module/pkg/func_test.k diff --git a/kclvm/api/src/testdata/update_dependencies/kcl.mod b/crates/api/src/testdata/update_dependencies/kcl.mod similarity index 100% rename from kclvm/api/src/testdata/update_dependencies/kcl.mod rename to crates/api/src/testdata/update_dependencies/kcl.mod diff --git a/kclvm/api/src/testdata/validate-code-file-with-dep.json b/crates/api/src/testdata/validate-code-file-with-dep.json similarity index 100% rename from kclvm/api/src/testdata/validate-code-file-with-dep.json rename to crates/api/src/testdata/validate-code-file-with-dep.json diff --git a/kclvm/api/src/testdata/validate-code-file-with-dep.response.json b/crates/api/src/testdata/validate-code-file-with-dep.response.json similarity index 100% rename from kclvm/api/src/testdata/validate-code-file-with-dep.response.json rename to crates/api/src/testdata/validate-code-file-with-dep.response.json diff --git a/kclvm/api/src/testdata/validate-code-file.json b/crates/api/src/testdata/validate-code-file.json similarity index 100% rename from kclvm/api/src/testdata/validate-code-file.json rename to crates/api/src/testdata/validate-code-file.json diff --git a/kclvm/api/src/testdata/validate-code-file.response.json b/crates/api/src/testdata/validate-code-file.response.json similarity index 100% rename from kclvm/api/src/testdata/validate-code-file.response.json rename to crates/api/src/testdata/validate-code-file.response.json diff --git a/kclvm/api/src/testdata/validate-code.json b/crates/api/src/testdata/validate-code.json similarity index 100% rename from kclvm/api/src/testdata/validate-code.json rename to crates/api/src/testdata/validate-code.json diff --git a/kclvm/api/src/testdata/validate-code.response.json b/crates/api/src/testdata/validate-code.response.json similarity index 100% rename from kclvm/api/src/testdata/validate-code.response.json rename to crates/api/src/testdata/validate-code.response.json diff --git a/kclvm/api/src/testdata/variables/main.k b/crates/api/src/testdata/variables/main.k similarity index 100% rename from kclvm/api/src/testdata/variables/main.k rename to crates/api/src/testdata/variables/main.k diff --git a/kclvm/api/src/testdata_external/external/kcl.mod b/crates/api/src/testdata_external/external/kcl.mod similarity index 100% rename from kclvm/api/src/testdata_external/external/kcl.mod rename to crates/api/src/testdata_external/external/kcl.mod diff --git a/kclvm/api/src/testdata_external/external/main.k b/crates/api/src/testdata_external/external/main.k similarity index 100% rename from kclvm/api/src/testdata_external/external/main.k rename to crates/api/src/testdata_external/external/main.k diff --git a/kclvm/api/src/testdata_external/external_1/kcl.mod b/crates/api/src/testdata_external/external_1/kcl.mod similarity index 100% rename from kclvm/api/src/testdata_external/external_1/kcl.mod rename to crates/api/src/testdata_external/external_1/kcl.mod diff --git a/kclvm/api/src/testdata_external/external_1/main.k b/crates/api/src/testdata_external/external_1/main.k similarity index 100% rename from kclvm/api/src/testdata_external/external_1/main.k rename to crates/api/src/testdata_external/external_1/main.k diff --git a/crates/ast/Cargo.toml b/crates/ast/Cargo.toml new file mode 100644 index 000000000..114f156f1 --- /dev/null +++ b/crates/ast/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "kcl-ast" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +uuid = { version = "1.4.1", features = ["v4"] } +compiler_base_span = "0.1.2" +serde = { version = "1", features = ["derive"] } +serde_json = "1.0" + +kcl-span = { path = "../span" } +kcl-error = { path = "../error" } +thread_local = "1.1.7" +kcl-utils = {path = "../utils"} +anyhow = "1.0" + +[dev-dependencies] +kcl-parser = { path = "../parser" } diff --git a/kclvm/ast/src/ast.rs b/crates/ast/src/ast.rs similarity index 99% rename from kclvm/ast/src/ast.rs rename to crates/ast/src/ast.rs index 9dbae2924..cc901363b 100644 --- a/kclvm/ast/src/ast.rs +++ b/crates/ast/src/ast.rs @@ -33,8 +33,8 @@ //! in the compiler and regenerate the walker code. //! :copyright: Copyright The KCL Authors. All rights reserved. -use kclvm_utils::path::PathPrefix; -use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer}; +use kcl_utils::path::PathPrefix; +use serde::{Deserialize, Serialize, Serializer, ser::SerializeStruct}; use std::{ collections::HashMap, sync::{RwLock, RwLockReadGuard, RwLockWriteGuard}, @@ -47,7 +47,7 @@ use uuid; use super::token; use crate::{node_ref, pos::ContainsPos}; -use kclvm_error::{diagnostic::Range, Position}; +use kcl_error::{Position, diagnostic::Range}; use std::cell::RefCell; thread_local! { @@ -210,7 +210,7 @@ impl Node { } pub fn node(node: T, (lo, hi): (Loc, Loc)) -> Self { - let filename = kclvm_utils::path::convert_windows_drive_letter(&format!( + let filename = kcl_utils::path::convert_windows_drive_letter(&format!( "{}", lo.file.name.prefer_remapped() )) @@ -2010,7 +2010,7 @@ impl TryFrom for UnaryOp { type Error = (); fn try_from(token: token::Token) -> Result { - use kclvm_span::symbol::kw; + use kcl_span::symbol::kw; match token.kind { token::TokenKind::UnaryOp(token::UnaryOpToken::UTilde) => Ok(UnaryOp::Invert), @@ -2041,7 +2041,7 @@ impl TryFrom for BinOrCmpOp { type Error = (); fn try_from(token: token::Token) -> Result { - use kclvm_span::symbol::kw; + use kcl_span::symbol::kw; match token.kind { token::TokenKind::BinOp(ot) => match ot { diff --git a/crates/ast/src/config.rs b/crates/ast/src/config.rs new file mode 100644 index 000000000..3b738b99c --- /dev/null +++ b/crates/ast/src/config.rs @@ -0,0 +1,34 @@ +use crate::ast; + +/// Try get a config expr mut ref from a expr if the expr is a schema or a config. +/// If not, return [None]. +/// TODO: use [TryInto]? +/// +/// # Examples +/// +/// ``` +/// use kcl_parser::parse_expr; +/// use kcl_ast::ast; +/// use kcl_ast::config::try_get_config_expr_mut; +/// +/// let mut expr = parse_expr(r#"{ +/// a: {b: {c = 1}} +/// } +/// "#).unwrap(); +/// assert!(matches!(try_get_config_expr_mut(&mut expr.node), Some(_))); +/// let mut expr = parse_expr(r#"1"#).unwrap(); +/// assert!(matches!(try_get_config_expr_mut(&mut expr.node), None)); +/// ``` +pub fn try_get_config_expr_mut(expr: &mut ast::Expr) -> Option<&mut ast::ConfigExpr> { + match expr { + ast::Expr::Schema(schema_expr) => { + if let ast::Expr::Config(config_expr) = &mut schema_expr.config.node { + Some(config_expr) + } else { + None + } + } + ast::Expr::Config(config_expr) => Some(config_expr), + _ => None, + } +} diff --git a/kclvm/ast/src/lib.rs b/crates/ast/src/lib.rs similarity index 100% rename from kclvm/ast/src/lib.rs rename to crates/ast/src/lib.rs diff --git a/crates/ast/src/path.rs b/crates/ast/src/path.rs new file mode 100644 index 000000000..1f39c9443 --- /dev/null +++ b/crates/ast/src/path.rs @@ -0,0 +1,170 @@ +use crate::ast; + +/// Get config key path from the AST key node and convert string-based AST nodes including +/// `ast::Expr::Identifier` and `ast::Expr::StringLit` to strings. +/// +/// # Examples +/// +/// ``` +/// use kcl_ast::ast; +/// use kcl_ast::path::get_key_path; +/// +/// let ident = Some(Box::new(ast::Node::dummy_node(ast::Expr::Identifier(ast::Identifier { +/// names: vec![ast::Node::dummy_node("alice".to_string())], +/// pkgpath: "".to_string(), +/// ctx: ast::ExprContext::Load, +/// })))); +/// assert_eq!(get_key_path(&ident), "alice"); +/// let str_lit = Some(Box::new(ast::Node::dummy_node(ast::Expr::StringLit(ast::StringLit { +/// is_long_string: false, +/// raw_value: "\"Alice\"".to_string(), +/// value: "Alice".to_string(), +/// })))); +/// assert_eq!(get_key_path(&str_lit), "Alice"); +/// ``` +#[inline] +pub fn get_key_path(key: &Option>) -> String { + match key { + Some(key) => match &key.node { + ast::Expr::Identifier(identifier) => identifier.get_name(), + ast::Expr::StringLit(string_lit) => string_lit.value.clone(), + _ => "".to_string(), + }, + None => "".to_string(), + } +} + +/// Get config key parts from the AST key node and convert string-based AST nodes including +/// `ast::Expr::Identifier` and `ast::Expr::StringLit` to strings. +#[inline] +pub fn get_key_parts(key: &Option>) -> Vec<&str> { + match key { + Some(key) => match &key.node { + ast::Expr::Identifier(identifier) => { + identifier.names.iter().map(|v| v.node.as_str()).collect() + } + ast::Expr::StringLit(string_lit) => vec![string_lit.value.as_str()], + _ => vec![], + }, + None => vec![], + } +} + +/// Get assign target path from the AST key node and convert string-based AST nodes including +/// `ast::Expr::Identifier` and `ast::Expr::StringLit` to strings. +/// +/// # Examples +/// +/// ``` +/// use kcl_ast::ast; +/// use kcl_ast::path::get_target_path; +/// +/// let target = ast::Target { +/// name: ast::Node::dummy_node("alice".to_string()), +/// paths: vec![], +/// pkgpath: "".to_string(), +/// }; +/// assert_eq!(get_target_path(&target), "alice"); +/// ``` +#[inline] +pub fn get_target_path(key: &ast::Target) -> String { + let mut result = key.name.node.to_string(); + for path in &key.paths { + match path { + ast::MemberOrIndex::Member(member) => { + result.push('.'); + result.push_str(&member.node); + } + ast::MemberOrIndex::Index(index) => { + result.push('['); + match &index.node { + ast::Expr::Unary(unary_expr) => match &unary_expr.operand.node { + ast::Expr::NumberLit(number) => { + result.push_str(&unary_expr.op.symbol()); + result.push_str(&number.to_string()); + } + _ => { + result.push_str("..."); + } + }, + ast::Expr::NumberLit(number) => { + result.push_str(&number.to_string()); + } + ast::Expr::StringLit(string_lit) => { + result.push_str(&format!("{:?}", string_lit.value)); + } + _ => { + result.push_str("..."); + } + } + result.push(']'); + } + } + } + result +} + +/// Get all attribute paths recursively from a config expression AST node. +/// +/// # Examples +/// +/// ``` +/// use kcl_parser::parse_expr; +/// use kcl_ast::ast; +/// use kcl_ast::path::get_attr_paths_from_config_expr; +/// +/// let expr = parse_expr(r#"{ +/// a: {b: {c = 1}} +/// } +/// "#).unwrap(); +/// if let ast::Expr::Config(config_expr) = &expr.node { +/// assert_eq!(get_attr_paths_from_config_expr(&config_expr), vec![ +/// "a".to_string(), +/// "a.b".to_string(), +/// "a.b.c".to_string(), +/// ]) +/// } else { +/// panic!("invalid config expr {:?}", expr) +/// } +/// ``` +pub fn get_attr_paths_from_config_expr(config: &ast::ConfigExpr) -> Vec { + let mut paths = vec![]; + for entry in &config.items { + let mut entry_paths = get_entry_paths(&entry.node); + paths.append(&mut entry_paths); + } + paths +} + +/// Get all attribute paths from a config entry. +fn get_entry_paths(entry: &ast::ConfigEntry) -> Vec { + let mut paths = vec![]; + let path = get_key_path(&entry.key); + if path.is_empty() || path.trim().is_empty() { + return paths; + } + paths.push(path.clone()); + let option_config_expr = match &entry.value.node { + ast::Expr::Schema(schema_expr) => { + if let ast::Expr::Config(config_expr) = &schema_expr.config.node { + Some(config_expr) + } else { + None + } + } + ast::Expr::Config(config_expr) => Some(config_expr), + _ => None, + }; + if let Some(config_expr) = option_config_expr { + let value_paths = get_attr_paths_from_config_expr(config_expr); + if !value_paths.is_empty() { + paths.append( + &mut value_paths + .iter() + .map(|value_path| format!("{}.{}", path, value_path)) + .collect::>(), + ); + } + } + paths +} diff --git a/kclvm/ast/src/pos.rs b/crates/ast/src/pos.rs similarity index 98% rename from kclvm/ast/src/pos.rs rename to crates/ast/src/pos.rs index f8d56fa2c..a4e5585b2 100644 --- a/kclvm/ast/src/pos.rs +++ b/crates/ast/src/pos.rs @@ -1,4 +1,4 @@ -use kclvm_error::{diagnostic::Range, Position}; +use kcl_error::{Position, diagnostic::Range}; use crate::ast; diff --git a/crates/ast/src/tests.rs b/crates/ast/src/tests.rs new file mode 100644 index 000000000..cd2285bef --- /dev/null +++ b/crates/ast/src/tests.rs @@ -0,0 +1,276 @@ +use crate::node_ref; +use crate::walker::MutSelfMutWalker; +use crate::{ast, ast::*}; + +/// Construct an AssignStmt node with assign_value as value +fn build_assign_node(attr_name: &str, assign_value: NodeRef) -> NodeRef { + let target = node_ref!(Target { + name: Node::dummy_node(attr_name.to_string()), + paths: vec![], + pkgpath: "".to_string() + }); + + node_ref!(Stmt::Assign(AssignStmt { + value: assign_value, + targets: vec![target], + ty: None + })) +} + +fn get_dummy_assign_ast() -> ast::Node { + let filename = "main.k"; + let line = 1; + let column = 1; + let end_line = 1; + let end_column = 2; + ast::Node::new( + ast::AssignStmt { + targets: vec![Box::new(ast::Node::new( + ast::Target { + name: Node::dummy_node(String::from("a")), + paths: vec![], + pkgpath: "".to_string(), + }, + String::from(filename), + line, + column, + end_line, + end_column, + ))], + value: Box::new(ast::Node::new( + ast::Expr::StringLit(ast::StringLit { + is_long_string: false, + raw_value: String::from("s"), + value: String::from("s"), + }), + String::from(filename), + line, + column, + end_line, + end_column, + )), + ty: None, + }, + String::from(filename), + line, + column, + end_line, + end_column, + ) +} + +fn get_dummy_assign_binary_ast() -> ast::Node { + let filename = "main.k"; + let line = 1; + let column = 1; + let end_line = 1; + let end_column = 2; + ast::Node::new( + ast::AssignStmt { + targets: vec![Box::new(ast::Node::new( + ast::Target { + name: Node::dummy_node(String::from("a")), + paths: vec![], + pkgpath: "".to_string(), + }, + String::from(filename), + line, + column, + end_line, + end_column, + ))], + value: Box::new(ast::Node::new( + ast::Expr::Binary(ast::BinaryExpr { + op: ast::BinOp::Add, + left: Box::new(ast::Node::new( + ast::Expr::Identifier(ast::Identifier { + names: vec![Node::dummy_node(String::from("a"))], + pkgpath: String::from(filename), + ctx: ast::ExprContext::Load, + }), + String::from(filename), + line, + column, + end_line, + end_column, + )), + right: Box::new(ast::Node::new( + ast::Expr::Identifier(ast::Identifier { + names: vec![Node::dummy_node(String::from("a"))], + pkgpath: String::from(filename), + ctx: ast::ExprContext::Load, + }), + String::from(filename), + line, + column, + end_line, + end_column, + )), + }), + String::from(filename), + line, + column, + end_line, + end_column, + )), + ty: None, + }, + String::from(filename), + line, + column, + end_line, + end_column, + ) +} + +#[test] +fn test_ast_print_assign() { + let assign_stmt = get_dummy_assign_ast(); + println!("{:?}", assign_stmt); + let json_str = serde_json::to_string(&assign_stmt).unwrap(); + println!("{:?}", json_str); +} + +#[test] +fn test_ast_print_assign_binary() { + let assign_stmt = get_dummy_assign_binary_ast(); + println!("{:?}", assign_stmt); + let json_str = serde_json::to_string(&assign_stmt).unwrap(); + println!("{:?}", json_str); +} + +#[test] +fn test_mut_walker() { + pub struct VarMutSelfMutWalker; + impl<'ctx> MutSelfMutWalker<'ctx> for VarMutSelfMutWalker { + fn walk_target(&mut self, target: &'ctx mut ast::Target) { + if target.name.node == "a" { + target.name.node = "x".to_string(); + } + } + } + let mut assign_stmt = get_dummy_assign_ast(); + VarMutSelfMutWalker {}.walk_assign_stmt(&mut assign_stmt.node); + assert_eq!(assign_stmt.node.targets[0].node.name.node, "x") +} + +#[test] +fn test_try_from_for_stringlit() { + let str_lit = ast::StringLit::try_from("test_str".to_string()).unwrap(); + let json_str = serde_json::to_string(&str_lit).unwrap(); + + let str_expected = + r#"{"is_long_string":false,"raw_value":"\"test_str\"","value":"test_str"}"#.to_string(); + assert_eq!(str_expected, json_str); +} + +#[test] +fn test_try_from_for_nameconstant() { + let name_cons = ast::NameConstant::try_from(true).unwrap(); + let json_str = serde_json::to_string(&name_cons).unwrap(); + assert_eq!("\"True\"", json_str); + + let name_cons = ast::NameConstant::try_from(false).unwrap(); + let json_str = serde_json::to_string(&name_cons).unwrap(); + assert_eq!("\"False\"", json_str); +} + +#[test] +fn test_filter_schema_with_no_schema() { + let ast_mod = Module { + filename: "".to_string(), + doc: Some(node_ref!("".to_string())), + body: vec![], + comments: vec![], + }; + let schema_stmts = ast_mod.filter_schema_stmt_from_module(); + assert_eq!(schema_stmts.len(), 0); +} + +#[test] +fn test_filter_schema_with_one_schema() { + let mut ast_mod = Module { + filename: "".to_string(), + doc: Some(node_ref!("".to_string())), + body: vec![], + comments: vec![], + }; + let mut gen_schema_stmts = gen_schema_stmt(1); + ast_mod.body.append(&mut gen_schema_stmts); + let schema_stmts = ast_mod.filter_schema_stmt_from_module(); + assert_eq!(schema_stmts.len(), 1); + assert_eq!(schema_stmts[0].node.name.node, "schema_stmt_0".to_string()); +} + +#[test] +fn test_filter_schema_with_mult_schema() { + let mut ast_mod = Module { + filename: "".to_string(), + doc: Some(node_ref!("".to_string())), + body: vec![], + comments: vec![], + }; + let mut gen_schema_stmts = gen_schema_stmt(10); + ast_mod.body.append(&mut gen_schema_stmts); + let schema_stmts = ast_mod.filter_schema_stmt_from_module(); + assert_eq!(schema_stmts.len(), 10); + for i in 0..10 { + assert_eq!( + schema_stmts[i].node.name.node, + "schema_stmt_".to_string() + &i.to_string() + ) + } +} + +#[test] +fn test_build_assign_stmt() { + let test_expr = node_ref!(ast::Expr::Identifier(Identifier { + names: vec![ + Node::dummy_node("name1".to_string()), + Node::dummy_node("name2".to_string()) + ], + pkgpath: "test".to_string(), + ctx: ast::ExprContext::Load + })); + let assgin_stmt = build_assign_node("test_attr_name", test_expr); + + if let ast::Stmt::Assign(assign) = assgin_stmt.node { + if let ast::Expr::Identifier(iden) = &assign.value.node { + assert_eq!(iden.names.len(), 2); + assert_eq!(iden.names[0].node, "name1".to_string()); + assert_eq!(iden.names[1].node, "name2".to_string()); + assert_eq!(iden.pkgpath, "test".to_string()); + match iden.ctx { + ast::ExprContext::Load => {} + _ => { + assert!(false); + } + } + } else { + assert!(false); + } + } else { + assert!(false); + } +} + +fn gen_schema_stmt(count: i32) -> Vec> { + let mut schema_stmts = Vec::new(); + for c in 0..count { + schema_stmts.push(node_ref!(ast::Stmt::Schema(SchemaStmt { + doc: Some(node_ref!("".to_string())), + name: node_ref!("schema_stmt_".to_string() + &c.to_string()), + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: vec![], + body: vec![], + decorators: vec![], + checks: vec![], + index_signature: None + }))) + } + schema_stmts +} diff --git a/kclvm/ast/src/token.rs b/crates/ast/src/token.rs similarity index 98% rename from kclvm/ast/src/token.rs rename to crates/ast/src/token.rs index d375b4c07..a328ced76 100644 --- a/kclvm/ast/src/token.rs +++ b/crates/ast/src/token.rs @@ -10,8 +10,8 @@ pub use LitKind::*; pub use TokenKind::*; pub use UnaryOpToken::*; -use compiler_base_span::{Span, DUMMY_SP}; -pub use kclvm_span::symbol::{Ident, Symbol}; +use compiler_base_span::{DUMMY_SP, Span}; +pub use kcl_span::symbol::{Ident, Symbol}; pub const VALID_SPACES_LENGTH: usize = 0; #[derive(Clone, Copy, PartialEq, Debug)] diff --git a/kclvm/ast/src/token_stream.rs b/crates/ast/src/token_stream.rs similarity index 100% rename from kclvm/ast/src/token_stream.rs rename to crates/ast/src/token_stream.rs diff --git a/kclvm/ast/src/walker.rs b/crates/ast/src/walker.rs similarity index 99% rename from kclvm/ast/src/walker.rs rename to crates/ast/src/walker.rs index 916eb1b9a..9e6f84ac4 100644 --- a/kclvm/ast/src/walker.rs +++ b/crates/ast/src/walker.rs @@ -114,7 +114,7 @@ pub trait TypedResultWalker<'ctx>: Sized { fn walk_number_lit(&self, number_lit: &'ctx ast::NumberLit) -> Self::Result; fn walk_string_lit(&self, string_lit: &'ctx ast::StringLit) -> Self::Result; fn walk_name_constant_lit(&self, name_constant_lit: &'ctx ast::NameConstantLit) - -> Self::Result; + -> Self::Result; fn walk_joined_string(&self, joined_string: &'ctx ast::JoinedString) -> Self::Result; fn walk_formatted_value(&self, formatted_value: &'ctx ast::FormattedValue) -> Self::Result; fn walk_comment(&self, comment: &'ctx ast::Comment) -> Self::Result; diff --git a/crates/ast_pretty/Cargo.toml b/crates/ast_pretty/Cargo.toml new file mode 100644 index 000000000..1d93512ab --- /dev/null +++ b/crates/ast_pretty/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "kcl-ast-pretty" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +kcl-error = { path = "../error" } +kcl-ast = { path = "../ast" } +kcl-primitives = { path = "../primitives" } + +fancy-regex = "0.7.1" +pretty_assertions = "1.3.0" +compiler_base_session = "0.1.3" +compiler_base_macros = "0.1.1" + +[dev-dependencies] +kcl-parser = { path = "../parser" } diff --git a/crates/ast_pretty/src/lib.rs b/crates/ast_pretty/src/lib.rs new file mode 100644 index 000000000..cc8b69703 --- /dev/null +++ b/crates/ast_pretty/src/lib.rs @@ -0,0 +1,354 @@ +use kcl_ast::{ + ast::{self, Module}, + token::TokenKind, + walker::MutSelfTypedResultWalker, +}; +use kcl_primitives::IndexMap; +use std::collections::VecDeque; +mod node; + +#[cfg(test)] +mod tests; + +pub const WHITESPACE: &str = " "; +pub const TAB: &str = "\t"; +pub const NEWLINE: &str = "\n"; + +#[derive(Debug, Clone)] +pub enum Indentation { + Indent = 0, + Dedent = 1, + Newline = 2, + IndentWithNewline = 3, + DedentWithNewline = 4, + Fill = 5, +} + +/// Printer config +#[derive(Debug)] +pub struct Config { + pub tab_len: usize, + pub indent_len: usize, + pub use_spaces: bool, + pub write_comments: bool, +} + +impl Default for Config { + fn default() -> Self { + Self { + tab_len: 4, + indent_len: 4, + use_spaces: true, + write_comments: true, + } + } +} + +#[derive(Copy, Clone)] +pub struct NoHook; + +impl PrinterHook for NoHook {} + +pub enum ASTNode<'p> { + Stmt(&'p ast::NodeRef), + Expr(&'p ast::NodeRef), +} + +pub trait PrinterHook { + fn pre(&self, _printer: &mut Printer<'_>, _node: ASTNode<'_>) {} + fn post(&self, _printer: &mut Printer<'_>, _node: ASTNode<'_>) {} +} + +pub struct Printer<'p> { + /// Output string buffer. + pub out: String, + pub indent: usize, + pub cfg: Config, + /// Print comments, + pub comments: VecDeque>, + pub import_spec: IndexMap, + pub hook: &'p (dyn PrinterHook + 'p), + /// Last AST expr/stmt line, default is 0. + last_ast_line: u64, + /// Stack of the current expression span (start_line, end_line). + expr_span_stack: Vec<(u64, u64)>, +} + +impl Default for Printer<'_> { + fn default() -> Self { + Self { + hook: &NoHook, + out: Default::default(), + indent: Default::default(), + cfg: Default::default(), + comments: Default::default(), + import_spec: Default::default(), + last_ast_line: Default::default(), + expr_span_stack: Default::default(), + } + } +} + +impl<'p> Printer<'p> { + pub fn new(cfg: Config, hook: &'p (dyn PrinterHook + 'p)) -> Self { + Self { + out: "".to_string(), + indent: 0, + cfg, + comments: VecDeque::default(), + import_spec: IndexMap::default(), + hook, + last_ast_line: 0, + expr_span_stack: Vec::default(), + } + } + + // -------------------------- + // Write functions + // -------------------------- + + /// Write a string + #[inline] + pub fn write(&mut self, text: &str) { + self.write_string(text); + } + + /// Write a string with newline. + #[inline] + pub fn writeln(&mut self, text: &str) { + self.write_string(text); + self.write_string(NEWLINE); + self.fill(""); + } + + /// Write a space. + #[inline] + pub fn write_space(&mut self) { + self.write_string(WHITESPACE); + } + + /// Fill a indent + pub fn fill(&mut self, text: &str) { + if self.cfg.use_spaces { + self.write(&format!( + "{}{}", + WHITESPACE.repeat(self.indent * self.cfg.indent_len), + text + )); + } else { + self.write(&format!("{}{}", TAB.repeat(self.indent), text)); + } + } + + /// Print string + #[inline] + pub fn write_string(&mut self, string: &str) { + self.out.push_str(string); + } + + pub fn write_indentation(&mut self, indentation: Indentation) { + match indentation { + Indentation::Indent => self.enter(), + Indentation::Dedent => self.leave(), + Indentation::Newline => self.write_newline(), + Indentation::IndentWithNewline => { + self.enter(); + self.write_newline() + } + Indentation::DedentWithNewline => { + self.leave(); + self.write_newline(); + } + Indentation::Fill => self.fill(""), + } + } + + #[inline] + pub fn write_newline(&mut self) { + self.writeln("") + } + + #[inline] + pub fn write_newline_without_fill(&mut self) { + self.write_string(NEWLINE); + } + + /// Print value + #[inline] + pub fn write_value(&mut self, value: T) { + self.write(&format!("{}", value)); + } + + /// Print ast token + #[inline] + pub fn write_token(&mut self, tok: TokenKind) { + let tok_str: String = tok.into(); + self.write_string(&tok_str); + } + + /// Print ast node + #[inline] + pub fn write_node(&mut self, node: ASTNode<'_>) { + match node { + ASTNode::Stmt(stmt) => self.stmt(stmt), + ASTNode::Expr(expr) => self.expr(expr), + } + } + + /// Print ast module. + #[inline] + pub fn write_module(&mut self, module: &ast::Module) { + self.walk_module(module); + while let Some(comment) = self.comments.pop_front() { + self.writeln(&comment.node.text); + self.fill(""); + } + } + + /// Wether has comments on ast node. + pub(crate) fn has_comments_on_node(&mut self, node: &ast::NodeRef) -> bool { + if !self.cfg.write_comments { + return false; + } + let mut index = None; + for (i, comment) in self.comments.iter().enumerate() { + if comment.line <= node.line { + index = Some(i); + } else { + break; + } + } + index.is_some() + } + + /// Print ast comments. + pub fn update_last_ast_line(&mut self, node: &ast::NodeRef) { + if node.line > self.last_ast_line { + self.last_ast_line = node.line; + } + } + + /// Print ast comments. + pub fn write_comments_before_node(&mut self, node: &ast::NodeRef) { + if !self.cfg.write_comments { + return; + } + if node.line > self.last_ast_line { + self.last_ast_line = node.line; + let mut index = None; + for (i, comment) in self.comments.iter().enumerate() { + if comment.line <= node.line { + index = Some(i); + } else { + break; + } + } + if let Some(index) = index { + let mut count = index as isize; + while count >= 0 { + match self.comments.pop_front() { + Some(comment) => { + self.writeln(&comment.node.text); + match self.comments.front() { + Some(next_comment) => { + if next_comment.line >= comment.line + 2 && count > 0 { + self.write_newline(); + } + } + None => {} + } + } + None => break, + } + count -= 1; + } + } + } + } + + pub fn write_comments_until_line(&mut self, line: u64) { + if !self.cfg.write_comments || line == 0 { + return; + } + + let mut comments_written = 0; + while let Some(comment) = self.comments.front() { + if comment.line == 0 || comment.line > line { + break; + } + + let comment = self.comments.pop_front().unwrap(); + + // Add newline before first comment if not already at line start + if comments_written == 0 && !self.out.ends_with('\n') { + self.write_newline_without_fill(); + } + + self.fill(""); + self.write(&comment.node.text); + self.write_newline_without_fill(); + + // Add extra newline if next comment is 2+ lines away + if let Some(next) = self.comments.front() { + if next.line >= comment.line + 2 && next.line <= line { + self.write_newline_without_fill(); + } + } + + self.last_ast_line = self.last_ast_line.max(comment.line); + comments_written += 1; + } + + // Remove trailing newline if we wrote any comments + if comments_written > 0 && self.out.ends_with('\n') { + self.out.pop(); + } + } + + // -------------------------- + // Indent and scope functions + // -------------------------- + + /// Enter with a indent + pub fn enter(&mut self) { + self.indent += 1; + } + + /// Leave with a dedent + pub fn leave(&mut self) { + self.indent -= 1; + } + + pub(crate) fn push_expr_span(&mut self, start_line: u64, end_line: u64) { + self.expr_span_stack.push((start_line, end_line)); + } + + pub(crate) fn pop_expr_span(&mut self) { + self.expr_span_stack.pop(); + } + + pub(crate) fn current_expr_end_line(&self) -> Option { + self.expr_span_stack.last().map(|(_, end_line)| *end_line) + } +} + +/// Print AST to string. The default format is according to the KCL code style defined here: https://kcl-lang.io/docs/reference/lang/spec/codestyle +pub fn print_ast_module(module: &Module) -> String { + let mut printer = Printer::default(); + printer.write_module(module); + printer.out +} + +/// Print AST to string +pub fn print_ast_node(node: ASTNode) -> String { + let mut printer = Printer::default(); + printer.write_node(node); + printer.out +} + +/// Print schema expression AST node to string. +pub fn print_schema_expr(schema_expr: &ast::SchemaExpr) -> String { + let mut printer = Printer::default(); + printer.walk_schema_expr(schema_expr); + printer.out +} diff --git a/crates/ast_pretty/src/node.rs b/crates/ast_pretty/src/node.rs new file mode 100644 index 000000000..1887da722 --- /dev/null +++ b/crates/ast_pretty/src/node.rs @@ -0,0 +1,1022 @@ +use std::collections::HashSet; + +use compiler_base_macros::bug; +use kcl_ast::{ + ast::{self, CallExpr}, + token::{DelimToken, TokenKind}, + walker::MutSelfTypedResultWalker, +}; + +use super::{Indentation, Printer}; + +type ParameterType<'a> = ( + (&'a ast::NodeRef, Option), + &'a Option>, +); + +const COMMA_WHITESPACE: &str = ", "; +const IDENTIFIER_REGEX: &str = r#"^\$?[a-zA-Z_]\w*$"#; + +macro_rules! interleave { + ($inter: expr, $f: expr, $seq: expr) => { + if !$seq.is_empty() { + $f(&$seq[0]); + for s in &$seq[1..] { + $inter(); + $f(s); + } + } + }; +} + +impl<'p, 'ctx> MutSelfTypedResultWalker<'ctx> for Printer<'p> { + type Result = (); + + fn walk_module(&mut self, module: &'ctx ast::Module) -> Self::Result { + for comment in &module.comments { + self.comments.push_back(comment.clone()); + } + if let Some(doc) = &module.doc { + self.write(&doc.node); + self.write_newline(); + self.write_newline(); + } + + self.stmts(&module.body); + } + + fn walk_expr_stmt(&mut self, expr_stmt: &'ctx ast::ExprStmt) -> Self::Result { + interleave!( + || self.write(COMMA_WHITESPACE), + |expr| self.expr(expr), + expr_stmt.exprs + ); + self.write_newline_without_fill(); + } + + fn walk_unification_stmt( + &mut self, + unification_stmt: &'ctx ast::UnificationStmt, + ) -> Self::Result { + self.walk_identifier(&unification_stmt.target.node); + self.write(": "); + self.walk_schema_expr(&unification_stmt.value.node); + self.write_newline_without_fill(); + } + + fn walk_type_alias_stmt(&mut self, type_alias_stmt: &'ctx ast::TypeAliasStmt) -> Self::Result { + self.write("type"); + self.write_space(); + self.walk_identifier(&type_alias_stmt.type_name.node); + self.write(" = "); + self.write(&type_alias_stmt.type_value.node); + self.write_newline_without_fill(); + } + + fn walk_assign_stmt(&mut self, assign_stmt: &'ctx ast::AssignStmt) -> Self::Result { + for (i, target) in assign_stmt.targets.iter().enumerate() { + self.walk_target(&target.node); + if i == 0 { + if let Some(ty) = &assign_stmt.ty { + self.write(": "); + self.write(&ty.node.to_string()); + } + } + self.write(" = "); + } + self.expr(&assign_stmt.value); + self.write_newline_without_fill(); + } + + fn walk_aug_assign_stmt(&mut self, aug_assign_stmt: &'ctx ast::AugAssignStmt) -> Self::Result { + self.walk_target(&aug_assign_stmt.target.node); + self.write_space(); + self.write(aug_assign_stmt.op.symbol()); + self.write_space(); + self.expr(&aug_assign_stmt.value); + self.write_newline_without_fill(); + } + + fn walk_assert_stmt(&mut self, assert_stmt: &'ctx ast::AssertStmt) -> Self::Result { + self.write("assert "); + self.expr(&assert_stmt.test); + if let Some(if_cond) = &assert_stmt.if_cond { + self.write(" if "); + self.expr(if_cond); + } + if let Some(msg) = &assert_stmt.msg { + self.write(COMMA_WHITESPACE); + self.expr(msg); + } + self.write_newline_without_fill(); + } + + fn walk_if_stmt(&mut self, if_stmt: &'ctx ast::IfStmt) -> Self::Result { + self.write("if "); + self.expr(&if_stmt.cond); + self.write_token(TokenKind::Colon); + self.write_newline_without_fill(); + self.write_indentation(Indentation::Indent); + self.stmts(&if_stmt.body); + self.write_indentation(Indentation::Dedent); + + if !if_stmt.orelse.is_empty() { + // Check if orelse contains exactly one if statement + if if_stmt.orelse.len() == 1 { + if let ast::Stmt::If(elif_stmt) = &if_stmt.orelse[0].node { + // Nested if statements need to be considered, + // so `el` needs to be preceded by the current indentation. + self.fill("el"); + self.walk_if_stmt(elif_stmt); + } else { + self.fill("else:"); + self.write_newline_without_fill(); + self.write_indentation(Indentation::Indent); + self.stmts(&if_stmt.orelse); + self.write_indentation(Indentation::Dedent); + } + } else { + // Handle multiple else statements + self.fill("else:"); + self.write_newline_without_fill(); + self.write_indentation(Indentation::Indent); + self.stmts(&if_stmt.orelse); + self.write_indentation(Indentation::Dedent); + } + } else { + self.write_newline_without_fill(); + } + } + + fn walk_import_stmt(&mut self, import_stmt: &'ctx ast::ImportStmt) -> Self::Result { + self.write("import "); + // use `import_stmt.rawpath` to write the raw path + // otherwise, use `import_stmt.path` will replace `import .xxx` with `import xxx` + self.write(&import_stmt.rawpath); + if let Some(as_name) = &import_stmt.asname { + self.write(" as "); + self.write(&as_name.node); + } + self.write_newline_without_fill(); + } + + fn walk_schema_stmt(&mut self, schema_stmt: &'ctx ast::SchemaStmt) -> Self::Result { + interleave!( + || self.write_newline(), + |expr: &ast::NodeRef| { + self.write_comments_before_node(&expr); + self.write("@"); + self.walk_call_expr(&expr.node); + }, + schema_stmt.decorators + ); + if !schema_stmt.decorators.is_empty() { + self.write_newline(); + } + if schema_stmt.is_mixin { + self.write("mixin "); + } else if schema_stmt.is_protocol { + self.write("protocol "); + } else { + self.write("schema "); + } + self.write(&schema_stmt.name.node); + if let Some(args) = &schema_stmt.args { + self.write("["); + self.walk_arguments(&args.node); + self.write("]"); + } + if let Some(parent_name) = &schema_stmt.parent_name { + self.write("("); + self.walk_identifier(&parent_name.node); + self.write(")"); + } + if let Some(host_name) = &schema_stmt.for_host_name { + self.write(" for "); + self.walk_identifier(&host_name.node); + } + self.write_token(TokenKind::Colon); + self.write_newline_without_fill(); + self.write_indentation(Indentation::Indent); + + if let Some(doc) = &schema_stmt.doc { + self.fill(""); + self.write(&doc.node); + self.write_newline_without_fill(); + } + + if !schema_stmt.mixins.is_empty() { + self.fill(""); + self.write("mixin ["); + self.write_indentation(Indentation::IndentWithNewline); + interleave!( + || { + self.write(","); + self.write_newline(); + }, + |mixin_name: &ast::NodeRef| { + self.write_comments_before_node(&mixin_name); + self.walk_identifier(&mixin_name.node); + }, + schema_stmt.mixins + ); + self.write_indentation(Indentation::Dedent); + self.write_newline(); + self.write("]"); + self.write_newline_without_fill(); + } + if let Some(index_signature) = &schema_stmt.index_signature { + self.fill(""); + self.write_comments_before_node(index_signature); + self.write_token(TokenKind::OpenDelim(DelimToken::Bracket)); + if index_signature.node.any_other { + self.write_token(TokenKind::DotDotDot); + } + if let Some(key_name) = &index_signature.node.key_name { + self.write(&format!("{}: ", key_name.node)); + } + self.write(&index_signature.node.key_ty.node.to_string()); + self.write_token(TokenKind::CloseDelim(DelimToken::Bracket)); + self.write_token(TokenKind::Colon); + self.write_space(); + self.write(&index_signature.node.value_ty.node.to_string()); + if let Some(value) = &index_signature.node.value { + self.write(" = "); + self.expr(value); + } + self.write_newline_without_fill(); + } + self.stmts(&schema_stmt.body); + self.write_newline_without_fill(); + if !schema_stmt.checks.is_empty() { + self.fill("check:"); + // Schema check indent + self.write_indentation(Indentation::IndentWithNewline); + interleave!( + || self.write_newline(), + |check_expr: &ast::NodeRef| { + self.write_comments_before_node(&check_expr); + self.walk_check_expr(&check_expr.node); + }, + schema_stmt.checks + ); + self.write_newline_without_fill(); + // Schema check dedent + self.write_indentation(Indentation::Dedent); + self.write_newline_without_fill(); + } + // Schema Stmt dedent + self.write_indentation(Indentation::Dedent); + } + + fn walk_rule_stmt(&mut self, rule_stmt: &'ctx ast::RuleStmt) -> Self::Result { + interleave!( + || self.write_newline(), + |expr: &ast::NodeRef| { + self.write("@"); + self.walk_call_expr(&expr.node); + }, + rule_stmt.decorators + ); + if !rule_stmt.decorators.is_empty() { + self.write_newline(); + } + self.write("rule "); + self.write(&rule_stmt.name.node); + if let Some(args) = &rule_stmt.args { + self.write("["); + self.walk_arguments(&args.node); + self.write("]"); + } + if !rule_stmt.parent_rules.is_empty() { + self.write("("); + interleave!( + || self.write(COMMA_WHITESPACE), + |identifier: &ast::NodeRef| self.walk_identifier(&identifier.node), + rule_stmt.parent_rules + ); + self.write(")"); + } + if let Some(host_name) = &rule_stmt.for_host_name { + self.write(" for "); + self.walk_identifier(&host_name.node); + } + self.write_token(TokenKind::Colon); + // Rule Stmt indent + self.write_indentation(Indentation::IndentWithNewline); + if let Some(doc) = &rule_stmt.doc { + self.write(&doc.node); + self.write_newline(); + } + if !rule_stmt.checks.is_empty() { + interleave!( + || self.write_newline(), + |check_expr: &ast::NodeRef| { + self.write_comments_before_node(&check_expr); + self.walk_check_expr(&check_expr.node); + }, + rule_stmt.checks + ); + self.write_newline_without_fill(); + } + // Rule Stmt dedent + self.write_indentation(Indentation::Dedent); + } + + fn walk_quant_expr(&mut self, quant_expr: &'ctx ast::QuantExpr) -> Self::Result { + let in_one_line = self.last_ast_line > 0 && quant_expr.test.line == self.last_ast_line; + let quant_op_string: String = quant_expr.op.clone().into(); + self.write(&quant_op_string); + self.write_space(); + interleave!( + || self.write(COMMA_WHITESPACE), + |identifier: &ast::NodeRef| self.walk_identifier(&identifier.node), + quant_expr.variables + ); + self.write(" in "); + self.expr(&quant_expr.target); + self.write(" {"); + if !in_one_line { + self.write_indentation(Indentation::IndentWithNewline); + } + self.expr(&quant_expr.test); + if let Some(if_cond) = &quant_expr.if_cond { + self.write(" if "); + self.expr(if_cond); + } + if !in_one_line { + self.write_indentation(Indentation::DedentWithNewline) + } + self.write("}") + } + + fn walk_schema_attr(&mut self, schema_attr: &'ctx ast::SchemaAttr) -> Self::Result { + interleave!( + || self.write_newline(), + |expr: &ast::NodeRef| { + self.write_comments_before_node(&expr); + self.write("@"); + self.walk_call_expr(&expr.node) + }, + schema_attr.decorators + ); + if !schema_attr.decorators.is_empty() { + self.write_newline(); + } + // A schema string attribute needs quote. + if !schema_attr.is_ident_attr() { + self.write(&format!("{:?}", schema_attr.name.node)); + } else { + self.write_attribute(&schema_attr.name); + } + if schema_attr.is_optional { + self.write("?"); + } + self.write(": "); + self.write(&schema_attr.ty.node.to_string()); + if let Some(op) = &schema_attr.op { + let symbol = op.symbol(); + self.write_space(); + self.write(symbol); + self.write_space(); + } + if let Some(value) = &schema_attr.value { + self.expr(value); + } + self.write_newline_without_fill(); + } + + fn walk_if_expr(&mut self, if_expr: &'ctx ast::IfExpr) -> Self::Result { + self.expr(&if_expr.body); + self.write(" if "); + self.expr(&if_expr.cond); + self.write(" else "); + self.expr(&if_expr.orelse); + } + + fn walk_unary_expr(&mut self, unary_expr: &'ctx ast::UnaryExpr) -> Self::Result { + self.write(unary_expr.op.symbol()); + // Four forms: `+expr`, `-expr`, `~expr`, `not expr` + // `not expr` needs a space between `not` and `expr` + if matches!(unary_expr.op, ast::UnaryOp::Not) { + self.write_space(); + } + self.expr(&unary_expr.operand); + } + + fn walk_binary_expr(&mut self, binary_expr: &'ctx ast::BinaryExpr) -> Self::Result { + let symbol = binary_expr.op.symbol(); + self.expr(&binary_expr.left); + self.write_space(); + self.write(symbol); + self.write_space(); + self.expr(&binary_expr.right); + } + + fn walk_selector_expr(&mut self, selector_expr: &'ctx ast::SelectorExpr) -> Self::Result { + self.expr(&selector_expr.value); + self.write(if selector_expr.has_question { + "?." + } else { + "." + }); + self.walk_identifier(&selector_expr.attr.node); + } + + fn walk_call_expr(&mut self, call_expr: &'ctx ast::CallExpr) -> Self::Result { + self.expr(&call_expr.func); + self.write("("); + self.write_args_and_kwargs(&call_expr.args, &call_expr.keywords); + self.write(")"); + } + + fn walk_subscript(&mut self, subscript: &'ctx ast::Subscript) -> Self::Result { + self.expr(&subscript.value); + if subscript.has_question { + self.write("?"); + } + self.write("["); + if let Some(index) = &subscript.index { + self.expr(index); + } else { + if let Some(lower) = &subscript.lower { + self.expr(lower); + } + self.write_token(TokenKind::Colon); + if let Some(upper) = &subscript.upper { + self.expr(upper); + } + self.write_token(TokenKind::Colon); + if let Some(step) = &subscript.step { + self.expr(step); + } + } + self.write("]"); + } + + fn walk_paren_expr(&mut self, paren_expr: &'ctx ast::ParenExpr) -> Self::Result { + self.write_token(TokenKind::OpenDelim(DelimToken::Paren)); + self.expr(&paren_expr.expr); + self.write_token(TokenKind::CloseDelim(DelimToken::Paren)); + } + + fn walk_list_expr(&mut self, list_expr: &'ctx ast::ListExpr) -> Self::Result { + let mut line_set = list_expr + .elts + .iter() + .map(|e| e.line) + .filter(|l| *l > 0) + .collect::>(); + if self.last_ast_line > 0 { + line_set.insert(self.last_ast_line); + } + // There are comments in the configuration block. + let has_comment = !list_expr.elts.is_empty() + && list_expr + .elts + .iter() + .map(|e| self.has_comments_on_node(e)) + .all(|r| r); + // When there are comments in the configuration block, print them as multiline configurations. + let mut in_one_line = line_set.len() <= 1 && !has_comment; + if let Some(elt) = list_expr.elts.first() { + if let ast::Expr::ListIfItem(_) = &elt.node { + in_one_line = false; + } + } + self.write_token(TokenKind::OpenDelim(DelimToken::Bracket)); + if !in_one_line { + self.write_indentation(Indentation::IndentWithNewline); + } + interleave!( + || if in_one_line { + self.write(COMMA_WHITESPACE); + } else { + self.write_newline(); + }, + |elt| { + self.write_comments_before_node(elt); + self.expr(elt); + }, + list_expr.elts + ); + if !in_one_line { + if let Some(end_line) = self.current_expr_end_line() { + self.write_comments_until_line(end_line.saturating_sub(1)); + } + self.write_indentation(Indentation::DedentWithNewline); + } + self.write_token(TokenKind::CloseDelim(DelimToken::Bracket)); + } + + fn walk_list_comp(&mut self, list_comp: &'ctx ast::ListComp) -> Self::Result { + self.write_token(TokenKind::OpenDelim(DelimToken::Bracket)); + self.expr(&list_comp.elt); + for g in &list_comp.generators { + self.walk_comp_clause(&g.node); + } + self.write_token(TokenKind::CloseDelim(DelimToken::Bracket)); + } + + fn walk_list_if_item_expr( + &mut self, + list_if_item_expr: &'ctx ast::ListIfItemExpr, + ) -> Self::Result { + self.write("if "); + self.expr(&list_if_item_expr.if_cond); + self.write(":"); + self.write_indentation(Indentation::IndentWithNewline); + interleave!( + || self.write_newline(), + |expr| { + self.write_comments_before_node(expr); + self.expr(expr); + }, + list_if_item_expr.exprs + ); + self.write_indentation(Indentation::Dedent); + if let Some(orelse) = &list_if_item_expr.orelse { + self.write_newline(); + match &orelse.node { + ast::Expr::List(list_expr) => { + self.write("else:"); + self.write_indentation(Indentation::IndentWithNewline); + interleave!( + || self.write_newline(), + |expr| { + self.write_comments_before_node(expr); + self.expr(expr); + }, + list_expr.elts + ); + self.write_indentation(Indentation::Dedent); + } + ast::Expr::ListIfItem(_) => { + self.write("el"); + self.expr(orelse); + } + _ => bug!("Invalid list if expr orelse node {:?}", orelse.node), + } + } + } + + fn walk_starred_expr(&mut self, starred_expr: &'ctx ast::StarredExpr) -> Self::Result { + self.write("*"); + self.expr(&starred_expr.value) + } + + fn walk_dict_comp(&mut self, dict_comp: &'ctx ast::DictComp) -> Self::Result { + self.write_token(TokenKind::OpenDelim(DelimToken::Brace)); + self.expr(match &dict_comp.entry.key { + Some(key) => key, + None => bug!("Invalid dict comp key"), + }); + if !matches!(dict_comp.entry.operation, ast::ConfigEntryOperation::Union) { + self.write_space(); + } + self.write(dict_comp.entry.operation.symbol()); + self.write_space(); + self.expr(&dict_comp.entry.value); + for g in &dict_comp.generators { + self.walk_comp_clause(&g.node); + } + self.write_token(TokenKind::CloseDelim(DelimToken::Brace)); + } + + fn walk_config_if_entry_expr( + &mut self, + config_if_entry_expr: &'ctx ast::ConfigIfEntryExpr, + ) -> Self::Result { + self.write("if "); + self.expr(&config_if_entry_expr.if_cond); + self.write_token(TokenKind::Colon); + self.write_indentation(Indentation::IndentWithNewline); + interleave!( + || self.write_newline(), + |entry: &ast::NodeRef| self.write_entry(entry), + config_if_entry_expr.items + ); + self.write_indentation(Indentation::Dedent); + if let Some(orelse) = &config_if_entry_expr.orelse { + self.write_newline(); + match &orelse.node { + ast::Expr::Config(config_expr) => { + self.write("else:"); + self.write_indentation(Indentation::IndentWithNewline); + interleave!( + || self.write_newline(), + |entry: &ast::NodeRef| self.write_entry(entry), + config_expr.items + ); + self.write_indentation(Indentation::Dedent); + } + ast::Expr::ConfigIfEntry(_) => { + self.write("el"); + self.expr(orelse); + } + _ => bug!("Invalid config if expr orelse node {:?}", orelse.node), + } + } + } + + fn walk_comp_clause(&mut self, comp_clause: &'ctx ast::CompClause) -> Self::Result { + self.write(" for "); + interleave!( + || self.write(COMMA_WHITESPACE), + |target: &ast::NodeRef| self.walk_identifier(&target.node), + comp_clause.targets + ); + self.write(" in "); + self.expr(&comp_clause.iter); + for if_clause in &comp_clause.ifs { + self.write(" if "); + self.expr(if_clause); + } + } + + fn walk_schema_expr(&mut self, schema_expr: &'ctx ast::SchemaExpr) -> Self::Result { + self.walk_identifier(&schema_expr.name.node); + if !schema_expr.args.is_empty() || !schema_expr.kwargs.is_empty() { + self.write_token(TokenKind::OpenDelim(DelimToken::Paren)); + self.write_args_and_kwargs(&schema_expr.args, &schema_expr.kwargs); + self.write_token(TokenKind::CloseDelim(DelimToken::Paren)); + } + self.write_space(); + self.expr(&schema_expr.config) + } + + fn walk_config_expr(&mut self, config_expr: &'ctx ast::ConfigExpr) -> Self::Result { + let mut line_set: HashSet = config_expr + .items + .iter() + .map(|item| item.line) + .filter(|l| *l > 0) + .collect(); + if self.last_ast_line > 0 { + line_set.insert(self.last_ast_line); + } + // There are comments in the configuration block. + let has_comment = !config_expr.items.is_empty() + && config_expr + .items + .iter() + .map(|item| self.has_comments_on_node(item)) + .all(|r| r); + // When there are comments in the configuration block, print them as multiline configurations. + let mut in_one_line = line_set.len() <= 1 && !has_comment; + // When there are complex configuration blocks in the configuration block, print them as multiline configurations. + if config_expr.items.len() == 1 && in_one_line { + if let Some(item) = config_expr.items.first() { + if matches!( + &item.node.value.node, + ast::Expr::ConfigIfEntry(_) | ast::Expr::Config(_) | ast::Expr::Schema(_) + ) { + in_one_line = false; + } + } + } + self.write_token(TokenKind::OpenDelim(DelimToken::Brace)); + if !config_expr.items.is_empty() { + if !in_one_line { + self.write_indentation(Indentation::IndentWithNewline); + } + interleave!( + || if in_one_line { + self.write(COMMA_WHITESPACE); + } else { + self.write_newline(); + }, + |entry: &ast::NodeRef| self.write_entry(entry), + config_expr.items + ); + if !in_one_line { + if let Some(end_line) = self.current_expr_end_line() { + self.write_comments_until_line(end_line.saturating_sub(1)); + } + self.write_indentation(Indentation::DedentWithNewline); + } + } + self.write_token(TokenKind::CloseDelim(DelimToken::Brace)); + } + + fn walk_check_expr(&mut self, check_expr: &'ctx ast::CheckExpr) -> Self::Result { + self.expr(&check_expr.test); + if let Some(if_cond) = &check_expr.if_cond { + self.write(" if "); + self.expr(if_cond); + } + if let Some(msg) = &check_expr.msg { + self.write(COMMA_WHITESPACE); + self.expr(msg); + } + } + + fn walk_lambda_expr(&mut self, lambda_expr: &'ctx ast::LambdaExpr) -> Self::Result { + self.write("lambda"); + if let Some(args) = &lambda_expr.args { + self.write_space(); + self.walk_arguments(&args.node); + } + if let Some(ty_str) = &lambda_expr.return_ty { + self.write_space(); + self.write_token(TokenKind::RArrow); + self.write_space(); + self.write(&ty_str.node.to_string()); + } + self.write_space(); + self.write_token(TokenKind::OpenDelim(DelimToken::Brace)); + self.write_newline_without_fill(); + self.write_indentation(Indentation::Indent); + + // lambda body + self.stmts(&lambda_expr.body); + + self.write_indentation(Indentation::Dedent); + self.fill(""); + self.write_token(TokenKind::CloseDelim(DelimToken::Brace)); + } + + fn walk_keyword(&mut self, keyword: &'ctx ast::Keyword) -> Self::Result { + self.walk_identifier(&keyword.arg.node); + if let Some(value) = &keyword.value { + self.write("="); + self.expr(value); + } + } + + fn walk_arguments(&mut self, arguments: &'ctx ast::Arguments) -> Self::Result { + let parameter_zip_list: Vec> = arguments + .args + .iter() + .zip( + arguments + .ty_list + .iter() + .map(|ty| ty.clone().map(|n| n.node.to_string())), + ) + .zip(arguments.defaults.iter()) + .collect(); + interleave!( + || self.write(COMMA_WHITESPACE), + |para: &ParameterType<'_>| { + let ((arg, ty_str), default) = para; + self.walk_identifier(&arg.node); + if let Some(ty_str) = ty_str { + self.write(&format!(": {}", ty_str)); + } + if let Some(default) = default { + self.write(" = "); + self.expr(default); + } + }, + parameter_zip_list + ); + } + + fn walk_compare(&mut self, compare: &'ctx ast::Compare) -> Self::Result { + self.expr(&compare.left); + for (op, expr) in compare.ops.iter().zip(compare.comparators.iter()) { + self.write_space(); + self.write(op.symbol()); + self.write_space(); + self.expr(expr); + } + } + + #[inline] + fn walk_identifier(&mut self, identifier: &'ctx ast::Identifier) -> Self::Result { + self.write(&identifier.get_name()); + } + + #[inline] + fn walk_target(&mut self, target: &'ctx ast::Target) -> Self::Result { + self.write(target.get_name()); + for path in &target.paths { + match path { + ast::MemberOrIndex::Member(member) => { + self.write("."); + self.write(&member.node) + } + ast::MemberOrIndex::Index(index) => { + self.write("["); + self.walk_expr(&index.node); + self.write("]"); + } + } + } + } + + fn walk_number_lit(&mut self, number_lit: &'ctx ast::NumberLit) -> Self::Result { + match &number_lit.value { + ast::NumberLitValue::Int(int_val) => self.write(&int_val.to_string()), + ast::NumberLitValue::Float(float_val) => self.write(&float_val.to_string()), + } + // Number suffix e.g., 1Gi + if let Some(binary_suffix) = &number_lit.binary_suffix { + self.write(&binary_suffix.value()) + } + } + + fn walk_string_lit(&mut self, string_lit: &'ctx ast::StringLit) -> Self::Result { + if !string_lit.raw_value.is_empty() { + self.write(&string_lit.raw_value) + } else { + self.write(&if string_lit.is_long_string { + format!("\"\"\"{}\"\"\"", string_lit.value.replace('\"', "\\\"")) + } else { + format!("\"{}\"", string_lit.value.replace('\"', "\\\"")) + }); + } + } + + #[inline] + fn walk_name_constant_lit( + &mut self, + name_constant_lit: &'ctx ast::NameConstantLit, + ) -> Self::Result { + self.write(name_constant_lit.value.symbol()); + } + + fn walk_joined_string(&mut self, joined_string: &'ctx ast::JoinedString) -> Self::Result { + if !joined_string.raw_value.is_empty() { + self.write(&joined_string.raw_value) + } else { + let quote_str = if joined_string.is_long_string { + "\"\"\"" + } else { + "\"" + }; + self.write(quote_str); + for value in &joined_string.values { + match &value.node { + ast::Expr::StringLit(string_lit) => { + self.write(&string_lit.value.replace('\"', "\\\"")); + } + _ => self.expr(value), + } + } + self.write(quote_str); + } + } + + fn walk_formatted_value(&mut self, formatted_value: &'ctx ast::FormattedValue) -> Self::Result { + self.write("${"); + self.expr(&formatted_value.value); + if let Some(spec) = &formatted_value.format_spec { + self.write(&format!(": {}", spec)); + } + self.write("}"); + } + + fn walk_comment(&mut self, comment: &'ctx ast::Comment) -> Self::Result { + self.writeln(&comment.text); + self.fill(""); + } + + fn walk_missing_expr(&mut self, _missing_expr: &'ctx ast::MissingExpr) -> Self::Result { + // Nothing to do + } +} + +impl<'p> Printer<'p> { + pub fn write_args_and_kwargs( + &mut self, + args: &[ast::NodeRef], + kwargs: &[ast::NodeRef], + ) { + interleave!(|| self.write(COMMA_WHITESPACE), |arg| self.expr(arg), args); + if !args.is_empty() && !kwargs.is_empty() { + self.write(COMMA_WHITESPACE); + } + interleave!( + || self.write(COMMA_WHITESPACE), + |kwarg: &ast::NodeRef| self.walk_keyword(&kwarg.node), + kwargs + ); + } + + pub fn write_entry(&mut self, item: &ast::NodeRef) { + match &item.node.key { + Some(key) => { + let print_right_brace_count = self.write_config_key(key); + if !matches!(item.node.operation, ast::ConfigEntryOperation::Union) { + self.write_space(); + } + self.write(item.node.operation.symbol()); + self.write_space(); + self.expr(&item.node.value); + self.write(&"}".repeat(print_right_brace_count)); + } + None => { + self.write_comments_before_node(&item); + if !matches!(&item.node.value.node, ast::Expr::ConfigIfEntry(_)) { + self.write("**"); + } + self.expr(&item.node.value) + } + }; + } + + fn write_config_key(&mut self, key: &ast::NodeRef) -> usize { + match &key.node { + ast::Expr::Identifier(identifier) => { + self.hook.pre(self, super::ASTNode::Expr(key)); + self.write_comments_before_node(key); + // Judge contains string or dot identifier, e.g., "x-y-z" and "a.b.c" + let names = &identifier.names; + + let re = fancy_regex::Regex::new(IDENTIFIER_REGEX).unwrap(); + let need_right_brace = !names.iter().all(|n| re.is_match(&n.node).unwrap_or(false)); + let count = if need_right_brace { + self.write( + &names + .iter() + .map(|n| format!("{:?}", n.node)) + .collect::>() + .join(": {"), + ); + names.len() - 1 + } else { + self.expr(key); + 0 + }; + self.hook.post(self, super::ASTNode::Expr(key)); + count + } + _ => { + self.write_comments_before_node(key); + self.expr(key); + 0 + } + } + } + + fn write_attribute(&mut self, attr: &ast::NodeRef) { + let re = fancy_regex::Regex::new(IDENTIFIER_REGEX).unwrap(); + let need_quote = !re.is_match(&attr.node).unwrap(); + if need_quote { + self.write(&format!("{:?}", attr.node)); + } else { + self.write(&attr.node); + }; + } +} + +impl<'p> Printer<'p> { + // ------------------------------ + // Expr and Stmt walker functions + // ------------------------------ + + pub fn expr(&mut self, expr: &ast::NodeRef) { + self.push_expr_span(expr.line, expr.end_line); + self.hook.pre(self, super::ASTNode::Expr(expr)); + self.update_last_ast_line(expr); + self.walk_expr(&expr.node); + self.hook.post(self, super::ASTNode::Expr(expr)); + self.pop_expr_span(); + } + + pub fn stmt(&mut self, stmt: &ast::NodeRef) { + self.hook.pre(self, super::ASTNode::Stmt(stmt)); + self.fill(""); + self.write_comments_before_node(stmt); + self.walk_stmt(&stmt.node); + self.hook.post(self, super::ASTNode::Stmt(stmt)); + } + + pub fn exprs(&mut self, exprs: &[ast::NodeRef]) { + for expr in exprs { + self.expr(expr); + } + } + + pub fn stmts(&mut self, stmts: &[ast::NodeRef]) { + // Hold the prev statement pointer. + let mut prev_stmt: Option<&ast::NodeRef> = None; + for stmt in stmts { + let import_stmt_alter = match (prev_stmt.map(|s| &s.node).as_ref(), &stmt.node) { + (Some(ast::Stmt::Import(_)), ast::Stmt::Import(_)) => false, + (Some(ast::Stmt::Import(_)), _) => true, + _ => false, + }; + // Do not format out user-reserved blank lines: which does not mean that to preserve all user-written blank lines. + // For situations where there are more than two blank lines, we only keep one blank line. + let need_newline = if let Some(prev_stmt) = prev_stmt { + if stmt.line > prev_stmt.end_line + 2 { + true + } else if stmt.line == prev_stmt.end_line + 2 { + stmt.line > 0 && !self.has_comments_on_node(stmt) + } else { + false + } + } else { + false + }; + if import_stmt_alter || need_newline { + self.write_newline_without_fill(); + } + self.stmt(stmt); + prev_stmt = Some(stmt); + } + } +} diff --git a/kclvm/ast_pretty/src/test_data/arguments.input b/crates/ast_pretty/src/test_data/arguments.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/arguments.input rename to crates/ast_pretty/src/test_data/arguments.input diff --git a/kclvm/ast_pretty/src/test_data/arguments.output b/crates/ast_pretty/src/test_data/arguments.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/arguments.output rename to crates/ast_pretty/src/test_data/arguments.output diff --git a/kclvm/ast_pretty/src/test_data/codelayout.input b/crates/ast_pretty/src/test_data/codelayout.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/codelayout.input rename to crates/ast_pretty/src/test_data/codelayout.input diff --git a/kclvm/ast_pretty/src/test_data/codelayout.output b/crates/ast_pretty/src/test_data/codelayout.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/codelayout.output rename to crates/ast_pretty/src/test_data/codelayout.output diff --git a/kclvm/ast_pretty/src/test_data/collection_if.input b/crates/ast_pretty/src/test_data/collection_if.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/collection_if.input rename to crates/ast_pretty/src/test_data/collection_if.input diff --git a/kclvm/ast_pretty/src/test_data/collection_if.output b/crates/ast_pretty/src/test_data/collection_if.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/collection_if.output rename to crates/ast_pretty/src/test_data/collection_if.output diff --git a/kclvm/ast_pretty/src/test_data/comment.input b/crates/ast_pretty/src/test_data/comment.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/comment.input rename to crates/ast_pretty/src/test_data/comment.input diff --git a/kclvm/ast_pretty/src/test_data/comment.output b/crates/ast_pretty/src/test_data/comment.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/comment.output rename to crates/ast_pretty/src/test_data/comment.output diff --git a/kclvm/ast_pretty/src/test_data/empty.input b/crates/ast_pretty/src/test_data/empty.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/empty.input rename to crates/ast_pretty/src/test_data/empty.input diff --git a/kclvm/ast_pretty/src/test_data/empty.output b/crates/ast_pretty/src/test_data/empty.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/empty.output rename to crates/ast_pretty/src/test_data/empty.output diff --git a/kclvm/ast_pretty/src/test_data/if_stmt.input b/crates/ast_pretty/src/test_data/if_stmt.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/if_stmt.input rename to crates/ast_pretty/src/test_data/if_stmt.input diff --git a/kclvm/ast_pretty/src/test_data/if_stmt.output b/crates/ast_pretty/src/test_data/if_stmt.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/if_stmt.output rename to crates/ast_pretty/src/test_data/if_stmt.output diff --git a/kclvm/ast_pretty/src/test_data/import.input b/crates/ast_pretty/src/test_data/import.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/import.input rename to crates/ast_pretty/src/test_data/import.input diff --git a/kclvm/ast_pretty/src/test_data/import.output b/crates/ast_pretty/src/test_data/import.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/import.output rename to crates/ast_pretty/src/test_data/import.output diff --git a/kclvm/ast_pretty/src/test_data/index_sign.input b/crates/ast_pretty/src/test_data/index_sign.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/index_sign.input rename to crates/ast_pretty/src/test_data/index_sign.input diff --git a/kclvm/ast_pretty/src/test_data/index_sign.output b/crates/ast_pretty/src/test_data/index_sign.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/index_sign.output rename to crates/ast_pretty/src/test_data/index_sign.output diff --git a/kclvm/ast_pretty/src/test_data/joined_str.input b/crates/ast_pretty/src/test_data/joined_str.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/joined_str.input rename to crates/ast_pretty/src/test_data/joined_str.input diff --git a/kclvm/ast_pretty/src/test_data/joined_str.output b/crates/ast_pretty/src/test_data/joined_str.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/joined_str.output rename to crates/ast_pretty/src/test_data/joined_str.output diff --git a/kclvm/ast_pretty/src/test_data/lambda.input b/crates/ast_pretty/src/test_data/lambda.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/lambda.input rename to crates/ast_pretty/src/test_data/lambda.input diff --git a/kclvm/ast_pretty/src/test_data/lambda.output b/crates/ast_pretty/src/test_data/lambda.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/lambda.output rename to crates/ast_pretty/src/test_data/lambda.output diff --git a/kclvm/ast_pretty/src/test_data/orelse.input b/crates/ast_pretty/src/test_data/orelse.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/orelse.input rename to crates/ast_pretty/src/test_data/orelse.input diff --git a/kclvm/ast_pretty/src/test_data/orelse.output b/crates/ast_pretty/src/test_data/orelse.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/orelse.output rename to crates/ast_pretty/src/test_data/orelse.output diff --git a/kclvm/ast_pretty/src/test_data/quant.input b/crates/ast_pretty/src/test_data/quant.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/quant.input rename to crates/ast_pretty/src/test_data/quant.input diff --git a/kclvm/ast_pretty/src/test_data/quant.output b/crates/ast_pretty/src/test_data/quant.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/quant.output rename to crates/ast_pretty/src/test_data/quant.output diff --git a/kclvm/ast_pretty/src/test_data/rule.input b/crates/ast_pretty/src/test_data/rule.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/rule.input rename to crates/ast_pretty/src/test_data/rule.input diff --git a/kclvm/ast_pretty/src/test_data/rule.output b/crates/ast_pretty/src/test_data/rule.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/rule.output rename to crates/ast_pretty/src/test_data/rule.output diff --git a/kclvm/ast_pretty/src/test_data/str.input b/crates/ast_pretty/src/test_data/str.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/str.input rename to crates/ast_pretty/src/test_data/str.input diff --git a/kclvm/ast_pretty/src/test_data/str.output b/crates/ast_pretty/src/test_data/str.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/str.output rename to crates/ast_pretty/src/test_data/str.output diff --git a/kclvm/ast_pretty/src/test_data/type_alias.input b/crates/ast_pretty/src/test_data/type_alias.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/type_alias.input rename to crates/ast_pretty/src/test_data/type_alias.input diff --git a/kclvm/ast_pretty/src/test_data/type_alias.output b/crates/ast_pretty/src/test_data/type_alias.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/type_alias.output rename to crates/ast_pretty/src/test_data/type_alias.output diff --git a/kclvm/ast_pretty/src/test_data/unary.input b/crates/ast_pretty/src/test_data/unary.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/unary.input rename to crates/ast_pretty/src/test_data/unary.input diff --git a/kclvm/ast_pretty/src/test_data/unary.output b/crates/ast_pretty/src/test_data/unary.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/unary.output rename to crates/ast_pretty/src/test_data/unary.output diff --git a/kclvm/ast_pretty/src/test_data/unification.input b/crates/ast_pretty/src/test_data/unification.input similarity index 100% rename from kclvm/ast_pretty/src/test_data/unification.input rename to crates/ast_pretty/src/test_data/unification.input diff --git a/kclvm/ast_pretty/src/test_data/unification.output b/crates/ast_pretty/src/test_data/unification.output similarity index 100% rename from kclvm/ast_pretty/src/test_data/unification.output rename to crates/ast_pretty/src/test_data/unification.output diff --git a/crates/ast_pretty/src/tests.rs b/crates/ast_pretty/src/tests.rs new file mode 100644 index 000000000..c899645cb --- /dev/null +++ b/crates/ast_pretty/src/tests.rs @@ -0,0 +1,65 @@ +use std::path::{Path, PathBuf}; + +use super::print_ast_module; +use kcl_parser::parse_file_force_errors; +use pretty_assertions::assert_eq; + +const FILE_INPUT_SUFFIX: &str = ".input"; +const FILE_OUTPUT_SUFFIX: &str = ".output"; +const TEST_CASES: &[&str] = &[ + "arguments", + "empty", + "if_stmt", + "import", + "unary", + "codelayout", + "collection_if", + "comment", + "index_sign", + "joined_str", + "lambda", + "orelse", + "quant", + "rule", + "str", + "type_alias", + "unification", +]; + +fn read_data(data_name: &str) -> (String, String) { + let mut filename = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + filename.push( + Path::new("src") + .join("test_data") + .join(format!("{}{}", data_name, FILE_INPUT_SUFFIX)) + .display() + .to_string(), + ); + + let module = parse_file_force_errors(filename.to_str().unwrap(), None); + + let mut filename_expect = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + filename_expect.push( + Path::new("src") + .join("test_data") + .join(format!("{}{}", data_name, FILE_OUTPUT_SUFFIX)) + .display() + .to_string(), + ); + ( + print_ast_module(&module.unwrap()), + std::fs::read_to_string(filename_expect.to_str().unwrap()).unwrap(), + ) +} + +#[test] +fn test_ast_printer() { + for case in TEST_CASES { + let (data_input, data_output) = read_data(case); + + #[cfg(target_os = "windows")] + let data_output = data_output.replace("\r\n", "\n"); + + assert_eq!(data_input, data_output, "Test failed on {}", case); + } +} diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml new file mode 100644 index 000000000..672070eed --- /dev/null +++ b/crates/cli/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "kcl_cli" +version.workspace = true +edition.workspace = true + +[[bin]] +path = "src/main.rs" +name = "libkcl" diff --git a/crates/cli/build.rs b/crates/cli/build.rs new file mode 100644 index 000000000..70934fa0f --- /dev/null +++ b/crates/cli/build.rs @@ -0,0 +1,13 @@ +fn main() { + if cfg!(target_os = "windows") { + println!("cargo:rustc-link-search=target\\release"); + } else { + println!("cargo:rustc-link-search=target/release"); + } + println!("cargo:rustc-link-lib=dylib=kcl"); + if cfg!(target_os = "macos") { + println!("cargo:rustc-link-arg=-Wl,-rpath,@loader_path"); + } else if cfg!(target_os = "linux") { + println!("cargo:rustc-link-arg=-Wl,-rpath,$ORIGIN"); + } +} diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs new file mode 100644 index 000000000..2c6941151 --- /dev/null +++ b/crates/cli/src/main.rs @@ -0,0 +1,30 @@ +//! The `libkcl` command-line interface. + +use std::{ + ffi::{CString, c_char, c_int}, + process::ExitCode, +}; + +#[link(name = "kcl")] +#[allow(improper_ctypes)] +unsafe extern "C-unwind" { + unsafe fn libkcl_main(argc: c_int, argv: *const *const c_char) -> *mut ExitCode; +} + +fn main() -> ExitCode { + // create a vector of zero terminated strings + let args = std::env::args() + .map(|arg| CString::new(arg).unwrap()) + .collect::>(); + // convert the strings to raw pointers + let c_args = args + .iter() + .map(|arg| arg.as_ptr()) + .collect::>(); + unsafe { + // pass the pointer of the vector's internal buffer to a C function + let result = libkcl_main(c_args.len() as c_int, c_args.as_ptr()); + let result = Box::from_raw(result); + *result + } +} diff --git a/crates/cmd/Cargo.toml b/crates/cmd/Cargo.toml new file mode 100644 index 000000000..803888293 --- /dev/null +++ b/crates/cmd/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "kcl-cmd" +version.workspace = true +edition.workspace = true + +[dependencies] +anyhow = "1.0" +clap = "4.3.0" +compiler_base_session = "0.1.3" + +kcl-api.workspace = true +kcl-parser.workspace = true +kcl-runner.workspace = true +kcl-config.workspace = true +kcl-driver.workspace = true +kcl-runtime.workspace = true +kcl-tools.workspace = true +kcl-error.workspace = true +kcl-version.workspace = true diff --git a/crates/cmd/src/lib.rs b/crates/cmd/src/lib.rs new file mode 100644 index 000000000..2f2c7a427 --- /dev/null +++ b/crates/cmd/src/lib.rs @@ -0,0 +1,64 @@ +//! The `libkcl` command-line interface. + +#[macro_use] +extern crate clap; + +pub mod run; +pub mod settings; +pub(crate) mod util; + +#[cfg(test)] +mod tests; + +use clap::{ArgAction, Command}; + +use std::io; + +use anyhow::Result; +use run::run_command; + +/// Run the KCL main command. +pub fn main(args: &[&str]) -> Result<()> { + let matches = app().arg_required_else_help(true).get_matches_from(args); + // Sub commands + match matches.subcommand() { + Some(("run", sub_matches)) => run_command(sub_matches, &mut io::stdout()), + Some(("version", _)) => { + println!("{}", kcl_version::get_version_info()); + Ok(()) + } + #[cfg(not(target_arch = "wasm32"))] + Some(("server", _)) => kcl_api::service::jsonrpc::start_stdio_server(), + _ => Ok(()), + } +} + +/// Get the CLI application including a run command and +/// a gPRC server command to interacting with external systems. +pub fn app() -> Command { + Command::new("libkcl") + .version(kcl_version::VERSION) + .about("KCL main CLI.") + .subcommand( + Command::new("run") + .about("run") + .arg(arg!([input] ... "Specify the input files to run").num_args(0..)) + .arg(arg!(output: -o --output "Specify the YAML output file path")) + .arg(arg!(setting: -Y --setting ... "Specify the input setting file").num_args(1..)) + .arg(arg!(verbose: -v --verbose "Print test information verbosely").action(ArgAction::Count)) + .arg(arg!(disable_none: -n --disable_none "Disable dumping None values")) + .arg(arg!(strict_range_check: -r --strict_range_check "Do perform strict numeric range checks")) + .arg(arg!(debug: -d --debug "Run in debug mode (for developers only)")) + .arg(arg!(sort_keys: -k --sort_keys "Sort result keys")) + .arg(arg!(show_hidden: -H --show_hidden "Display hidden attributes")) + .arg(arg!(fast_eval: -K --fast_eval "Use the fast evaluation mode")) + .arg(arg!(arguments: -D --argument ... "Specify the top-level argument").num_args(1..)) + .arg(arg!(path_selector: -S --path_selector ... "Specify the path selector").num_args(1..)) + .arg(arg!(overrides: -O --overrides ... "Specify the configuration override path and value").num_args(1..)) + .arg(arg!(target: --target "Specify the target type")) + .arg(arg!(recursive: -R --recursive "Compile the files directory recursively")) + .arg(arg!(package_map: -E --external ... "Mapping of package name and path where the package is located").num_args(1..)), + ) + .subcommand(Command::new("server").about("Start a rpc server for APIs")) + .subcommand(Command::new("version").about("Show the KCL version")) +} diff --git a/kclvm/cmd/src/run.rs b/crates/cmd/src/run.rs similarity index 94% rename from kclvm/cmd/src/run.rs rename to crates/cmd/src/run.rs index 9ab1fd469..a068383f7 100644 --- a/kclvm/cmd/src/run.rs +++ b/crates/cmd/src/run.rs @@ -1,8 +1,8 @@ use anyhow::Result; use clap::ArgMatches; -use kclvm_error::StringError; -use kclvm_parser::ParseSession; -use kclvm_runner::exec_program; +use kcl_error::StringError; +use kcl_parser::ParseSession; +use kcl_runner::exec_program; use std::io::Write; use std::sync::Arc; diff --git a/crates/cmd/src/settings.rs b/crates/cmd/src/settings.rs new file mode 100644 index 000000000..c33ec19de --- /dev/null +++ b/crates/cmd/src/settings.rs @@ -0,0 +1,73 @@ +use crate::util::*; +use anyhow::Result; +use clap::ArgMatches; +use kcl_config::settings::{Config, SettingsFile, SettingsPathBuf, build_settings_pathbuf}; +use kcl_driver::arguments::parse_key_value_pair; +use kcl_error::Handler; +use kcl_runtime::PanicInfo; + +/// Build settings from arg matches. +pub(crate) fn must_build_settings(matches: &ArgMatches) -> SettingsPathBuf { + match build_settings(matches) { + Ok(settings) => settings, + Err(err) => { + // New an error handler. + let mut handler = Handler::default(); + handler + .add_panic_info(&PanicInfo { + message: err.to_string(), + ..Default::default() + }) + .abort_if_any_errors(); + SettingsPathBuf::default() + } + } +} + +/// Build settings from arg matches. +pub(crate) fn build_settings(matches: &ArgMatches) -> Result { + let files: Vec<&str> = match matches.get_many::("input") { + Some(files) => files.into_iter().map(|f| f.as_str()).collect::>(), + None => vec![], + }; + + let setting_files = matches + .get_many::("setting") + .map(|files| files.into_iter().map(|f| f.as_str()).collect::>()); + + let arguments = strings_from_matches(matches, "arguments"); + + let package_maps = hashmaps_from_matches(matches, "package_map").transpose()?; + + build_settings_pathbuf( + files.as_slice(), + setting_files, + Some(SettingsFile { + kcl_cli_configs: Some(Config { + output: matches.get_one::("output").map(|v| v.to_string()), + overrides: strings_from_matches(matches, "overrides"), + path_selector: strings_from_matches(matches, "path_selector"), + strict_range_check: bool_from_matches(matches, "strict_range_check"), + disable_none: bool_from_matches(matches, "disable_none"), + verbose: u32_from_matches(matches, "verbose"), + debug: bool_from_matches(matches, "debug"), + sort_keys: bool_from_matches(matches, "sort_keys"), + show_hidden: bool_from_matches(matches, "show_hidden"), + fast_eval: bool_from_matches(matches, "fast_eval"), + package_maps, + ..Default::default() + }), + kcl_options: if arguments.is_some() { + let mut key_value_pairs = vec![]; + if let Some(arguments) = arguments { + for arg in arguments { + key_value_pairs.push(parse_key_value_pair(&arg)?); + } + } + Some(key_value_pairs) + } else { + None + }, + }), + ) +} diff --git a/kclvm/cmd/src/test_data/cache/main/kcl.mod b/crates/cmd/src/test_data/cache/main/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/cache/main/kcl.mod rename to crates/cmd/src/test_data/cache/main/kcl.mod diff --git a/kclvm/cmd/src/test_data/cache/main/main.k b/crates/cmd/src/test_data/cache/main/main.k similarity index 100% rename from kclvm/cmd/src/test_data/cache/main/main.k rename to crates/cmd/src/test_data/cache/main/main.k diff --git a/kclvm/cmd/src/test_data/cache/main/main.k.v1 b/crates/cmd/src/test_data/cache/main/main.k.v1 similarity index 100% rename from kclvm/cmd/src/test_data/cache/main/main.k.v1 rename to crates/cmd/src/test_data/cache/main/main.k.v1 diff --git a/kclvm/cmd/src/test_data/cache/main/main.k.v2 b/crates/cmd/src/test_data/cache/main/main.k.v2 similarity index 100% rename from kclvm/cmd/src/test_data/cache/main/main.k.v2 rename to crates/cmd/src/test_data/cache/main/main.k.v2 diff --git a/kclvm/cmd/src/test_data/cache/v1/kcl1/kcl.mod b/crates/cmd/src/test_data/cache/v1/kcl1/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/cache/v1/kcl1/kcl.mod rename to crates/cmd/src/test_data/cache/v1/kcl1/kcl.mod diff --git a/kclvm/cmd/src/test_data/cache/v1/kcl1/main.k b/crates/cmd/src/test_data/cache/v1/kcl1/main.k similarity index 100% rename from kclvm/cmd/src/test_data/cache/v1/kcl1/main.k rename to crates/cmd/src/test_data/cache/v1/kcl1/main.k diff --git a/kclvm/cmd/src/test_data/cache/v2/kcl1/kcl.mod b/crates/cmd/src/test_data/cache/v2/kcl1/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/cache/v2/kcl1/kcl.mod rename to crates/cmd/src/test_data/cache/v2/kcl1/kcl.mod diff --git a/kclvm/cmd/src/test_data/cache/v2/kcl1/main.k b/crates/cmd/src/test_data/cache/v2/kcl1/main.k similarity index 100% rename from kclvm/cmd/src/test_data/cache/v2/kcl1/main.k rename to crates/cmd/src/test_data/cache/v2/kcl1/main.k diff --git a/kclvm/cmd/src/test_data/cache_test/kcl.mod b/crates/cmd/src/test_data/cache_test/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/cache_test/kcl.mod rename to crates/cmd/src/test_data/cache_test/kcl.mod diff --git a/kclvm/cmd/src/test_data/cache_test/main.k b/crates/cmd/src/test_data/cache_test/main.k similarity index 100% rename from kclvm/cmd/src/test_data/cache_test/main.k rename to crates/cmd/src/test_data/cache_test/main.k diff --git a/kclvm/cmd/src/test_data/cases/import_1/main.k b/crates/cmd/src/test_data/cases/import_1/main.k similarity index 100% rename from kclvm/cmd/src/test_data/cases/import_1/main.k rename to crates/cmd/src/test_data/cases/import_1/main.k diff --git a/kclvm/cmd/src/test_data/cases/import_1/stdout b/crates/cmd/src/test_data/cases/import_1/stdout similarity index 100% rename from kclvm/cmd/src/test_data/cases/import_1/stdout rename to crates/cmd/src/test_data/cases/import_1/stdout diff --git a/kclvm/cmd/src/test_data/cases/import_konfig_1/main.k b/crates/cmd/src/test_data/cases/import_konfig_1/main.k similarity index 100% rename from kclvm/cmd/src/test_data/cases/import_konfig_1/main.k rename to crates/cmd/src/test_data/cases/import_konfig_1/main.k diff --git a/kclvm/cmd/src/test_data/cases/import_konfig_1/stdout b/crates/cmd/src/test_data/cases/import_konfig_1/stdout similarity index 100% rename from kclvm/cmd/src/test_data/cases/import_konfig_1/stdout rename to crates/cmd/src/test_data/cases/import_konfig_1/stdout diff --git a/kclvm/cmd/src/test_data/cases/vendor/kcl4/container/kcl4.k b/crates/cmd/src/test_data/cases/vendor/kcl4/container/kcl4.k similarity index 100% rename from kclvm/cmd/src/test_data/cases/vendor/kcl4/container/kcl4.k rename to crates/cmd/src/test_data/cases/vendor/kcl4/container/kcl4.k diff --git a/kclvm/cmd/src/test_data/cases/vendor/kcl4/kcl.mod b/crates/cmd/src/test_data/cases/vendor/kcl4/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/cases/vendor/kcl4/kcl.mod rename to crates/cmd/src/test_data/cases/vendor/kcl4/kcl.mod diff --git a/kclvm/cmd/src/test_data/cases/vendor/kcl4/kcl4.k b/crates/cmd/src/test_data/cases/vendor/kcl4/kcl4.k similarity index 100% rename from kclvm/cmd/src/test_data/cases/vendor/kcl4/kcl4.k rename to crates/cmd/src/test_data/cases/vendor/kcl4/kcl4.k diff --git a/kclvm/cmd/src/test_data/failed/keyword_argument_error.k b/crates/cmd/src/test_data/failed/keyword_argument_error.k similarity index 100% rename from kclvm/cmd/src/test_data/failed/keyword_argument_error.k rename to crates/cmd/src/test_data/failed/keyword_argument_error.k diff --git a/kclvm/cmd/src/test_data/fmt/test.k b/crates/cmd/src/test_data/fmt/test.k similarity index 100% rename from kclvm/cmd/src/test_data/fmt/test.k rename to crates/cmd/src/test_data/fmt/test.k diff --git a/kclvm/cmd/src/test_data/fuzz_match/main.k b/crates/cmd/src/test_data/fuzz_match/main.k similarity index 100% rename from kclvm/cmd/src/test_data/fuzz_match/main.k rename to crates/cmd/src/test_data/fuzz_match/main.k diff --git a/kclvm/cmd/src/test_data/fuzz_match/main_unmatched.k b/crates/cmd/src/test_data/fuzz_match/main_unmatched.k similarity index 100% rename from kclvm/cmd/src/test_data/fuzz_match/main_unmatched.k rename to crates/cmd/src/test_data/fuzz_match/main_unmatched.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_1/expected b/crates/cmd/src/test_data/instances/test_inst_1/expected similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_1/expected rename to crates/cmd/src/test_data/instances/test_inst_1/expected diff --git a/kclvm/cmd/src/test_data/instances/test_inst_1/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_1/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_1/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_1/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_1/kcl.yaml b/crates/cmd/src/test_data/instances/test_inst_1/kcl.yaml similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_1/kcl.yaml rename to crates/cmd/src/test_data/instances/test_inst_1/kcl.yaml diff --git a/kclvm/cmd/src/test_data/instances/test_inst_1/main.k b/crates/cmd/src/test_data/instances/test_inst_1/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_1/main.k rename to crates/cmd/src/test_data/instances/test_inst_1/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_1/main1.k b/crates/cmd/src/test_data/instances/test_inst_1/main1.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_1/main1.k rename to crates/cmd/src/test_data/instances/test_inst_1/main1.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_10/expected b/crates/cmd/src/test_data/instances/test_inst_10/expected similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_10/expected rename to crates/cmd/src/test_data/instances/test_inst_10/expected diff --git a/kclvm/cmd/src/test_data/instances/test_inst_10/kcl.yaml b/crates/cmd/src/test_data/instances/test_inst_10/kcl.yaml similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_10/kcl.yaml rename to crates/cmd/src/test_data/instances/test_inst_10/kcl.yaml diff --git a/kclvm/cmd/src/test_data/instances/test_inst_10/test_inst_101/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_10/test_inst_101/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_10/test_inst_101/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_10/test_inst_101/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_10/test_inst_101/main.k b/crates/cmd/src/test_data/instances/test_inst_10/test_inst_101/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_10/test_inst_101/main.k rename to crates/cmd/src/test_data/instances/test_inst_10/test_inst_101/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_10/test_inst_102/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_10/test_inst_102/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_10/test_inst_102/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_10/test_inst_102/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_10/test_inst_102/main.k b/crates/cmd/src/test_data/instances/test_inst_10/test_inst_102/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_10/test_inst_102/main.k rename to crates/cmd/src/test_data/instances/test_inst_10/test_inst_102/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_11/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_11/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_11/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_11/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_11/model/main.k b/crates/cmd/src/test_data/instances/test_inst_11/model/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_11/model/main.k rename to crates/cmd/src/test_data/instances/test_inst_11/model/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_11/sub/main.k b/crates/cmd/src/test_data/instances/test_inst_11/sub/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_11/sub/main.k rename to crates/cmd/src/test_data/instances/test_inst_11/sub/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_11/test_inst_111/expected b/crates/cmd/src/test_data/instances/test_inst_11/test_inst_111/expected similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_11/test_inst_111/expected rename to crates/cmd/src/test_data/instances/test_inst_11/test_inst_111/expected diff --git a/kclvm/cmd/src/test_data/instances/test_inst_11/test_inst_111/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_11/test_inst_111/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_11/test_inst_111/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_11/test_inst_111/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_11/test_inst_111/kcl.yaml b/crates/cmd/src/test_data/instances/test_inst_11/test_inst_111/kcl.yaml similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_11/test_inst_111/kcl.yaml rename to crates/cmd/src/test_data/instances/test_inst_11/test_inst_111/kcl.yaml diff --git a/kclvm/cmd/src/test_data/instances/test_inst_11/test_inst_111/main.k b/crates/cmd/src/test_data/instances/test_inst_11/test_inst_111/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_11/test_inst_111/main.k rename to crates/cmd/src/test_data/instances/test_inst_11/test_inst_111/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_2/expected b/crates/cmd/src/test_data/instances/test_inst_2/expected similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_2/expected rename to crates/cmd/src/test_data/instances/test_inst_2/expected diff --git a/kclvm/cmd/src/test_data/instances/test_inst_2/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_2/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_2/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_2/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_2/kcl.yaml b/crates/cmd/src/test_data/instances/test_inst_2/kcl.yaml similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_2/kcl.yaml rename to crates/cmd/src/test_data/instances/test_inst_2/kcl.yaml diff --git a/kclvm/cmd/src/test_data/instances/test_inst_2/main.k b/crates/cmd/src/test_data/instances/test_inst_2/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_2/main.k rename to crates/cmd/src/test_data/instances/test_inst_2/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_2/sub/main.k b/crates/cmd/src/test_data/instances/test_inst_2/sub/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_2/sub/main.k rename to crates/cmd/src/test_data/instances/test_inst_2/sub/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_3/expected b/crates/cmd/src/test_data/instances/test_inst_3/expected similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_3/expected rename to crates/cmd/src/test_data/instances/test_inst_3/expected diff --git a/kclvm/cmd/src/test_data/instances/test_inst_3/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_3/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_3/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_3/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_3/kcl.yaml b/crates/cmd/src/test_data/instances/test_inst_3/kcl.yaml similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_3/kcl.yaml rename to crates/cmd/src/test_data/instances/test_inst_3/kcl.yaml diff --git a/kclvm/cmd/src/test_data/instances/test_inst_3/main.k b/crates/cmd/src/test_data/instances/test_inst_3/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_3/main.k rename to crates/cmd/src/test_data/instances/test_inst_3/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_3/main1.k b/crates/cmd/src/test_data/instances/test_inst_3/main1.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_3/main1.k rename to crates/cmd/src/test_data/instances/test_inst_3/main1.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_3/sub/main.k b/crates/cmd/src/test_data/instances/test_inst_3/sub/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_3/sub/main.k rename to crates/cmd/src/test_data/instances/test_inst_3/sub/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_4/expected b/crates/cmd/src/test_data/instances/test_inst_4/expected similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_4/expected rename to crates/cmd/src/test_data/instances/test_inst_4/expected diff --git a/kclvm/cmd/src/test_data/instances/test_inst_4/kcl.yaml b/crates/cmd/src/test_data/instances/test_inst_4/kcl.yaml similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_4/kcl.yaml rename to crates/cmd/src/test_data/instances/test_inst_4/kcl.yaml diff --git a/kclvm/cmd/src/test_data/instances/test_inst_4/test_inst_41/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_4/test_inst_41/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_4/test_inst_41/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_4/test_inst_41/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_4/test_inst_41/main.k b/crates/cmd/src/test_data/instances/test_inst_4/test_inst_41/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_4/test_inst_41/main.k rename to crates/cmd/src/test_data/instances/test_inst_4/test_inst_41/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_4/test_inst_42/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_4/test_inst_42/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_4/test_inst_42/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_4/test_inst_42/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_4/test_inst_42/main.k b/crates/cmd/src/test_data/instances/test_inst_4/test_inst_42/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_4/test_inst_42/main.k rename to crates/cmd/src/test_data/instances/test_inst_4/test_inst_42/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_5/expected b/crates/cmd/src/test_data/instances/test_inst_5/expected similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_5/expected rename to crates/cmd/src/test_data/instances/test_inst_5/expected diff --git a/kclvm/cmd/src/test_data/instances/test_inst_5/kcl.yaml b/crates/cmd/src/test_data/instances/test_inst_5/kcl.yaml similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_5/kcl.yaml rename to crates/cmd/src/test_data/instances/test_inst_5/kcl.yaml diff --git a/kclvm/cmd/src/test_data/instances/test_inst_5/test_inst_51/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_5/test_inst_51/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_5/test_inst_51/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_5/test_inst_51/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_5/test_inst_51/main.k b/crates/cmd/src/test_data/instances/test_inst_5/test_inst_51/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_5/test_inst_51/main.k rename to crates/cmd/src/test_data/instances/test_inst_5/test_inst_51/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_5/test_inst_51/main1.k b/crates/cmd/src/test_data/instances/test_inst_5/test_inst_51/main1.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_5/test_inst_51/main1.k rename to crates/cmd/src/test_data/instances/test_inst_5/test_inst_51/main1.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_5/test_inst_52/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_5/test_inst_52/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_5/test_inst_52/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_5/test_inst_52/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_5/test_inst_52/main.k b/crates/cmd/src/test_data/instances/test_inst_5/test_inst_52/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_5/test_inst_52/main.k rename to crates/cmd/src/test_data/instances/test_inst_5/test_inst_52/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_5/test_inst_53/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_5/test_inst_53/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_5/test_inst_53/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_5/test_inst_53/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_5/test_inst_53/main.k b/crates/cmd/src/test_data/instances/test_inst_5/test_inst_53/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_5/test_inst_53/main.k rename to crates/cmd/src/test_data/instances/test_inst_5/test_inst_53/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_6/expected b/crates/cmd/src/test_data/instances/test_inst_6/expected similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_6/expected rename to crates/cmd/src/test_data/instances/test_inst_6/expected diff --git a/kclvm/cmd/src/test_data/instances/test_inst_6/kcl.yaml b/crates/cmd/src/test_data/instances/test_inst_6/kcl.yaml similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_6/kcl.yaml rename to crates/cmd/src/test_data/instances/test_inst_6/kcl.yaml diff --git a/kclvm/cmd/src/test_data/instances/test_inst_6/test_inst_61/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_6/test_inst_61/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_6/test_inst_61/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_6/test_inst_61/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_6/test_inst_61/main.k b/crates/cmd/src/test_data/instances/test_inst_6/test_inst_61/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_6/test_inst_61/main.k rename to crates/cmd/src/test_data/instances/test_inst_6/test_inst_61/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_6/test_inst_62/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_6/test_inst_62/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_6/test_inst_62/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_6/test_inst_62/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_6/test_inst_62/main.k b/crates/cmd/src/test_data/instances/test_inst_6/test_inst_62/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_6/test_inst_62/main.k rename to crates/cmd/src/test_data/instances/test_inst_6/test_inst_62/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_6/test_inst_63/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_6/test_inst_63/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_6/test_inst_63/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_6/test_inst_63/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_6/test_inst_63/main.k b/crates/cmd/src/test_data/instances/test_inst_6/test_inst_63/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_6/test_inst_63/main.k rename to crates/cmd/src/test_data/instances/test_inst_6/test_inst_63/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_7/expected b/crates/cmd/src/test_data/instances/test_inst_7/expected similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_7/expected rename to crates/cmd/src/test_data/instances/test_inst_7/expected diff --git a/kclvm/cmd/src/test_data/instances/test_inst_7/kcl.yaml b/crates/cmd/src/test_data/instances/test_inst_7/kcl.yaml similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_7/kcl.yaml rename to crates/cmd/src/test_data/instances/test_inst_7/kcl.yaml diff --git a/kclvm/cmd/src/test_data/instances/test_inst_7/test_inst_71/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_7/test_inst_71/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_7/test_inst_71/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_7/test_inst_71/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_7/test_inst_71/main.k b/crates/cmd/src/test_data/instances/test_inst_7/test_inst_71/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_7/test_inst_71/main.k rename to crates/cmd/src/test_data/instances/test_inst_7/test_inst_71/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_7/test_inst_72/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_7/test_inst_72/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_7/test_inst_72/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_7/test_inst_72/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_7/test_inst_72/main.k b/crates/cmd/src/test_data/instances/test_inst_7/test_inst_72/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_7/test_inst_72/main.k rename to crates/cmd/src/test_data/instances/test_inst_7/test_inst_72/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_7/test_inst_73/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_7/test_inst_73/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_7/test_inst_73/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_7/test_inst_73/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_7/test_inst_73/main.k b/crates/cmd/src/test_data/instances/test_inst_7/test_inst_73/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_7/test_inst_73/main.k rename to crates/cmd/src/test_data/instances/test_inst_7/test_inst_73/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_8/expected b/crates/cmd/src/test_data/instances/test_inst_8/expected similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_8/expected rename to crates/cmd/src/test_data/instances/test_inst_8/expected diff --git a/kclvm/cmd/src/test_data/instances/test_inst_8/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_8/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_8/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_8/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_8/kcl.yaml b/crates/cmd/src/test_data/instances/test_inst_8/kcl.yaml similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_8/kcl.yaml rename to crates/cmd/src/test_data/instances/test_inst_8/kcl.yaml diff --git a/kclvm/cmd/src/test_data/instances/test_inst_8/main.k b/crates/cmd/src/test_data/instances/test_inst_8/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_8/main.k rename to crates/cmd/src/test_data/instances/test_inst_8/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_8/main1.k b/crates/cmd/src/test_data/instances/test_inst_8/main1.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_8/main1.k rename to crates/cmd/src/test_data/instances/test_inst_8/main1.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_8/main2.k b/crates/cmd/src/test_data/instances/test_inst_8/main2.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_8/main2.k rename to crates/cmd/src/test_data/instances/test_inst_8/main2.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_81/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_8/test_inst_81/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_81/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_8/test_inst_81/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_81/main.k b/crates/cmd/src/test_data/instances/test_inst_8/test_inst_81/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_81/main.k rename to crates/cmd/src/test_data/instances/test_inst_8/test_inst_81/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_82/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_8/test_inst_82/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_82/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_8/test_inst_82/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_82/main.k b/crates/cmd/src/test_data/instances/test_inst_8/test_inst_82/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_82/main.k rename to crates/cmd/src/test_data/instances/test_inst_8/test_inst_82/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_83/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_8/test_inst_83/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_83/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_8/test_inst_83/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_83/main.k b/crates/cmd/src/test_data/instances/test_inst_8/test_inst_83/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_83/main.k rename to crates/cmd/src/test_data/instances/test_inst_8/test_inst_83/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_84/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_8/test_inst_84/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_84/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_8/test_inst_84/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_84/main.k b/crates/cmd/src/test_data/instances/test_inst_8/test_inst_84/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_8/test_inst_84/main.k rename to crates/cmd/src/test_data/instances/test_inst_8/test_inst_84/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_9/expected b/crates/cmd/src/test_data/instances/test_inst_9/expected similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_9/expected rename to crates/cmd/src/test_data/instances/test_inst_9/expected diff --git a/kclvm/cmd/src/test_data/instances/test_inst_9/kcl.yaml b/crates/cmd/src/test_data/instances/test_inst_9/kcl.yaml similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_9/kcl.yaml rename to crates/cmd/src/test_data/instances/test_inst_9/kcl.yaml diff --git a/kclvm/cmd/src/test_data/instances/test_inst_9/test_inst_91/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_9/test_inst_91/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_9/test_inst_91/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_9/test_inst_91/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_9/test_inst_91/main.k b/crates/cmd/src/test_data/instances/test_inst_9/test_inst_91/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_9/test_inst_91/main.k rename to crates/cmd/src/test_data/instances/test_inst_9/test_inst_91/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_9/test_inst_92/kcl.mod b/crates/cmd/src/test_data/instances/test_inst_9/test_inst_92/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_9/test_inst_92/kcl.mod rename to crates/cmd/src/test_data/instances/test_inst_9/test_inst_92/kcl.mod diff --git a/kclvm/cmd/src/test_data/instances/test_inst_9/test_inst_92/main.k b/crates/cmd/src/test_data/instances/test_inst_9/test_inst_92/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_9/test_inst_92/main.k rename to crates/cmd/src/test_data/instances/test_inst_9/test_inst_92/main.k diff --git a/kclvm/cmd/src/test_data/instances/test_inst_9/test_inst_92/sub/main.k b/crates/cmd/src/test_data/instances/test_inst_9/test_inst_92/sub/main.k similarity index 100% rename from kclvm/cmd/src/test_data/instances/test_inst_9/test_inst_92/sub/main.k rename to crates/cmd/src/test_data/instances/test_inst_9/test_inst_92/sub/main.k diff --git a/kclvm/cmd/src/test_data/lint/test.k b/crates/cmd/src/test_data/lint/test.k similarity index 100% rename from kclvm/cmd/src/test_data/lint/test.k rename to crates/cmd/src/test_data/lint/test.k diff --git a/kclvm/cmd/src/test_data/multimod/kcl1/kcl.mod b/crates/cmd/src/test_data/multimod/kcl1/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/multimod/kcl1/kcl.mod rename to crates/cmd/src/test_data/multimod/kcl1/kcl.mod diff --git a/kclvm/cmd/src/test_data/multimod/kcl1/main.k b/crates/cmd/src/test_data/multimod/kcl1/main.k similarity index 100% rename from kclvm/cmd/src/test_data/multimod/kcl1/main.k rename to crates/cmd/src/test_data/multimod/kcl1/main.k diff --git a/kclvm/cmd/src/test_data/multimod/kcl2/kcl.mod b/crates/cmd/src/test_data/multimod/kcl2/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/multimod/kcl2/kcl.mod rename to crates/cmd/src/test_data/multimod/kcl2/kcl.mod diff --git a/kclvm/cmd/src/test_data/multimod/kcl2/main.k b/crates/cmd/src/test_data/multimod/kcl2/main.k similarity index 100% rename from kclvm/cmd/src/test_data/multimod/kcl2/main.k rename to crates/cmd/src/test_data/multimod/kcl2/main.k diff --git a/kclvm/cmd/src/test_data/multimod/kcl3/kcl.mod b/crates/cmd/src/test_data/multimod/kcl3/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/multimod/kcl3/kcl.mod rename to crates/cmd/src/test_data/multimod/kcl3/kcl.mod diff --git a/kclvm/cmd/src/test_data/multimod/kcl3/kcl4/kcl.mod b/crates/cmd/src/test_data/multimod/kcl3/kcl4/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/multimod/kcl3/kcl4/kcl.mod rename to crates/cmd/src/test_data/multimod/kcl3/kcl4/kcl.mod diff --git a/kclvm/cmd/src/test_data/multimod/kcl3/kcl4/main.k b/crates/cmd/src/test_data/multimod/kcl3/kcl4/main.k similarity index 100% rename from kclvm/cmd/src/test_data/multimod/kcl3/kcl4/main.k rename to crates/cmd/src/test_data/multimod/kcl3/kcl4/main.k diff --git a/kclvm/cmd/src/test_data/multimod/kcl3/main.k b/crates/cmd/src/test_data/multimod/kcl3/main.k similarity index 100% rename from kclvm/cmd/src/test_data/multimod/kcl3/main.k rename to crates/cmd/src/test_data/multimod/kcl3/main.k diff --git a/kclvm/cmd/src/test_data/plugin/plugin_not_found/kcl.mod b/crates/cmd/src/test_data/plugin/plugin_not_found/kcl.mod similarity index 100% rename from kclvm/cmd/src/test_data/plugin/plugin_not_found/kcl.mod rename to crates/cmd/src/test_data/plugin/plugin_not_found/kcl.mod diff --git a/kclvm/cmd/src/test_data/plugin/plugin_not_found/main.k b/crates/cmd/src/test_data/plugin/plugin_not_found/main.k similarity index 100% rename from kclvm/cmd/src/test_data/plugin/plugin_not_found/main.k rename to crates/cmd/src/test_data/plugin/plugin_not_found/main.k diff --git a/kclvm/cmd/src/test_data/settings/kcl.yaml b/crates/cmd/src/test_data/settings/kcl.yaml similarity index 100% rename from kclvm/cmd/src/test_data/settings/kcl.yaml rename to crates/cmd/src/test_data/settings/kcl.yaml diff --git a/kclvm/cmd/src/test_data/sym_link/origin/a.k b/crates/cmd/src/test_data/sym_link/origin/a.k similarity index 100% rename from kclvm/cmd/src/test_data/sym_link/origin/a.k rename to crates/cmd/src/test_data/sym_link/origin/a.k diff --git a/kclvm/cmd/src/test_data/sym_link/origin/sub/a.k b/crates/cmd/src/test_data/sym_link/origin/sub/a.k similarity index 100% rename from kclvm/cmd/src/test_data/sym_link/origin/sub/a.k rename to crates/cmd/src/test_data/sym_link/origin/sub/a.k diff --git a/kclvm/cmd/src/test_data/vet/data.json b/crates/cmd/src/test_data/vet/data.json similarity index 100% rename from kclvm/cmd/src/test_data/vet/data.json rename to crates/cmd/src/test_data/vet/data.json diff --git a/kclvm/cmd/src/test_data/vet/test.k b/crates/cmd/src/test_data/vet/test.k similarity index 100% rename from kclvm/cmd/src/test_data/vet/test.k rename to crates/cmd/src/test_data/vet/test.k diff --git a/crates/cmd/src/tests.rs b/crates/cmd/src/tests.rs new file mode 100644 index 000000000..7e676492a --- /dev/null +++ b/crates/cmd/src/tests.rs @@ -0,0 +1,572 @@ +use std::{ + env, + fs::{self, remove_file}, + path::{Path, PathBuf}, + sync::Arc, +}; + +use kcl_config::modfile::KCL_PKG_PATH; +use kcl_parser::ParseSession; +use kcl_runner::{MapErrorResult, exec_program}; + +use crate::{ + app, + run::run_command, + settings::{build_settings, must_build_settings}, + util::hashmaps_from_matches, +}; + +#[cfg(unix)] +use std::os::unix::fs::symlink; +#[cfg(windows)] +use std::os::windows::fs::symlink_file as symlink; + +const ROOT_CMD: &str = "libkcl"; + +#[test] +fn test_build_settings() { + let work_dir = work_dir(); + let matches = app().get_matches_from(settings_arguments(work_dir.join("kcl.yaml"))); + let matches = matches.subcommand_matches("run").unwrap(); + let s = build_settings(matches).unwrap(); + // Testing work directory + assert_eq!(s.path().as_ref().unwrap().to_str(), work_dir.to_str()); + // Testing CLI configs + assert_eq!( + s.settings().kcl_cli_configs.as_ref().unwrap().files, + Some(vec!["hello.k".to_string()]) + ); + assert_eq!( + s.settings().kcl_cli_configs.as_ref().unwrap().disable_none, + Some(true) + ); + assert_eq!( + s.settings() + .kcl_cli_configs + .as_ref() + .unwrap() + .strict_range_check, + Some(true) + ); + assert_eq!( + s.settings().kcl_cli_configs.as_ref().unwrap().overrides, + Some(vec!["c.a=1".to_string(), "c.b=1".to_string(),]) + ); + assert_eq!( + s.settings().kcl_cli_configs.as_ref().unwrap().path_selector, + Some(vec!["a.b.c".to_string()]) + ); + assert_eq!(s.settings().input(), vec!["hello.k".to_string()]); +} + +#[test] +fn test_build_settings_fail() { + let matches = app().get_matches_from(settings_arguments(work_dir().join("error_kcl.yaml"))); + let matches = matches.subcommand_matches("run").unwrap(); + assert!(build_settings(matches).is_err()); +} + +fn work_dir() -> std::path::PathBuf { + std::path::Path::new(".") + .join("src") + .join("test_data") + .join("settings") +} + +fn settings_arguments(path: std::path::PathBuf) -> Vec { + vec![ + ROOT_CMD.to_string(), + "run".to_string(), + "-Y".to_string(), + path.to_str().unwrap().to_string(), + "-r".to_string(), + "-O".to_string(), + "c.a=1".to_string(), + "-O".to_string(), + "c.b=1".to_string(), + "-S".to_string(), + "a.b.c".to_string(), + ] +} + +#[test] +fn test_external_cmd() { + let matches = app().get_matches_from(&[ROOT_CMD, "run", "-E", "test_name=test_path"]); + let matches = matches.subcommand_matches("run").unwrap(); + let pair = hashmaps_from_matches(matches, "package_map") + .unwrap() + .unwrap(); + assert_eq!(pair.len(), 1); + assert!(pair.contains_key("test_name")); + assert_eq!(pair.get("test_name").unwrap(), "test_path"); +} + +#[test] +fn test_version_cmd() { + let matches = app().get_matches_from(&[ROOT_CMD, "version"]); + assert!(matches.subcommand_matches("version").is_some()) +} + +#[test] +fn test_multi_external_cmd() { + let matches = app().get_matches_from(&[ + ROOT_CMD, + "run", + "-E", + "test_name=test_path", + "-E", + "test_name1=test_path1", + ]); + let matches = matches.subcommand_matches("run").unwrap(); + let pair = hashmaps_from_matches(matches, "package_map") + .unwrap() + .unwrap(); + + assert_eq!(pair.len(), 2); + assert!(pair.contains_key("test_name")); + assert!(pair.contains_key("test_name1")); + assert_eq!(pair.get("test_name").unwrap(), "test_path"); + assert_eq!(pair.get("test_name1").unwrap(), "test_path1"); +} + +#[test] +fn test_multi_external_with_same_key_cmd() { + let matches = app().get_matches_from(&[ + ROOT_CMD, + "run", + "-E", + "test_name=test_path", + "-E", + "test_name=test_path1", + ]); + let matches = matches.subcommand_matches("run").unwrap(); + let pair = hashmaps_from_matches(matches, "package_map") + .unwrap() + .unwrap(); + assert_eq!(pair.len(), 1); + assert!(pair.contains_key("test_name")); + assert_eq!(pair.get("test_name").unwrap(), "test_path1"); +} + +#[test] +fn test_external_cmd_invalid() { + let invalid_cases: [&str; 5] = [ + "test_nametest_path", + "test_name=test_path=test_suffix", + "=test_path", + "test_name=", + "=test_name=test_path=", + ]; + for case in invalid_cases { + let matches = app().get_matches_from(&[ROOT_CMD, "run", "-E", case]); + let matches = matches.subcommand_matches("run").unwrap(); + match hashmaps_from_matches(matches, "package_map").unwrap() { + Ok(_) => { + panic!("unreachable code.") + } + Err(err) => { + assert!(format!("{:?}", err).contains("Invalid value for top level arguments")); + } + }; + } +} + +#[test] +#[cfg(not(windows))] +// All the unit test cases in [`test_run_command`] can not be executed concurrently. +fn test_run_command() { + test_run_command_with_import(); + test_load_cache_with_different_pkg(); + test_kcl_path_is_sym_link(); + test_compile_two_kcl_mod(); + test_main_pkg_not_found(); + test_multi_mod_file(); + test_instances_with_yaml(); + test_plugin_not_found(); + test_error_message_fuzz_matched(); + test_error_message_fuzz_unmatched(); + test_keyword_argument_error_message(); +} + +fn test_run_command_with_import() { + let vendor_path = PathBuf::from("./src/test_data/cases/vendor"); + + let test_cases = vec!["import_1"]; + let test_case_root = PathBuf::from("./src/test_data/cases") + .canonicalize() + .unwrap(); + + for test_case in test_cases { + check_run_command_with_env( + test_case_root.join(test_case), + vendor_path.canonicalize().unwrap().display().to_string(), + ); + } +} + +fn test_load_cache_with_different_pkg() { + let main_path = PathBuf::from("./src/test_data/cache/main/main.k"); + let main_v1_path = PathBuf::from("./src/test_data/cache/main/main.k.v1"); + let main_v2_path = PathBuf::from("./src/test_data/cache/main/main.k.v2"); + let kcl1_v1_path = PathBuf::from("./src/test_data/cache/v1/kcl1"); + let kcl1_v2_path = PathBuf::from("./src/test_data/cache/v2/kcl1"); + + // Copy the content from main.k.v1 to main.k + fs::copy(main_v1_path, &main_path).unwrap(); + let matches = app().get_matches_from(&[ + ROOT_CMD, + "run", + main_path.to_str().unwrap(), + "-E", + format!("kcl1={}", kcl1_v1_path.display()).as_str(), + ]); + + let matches = matches.subcommand_matches("run").unwrap(); + let mut buf = Vec::new(); + run_command(matches, &mut buf).unwrap(); + assert_eq!( + String::from_utf8(buf).unwrap(), + "The_first_kcl_program: 1\n" + ); + + // Copy the content from main.k.v2 to main.k + fs::copy(main_v2_path, &main_path).unwrap(); + let matches = app().get_matches_from(&[ + ROOT_CMD, + "run", + main_path.to_str().unwrap(), + "-E", + format!("kcl1={}", kcl1_v2_path.display()).as_str(), + ]); + + let matches = matches.subcommand_matches("run").unwrap(); + let mut buf = Vec::new(); + run_command(matches, &mut buf).unwrap(); + assert_eq!( + String::from_utf8(buf).unwrap(), + "The_first_kcl_program: 1\nkcl1_schema:\n name: kcl1\n" + ); +} + +/// rust crate [`gag`]: https://crates.io/crates/gag +/// allows redirecting stderr or stdout either to a file or to nothing, +/// but it only works on unix systems. +/// After [`gag`] can better support windows in the future, it may be considered to test the `println!`. +fn check_run_command_with_env(test_case_path: PathBuf, kcl_pkg_path_env: String) { + unsafe { env::set_var(KCL_PKG_PATH, kcl_pkg_path_env) }; + + let test_case_expect_file = test_case_path.join("stdout").display().to_string(); + let expect = fs::read_to_string(test_case_expect_file).expect("Unable to read file"); + + let matches = app().arg_required_else_help(true).get_matches_from(&[ + ROOT_CMD, + "run", + &test_case_path.join("main.k").display().to_string(), + ]); + + let mut buf = Vec::new(); + run_command(matches.subcommand_matches("run").unwrap(), &mut buf).unwrap(); + + #[cfg(target_os = "windows")] + let expect = expect.replace("\r\n", "\n"); + assert_eq!(String::from_utf8(buf).unwrap(), expect); +} + +fn test_kcl_path_is_sym_link() { + let origin = "./src/test_data/sym_link/origin"; + let link = "./src/test_data/sym_link/sym_link"; + + let origin_k_file_path = PathBuf::from(origin).join("a.k"); + let origin_matches = app().arg_required_else_help(true).get_matches_from(&[ + ROOT_CMD, + "run", + origin_k_file_path.to_str().unwrap(), + ]); + + let mut origin_res = Vec::new(); + run_command( + origin_matches.subcommand_matches("run").unwrap(), + &mut origin_res, + ) + .unwrap(); + + // Create a symlink + symlink( + PathBuf::from(origin).canonicalize().unwrap(), + Path::new(link), + ) + .unwrap(); + + let sym_link_k_file_path = PathBuf::from(link).join("a.k"); + let mut sym_link_res = Vec::new(); + let sym_link_matches = app().arg_required_else_help(true).get_matches_from(&[ + ROOT_CMD, + "run", + sym_link_k_file_path.to_str().unwrap(), + ]); + run_command( + sym_link_matches.subcommand_matches("run").unwrap(), + &mut sym_link_res, + ) + .unwrap(); + + // compare the result from origin kcl path and symlink kcl path. + assert_eq!( + String::from_utf8(sym_link_res), + String::from_utf8(origin_res) + ); + + // clean up the symlink + remove_file(link).unwrap(); +} + +fn test_compile_two_kcl_mod() { + let test_case_path = PathBuf::from("./src/test_data/multimod"); + + let matches = app().arg_required_else_help(true).get_matches_from(&[ + ROOT_CMD, + "run", + &test_case_path.join("kcl1/main.k").display().to_string(), + "${kcl2:KCL_MOD}/main.k", + "-E", + &format!("kcl2={}", test_case_path.join("kcl2").display().to_string()), + ]); + + let mut buf = Vec::new(); + run_command(matches.subcommand_matches("run").unwrap(), &mut buf).unwrap(); + + assert_eq!( + "kcl1: hello 1\nkcl2: hello 2\n", + String::from_utf8(buf).unwrap() + ); + + let matches = app().arg_required_else_help(true).get_matches_from(&[ + ROOT_CMD, + "run", + &test_case_path.join("kcl2/main.k").display().to_string(), + "${kcl1:KCL_MOD}/main.k", + "-E", + &format!("kcl1={}", test_case_path.join("kcl1").display().to_string()), + ]); + + let mut buf = Vec::new(); + run_command(matches.subcommand_matches("run").unwrap(), &mut buf).unwrap(); + + assert_eq!( + "kcl2: hello 2\nkcl1: hello 1\n", + String::from_utf8(buf).unwrap() + ); + + let matches = app().arg_required_else_help(true).get_matches_from(&[ + ROOT_CMD, + "run", + &test_case_path.join("kcl3/main.k").display().to_string(), + "${kcl4:KCL_MOD}/main.k", + "-E", + &format!( + "kcl4={}", + test_case_path + .join("kcl3") + .join("kcl4") + .display() + .to_string() + ), + ]); + + let mut buf = Vec::new(); + run_command(matches.subcommand_matches("run").unwrap(), &mut buf).unwrap(); + + assert_eq!( + "k3: Hello World 3\nk4: Hello World 4\n", + String::from_utf8(buf).unwrap() + ); + + let matches = app().arg_required_else_help(true).get_matches_from(&[ + ROOT_CMD, + "run", + &test_case_path + .join("kcl3/kcl4/main.k") + .display() + .to_string(), + "${kcl3:KCL_MOD}/main.k", + "-E", + &format!("kcl3={}", test_case_path.join("kcl3").display().to_string()), + ]); + + let mut buf = Vec::new(); + run_command(matches.subcommand_matches("run").unwrap(), &mut buf).unwrap(); + + assert_eq!( + "k4: Hello World 4\nk3: Hello World 3\n", + String::from_utf8(buf).unwrap() + ); +} + +fn test_instances_with_yaml() { + let test_cases = [ + "test_inst_1", + "test_inst_2", + "test_inst_3", + "test_inst_4", + "test_inst_5", + "test_inst_6", + "test_inst_7", + "test_inst_8", + "test_inst_9", + "test_inst_10", + "test_inst_11/test_inst_111", + ]; + + for case in &test_cases { + let expected = format!("{}/expected", case); + let case_yaml = format!("{}/kcl.yaml", case); + test_instances(&case_yaml, &expected); + } +} + +fn test_instances(kcl_yaml_path: &str, expected_file_path: &str) { + let test_case_path = PathBuf::from("./src/test_data/instances"); + let matches = app().arg_required_else_help(true).get_matches_from(&[ + ROOT_CMD, + "run", + "-Y", + &test_case_path.join(kcl_yaml_path).display().to_string(), + ]); + + let mut buf = Vec::new(); + run_command(matches.subcommand_matches("run").unwrap(), &mut buf).unwrap(); + let expect = fs::read_to_string( + test_case_path + .join(expected_file_path) + .display() + .to_string(), + ) + .unwrap(); + + assert_eq!( + expect.replace("\r\n", "\n"), + String::from_utf8(buf).unwrap() + ); +} + +fn test_main_pkg_not_found() { + let test_case_path = PathBuf::from("./src/test_data/multimod"); + + let matches = app().arg_required_else_help(true).get_matches_from(&[ + ROOT_CMD, + "run", + "${kcl3:KCL_MOD}/main.k", + "-E", + &format!("kcl3={}", test_case_path.join("kcl3").display().to_string()), + ]); + let settings = must_build_settings(matches.subcommand_matches("run").unwrap()); + let sess = Arc::new(ParseSession::default()); + match exec_program(sess.clone(), &settings.try_into().unwrap()) + .map_err_to_result() + .map_err(|e| e.to_string()) + { + Ok(_) => panic!("unreachable code."), + Err(msg) => assert_eq!( + msg, + "Cannot find the kcl file, please check the file path ${kcl3:KCL_MOD}/main.k" + ), + } +} + +fn test_multi_mod_file() { + let test_case_path = PathBuf::from("./src/test_data/multimod"); + + let matches = app().arg_required_else_help(true).get_matches_from(&[ + ROOT_CMD, + "run", + &test_case_path.join("kcl1").display().to_string(), + &test_case_path.join("kcl2").display().to_string(), + ]); + let settings = must_build_settings(matches.subcommand_matches("run").unwrap()); + let sess = Arc::new(ParseSession::default()); + match exec_program(sess.clone(), &settings.try_into().unwrap()) { + Ok(res) => { + assert_eq!(res.yaml_result, "kcl1: hello 1\nkcl2: hello 2"); + assert_eq!( + res.json_result, + "{\"kcl1\": \"hello 1\", \"kcl2\": \"hello 2\"}" + ); + } + Err(_) => panic!("unreachable code."), + } +} + +fn test_plugin_not_found() { + let test_case_path = PathBuf::from("./src/test_data/plugin/plugin_not_found"); + let matches = app().arg_required_else_help(true).get_matches_from(&[ + ROOT_CMD, + "run", + test_case_path.as_path().display().to_string().as_str(), + ]); + let settings = must_build_settings(matches.subcommand_matches("run").unwrap()); + let sess = Arc::new(ParseSession::default()); + match exec_program(sess.clone(), &settings.try_into().unwrap()).map_err_to_result().map_err(|e|e.to_string()) { + Ok(_) => panic!("unreachable code."), + Err(msg) => assert!(msg.contains("the plugin package `kcl_plugin.not_exist` is not found, please confirm if plugin mode is enabled")), + } +} + +fn test_error_message_fuzz_matched() { + let test_case_path = PathBuf::from("./src/test_data/fuzz_match/main.k"); + let matches = app().arg_required_else_help(true).get_matches_from(&[ + ROOT_CMD, + "run", + &test_case_path.canonicalize().unwrap().display().to_string(), + ]); + let settings = must_build_settings(matches.subcommand_matches("run").unwrap()); + let sess = Arc::new(ParseSession::default()); + match exec_program(sess.clone(), &settings.try_into().unwrap()) + .map_err_to_result() + .map_err(|e| e.to_string()) + { + Ok(_) => panic!("unreachable code."), + Err(msg) => { + assert!(msg.contains("attribute 'a' not found in 'Person', did you mean '[\"aa\"]'?")) + } + } +} + +fn test_error_message_fuzz_unmatched() { + let test_case_path = PathBuf::from("./src/test_data/fuzz_match/main_unmatched.k"); + let matches = app().arg_required_else_help(true).get_matches_from(&[ + ROOT_CMD, + "run", + &test_case_path.canonicalize().unwrap().display().to_string(), + ]); + let settings = must_build_settings(matches.subcommand_matches("run").unwrap()); + let sess = Arc::new(ParseSession::default()); + match exec_program(sess.clone(), &settings.try_into().unwrap()) + .map_err_to_result() + .map_err(|e| e.to_string()) + { + Ok(_) => panic!("unreachable code."), + Err(msg) => { + assert!(msg.contains("attribute 'a' not found in 'Person'")) + } + } +} + +fn test_keyword_argument_error_message() { + let test_case_path = PathBuf::from("./src/test_data/failed/keyword_argument_error.k"); + let matches = app().arg_required_else_help(true).get_matches_from(&[ + ROOT_CMD, + "run", + &test_case_path.canonicalize().unwrap().display().to_string(), + ]); + let settings = must_build_settings(matches.subcommand_matches("run").unwrap()); + let sess = Arc::new(ParseSession::default()); + match exec_program(sess.clone(), &settings.try_into().unwrap()) + .map_err_to_result() + .map_err(|e| e.to_string()) + { + Ok(_) => panic!("unreachable code."), + Err(msg) => { + assert!(msg.contains("keyword argument 'ID' not found")); + } + } +} diff --git a/kclvm/cmd/src/util.rs b/crates/cmd/src/util.rs similarity index 100% rename from kclvm/cmd/src/util.rs rename to crates/cmd/src/util.rs diff --git a/crates/compiler/Cargo.toml b/crates/compiler/Cargo.toml new file mode 100644 index 000000000..e335f1462 --- /dev/null +++ b/crates/compiler/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "kcl-compiler" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +time = "0.2.23" +phf = { version = "0.9", features = ["macros"] } +bit-set = "0.5.0" +bitflags = "1.2.1" +once_cell = "1.5.2" +fancy-regex = "0.7.1" +unicode_names2 = "0.4" +kcl-ast = { path = "../ast" } +kcl-sema = { path = "../sema" } +kcl-runtime = { path = "../runtime" } +kcl-error = { path = "../error" } +kcl-primitives = { path = "../primitives" } diff --git a/kclvm/compiler/src/codegen/abi.rs b/crates/compiler/src/codegen/abi.rs similarity index 100% rename from kclvm/compiler/src/codegen/abi.rs rename to crates/compiler/src/codegen/abi.rs diff --git a/kclvm/compiler/src/codegen/error.rs b/crates/compiler/src/codegen/error.rs similarity index 100% rename from kclvm/compiler/src/codegen/error.rs rename to crates/compiler/src/codegen/error.rs diff --git a/crates/compiler/src/codegen/mod.rs b/crates/compiler/src/codegen/mod.rs new file mode 100644 index 000000000..bbff000ab --- /dev/null +++ b/crates/compiler/src/codegen/mod.rs @@ -0,0 +1,55 @@ +//! Copyright The KCL Authors. All rights reserved. + +mod abi; +pub mod error; +mod traits; + +/// The kcl runner main function name. +pub const MODULE_NAME: &str = "kcl_main"; +/// The kcl runner main function entry block name. +pub const ENTRY_NAME: &str = "entry"; +/// The kcl runtime value type name. +pub const VALUE_TYPE_NAME: &str = "kcl_value_ref_t"; +/// The kcl runtime context type name. +pub const CONTEXT_TYPE_NAME: &str = "kcl_context_t"; +/// The kcl runtime evaluation type name. +pub const SCOPE_TYPE_NAME: &str = "kcl_eval_scope_t"; +/// Package init function name suffix +pub const PKG_INIT_FUNCTION_SUFFIX: &str = "init"; +/// Global level +pub const GLOBAL_LEVEL: usize = 1; +/// Inner level +pub const INNER_LEVEL: usize = 2; +/// Global variable alignment +pub const GLOBAL_VAL_ALIGNMENT: u32 = 8; +/// Object file type format suffix. +#[cfg(target_os = "windows")] +pub const OBJECT_FILE_SUFFIX: &str = ".obj"; +#[cfg(not(target_os = "windows"))] +pub const OBJECT_FILE_SUFFIX: &str = ".o"; +/// LLVM IR text format suffix .ll +pub const LL_FILE_SUFFIX: &str = ".ll"; + +/// CodeGenContext is a trait used by the compiler to emit code to different targets. +pub trait CodeGenContext: traits::ProgramCodeGen { + fn emit(&self, opt: &EmitOptions) -> Result<(), Box>; +} + +/// EmitOptions represents the general emit options +#[derive(Debug, Default)] +pub struct EmitOptions<'a> { + /// Path to load exist module, if not set, create an empty module. + pub from_path: Option<&'a str>, + /// Path to emit module. + pub emit_path: Option<&'a str>, + /// no_link indicates whether to link the generated code of different KCL packages to the same module. + pub no_link: bool, +} + +/// Emit code with the options using CodeGenContext. +pub fn emit_code_with( + ctx: impl CodeGenContext, + opt: &EmitOptions, +) -> Result<(), Box> { + ctx.emit(opt) +} diff --git a/kclvm/compiler/src/codegen/traits/backend.rs b/crates/compiler/src/codegen/traits/backend.rs similarity index 100% rename from kclvm/compiler/src/codegen/traits/backend.rs rename to crates/compiler/src/codegen/traits/backend.rs diff --git a/kclvm/compiler/src/codegen/traits/builder.rs b/crates/compiler/src/codegen/traits/builder.rs similarity index 100% rename from kclvm/compiler/src/codegen/traits/builder.rs rename to crates/compiler/src/codegen/traits/builder.rs diff --git a/kclvm/compiler/src/codegen/traits/mod.rs b/crates/compiler/src/codegen/traits/mod.rs similarity index 100% rename from kclvm/compiler/src/codegen/traits/mod.rs rename to crates/compiler/src/codegen/traits/mod.rs diff --git a/kclvm/compiler/src/codegen/traits/type.rs b/crates/compiler/src/codegen/traits/type.rs similarity index 100% rename from kclvm/compiler/src/codegen/traits/type.rs rename to crates/compiler/src/codegen/traits/type.rs diff --git a/kclvm/compiler/src/codegen/traits/value.rs b/crates/compiler/src/codegen/traits/value.rs similarity index 100% rename from kclvm/compiler/src/codegen/traits/value.rs rename to crates/compiler/src/codegen/traits/value.rs diff --git a/crates/compiler/src/lib.rs b/crates/compiler/src/lib.rs new file mode 100644 index 000000000..faf4b5fd7 --- /dev/null +++ b/crates/compiler/src/lib.rs @@ -0,0 +1,7 @@ +//! Copyright The KCL Authors. All rights reserved. + +pub mod codegen; +pub mod value; + +#[macro_use] +mod macros; diff --git a/kclvm/compiler/src/macros.rs b/crates/compiler/src/macros.rs similarity index 100% rename from kclvm/compiler/src/macros.rs rename to crates/compiler/src/macros.rs diff --git a/crates/compiler/src/value/lambda.rs b/crates/compiler/src/value/lambda.rs new file mode 100644 index 000000000..21ab6944e --- /dev/null +++ b/crates/compiler/src/value/lambda.rs @@ -0,0 +1,4 @@ +//! Copyright The KCL Authors. All rights reserved. + +pub const LAMBDA_NAME: &str = "kcl_lambda"; +pub const LAMBDA_CLOSURE: &str = "$lambda_closure"; diff --git a/kclvm/compiler/src/value/mod.rs b/crates/compiler/src/value/mod.rs similarity index 100% rename from kclvm/compiler/src/value/mod.rs rename to crates/compiler/src/value/mod.rs diff --git a/crates/compiler/src/value/schema.rs b/crates/compiler/src/value/schema.rs new file mode 100644 index 000000000..f5278ac58 --- /dev/null +++ b/crates/compiler/src/value/schema.rs @@ -0,0 +1,49 @@ +//! Copyright The KCL Authors. All rights reserved. + +pub const SCHEMA_NAME: &str = "$kcl_schema"; +pub const SCHEMA_ATTR_NAME: &str = "$kcl_schema_attr"; +pub const SCHEMA_CHECK_BLOCK_NAME: &str = "$kcl_schema_check_block"; +pub const SCHEMA_SELF_NAME: &str = "$schema_self"; +pub const SCHEMA_CONFIG_NAME: &str = "$schema_config"; +pub const SCHEMA_CONFIG_META_NAME: &str = "$schema_config_meta"; +pub const SCHEMA_CAL_MAP: &str = "$schema_cal_map"; +pub const SCHEMA_ARGS: &str = "$schema_args"; +pub const SCHEMA_KWARGS: &str = "$schema_kwargs"; +pub const SCHEMA_RUNTIME_TYPE: &str = "$schema_runtime_type"; +pub const SCHEMA_VARIABLE_LIST: &[&str] = &[ + BACKTRACK_CACHE, + BACKTRACK_LEVEL_MAP, + SCHEMA_CAL_MAP, + SCHEMA_CONFIG_NAME, + SCHEMA_CONFIG_META_NAME, + SCHEMA_SELF_NAME, + SCHEMA_ARGS, + SCHEMA_KWARGS, + SCHEMA_RUNTIME_TYPE, +]; +pub const BACKTRACK_LEVEL_MAP: &str = "$backtrack_level_map"; +pub const BACKTRACK_CACHE: &str = "$backtrack_cache"; +pub const GLOBAL_SETTER: &str = "$set"; + +/// KCL schema type +pub struct SchemaType { + pub name: String, + pub pkgpath: String, + pub runtime_type: String, + pub is_mixin: bool, + pub is_protocol: bool, + pub is_rule: bool, +} + +impl SchemaType { + pub fn new(name: &str, pkgpath: &str, runtime_type: &str, is_mixin: bool) -> SchemaType { + SchemaType { + name: name.to_string(), + pkgpath: pkgpath.to_string(), + runtime_type: runtime_type.to_string(), + is_mixin, + is_protocol: false, + is_rule: false, + } + } +} diff --git a/crates/config/Cargo.toml b/crates/config/Cargo.toml new file mode 100644 index 000000000..b52066260 --- /dev/null +++ b/crates/config/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "kcl-config" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_yaml_ng = "0.10.0" +serde_json = "1.0" +toml = "0.5.8" +ron = "0.7.0" +chrono = "0.4.19" +glob = "0.3.0" +pathdiff = "0.2.1" +anyhow = "1.0" + +kcl-version = {path = "../version"} +kcl-utils = {path = "../utils"} +kcl-ast = {path = "../ast"} +dirs = "5.0.0" +md-5 = "0.8.0" +regex = "1.10.4" +url = "2.5.4" diff --git a/kclvm/config/src/cache.rs b/crates/config/src/cache.rs similarity index 97% rename from kclvm/config/src/cache.rs rename to crates/config/src/cache.rs index adf1b5bc5..5c3c1529f 100644 --- a/kclvm/config/src/cache.rs +++ b/crates/config/src/cache.rs @@ -2,20 +2,20 @@ extern crate chrono; use super::modfile::KCL_FILE_SUFFIX; use anyhow::Result; -use kclvm_utils::fslock::open_lock_file; -use kclvm_utils::pkgpath::{parse_external_pkg_name, rm_external_pkg_name}; +use kcl_utils::fslock::open_lock_file; +use kcl_utils::pkgpath::{parse_external_pkg_name, rm_external_pkg_name}; use md5::{Digest, Md5}; -use serde::{de::DeserializeOwned, Serialize}; +use serde::{Serialize, de::DeserializeOwned}; use std::collections::HashMap; use std::error; -use std::fs::{create_dir_all, File}; +use std::fs::{File, create_dir_all}; use std::io::{Read, Write}; use std::path::Path; -use kclvm_version as version; +use kcl_version as version; const LOCK_SUFFIX: &str = ".lock"; -const DEFAULT_CACHE_DIR: &str = ".kclvm/cache"; +const DEFAULT_CACHE_DIR: &str = ".kcl/cache"; const CACHE_INFO_FILENAME: &str = "info"; const KCL_SUFFIX_PATTERN: &str = "*.k"; pub const KCL_CACHE_PATH_ENV_VAR: &str = "KCL_CACHE_PATH"; diff --git a/kclvm/config/src/lib.rs b/crates/config/src/lib.rs similarity index 100% rename from kclvm/config/src/lib.rs rename to crates/config/src/lib.rs diff --git a/kclvm/config/src/modfile.rs b/crates/config/src/modfile.rs similarity index 99% rename from kclvm/config/src/modfile.rs rename to crates/config/src/modfile.rs index 3c5410d2b..d36d9ed12 100644 --- a/kclvm/config/src/modfile.rs +++ b/crates/config/src/modfile.rs @@ -1,7 +1,7 @@ //! Copyright The KCL Authors. All rights reserved. use anyhow::Result; -use kclvm_utils::path::PathPrefix; +use kcl_utils::path::PathPrefix; use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, diff --git a/crates/config/src/path.rs b/crates/config/src/path.rs new file mode 100644 index 000000000..edbae6c75 --- /dev/null +++ b/crates/config/src/path.rs @@ -0,0 +1,201 @@ +//! The file provides the mod relative path type. +//! +//! The mod relative path is a path that is relative to the root package path. +//! The root package is can be specified by the prefix `${:KCL_MOD}`. +//! `` is the name of the root package. +//! If `` is omitted, the root package is the current package. +//! +//! # Examples +//! +//! `/usr/my_pkg` is the real path of the package `my_pkg`. +//! `${my_pkg:KCL_MOD}/sub/main.k` is a mod relative path. +//! The real path of `${my_pkg:KCL_MOD}/xxx/main.k` is `/usr/my_pkg/sub/main.k`. +use anyhow::Result; +use regex::Regex; +use std::path::PathBuf; + +#[derive(Clone, Debug, Default)] +/// [`ModRelativePath`] is a path that is relative to the root package path. +/// The root package is can be specified by the prefix `${:KCL_MOD}`. +/// `` is the name of the root package. +/// If `` is omitted, the root package is the current package. +/// +/// # Examples +/// +/// `/usr/my_pkg` is the real path of the package `my_pkg`. +/// `${my_pkg:KCL_MOD}/sub/main.k` is a mod relative path. +/// The real path of `${my_pkg:KCL_MOD}/xxx/main.k` is `/usr/my_pkg/sub/main.k`. +pub struct ModRelativePath { + path: String, +} + +/// The regular expression to match the mod relative path preffix. +const RELATIVE_PATH_PREFFIX: &str = r#"\$\{((?P[a-zA-Z0-9_-]+):)?KCL_MOD\}/"#; + +/// The name of the root package. +const ROOT_PKG_NAME_FLAG: &str = "name"; + +impl From for ModRelativePath { + fn from(path: String) -> Self { + ModRelativePath::new(path) + } +} + +impl ModRelativePath { + /// [`new`] creates a new [`ModRelativePath`] instance. + pub fn new(path: String) -> ModRelativePath { + ModRelativePath { path } + } + + /// [`get_path`] returns the clone string of path of the [`ModRelativePath`]. + pub fn get_path(&self) -> String { + self.path.clone() + } + + /// [`is_relative_path`] returns true if the path is a mod relative path. + /// + /// # Examples + /// + /// ```rust + /// use kcl_config::path::ModRelativePath; + /// let path = ModRelativePath::new("${my_pkg:KCL_MOD}/src/path.rs".to_string()); + /// assert_eq!(path.is_relative_path().unwrap(), true); + /// + /// let path = ModRelativePath::new("${KCL_MOD}/src/path.rs".to_string()); + /// assert_eq!(path.is_relative_path().unwrap(), true); + /// + /// let path = ModRelativePath::new("/usr/${my_pkg:KCL_MOD}/src/path.rs".to_string()); + /// assert_eq!(path.is_relative_path().unwrap(), false); + /// + /// let path = ModRelativePath::new("/src/path.rs".to_string()); + /// assert_eq!(path.is_relative_path().unwrap(), false); + /// ``` + pub fn is_relative_path(&self) -> Result { + Ok(Regex::new(RELATIVE_PATH_PREFFIX)? + .find(&self.path) + .map_or(false, |mat| mat.start() == 0)) + } + + /// [`get_root_pkg_name`] returns the name of the root package. + /// + /// # Examples + /// + /// ```rust + /// use kcl_config::path::ModRelativePath; + /// let path = ModRelativePath::new("${my_pkg:KCL_MOD}/src/path.rs".to_string()); + /// assert_eq!(path.get_root_pkg_name().unwrap(), Some("my_pkg".to_string())); + /// + /// let path = ModRelativePath::new("${KCL_MOD}/src/path.rs".to_string()); + /// assert_eq!(path.get_root_pkg_name().unwrap(), None); + /// + /// let path = ModRelativePath::new("/src/path.rs".to_string()); + /// assert_eq!(path.get_root_pkg_name().unwrap(), None); + /// ``` + pub fn get_root_pkg_name(&self) -> Result> { + if !self.is_relative_path()? { + return Ok(None); + } + + Ok(Regex::new(RELATIVE_PATH_PREFFIX)? + .captures(&self.path) + .and_then(|caps| caps.name(ROOT_PKG_NAME_FLAG)) + .map(|mat| mat.as_str().to_string())) + } + + /// [`canonicalize_by_root_path`] returns the canonicalized path by the root path. + /// + /// # Examples + /// + /// ```rust + /// use kcl_config::path::ModRelativePath; + /// let path = ModRelativePath::new("${name:KCL_MOD}/src/path".to_string()); + /// #[cfg(target_os = "windows")] + /// assert_eq!(path.canonicalize_by_root_path("/usr/my_pkg").unwrap(), "/usr/my_pkg\\src/path"); + /// #[cfg(not(target_os = "windows"))] + /// assert_eq!(path.canonicalize_by_root_path("/usr/my_pkg").unwrap(), "/usr/my_pkg/src/path"); + /// + /// let path = ModRelativePath::new("/src/path".to_string()); + /// assert_eq!(path.canonicalize_by_root_path("/usr/my_pkg").unwrap(), "/src/path"); + /// ``` + pub fn canonicalize_by_root_path(&self, root_path: &str) -> Result { + if !self.is_relative_path()? { + return Ok(self.get_path()); + } + + Ok(Regex::new(RELATIVE_PATH_PREFFIX)? + .captures(&self.path) + .map_or_else( + || self.get_path(), + |caps| { + // Due to the path format is different between windows and linux, + // Can not use the replace method directly + // by 'replace(std::str::from_utf8(caps.get(0).unwrap().as_bytes()).unwrap(), root_path)'. + let sub_path = self.get_path().replace(caps.get(0).unwrap().as_str(), ""); + let res = PathBuf::from(root_path) + .join(sub_path) + .display() + .to_string(); + + res + }, + )) + } +} + +#[cfg(test)] +mod test_relative_path { + use super::*; + + #[test] + fn test_is_relative_path() { + let path = ModRelativePath::new("${name:KCL_MOD}/src/path.rs".to_string()); + assert!(path.is_relative_path().unwrap()); + let path = ModRelativePath::new("${KCL_MOD}/src/path.rs".to_string()); + assert!(path.is_relative_path().unwrap()); + let path = ModRelativePath::new("/usr/${name:KCL_MOD}/src/path.rs".to_string()); + assert!(!path.is_relative_path().unwrap()); + let path = ModRelativePath::new("/src/path.rs".to_string()); + assert!(!path.is_relative_path().unwrap()); + let path = ModRelativePath::new("./src/path.rs".to_string()); + assert!(!path.is_relative_path().unwrap()); + let path = ModRelativePath::new("${K_MOD}/src/path.rs".to_string()); + assert!(!path.is_relative_path().unwrap()); + let path = ModRelativePath::new("${:KCL_MOD}/src/path.rs".to_string()); + assert!(!path.is_relative_path().unwrap()); + } + + #[test] + fn test_get_root_pkg_name() { + let path = ModRelativePath::new("${my_pkg:KCL_MOD}/src/path.rs".to_string()); + assert_eq!( + path.get_root_pkg_name().unwrap(), + Some("my_pkg".to_string()) + ); + + let path = ModRelativePath::new("${KCL_MOD}/src/path.rs".to_string()); + assert_eq!(path.get_root_pkg_name().unwrap(), None); + + let path = ModRelativePath::new("/src/path.rs".to_string()); + assert_eq!(path.get_root_pkg_name().unwrap(), None); + } + + #[test] + fn test_canonicalize_by_root_path() { + let path = ModRelativePath::new("${name:KCL_MOD}/src/path".to_string()); + #[cfg(target_os = "windows")] + assert_eq!( + path.canonicalize_by_root_path("C:\\usr\\my_pkg").unwrap(), + "C:\\usr\\my_pkg\\src/path" + ); + #[cfg(not(target_os = "windows"))] + assert_eq!( + path.canonicalize_by_root_path("/usr/my_pkg").unwrap(), + "/usr/my_pkg/src/path" + ); + let path = ModRelativePath::new("/src/path".to_string()); + assert_eq!( + path.canonicalize_by_root_path("/usr/my_pkg").unwrap(), + "/src/path" + ); + } +} diff --git a/crates/config/src/settings.rs b/crates/config/src/settings.rs new file mode 100644 index 000000000..4b1f740c6 --- /dev/null +++ b/crates/config/src/settings.rs @@ -0,0 +1,526 @@ +//! Copyright The KCL Authors. All rights reserved. +use anyhow::{Context, Result}; +use serde::{ + Deserialize, Serialize, + de::{DeserializeSeed, Error, MapAccess, SeqAccess, Unexpected, Visitor}, +}; +use std::{collections::HashMap, ops::Deref, path::PathBuf}; + +/// Default settings file `kcl.yaml` +pub const DEFAULT_SETTING_FILE: &str = "kcl.yaml"; + +/// Readonly settings with the filepath. +#[derive(Debug, Default, Clone)] +pub struct SettingsPathBuf(Option, SettingsFile); + +impl SettingsPathBuf { + /// New a settings with path and settings content. + #[inline] + pub fn new(path: Option, settings: SettingsFile) -> Self { + Self(path, settings) + } + + /// Get the output setting. + #[inline] + pub fn output(&self) -> Option { + match &self.1.kcl_cli_configs { + Some(c) => c.output.clone(), + None => None, + } + } + + /// Get the path. + #[inline] + pub fn path(&self) -> &Option { + &self.0 + } + + /// Get the settings. + #[inline] + pub fn settings(&self) -> &SettingsFile { + &self.1 + } +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct SettingsFile { + pub kcl_cli_configs: Option, + pub kcl_options: Option>, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +pub struct Config { + pub files: Option>, + pub file: Option>, + pub output: Option, + pub overrides: Option>, + pub path_selector: Option>, + pub strict_range_check: Option, + pub disable_none: Option, + pub verbose: Option, + pub debug: Option, + pub sort_keys: Option, + pub show_hidden: Option, + /// Whether including schema type in JSON/YAML result. + pub include_schema_type_path: Option, + /// kcl needs a mapping between the package name and the package path + /// to determine the source code path corresponding to different version package. + pub package_maps: Option>, + /// Use the evaluator to execute the AST program instead of AOT. + pub fast_eval: Option, +} + +impl SettingsFile { + pub fn new() -> Self { + SettingsFile { + kcl_cli_configs: Some(Config { + file: Some(vec![]), + files: Some(vec![]), + output: None, + overrides: Some(vec![]), + path_selector: Some(vec![]), + strict_range_check: Some(false), + disable_none: Some(false), + verbose: Some(0), + debug: Some(false), + sort_keys: Some(false), + show_hidden: Some(false), + fast_eval: Some(false), + include_schema_type_path: Some(false), + package_maps: Some(HashMap::default()), + }), + kcl_options: Some(vec![]), + } + } + + /// Get the output setting. + #[inline] + pub fn output(&self) -> Option { + match &self.kcl_cli_configs { + Some(c) => c.output.clone(), + None => None, + } + } + + /// Get the input setting. + #[inline] + pub fn input(&self) -> Vec { + match &self.kcl_cli_configs { + Some(c) => match &c.file { + Some(file) => match &c.files { + Some(files) if !files.is_empty() => files.clone(), + _ => file.clone(), + }, + None => match &c.files { + Some(files) => files.clone(), + None => vec![], + }, + }, + None => vec![], + } + } +} + +impl Default for SettingsFile { + fn default() -> Self { + Self::new() + } +} + +/// Top level argument key value pair. +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +pub struct KeyValuePair { + /// key is the top level argument key. + pub key: String, + // Note: here is a normal json string including int, float, string, bool list and dict. + pub value: ValueString, +} + +#[macro_export] +macro_rules! tri { + ($e:expr $(,)?) => { + match $e { + core::result::Result::Ok(val) => val, + core::result::Result::Err(err) => return core::result::Result::Err(err), + } + }; +} + +/// MapStringKey denotes the map deserialize key. +struct MapStringKey; +impl<'de> DeserializeSeed<'de> for MapStringKey { + type Value = String; + + fn deserialize(self, deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + deserializer.deserialize_str(self) + } +} + +impl<'de> Visitor<'de> for MapStringKey { + type Value = String; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("a string key") + } + + fn visit_str(self, s: &str) -> Result + where + E: serde::de::Error, + { + Ok(s.to_owned()) + } + + fn visit_string(self, s: String) -> Result + where + E: serde::de::Error, + { + Ok(s) + } +} + +/// Top level argument value string. +/// Note: here is a normal json string including int, float, string, bool list and dict. +#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)] +pub struct ValueString(pub String); + +impl Deref for ValueString { + type Target = String; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl From for ValueString { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for ValueString { + fn from(value: &str) -> Self { + Self(value.to_string()) + } +} + +impl<'de> Deserialize<'de> for ValueString { + #[inline] + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + struct ValueVisitor; + + impl<'de> Visitor<'de> for ValueVisitor { + type Value = ValueString; + + fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + formatter.write_str("any valid JSON value or KCL value expression") + } + + #[inline] + fn visit_bool(self, value: bool) -> Result + where + E: Error, + { + Ok(ValueString(serde_json::to_string(&value).map_err( + |_| Error::invalid_type(Unexpected::Bool(value), &self), + )?)) + } + + #[inline] + fn visit_i64(self, value: i64) -> Result + where + E: Error, + { + Ok(ValueString(serde_json::to_string(&value).map_err( + |_| Error::invalid_type(Unexpected::Signed(value), &self), + )?)) + } + + #[inline] + fn visit_u64(self, value: u64) -> Result + where + E: Error, + { + Ok(ValueString(serde_json::to_string(&value).map_err( + |_| Error::invalid_type(Unexpected::Unsigned(value), &self), + )?)) + } + + #[inline] + fn visit_f64(self, value: f64) -> Result + where + E: Error, + { + Ok(ValueString(serde_json::to_string(&value).map_err( + |_| Error::invalid_type(Unexpected::Float(value), &self), + )?)) + } + + #[inline] + fn visit_str(self, value: &str) -> Result + where + E: serde::de::Error, + { + self.visit_string(String::from(value)) + } + + #[inline] + fn visit_string(self, value: String) -> Result + where + E: Error, + { + Ok(ValueString(serde_json::to_string(&value).map_err( + |_| Error::invalid_type(Unexpected::Str(&value), &self), + )?)) + } + + #[inline] + fn visit_none(self) -> Result + where + E: Error, + { + Ok(ValueString("null".into())) + } + + #[inline] + fn visit_some(self, deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + D::Error: Error, + { + Deserialize::deserialize(deserializer) + } + + #[inline] + fn visit_unit(self) -> Result { + Ok(ValueString("null".into())) + } + + #[inline] + fn visit_seq(self, mut visitor: V) -> Result + where + V: SeqAccess<'de>, + V::Error: Error, + { + let mut vec: Vec = Vec::new(); + + while let Some(elem) = tri!(visitor.next_element()) { + vec.push(elem); + } + + Ok(ValueString(serde_json::to_string(&vec).map_err(|_| { + Error::invalid_type(Unexpected::Seq, &self) + })?)) + } + + fn visit_map(self, mut visitor: V) -> Result + where + V: MapAccess<'de>, + V::Error: Error, + { + match visitor.next_key_seed(MapStringKey)? { + Some(first_key) => { + let mut values: HashMap = HashMap::new(); + + values.insert(first_key, tri!(visitor.next_value())); + while let Some((key, value)) = tri!(visitor.next_entry()) { + values.insert(key, value); + } + + Ok(ValueString(serde_json::to_string(&values).map_err( + |_| Error::invalid_type(Unexpected::Map, &self), + )?)) + } + None => Ok(ValueString("{}".into())), + } + } + } + + deserializer.deserialize_any(ValueVisitor) + } +} + +#[derive(Serialize, Deserialize, Debug, Clone, Default)] +pub struct TestSettingsFile { + kcl_options: Option, +} + +/// Load kcl settings file. +pub fn load_file(filename: &str) -> Result { + let f = std::fs::File::open(filename) + .with_context(|| format!("Failed to load '{}', no such file or directory", filename))?; + let data: SettingsFile = serde_yaml_ng::from_reader(f) + .with_context(|| format!("Failed to load '{}', invalid setting file format", filename))?; + Ok(data) +} + +macro_rules! set_if { + ($result: expr, $attr: ident, $setting: expr) => { + if $setting.$attr.is_some() { + $result.$attr = $setting.$attr.clone(); + } + }; +} + +/// Merge multiple settings into one settings. +pub fn merge_settings(settings: &[SettingsFile]) -> SettingsFile { + let mut result = SettingsFile::new(); + for setting in settings { + if let Some(kcl_cli_configs) = &setting.kcl_cli_configs { + if result.kcl_cli_configs.is_none() { + result.kcl_cli_configs = Some(Config::default()); + } + if let Some(result_kcl_cli_configs) = result.kcl_cli_configs.as_mut() { + set_if!(result_kcl_cli_configs, files, kcl_cli_configs); + set_if!(result_kcl_cli_configs, file, kcl_cli_configs); + set_if!(result_kcl_cli_configs, output, kcl_cli_configs); + set_if!(result_kcl_cli_configs, overrides, kcl_cli_configs); + set_if!(result_kcl_cli_configs, path_selector, kcl_cli_configs); + set_if!(result_kcl_cli_configs, strict_range_check, kcl_cli_configs); + set_if!(result_kcl_cli_configs, disable_none, kcl_cli_configs); + set_if!(result_kcl_cli_configs, verbose, kcl_cli_configs); + set_if!(result_kcl_cli_configs, debug, kcl_cli_configs); + set_if!(result_kcl_cli_configs, sort_keys, kcl_cli_configs); + set_if!(result_kcl_cli_configs, show_hidden, kcl_cli_configs); + set_if!(result_kcl_cli_configs, fast_eval, kcl_cli_configs); + set_if!( + result_kcl_cli_configs, + include_schema_type_path, + kcl_cli_configs + ); + set_if!(result_kcl_cli_configs, package_maps, kcl_cli_configs); + } + } + if let Some(kcl_options) = &setting.kcl_options { + if result.kcl_options.is_none() { + result.kcl_options = Some(vec![]) + } + if let Some(result_kcl_options) = result.kcl_options.as_mut() { + for option in kcl_options { + result_kcl_options.push(option.clone()); + } + } + } + } + result +} + +/// Build SettingsPathBuf from args. +pub fn build_settings_pathbuf( + files: &[&str], + setting_files: Option>, + setting_config: Option, +) -> Result { + let mut path = None; + let settings = if let Some(files) = setting_files { + let mut settings = vec![]; + for file in &files { + let s = load_file(file)?; + if !s.input().is_empty() { + path = Some( + PathBuf::from(file) + .parent() + .map(|p| p.to_path_buf()) + .ok_or(anyhow::anyhow!("The parent path of {file} is not found"))?, + ) + } + settings.push(s); + } + merge_settings(&settings) + // If exists default kcl.yaml, load it. + } else if std::fs::metadata(DEFAULT_SETTING_FILE).is_ok() { + path = Some( + PathBuf::from(DEFAULT_SETTING_FILE) + .parent() + .map(|p| p.to_path_buf()) + .ok_or(anyhow::anyhow!( + "The parent path of {DEFAULT_SETTING_FILE} is not found" + ))?, + ); + load_file(DEFAULT_SETTING_FILE)? + } else { + SettingsFile::default() + }; + let mut settings = if let Some(setting_config) = setting_config { + merge_settings(&[settings, setting_config]) + } else { + settings + }; + if let Some(config) = &mut settings.kcl_cli_configs { + if !files.is_empty() { + config.files = Some(files.iter().map(|f| f.to_string()).collect()); + } + } + Ok(SettingsPathBuf::new(path, settings)) +} + +#[cfg(test)] +mod settings_test { + use crate::settings::*; + + const SETTINGS_FILE: &str = "./src/testdata/settings.yaml"; + + #[test] + fn test_settings_load_file() { + let settings = load_file(SETTINGS_FILE).unwrap(); + assert!(settings.kcl_cli_configs.is_some()); + assert!(settings.kcl_options.is_some()); + if let Some(kcl_cli_configs) = settings.kcl_cli_configs { + let files = vec![ + String::from("../main.k"), + String::from("./before/base.k"), + String::from("./main.k"), + String::from("./sub/sub.k"), + ]; + assert!(kcl_cli_configs.files.is_some()); + assert!(kcl_cli_configs.disable_none.is_some()); + assert!(kcl_cli_configs.strict_range_check.is_some()); + assert!(kcl_cli_configs.debug.is_some()); + assert!(kcl_cli_configs.path_selector.is_none()); + assert!(kcl_cli_configs.overrides.is_none()); + assert!(kcl_cli_configs.include_schema_type_path.is_none()); + assert!(kcl_cli_configs.show_hidden.is_none()); + assert!(kcl_cli_configs.fast_eval.is_none()); + assert_eq!(kcl_cli_configs.sort_keys, Some(true)); + if let Some(config_files) = kcl_cli_configs.files { + assert!(config_files == files); + } + } + if let Some(kcl_options) = settings.kcl_options { + assert!(kcl_options.len() == 6); + } + } + + #[test] + fn test_merge_settings() -> anyhow::Result<()> { + let settings1 = load_file(SETTINGS_FILE)?; + let settings2 = load_file(SETTINGS_FILE)?; + let settings = merge_settings(&vec![settings1, settings2]); + if let Some(kcl_cli_configs) = settings.kcl_cli_configs { + let files = vec![ + String::from("../main.k"), + String::from("./before/base.k"), + String::from("./main.k"), + String::from("./sub/sub.k"), + ]; + assert!(kcl_cli_configs.files.is_some()); + assert!(kcl_cli_configs.disable_none.is_some()); + assert!(kcl_cli_configs.strict_range_check.is_some()); + assert!(kcl_cli_configs.debug.is_some()); + assert!(kcl_cli_configs.path_selector.is_some()); + assert!(kcl_cli_configs.overrides.is_some()); + if let Some(config_files) = kcl_cli_configs.files { + assert!(config_files == files); + } + } + if let Some(kcl_options) = settings.kcl_options { + assert!(kcl_options.len() == 12); + } + Ok(()) + } +} diff --git a/kclvm/config/src/testdata/a/a.k b/crates/config/src/testdata/a/a.k similarity index 100% rename from kclvm/config/src/testdata/a/a.k rename to crates/config/src/testdata/a/a.k diff --git a/kclvm/config/src/testdata/b/b.k b/crates/config/src/testdata/b/b.k similarity index 100% rename from kclvm/config/src/testdata/b/b.k rename to crates/config/src/testdata/b/b.k diff --git a/kclvm/config/src/testdata/kcl.mod b/crates/config/src/testdata/kcl.mod similarity index 100% rename from kclvm/config/src/testdata/kcl.mod rename to crates/config/src/testdata/kcl.mod diff --git a/kclvm/config/src/testdata/kcl.work b/crates/config/src/testdata/kcl.work similarity index 100% rename from kclvm/config/src/testdata/kcl.work rename to crates/config/src/testdata/kcl.work diff --git a/crates/config/src/testdata/settings.yaml b/crates/config/src/testdata/settings.yaml new file mode 100644 index 000000000..c22703c12 --- /dev/null +++ b/crates/config/src/testdata/settings.yaml @@ -0,0 +1,33 @@ +kcl_cli_configs: + files: + - ../main.k + - ./before/base.k + - ./main.k + - ./sub/sub.k + disable_none: false + strict_range_check: false + debug: false + sort_keys: true +kcl_options: + - key: app-name + value: kcl + - key: image + value: kcl:v0.0.1 + - key: env-type + value: TEST + - key: deploy-topology + value: + - cluster: my-cluster + id: '000123' + idc: my-idc + is_dev: true + replicas: 2 + value: null + workspace: my-workspace + zone: my-zone + - key: labels + value: + app: app + env: env + - key: ports + value: [80, 8080] diff --git a/kclvm/config/src/testdata/test_cache/kcl.mod b/crates/config/src/testdata/test_cache/kcl.mod similarity index 100% rename from kclvm/config/src/testdata/test_cache/kcl.mod rename to crates/config/src/testdata/test_cache/kcl.mod diff --git a/kclvm/config/src/testdata/test_cache/main.k b/crates/config/src/testdata/test_cache/main.k similarity index 100% rename from kclvm/config/src/testdata/test_cache/main.k rename to crates/config/src/testdata/test_cache/main.k diff --git a/kclvm/config/src/testdata/test_settings.yaml b/crates/config/src/testdata/test_settings.yaml similarity index 100% rename from kclvm/config/src/testdata/test_settings.yaml rename to crates/config/src/testdata/test_settings.yaml diff --git a/kclvm/config/src/testdata/test_vendor/kcl.mod b/crates/config/src/testdata/test_vendor/kcl.mod similarity index 100% rename from kclvm/config/src/testdata/test_vendor/kcl.mod rename to crates/config/src/testdata/test_vendor/kcl.mod diff --git a/kclvm/config/src/testdata/test_vendor/main.k b/crates/config/src/testdata/test_vendor/main.k similarity index 100% rename from kclvm/config/src/testdata/test_vendor/main.k rename to crates/config/src/testdata/test_vendor/main.k diff --git a/crates/config/src/tests.rs b/crates/config/src/tests.rs new file mode 100644 index 000000000..cec69a94f --- /dev/null +++ b/crates/config/src/tests.rs @@ -0,0 +1,78 @@ +use kcl_utils::path::PathPrefix; +use kcl_version as version; +use std::{ + collections::HashMap, + env, + fs::{self, File}, + path::{Path, PathBuf}, +}; + +use crate::{ + cache::{CacheOption, load_pkg_cache, save_pkg_cache}, + modfile::{KCL_PKG_PATH, get_vendor_home}, +}; + +#[test] +fn test_vendor_home() { + unsafe { env::set_var(KCL_PKG_PATH, "test_vendor_home") }; + assert_eq!(get_vendor_home(), "test_vendor_home"); + unsafe { env::remove_var(KCL_PKG_PATH) }; + + #[cfg(target_os = "windows")] + let root_dir = env::var("USERPROFILE").unwrap(); + #[cfg(not(target_os = "windows"))] + let root_dir = env::var("HOME").unwrap(); + + let kpm_home = PathBuf::from(root_dir) + .join(".kcl") + .join("kpm") + .canonicalize() + .unwrap(); + assert_eq!( + get_vendor_home(), + kpm_home.display().to_string().adjust_canonicalization() + ) +} + +#[test] +fn test_pkg_cache() { + let root = PathBuf::from("./src/testdata/test_cache/") + .canonicalize() + .unwrap() + .display() + .to_string(); + let mut external_pkgs = HashMap::new(); + external_pkgs.insert( + "test_vendor".to_string(), + "./src/testdata/test_vendor".to_string(), + ); + + let lock_path = Path::new(&root) + .join(".kcl/cache") + .join(format!("{}-{}", version::VERSION, version::CHECK_SUM)) + .join("test_target"); + + fs::create_dir_all(lock_path.clone()).unwrap(); + File::create(lock_path.join("test_vendor.lock")).unwrap(); + + save_pkg_cache( + &root, + "test_target", + "test_vendor", + "test_data", + CacheOption::default(), + &external_pkgs, + ) + .unwrap(); + + assert_eq!( + load_pkg_cache( + &root, + "test_target", + "test_vendor", + CacheOption::default(), + &external_pkgs, + ), + Some("test_data".to_string()) + ) +} diff --git a/kclvm/config/src/vfs.rs b/crates/config/src/vfs.rs similarity index 99% rename from kclvm/config/src/vfs.rs rename to crates/config/src/vfs.rs index a0fbe3751..5d377e542 100644 --- a/kclvm/config/src/vfs.rs +++ b/crates/config/src/vfs.rs @@ -1,6 +1,6 @@ use std::path::Path; -use kclvm_utils::path::PathPrefix; +use kcl_utils::path::PathPrefix; extern crate pathdiff; diff --git a/kclvm/config/src/workfile.rs b/crates/config/src/workfile.rs similarity index 99% rename from kclvm/config/src/workfile.rs rename to crates/config/src/workfile.rs index fb09d7a16..bd13bc064 100644 --- a/kclvm/config/src/workfile.rs +++ b/crates/config/src/workfile.rs @@ -1,6 +1,6 @@ //! The config for IDE/LSP workspace config file `kcl.work' -use kclvm_utils::path::PathPrefix; +use kcl_utils::path::PathPrefix; use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, diff --git a/crates/driver/Cargo.toml b/crates/driver/Cargo.toml new file mode 100644 index 000000000..51dc4a99e --- /dev/null +++ b/crates/driver/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "kcl-driver" +version.workspace = true +edition.workspace = true + +# # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +serde_json = "1.0.86" + +kcl-config = { path = "../config" } +kcl-runtime = { path = "../runtime" } +kcl-utils = { path = "../utils" } +kcl-parser = { path = "../parser" } +kcl-ast = { path = "../ast" } +kcl-primitives = { path = "../primitives" } +walkdir = "2" +serde = { version = "1.0", features = ["derive"] } +anyhow = { version = "1.0.70", features = ["backtrace"] } + +flate2 = "1.0.30" +tar = "0.4.40" +once_cell = "1.19.0" +parking_lot = "0.12.3" + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +oci-client = { default-features = false, version = "0.11.0", features = [ + "rustls-tls", +] } +tokio = { version = "1.37.0", features = ["full"] } diff --git a/kclvm/driver/src/arguments.rs b/crates/driver/src/arguments.rs similarity index 93% rename from kclvm/driver/src/arguments.rs rename to crates/driver/src/arguments.rs index 9655ba414..2b8c8f12a 100644 --- a/kclvm/driver/src/arguments.rs +++ b/crates/driver/src/arguments.rs @@ -1,7 +1,7 @@ use anyhow::Result; -use kclvm_ast::ast; -use kclvm_config::settings::KeyValuePair; -use kclvm_parser::parse_expr; +use kcl_ast::ast; +use kcl_config::settings::KeyValuePair; +use kcl_parser::parse_expr; /// Parse key value pair string k=v to [KeyValuePair], note the value will be convert a json string. pub fn parse_key_value_pair(spec: &str) -> Result { diff --git a/kclvm/driver/src/client/fs.rs b/crates/driver/src/client/fs.rs similarity index 100% rename from kclvm/driver/src/client/fs.rs rename to crates/driver/src/client/fs.rs diff --git a/kclvm/driver/src/client/git.rs b/crates/driver/src/client/git.rs similarity index 98% rename from kclvm/driver/src/client/git.rs rename to crates/driver/src/client/git.rs index feb078d2b..42948e952 100644 --- a/kclvm/driver/src/client/git.rs +++ b/crates/driver/src/client/git.rs @@ -4,7 +4,7 @@ use std::process::Command; use crate::client::fs::directory_is_not_empty; use anyhow::Result; -use kclvm_utils::path::PathPrefix; +use kcl_utils::path::PathPrefix; pub(crate) fn cmd_clone_git_repo_to( url: &str, diff --git a/crates/driver/src/client/mod.rs b/crates/driver/src/client/mod.rs new file mode 100644 index 000000000..8bc9e36d8 --- /dev/null +++ b/crates/driver/src/client/mod.rs @@ -0,0 +1,311 @@ +mod fs; +mod git; +mod oci; + +use anyhow::Result; +use git::cmd_clone_git_repo_to; +use kcl_config::modfile::{Dependency, GitSource, ModFile, OciSource}; +use kcl_config::modfile::{ + LockDependency, ModLockFile, get_vendor_home, load_mod_file, load_mod_lock_file, +}; +use kcl_primitives::IndexSet; +use kcl_utils::fslock::open_lock_file; +use oci_client::secrets::RegistryAuth; +use oci_client::{Client, Reference, RegistryOperation}; +use std::path::Path; +use std::path::PathBuf; +use std::sync::Arc; + +use crate::toolchain::{Metadata, Package}; + +pub const DEFAULT_OCI_REGISTRY: &str = "ghcr.io/kcl-lang"; +pub const KCL_SRC_URL_ENV_VAR: &str = "KCL_SRC_URL"; +pub const KCL_SRC_URL_USERNAME_ENV_VAR: &str = "KCL_SRC_USERNAME"; +pub const KCL_SRC_URL_PASSWORD_ENV_VAR: &str = "KCL_SRC_PASSWORD"; + +#[derive(Default)] +pub struct ModClient { + /// The mod file config of current module. + mod_file: ModFile, + /// The mod lock file config of current module. + mod_lock_file: Option, + /// The package search work directory. + work_dir: PathBuf, + /// Optional vendor home. + vendor: Option, + /// A lazy OCI client. + oci_client: Arc, +} + +unsafe impl Send for ModClient {} +unsafe impl Sync for ModClient {} + +impl ModClient { + /// New a default mod client to fetch metadata ot update dependencies. + #[inline] + pub fn new>(work_dir: P) -> Result { + Self::new_with_oci_client(work_dir, Arc::new(Client::default())) + } + + /// New a default mod client to fetch metadata ot update dependencies. + pub fn new_with_oci_client>( + work_dir: P, + oci_client: Arc, + ) -> Result { + Ok(Self { + work_dir: work_dir.as_ref().to_path_buf(), + mod_file: load_mod_file(&work_dir)?, + mod_lock_file: load_mod_lock_file(&work_dir).ok(), + vendor: None, + oci_client, + }) + } + + /// Auth the oci client + pub fn auth(&self) -> Result<()> { + if let (Ok(username), Ok(password)) = ( + std::env::var(KCL_SRC_URL_USERNAME_ENV_VAR), + std::env::var(KCL_SRC_URL_PASSWORD_ENV_VAR), + ) { + let rt = tokio::runtime::Runtime::new()?; + let image: Reference = self.default_oci_registry().parse()?; + let auth = RegistryAuth::Basic(username, password); + let _ = rt.block_on(async { + self.oci_client + .auth(&image, &auth, RegistryOperation::Pull) + .await + .ok()? + }); + } + Ok(()) + } + + #[inline] + pub fn default_oci_registry(&self) -> String { + std::env::var(KCL_SRC_URL_ENV_VAR).unwrap_or(DEFAULT_OCI_REGISTRY.to_string()) + } + + /// Change the work directory. + pub fn change_work_dir>(&mut self, work_dir: P) -> Result<()> { + let work_dir = work_dir.as_ref().to_path_buf(); + self.mod_file = load_mod_file(&work_dir)?; + if let Ok(mod_lock_file) = load_mod_lock_file(&work_dir) { + self.mod_lock_file = Some(mod_lock_file); + } + self.work_dir = work_dir; + Ok(()) + } + + /// Set the vendor path. + pub fn set_vendor>(&mut self, vendor: P) -> &mut Self { + let vendor = vendor.as_ref().to_path_buf(); + self.vendor = Some(vendor); + self + } + + /// Lock the kcl.mod file and resolve package deps to metadata, note this function will download + /// deps from remote sources. If the dependency is downloaded to the local path, calculate the + /// package metadata. + pub fn lock_and_resolve_all_deps>( + &mut self, + lock_file: P, + update: bool, + ) -> Result { + let mut lock_guard = + open_lock_file(lock_file.as_ref().to_string_lossy().to_string().as_str())?; + lock_guard.lock()?; + self.resolve_all_deps(update) + } + + /// Resolve package deps to metadata, note this function will download deps from remote sources. + /// If the dependency is downloaded to the local path, calculate the package metadata. + pub fn resolve_all_deps(&mut self, update: bool) -> Result { + let mut metadata = Metadata::default(); + match &self.mod_file.dependencies { + Some(dependencies) if !dependencies.is_empty() => { + let vendor = self.get_vendor_path()?; + let mut paths: IndexSet = IndexSet::default(); + for (name, dep) in dependencies { + let path = if update { + let path = self.download_dep_to_vendor(name, dep, &vendor)?; + paths.insert(path.clone()); + path + } else { + Default::default() + }; + metadata.packages.insert( + name.replace('-', "_"), + Package { + name: name.to_string(), + manifest_path: path, + }, + ); + } + for path in paths { + if let Ok(mut client) = + ModClient::new_with_oci_client(path, self.oci_client.clone()) + { + let new_metadata = client.resolve_all_deps(update)?; + for (name, package) in new_metadata.packages { + metadata.packages.entry(name).or_insert(package); + } + } + } + Ok(metadata) + } + _ => Ok(metadata), + } + } + + /// Download a dependency to the local path. + pub fn download_dep_to_vendor( + &self, + name: &str, + dep: &Dependency, + vendor: &Path, + ) -> Result { + let path = self.get_local_path_from_dep(name, dep); + let path = Path::new(vendor).join(path); + match dep { + Dependency::Version(version) => self.download_oci_source_to( + name, + &OciSource { + oci: oci::oci_reg_repo_join(&self.default_oci_registry(), name), + tag: Some(version.to_string()), + }, + &path, + ), + Dependency::Git(git_source) => self.download_git_source_to(git_source, &path), + Dependency::Oci(oci_source) => self.download_oci_source_to(name, oci_source, &path), + Dependency::Local(_) => { + // Nothing to do for the local source. + Ok(path) + } + } + } + + /// Get the vendor path. + pub fn get_vendor_path(&self) -> Result { + Ok(match &self.vendor { + Some(vendor) => { + std::fs::create_dir_all(vendor)?; + vendor.to_path_buf() + } + None => PathBuf::from(get_vendor_home()), + }) + } + + pub fn download_git_source_to(&self, git_source: &GitSource, path: &Path) -> Result { + let path = cmd_clone_git_repo_to( + &git_source.git, + &git_source.branch, + &git_source.tag, + &git_source.commit, + path, + )?; + Ok(path) + } + + pub fn download_oci_source_to( + &self, + name: &str, + oci_source: &OciSource, + path: &Path, + ) -> Result { + let rt = tokio::runtime::Runtime::new()?; + let path = rt.block_on(async { + oci::pull_oci_and_extract_layer( + &self.oci_client, + name, + &oci_source.oci, + &oci_source.tag, + path, + ) + .await + })?; + Ok(path) + } + + /// Get the dependency store path + pub fn get_local_path_from_dep(&self, name: &str, dep: &Dependency) -> String { + match dep { + Dependency::Version(version) => { + format!("{}_{}", name, version) + } + Dependency::Git(git_source) => { + if let Some(tag) = &git_source.tag { + format!("{}_{}", name, tag) + } else if let Some(commit) = &git_source.commit { + format!("{}_{}", name, commit) + } else if let Some(branch) = &git_source.branch { + format!("{}_{}", name, branch) + } else { + format!("{name}_latest") + } + } + // Just returns the folder. + Dependency::Oci(_) => "".to_string(), + Dependency::Local(local_source) => { + let local_path = PathBuf::from(&local_source.path); + if local_path.is_absolute() { + local_source.path.clone() + } else { + self.work_dir + .join(&local_source.path) + .to_string_lossy() + .to_string() + } + } + } + } + + /// Get the lock dependency store path + pub fn get_local_path_from_lock_dep(&self, lock_dep: &LockDependency) -> Option { + if lock_dep.reg.is_some() { + lock_dep.full_name.clone() + } else if let Some(git_url) = &lock_dep.url { + Some(self.get_local_path_from_dep( + &lock_dep.gen_filename(), + &Dependency::Git(GitSource { + git: git_url.to_string(), + branch: lock_dep.branch.clone(), + commit: lock_dep.commit.clone(), + tag: lock_dep.git_tag.clone(), + version: lock_dep.version.clone(), + }), + )) + } else { + match &self.mod_file.dependencies { + Some(dependencies) => dependencies + .get(&lock_dep.name) + .as_ref() + .map(|dep| self.get_local_path_from_dep(&lock_dep.name, dep)), + None => None, + } + } + } + + /// Get the package metadata from the kcl.mod.lock file. + pub fn get_metadata_from_mod_lock_file(&self) -> Option { + if let Some(mod_lock_file) = &self.mod_lock_file { + if let Some(dependencies) = &mod_lock_file.dependencies { + let vendor = self.get_vendor_path().ok()?; + let mut metadata = Metadata::default(); + for (name, dep) in dependencies { + metadata.packages.insert( + name.replace('-', "_").to_string(), + Package { + name: name.to_string(), + manifest_path: match self.get_local_path_from_lock_dep(dep) { + Some(path) => vendor.join(path), + None => "".into(), + }, + }, + ); + } + return Some(metadata); + } + } + None + } +} diff --git a/kclvm/driver/src/client/oci.rs b/crates/driver/src/client/oci.rs similarity index 100% rename from kclvm/driver/src/client/oci.rs rename to crates/driver/src/client/oci.rs diff --git a/crates/driver/src/lib.rs b/crates/driver/src/lib.rs new file mode 100644 index 000000000..2ad887fbf --- /dev/null +++ b/crates/driver/src/lib.rs @@ -0,0 +1,476 @@ +pub mod arguments; +#[cfg(not(target_arch = "wasm32"))] +pub mod client; +pub mod toolchain; + +#[cfg(test)] +mod tests; + +use anyhow::Result; +use kcl_config::{ + modfile::{KCL_FILE_EXTENSION, KCL_MOD_FILE, KCL_WORK_FILE, get_pkg_root, load_mod_file}, + settings::{DEFAULT_SETTING_FILE, build_settings_pathbuf}, + workfile::load_work_file, +}; +use kcl_parser::{LoadProgramOptions, get_kcl_files}; +use kcl_utils::path::PathPrefix; +use std::iter; +use std::{collections::HashMap, env}; +use std::{ + collections::HashSet, + fs::read_dir, + io::{self, ErrorKind}, + path::{Path, PathBuf}, +}; +use toolchain::{Metadata, Toolchain, fill_pkg_maps_for_k_file}; +use walkdir::WalkDir; + +/// Get compile workspace(files and options) from a single file input. +/// 1. Lookup entry files in kcl.yaml +/// 2. Lookup entry files in kcl.mod +/// 3. If not found, consider the path or folder where the file is +/// located as the compilation entry point +pub fn lookup_compile_workspace( + tool: &dyn Toolchain, + file: &str, + load_pkg: bool, +) -> CompileUnitOptions { + fn default_res(tool: &dyn Toolchain, file: &str, load_pkg: bool) -> CompileUnitOptions { + let mut default_res: CompileUnitOptions = (vec![], None, None); + let mut load_opt = kcl_parser::LoadProgramOptions::default(); + let metadata = fill_pkg_maps_for_k_file(tool, file.into(), &mut load_opt).unwrap_or(None); + let path = Path::new(file); + if let Some(ext) = path.extension() { + if load_pkg { + if let Some(parent) = path.parent() { + if let Ok(files) = get_kcl_files(parent, false) { + default_res = (files, Some(load_opt), metadata); + } + } + } else { + if ext == KCL_FILE_EXTENSION && path.is_file() { + default_res = (vec![file.to_string()], Some(load_opt), metadata); + } + } + } + default_res + } + + match lookup_compile_unit_path(file) { + Ok(CompileUnitPath::SettingFile(dir)) => { + let settings_files = lookup_setting_files(&dir); + let files = if settings_files.is_empty() { + default_res(tool, file, load_pkg) + .0 + .iter() + .map(|s| s.clone()) + .collect() + } else { + vec![] + }; + let files: Vec<&str> = files.iter().map(|s| s.as_str()).collect(); + let settings_files: Vec<&str> = + settings_files.iter().map(|f| f.to_str().unwrap()).collect(); + match build_settings_pathbuf(&files, Some(settings_files), None) { + Ok(setting_buf) => { + let setting = setting_buf.settings(); + let files = setting.input(); + + let work_dir = setting_buf + .path() + .clone() + .map(|p| p.to_string_lossy().to_string()) + .unwrap_or_default(); + + let mut load_opt = kcl_parser::LoadProgramOptions { + work_dir: work_dir.clone(), + ..Default::default() + }; + let metadata = + fill_pkg_maps_for_k_file(tool, file.into(), &mut load_opt).unwrap_or(None); + if files.is_empty() { + default_res(tool, file, load_pkg) + } else { + (files, Some(load_opt), metadata) + } + } + Err(_) => default_res(tool, file, load_pkg), + } + } + Ok(CompileUnitPath::ModFile(dir)) => match load_mod_file(&dir) { + Ok(mod_file) => { + let mut load_opt = kcl_parser::LoadProgramOptions::default(); + let metadata = + fill_pkg_maps_for_k_file(tool, file.into(), &mut load_opt).unwrap_or(None); + if let Some(files) = mod_file.get_entries() { + let work_dir = dir.to_string_lossy().to_string(); + load_opt.work_dir = work_dir.clone(); + (files, Some(load_opt), metadata) + } else { + default_res(tool, file, load_pkg) + } + } + Err(_) => default_res(tool, file, load_pkg), + }, + Ok(CompileUnitPath::NotFound) | Err(_) => default_res(tool, file, load_pkg), + } +} + +pub fn lookup_compile_workspaces( + tool: &dyn Toolchain, + path: &str, + load_pkg: bool, +) -> ( + HashMap, + Option>, +) { + let mut workspaces = HashMap::new(); + match lookup_workspace(path) { + Ok(workspace) => match &workspace { + WorkSpaceKind::WorkFile(work_file_path) => { + if let Ok(mut workfile) = load_work_file(work_file_path) { + let root = work_file_path.parent().unwrap(); + workfile.canonicalize(root.to_path_buf()); + for work in workfile.workspaces { + match lookup_workspace(&work.abs_path) { + Ok(workspace) => { + workspaces.insert( + workspace.clone(), + lookup_compile_workspace(tool, &work.abs_path, load_pkg), + ); + } + Err(_) => {} + } + } + return (workspaces, Some(workfile.failed.clone())); + } + } + WorkSpaceKind::Folder(folder) => { + let load_opt = kcl_parser::LoadProgramOptions::default(); + let metadata = None; + + if load_pkg { + if folder.is_dir() { + if let Ok(files) = get_kcl_files(folder.clone(), false) { + match lookup_the_nearest_file_dir(folder.to_path_buf(), KCL_MOD_FILE) { + Some(dir) => { + let nearest_mod = dir.join(KCL_MOD_FILE); + let (_, opt, metadata) = lookup_compile_workspace( + tool, + &nearest_mod.adjust_canonicalization(), + load_pkg, + ); + workspaces.insert(workspace, (files, opt, metadata)); + } + None => { + workspaces.insert(workspace, (files, Some(load_opt), metadata)); + } + } + return (workspaces, None); + } + } + } + workspaces.insert( + workspace, + (vec![path.to_string()], Some(load_opt), metadata), + ); + } + WorkSpaceKind::SettingFile(setting_file) => { + workspaces.insert( + workspace.clone(), + lookup_compile_workspace( + tool, + &setting_file.as_path().adjust_canonicalization(), + load_pkg, + ), + ); + } + WorkSpaceKind::ModFile(mod_file) => { + workspaces.insert( + workspace.clone(), + lookup_compile_workspace( + tool, + &mod_file.as_path().adjust_canonicalization(), + load_pkg, + ), + ); + } + WorkSpaceKind::File(_) | WorkSpaceKind::NotFound => { + let pathbuf = PathBuf::from(path); + let file_path = pathbuf.as_path(); + if file_path.is_file() { + workspaces.insert(workspace, lookup_compile_workspace(tool, path, load_pkg)); + } + } + }, + Err(_) => {} + } + + (workspaces, None) +} + +/// Lookup default setting files e.g. kcl.yaml +pub fn lookup_setting_files(dir: &Path) -> Vec { + let mut settings = vec![]; + if let Ok(p) = lookup_kcl_yaml(dir) { + settings.push(p); + } + settings +} + +fn lookup_kcl_yaml(dir: &Path) -> io::Result { + let mut path = dir.to_path_buf(); + path.push(DEFAULT_SETTING_FILE); + if path.is_file() { + Ok(path) + } else { + Err(io::Error::new( + ErrorKind::NotFound, + "Ran out of places to find kcl.yaml", + )) + } +} + +pub type CompileUnitOptions = (Vec, Option, Option); + +/// CompileUnitPath is the kcl program default entries that are defined +/// in the config files. +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum CompileUnitPath { + SettingFile(PathBuf), + ModFile(PathBuf), + NotFound, +} + +/// LSP workspace, will replace CompileUnitPath +#[derive(Debug, PartialEq, Eq, Clone, Hash)] +pub enum WorkSpaceKind { + WorkFile(PathBuf), + ModFile(PathBuf), + SettingFile(PathBuf), + Folder(PathBuf), + File(PathBuf), + NotFound, +} + +/// For the KCL project, some definitions may be introduced through multi-file +/// compilation (kcl.yaml). This function is used to start from a single file and try +/// to find a `compile unit` that contains all definitions +/// Given a file path, search for the nearest "kcl.yaml" file or the nearest "kcl.mod" file. +/// If a "kcl.yaml" file is found, return the path of the directory containing the file. +/// If a "kcl.mod" file is found, return the path of the directory containing the file. +/// If none of these files are found, return an error indicating that the files were not found. +/// +/// Example: +/// +-- project +/// | +-- base +/// | | +-- base.k +/// | +-- prod +/// | | +-- main.k +/// | | +-- kcl.yaml +/// | +-- test +/// | | +-- main.k +/// | | +-- kcl.yaml +/// | +-- kcl.mod +/// +/// If the input file is project/prod/main.k or project/test/main.k, it will return +/// Path("project/prod") or Path("project/test") +pub fn lookup_compile_unit_path(file: &str) -> io::Result { + let path = PathBuf::from(file); + let current_dir_path = path.as_path().parent().unwrap(); + let entries = read_dir(current_dir_path)?; + for entry in entries { + let entry = entry?; + // The entry priority of `kcl.yaml`` is higher than that of `kcl.mod`. + if entry.file_name() == *DEFAULT_SETTING_FILE { + // If find "kcl.yaml", the input file is in a compile stack, return the + // path of this compile stack + return Ok(CompileUnitPath::SettingFile(PathBuf::from( + current_dir_path, + ))); + } else if entry.file_name() == *KCL_MOD_FILE { + return Ok(CompileUnitPath::ModFile(PathBuf::from(current_dir_path))); + } + } + Ok(CompileUnitPath::NotFound) +} + +/// It will replace lookup_compile_unit_path() +pub fn lookup_workspace(path: &str) -> io::Result { + let pathbuf = PathBuf::from(path); + let path = pathbuf.as_path(); + if path.is_dir() { + for entry in read_dir(path)? { + let entry = entry?; + if entry.file_name() == *KCL_WORK_FILE { + return Ok(WorkSpaceKind::WorkFile(entry.path())); + } + } + + for entry in read_dir(path)? { + let entry = entry?; + if entry.file_name() == *KCL_MOD_FILE { + return Ok(WorkSpaceKind::ModFile(entry.path())); + } + } + + for entry in read_dir(path)? { + let entry = entry?; + if entry.file_name() == *DEFAULT_SETTING_FILE { + return Ok(WorkSpaceKind::SettingFile(entry.path())); + } + } + + return Ok(WorkSpaceKind::Folder(PathBuf::from(path))); + } + if path.is_file() { + if let Some(ext) = path.extension() { + if ext.to_str().unwrap() == KCL_FILE_EXTENSION { + return Ok(WorkSpaceKind::File(PathBuf::from(path))); + } + } + } + Ok(WorkSpaceKind::NotFound) +} + +/// Get the package string list form the package path. +pub fn get_pkg_list(pkgpath: &str) -> Result> { + let mut dir_list: Vec = Vec::new(); + let mut dir_map: HashSet = HashSet::new(); + let cwd = std::env::current_dir()?; + + let pkgpath = if pkgpath.is_empty() { + cwd.to_string_lossy().to_string() + } else { + pkgpath.to_string() + }; + + let include_sub_pkg = pkgpath.ends_with("/..."); + let pkgpath = if include_sub_pkg { + pkgpath.trim_end_matches("/...").to_string() + } else { + pkgpath + }; + + if pkgpath != "." && pkgpath.ends_with('.') { + return Ok(Vec::new()); + } + + if pkgpath.is_empty() { + return Ok(Vec::new()); + } + + match pkgpath.chars().next() { + Some('.') => { + let pkgpath = Path::new(&cwd).join(&pkgpath); + pkgpath.to_string_lossy().to_string() + } + _ => { + if Path::new(&pkgpath).is_absolute() { + pkgpath.clone() + } else if !pkgpath.contains('/') && !pkgpath.contains('\\') { + pkgpath.replace('.', "/") + } else { + let pkgroot = + get_pkg_root(cwd.to_str().ok_or(anyhow::anyhow!("cwd path not found"))?) + .unwrap_or_default(); + if !pkgroot.is_empty() { + PathBuf::from(pkgroot) + .join(&pkgpath) + .to_string_lossy() + .to_string() + } else { + Path::new(&cwd).join(&pkgpath).to_string_lossy().to_string() + } + } + } + }; + + if !include_sub_pkg { + return Ok(vec![pkgpath]); + } + + for entry in WalkDir::new(&pkgpath).into_iter().filter_map(|e| e.ok()) { + let path = entry.path(); + if !path.is_dir() + && path.extension().and_then(|ext| ext.to_str()) == Some(KCL_FILE_EXTENSION) + && !path + .file_name() + .map(|name| name.to_string_lossy().starts_with('_')) + .unwrap_or(false) + { + if let Some(dir) = path.parent().map(|p| p.to_string_lossy().to_string()) { + if !dir_map.contains(&dir) { + dir_list.push(dir.clone()); + dir_map.insert(dir); + } + } + } + } + + Ok(dir_list) +} + +/// [`lookup_the_nearest_file_dir`] will start from [`from`] and search for file [`the_nearest_file`] in the parent directories. +/// If found, it will return the [`Some`] of [`the_nearest_file`] file path. If not found, it will return [`None`] +pub(crate) fn lookup_the_nearest_file_dir( + from: PathBuf, + the_nearest_file: &str, +) -> Option { + let mut current_dir = from; + + loop { + let found_path = current_dir.join(the_nearest_file); + if found_path.is_file() { + return current_dir.canonicalize().ok(); + } + + match current_dir.parent() { + Some(parent) => current_dir = parent.to_path_buf(), + None => return None, + } + } +} + +/// [`kcl`] will return the path for executable kcl binary. +pub fn kcl() -> PathBuf { + get_path_for_executable("kcl") +} + +/// [`get_path_for_executable`] will return the path for [`executable_name`]. +pub fn get_path_for_executable(executable_name: &'static str) -> PathBuf { + // The current implementation checks $PATH for an executable to use: + // `` + // example: for , this tries just , which will succeed if is on the $PATH + + if lookup_in_path(executable_name) { + return executable_name.into(); + } + + executable_name.into() +} + +/// [`lookup_in_path`] will search for an executable file [`exec`] in the environment variable ‘PATH’. +/// If found, return true, otherwise return false. +fn lookup_in_path(exec: &str) -> bool { + let paths = env::var_os("PATH").unwrap_or_default(); + env::split_paths(&paths) + .map(|path| path.join(exec)) + .find_map(probe) + .is_some() +} + +/// [`probe`] check if the given path points to a file. +/// If it does, return [`Some`] of the path. +/// If not, check if adding the current operating system's executable file extension (if any) to the path points to a file. +/// If it does, return [`Some`] of the path with the extension added. +/// If neither, return [`None`]. +fn probe(path: PathBuf) -> Option { + let with_extension = match env::consts::EXE_EXTENSION { + "" => None, + it => Some(path.with_extension(it)), + }; + iter::once(path) + .chain(with_extension) + .find(|it| it.is_file()) +} diff --git a/kclvm/driver/src/test_data/kpm_metadata/kcl.mod b/crates/driver/src/test_data/kpm_metadata/kcl.mod similarity index 100% rename from kclvm/driver/src/test_data/kpm_metadata/kcl.mod rename to crates/driver/src/test_data/kpm_metadata/kcl.mod diff --git a/kclvm/driver/src/test_data/kpm_metadata/subdir/main.k b/crates/driver/src/test_data/kpm_metadata/subdir/main.k similarity index 100% rename from kclvm/driver/src/test_data/kpm_metadata/subdir/main.k rename to crates/driver/src/test_data/kpm_metadata/subdir/main.k diff --git a/kclvm/driver/src/test_data/kpm_metadata_with_line/dep-with-line/kcl.mod b/crates/driver/src/test_data/kpm_metadata_with_line/dep-with-line/kcl.mod similarity index 100% rename from kclvm/driver/src/test_data/kpm_metadata_with_line/dep-with-line/kcl.mod rename to crates/driver/src/test_data/kpm_metadata_with_line/dep-with-line/kcl.mod diff --git a/kclvm/driver/src/test_data/kpm_metadata_with_line/dep-with-line/main.k b/crates/driver/src/test_data/kpm_metadata_with_line/dep-with-line/main.k similarity index 100% rename from kclvm/driver/src/test_data/kpm_metadata_with_line/dep-with-line/main.k rename to crates/driver/src/test_data/kpm_metadata_with_line/dep-with-line/main.k diff --git a/kclvm/driver/src/test_data/kpm_metadata_with_line/main_pkg/kcl.mod b/crates/driver/src/test_data/kpm_metadata_with_line/main_pkg/kcl.mod similarity index 100% rename from kclvm/driver/src/test_data/kpm_metadata_with_line/main_pkg/kcl.mod rename to crates/driver/src/test_data/kpm_metadata_with_line/main_pkg/kcl.mod diff --git a/kclvm/driver/src/test_data/kpm_metadata_with_line/main_pkg/main.k b/crates/driver/src/test_data/kpm_metadata_with_line/main_pkg/main.k similarity index 100% rename from kclvm/driver/src/test_data/kpm_metadata_with_line/main_pkg/main.k rename to crates/driver/src/test_data/kpm_metadata_with_line/main_pkg/main.k diff --git a/kclvm/driver/src/test_data/kpm_update/kcl.mod b/crates/driver/src/test_data/kpm_update/kcl.mod similarity index 100% rename from kclvm/driver/src/test_data/kpm_update/kcl.mod rename to crates/driver/src/test_data/kpm_update/kcl.mod diff --git a/kclvm/driver/src/test_data/pkg_list/pkg1/pkg.k b/crates/driver/src/test_data/pkg_list/pkg1/pkg.k similarity index 100% rename from kclvm/driver/src/test_data/pkg_list/pkg1/pkg.k rename to crates/driver/src/test_data/pkg_list/pkg1/pkg.k diff --git a/kclvm/driver/src/test_data/pkg_list/pkg1/sub_pkg1/pkg.k b/crates/driver/src/test_data/pkg_list/pkg1/sub_pkg1/pkg.k similarity index 100% rename from kclvm/driver/src/test_data/pkg_list/pkg1/sub_pkg1/pkg.k rename to crates/driver/src/test_data/pkg_list/pkg1/sub_pkg1/pkg.k diff --git a/kclvm/driver/src/test_data/pkg_list/pkg2/pkg.k b/crates/driver/src/test_data/pkg_list/pkg2/pkg.k similarity index 100% rename from kclvm/driver/src/test_data/pkg_list/pkg2/pkg.k rename to crates/driver/src/test_data/pkg_list/pkg2/pkg.k diff --git a/kclvm/driver/src/test_data/test_vendor/helloworld_0.1.0/0.0.1/README.md b/crates/driver/src/test_data/test_vendor/helloworld_0.1.0/0.0.1/README.md similarity index 100% rename from kclvm/driver/src/test_data/test_vendor/helloworld_0.1.0/0.0.1/README.md rename to crates/driver/src/test_data/test_vendor/helloworld_0.1.0/0.0.1/README.md diff --git a/kclvm/driver/src/test_data/test_vendor/helloworld_0.1.0/0.0.1/artifacthub-pkg.yaml b/crates/driver/src/test_data/test_vendor/helloworld_0.1.0/0.0.1/artifacthub-pkg.yaml similarity index 100% rename from kclvm/driver/src/test_data/test_vendor/helloworld_0.1.0/0.0.1/artifacthub-pkg.yaml rename to crates/driver/src/test_data/test_vendor/helloworld_0.1.0/0.0.1/artifacthub-pkg.yaml diff --git a/kclvm/driver/src/test_data/test_vendor/helloworld_0.1.0/README.md b/crates/driver/src/test_data/test_vendor/helloworld_0.1.0/README.md similarity index 100% rename from kclvm/driver/src/test_data/test_vendor/helloworld_0.1.0/README.md rename to crates/driver/src/test_data/test_vendor/helloworld_0.1.0/README.md diff --git a/kclvm/driver/src/test_data/test_vendor/helloworld_0.1.0/kcl.mod b/crates/driver/src/test_data/test_vendor/helloworld_0.1.0/kcl.mod similarity index 100% rename from kclvm/driver/src/test_data/test_vendor/helloworld_0.1.0/kcl.mod rename to crates/driver/src/test_data/test_vendor/helloworld_0.1.0/kcl.mod diff --git a/kclvm/driver/src/test_data/test_vendor/helloworld_0.1.0/main.k b/crates/driver/src/test_data/test_vendor/helloworld_0.1.0/main.k similarity index 100% rename from kclvm/driver/src/test_data/test_vendor/helloworld_0.1.0/main.k rename to crates/driver/src/test_data/test_vendor/helloworld_0.1.0/main.k diff --git a/kclvm/driver/src/test_data/test_vendor/kcl4_v0.0.1/k4/main.k b/crates/driver/src/test_data/test_vendor/kcl4_v0.0.1/k4/main.k similarity index 100% rename from kclvm/driver/src/test_data/test_vendor/kcl4_v0.0.1/k4/main.k rename to crates/driver/src/test_data/test_vendor/kcl4_v0.0.1/k4/main.k diff --git a/kclvm/driver/src/test_data/test_vendor/kcl4_v0.0.1/kcl.mod b/crates/driver/src/test_data/test_vendor/kcl4_v0.0.1/kcl.mod similarity index 100% rename from kclvm/driver/src/test_data/test_vendor/kcl4_v0.0.1/kcl.mod rename to crates/driver/src/test_data/test_vendor/kcl4_v0.0.1/kcl.mod diff --git a/crates/driver/src/tests.rs b/crates/driver/src/tests.rs new file mode 100644 index 000000000..66711898a --- /dev/null +++ b/crates/driver/src/tests.rs @@ -0,0 +1,150 @@ +use std::panic; +use std::path::PathBuf; + +use kcl_config::settings::KeyValuePair; + +use crate::arguments::parse_key_value_pair; +use crate::toolchain::NativeToolchain; +use crate::toolchain::Toolchain; +use crate::{get_pkg_list, lookup_the_nearest_file_dir, toolchain}; + +#[test] +fn test_parse_key_value_pair() { + let cases = [ + ( + "k=v", + KeyValuePair { + key: "k".to_string(), + value: "\"v\"".into(), + }, + ), + ( + "k=1", + KeyValuePair { + key: "k".to_string(), + value: "1".into(), + }, + ), + ( + "k=None", + KeyValuePair { + key: "k".to_string(), + value: "null".into(), + }, + ), + ( + "k=True", + KeyValuePair { + key: "k".to_string(), + value: "true".into(), + }, + ), + ( + "k=true", + KeyValuePair { + key: "k".to_string(), + value: "true".into(), + }, + ), + ( + "k={\"key\": \"value\"}", + KeyValuePair { + key: "k".to_string(), + value: "{\"key\": \"value\"}".into(), + }, + ), + ( + "k=[1, 2, 3]", + KeyValuePair { + key: "k".to_string(), + value: "[1, 2, 3]".into(), + }, + ), + ]; + for (value, pair) in cases { + let result = parse_key_value_pair(value).unwrap(); + assert_eq!(result.key, pair.key); + assert_eq!(result.value, pair.value); + } +} + +#[test] +fn test_parse_key_value_pair_fail() { + let cases = ["=v", "k=", "="]; + for case in cases { + assert!(parse_key_value_pair(case).is_err()); + } +} + +#[test] +fn test_lookup_the_nearest_file_dir() { + let path = PathBuf::from(".") + .join("src") + .join("test_data") + .join("kpm_metadata"); + let result = lookup_the_nearest_file_dir(path.clone(), "kcl.mod"); + assert!(result.is_some()); + assert_eq!( + result.unwrap().display().to_string(), + path.canonicalize().unwrap().display().to_string() + ); + + let main_path = path.join("subdir").join("main.k"); + let result = lookup_the_nearest_file_dir(main_path, "kcl.mod"); + assert!(result.is_some()); + assert_eq!( + result.unwrap().display().to_string(), + path.canonicalize().unwrap().display().to_string() + ); +} + +#[test] +fn test_fetch_metadata_invalid() { + let result = panic::catch_unwind(|| { + let tool = toolchain::default(); + let result = tool.fetch_metadata("invalid_path".to_string().into()); + match result { + Ok(_) => { + panic!("The method should not return Ok") + } + Err(_) => { + println!("return with an error.") + } + } + }); + + match result { + Ok(_) => println!("no panic"), + Err(e) => panic!("The method should not panic forever.: {:?}", e), + } +} + +#[test] +fn test_native_fetch_metadata_invalid() { + let result = panic::catch_unwind(|| { + let tool = NativeToolchain::default(); + let result = tool.fetch_metadata("invalid_path".to_string().into()); + match result { + Ok(_) => { + panic!("The method should not return Ok") + } + Err(_) => { + println!("return with an error.") + } + } + }); + + match result { + Ok(_) => println!("no panic"), + Err(e) => panic!("The method should not panic forever.: {:?}", e), + } +} + +#[test] +fn test_get_pkg_list() { + assert_eq!(get_pkg_list("./src/test_data/pkg_list/").unwrap().len(), 1); + assert_eq!( + get_pkg_list("./src/test_data/pkg_list/...").unwrap().len(), + 3 + ); +} diff --git a/kclvm/driver/src/toolchain.rs b/crates/driver/src/toolchain.rs similarity index 98% rename from kclvm/driver/src/toolchain.rs rename to crates/driver/src/toolchain.rs index 13774c6ed..c592aedc6 100644 --- a/kclvm/driver/src/toolchain.rs +++ b/crates/driver/src/toolchain.rs @@ -1,8 +1,8 @@ use crate::{kcl, lookup_the_nearest_file_dir}; -use anyhow::{bail, Result}; -use kclvm_config::modfile::KCL_MOD_FILE; -use kclvm_parser::LoadProgramOptions; -use kclvm_utils::pkgpath::rm_external_pkg_name; +use anyhow::{Result, bail}; +use kcl_config::modfile::KCL_MOD_FILE; +use kcl_parser::LoadProgramOptions; +use kcl_utils::pkgpath::rm_external_pkg_name; use serde::{Deserialize, Serialize}; use std::ffi::OsStr; use std::{collections::HashMap, path::PathBuf, process::Command}; diff --git a/crates/error/Cargo.toml b/crates/error/Cargo.toml new file mode 100644 index 000000000..ccc47ea10 --- /dev/null +++ b/crates/error/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "kcl-error" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +compiler_base_span = "0.1.2" +compiler_base_session = "0.1.3" +compiler_base_error = "0.1.6" +compiler_base_macros = "0.1.1" + +kcl-primitives = { path = "../primitives" } +kcl-span = { path = "../span" } +kcl-runtime = { path = "../runtime" } +kcl-utils = { path = "../utils" } + +anyhow = "1.0" +tracing = "0.1" +annotate-snippets = { version = "0.9.2", default-features = false, features = [ + "color", +] } +serde = { version = "1.0", features = ["derive"] } +termize = "0.1.1" +serde_json = "1.0" +thiserror = "2.0.17" diff --git a/kclvm/error/src/diagnostic.rs b/crates/error/src/diagnostic.rs similarity index 97% rename from kclvm/error/src/diagnostic.rs rename to crates/error/src/diagnostic.rs index 019c5c2e2..f9e6bc8f4 100644 --- a/kclvm/error/src/diagnostic.rs +++ b/crates/error/src/diagnostic.rs @@ -1,5 +1,5 @@ -use kclvm_primitives::IndexSet; -use kclvm_span::Loc; +use kcl_primitives::IndexSet; +use kcl_span::Loc; use std::fmt; use std::hash::Hash; @@ -84,7 +84,7 @@ impl Position { impl From for Position { fn from(loc: Loc) -> Self { - let filename = kclvm_utils::path::convert_windows_drive_letter(&format!( + let filename = kcl_utils::path::convert_windows_drive_letter(&format!( "{}", loc.file.name.prefer_remapped() )); diff --git a/kclvm/error/src/error.rs b/crates/error/src/error.rs similarity index 97% rename from kclvm/error/src/error.rs rename to crates/error/src/error.rs index f6d5df5c5..96159afc2 100644 --- a/kclvm/error/src/error.rs +++ b/crates/error/src/error.rs @@ -148,8 +148,8 @@ pub enum WarningKind { /// Test warning `fmt` /// ``` -/// use kclvm_error::*; -/// use kclvm_error::DiagnosticId::Warning; +/// use kcl_error::*; +/// use kcl_error::DiagnosticId::Warning; /// let mut handler = Handler::default(); /// handler.add_warning(WarningKind::UnusedImportWarning, &[ /// Message { @@ -175,8 +175,8 @@ impl std::fmt::Display for WarningKind { /// Test warning `name` /// ``` -/// use kclvm_error::*; -/// use kclvm_error::DiagnosticId::Warning; +/// use kcl_error::*; +/// use kcl_error::DiagnosticId::Warning; /// let mut handler = Handler::default(); /// handler.add_warning(WarningKind::UnusedImportWarning, &[ /// Message { diff --git a/kclvm/error/src/error_codes/E1001.md b/crates/error/src/error_codes/E1001.md similarity index 100% rename from kclvm/error/src/error_codes/E1001.md rename to crates/error/src/error_codes/E1001.md diff --git a/kclvm/error/src/error_codes/E1002.md b/crates/error/src/error_codes/E1002.md similarity index 100% rename from kclvm/error/src/error_codes/E1002.md rename to crates/error/src/error_codes/E1002.md diff --git a/kclvm/error/src/error_codes/E1003.md b/crates/error/src/error_codes/E1003.md similarity index 100% rename from kclvm/error/src/error_codes/E1003.md rename to crates/error/src/error_codes/E1003.md diff --git a/kclvm/error/src/error_codes/E1I37.md b/crates/error/src/error_codes/E1I37.md similarity index 100% rename from kclvm/error/src/error_codes/E1I37.md rename to crates/error/src/error_codes/E1I37.md diff --git a/kclvm/error/src/error_codes/E2A31.md b/crates/error/src/error_codes/E2A31.md similarity index 100% rename from kclvm/error/src/error_codes/E2A31.md rename to crates/error/src/error_codes/E2A31.md diff --git a/kclvm/error/src/error_codes/E2D34.md b/crates/error/src/error_codes/E2D34.md similarity index 100% rename from kclvm/error/src/error_codes/E2D34.md rename to crates/error/src/error_codes/E2D34.md diff --git a/kclvm/error/src/error_codes/E2F04.md b/crates/error/src/error_codes/E2F04.md similarity index 100% rename from kclvm/error/src/error_codes/E2F04.md rename to crates/error/src/error_codes/E2F04.md diff --git a/kclvm/error/src/error_codes/E2G22.md b/crates/error/src/error_codes/E2G22.md similarity index 100% rename from kclvm/error/src/error_codes/E2G22.md rename to crates/error/src/error_codes/E2G22.md diff --git a/kclvm/error/src/error_codes/E2H13.md b/crates/error/src/error_codes/E2H13.md similarity index 100% rename from kclvm/error/src/error_codes/E2H13.md rename to crates/error/src/error_codes/E2H13.md diff --git a/kclvm/error/src/error_codes/E2L23.md b/crates/error/src/error_codes/E2L23.md similarity index 100% rename from kclvm/error/src/error_codes/E2L23.md rename to crates/error/src/error_codes/E2L23.md diff --git a/kclvm/error/src/error_codes/E2L28.md b/crates/error/src/error_codes/E2L28.md similarity index 100% rename from kclvm/error/src/error_codes/E2L28.md rename to crates/error/src/error_codes/E2L28.md diff --git a/kclvm/error/src/error_codes/E3M38.md b/crates/error/src/error_codes/E3M38.md similarity index 100% rename from kclvm/error/src/error_codes/E3M38.md rename to crates/error/src/error_codes/E3M38.md diff --git a/crates/error/src/lib.rs b/crates/error/src/lib.rs new file mode 100644 index 000000000..41366cd7b --- /dev/null +++ b/crates/error/src/lib.rs @@ -0,0 +1,618 @@ +//! Diagnostics creation and emission for `KCL`. +//! This module contains the code for creating and emitting diagnostics. +//! +//! We can use `Handler` to create and emit diagnostics. + +pub mod diagnostic; +mod error; + +use annotate_snippets::{ + display_list::DisplayList, + display_list::FormatOptions, + snippet::{AnnotationType, Slice, Snippet, SourceAnnotation}, +}; +use anyhow::Result; +use compiler_base_error::StyledBuffer; +use compiler_base_error::errors::ComponentFormatError; +use compiler_base_error::{ + Component, Diagnostic as DiagnosticTrait, DiagnosticStyle, + components::{CodeSnippet, Label}, +}; +use compiler_base_session::{Session, SessionDiagnostic}; +use compiler_base_span::{Span, span::new_byte_pos}; +use diagnostic::Range; +use kcl_primitives::{DefaultHashBuilder, IndexSet}; +use kcl_runtime::PanicInfo; +use std::{any::Any, sync::Arc}; +use thiserror::Error; + +pub use diagnostic::{Diagnostic, DiagnosticId, Level, Message, Position, Style}; +pub use error::*; + +/// A handler deals with errors and other compiler output. +/// Certain errors (error, bug) may cause immediate exit, +/// others log errors for later reporting. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub struct Handler { + pub diagnostics: IndexSet, +} + +impl Handler { + /// New a handler using a emitter + pub fn new() -> Self { + Self { + diagnostics: Default::default(), + } + } + + /// Panic program and report a bug + #[inline] + pub fn bug(&self, msg: &str) -> ! { + compiler_base_macros::bug!("{}", msg) + } + + #[inline] + pub fn has_errors(&self) -> bool { + self.diagnostics + .iter() + .any(|diag| diag.level == Level::Error) + } + + /// Emit all diagnostics and return whether has errors. + pub fn emit(&mut self) -> Result { + let sess = Session::default(); + for diag in &self.diagnostics { + sess.add_err(diag.clone())?; + } + sess.emit_stashed_diagnostics()?; + Ok(self.has_errors()) + } + + /// Emit diagnostic to string. + pub fn emit_to_string(&mut self) -> Result { + let sess = Session::default(); + for diag in &self.diagnostics { + sess.add_err(diag.clone())?; + } + let errors = sess.emit_all_diags_into_string()?; + let mut error_strings = vec![]; + for error in errors { + error_strings.push(error?); + } + Ok(error_strings.join("\n")) + } + + /// Emit all diagnostics and abort if has any errors. + pub fn abort_if_any_errors(&mut self) { + match self.emit() { + Ok(has_error) => { + if has_error { + std::process::exit(1); + } + } + Err(err) => self.bug(&format!("{err}")), + } + } + + /// Construct a parse error and put it into the handler diagnostic buffer + pub fn add_syntex_error(&mut self, msg: &str, range: Range) -> &mut Self { + let message = format!("Invalid syntax: {msg}"); + let diag = Diagnostic::new_with_code( + Level::Error, + &message, + None, + range, + Some(DiagnosticId::Error(E1001.kind)), + None, + ); + self.add_diagnostic(diag); + + self + } + + /// Construct a type error and put it into the handler diagnostic buffer + pub fn add_type_error(&mut self, msg: &str, range: Range) -> &mut Self { + let diag = Diagnostic::new_with_code( + Level::Error, + msg, + None, + range, + Some(DiagnosticId::Error(E2G22.kind)), + None, + ); + self.add_diagnostic(diag); + + self + } + + /// Construct a type error and put it into the handler diagnostic buffer + pub fn add_compile_error(&mut self, msg: &str, range: Range) -> &mut Self { + self.add_compile_error_with_suggestions(msg, range, None) + } + + pub fn add_compile_error_with_suggestions( + &mut self, + msg: &str, + range: Range, + suggestions: Option>, + ) -> &mut Self { + let diag = Diagnostic::new_with_code( + Level::Error, + msg, + None, + range, + Some(DiagnosticId::Error(E2L23.kind)), + suggestions, + ); + self.add_diagnostic(diag); + + self + } + + /// Put a runtime panic info the handler diagnostic buffer. + pub fn add_panic_info(&mut self, panic_info: &PanicInfo) -> &mut Self { + self.add_diagnostic(panic_info.clone().into()); + + self + } + + /// Add an error into the handler + /// ``` + /// use kcl_error::*; + /// let mut handler = Handler::default(); + /// handler.add_error(ErrorKind::InvalidSyntax, &[ + /// Message { + /// range: (Position::dummy_pos(), Position::dummy_pos()), + /// style: Style::LineAndColumn, + /// message: "Invalid syntax: expected '+', got '-'".to_string(), + /// note: None, + /// suggested_replacement: None, + /// } + /// ]); + /// ``` + pub fn add_error(&mut self, err: ErrorKind, msgs: &[Message]) -> &mut Self { + let diag = Diagnostic { + level: Level::Error, + messages: msgs.to_owned(), + code: Some(DiagnosticId::Error(err)), + }; + self.add_diagnostic(diag); + + self + } + + pub fn add_suggestions(&mut self, msgs: Vec) -> &mut Self { + msgs.iter().for_each(|s| { + self.add_diagnostic(Diagnostic { + level: Level::Suggestions, + messages: vec![Message { + range: Range::default(), + style: Style::Line, + message: s.to_string(), + note: None, + suggested_replacement: None, + }], + code: Some(DiagnosticId::Suggestions), + }); + }); + + self + } + + /// Add an warning into the handler + /// ``` + /// use kcl_error::*; + /// let mut handler = Handler::default(); + /// handler.add_warning(WarningKind::UnusedImportWarning, &[ + /// Message { + /// range: (Position::dummy_pos(), Position::dummy_pos()), + /// style: Style::LineAndColumn, + /// message: "Module 'a' imported but unused.".to_string(), + /// note: None, + /// suggested_replacement: None, + /// }], + /// ); + /// ``` + pub fn add_warning(&mut self, warning: WarningKind, msgs: &[Message]) -> &mut Self { + let diag = Diagnostic { + level: Level::Warning, + messages: msgs.to_owned(), + code: Some(DiagnosticId::Warning(warning)), + }; + self.add_diagnostic(diag); + + self + } + + /// Classify diagnostics into errors and warnings. + pub fn classification(&self) -> (IndexSet, IndexSet) { + let (mut errs, mut warnings) = ( + IndexSet::with_hasher(DefaultHashBuilder::default()), + IndexSet::with_hasher(DefaultHashBuilder::default()), + ); + for diag in &self.diagnostics { + if diag.level == Level::Error || diag.level == Level::Suggestions { + errs.insert(diag.clone()); + } else if diag.level == Level::Warning { + warnings.insert(diag.clone()); + } else { + continue; + } + } + (errs, warnings) + } + + /// Store a diagnostics into the handler. + /// + /// # Example + /// + /// ``` + /// use kcl_error::*; + /// let mut handler = Handler::default(); + /// handler.add_diagnostic(Diagnostic::new_with_code(Level::Error, "error message", None, (Position::dummy_pos(), Position::dummy_pos()), Some(DiagnosticId::Error(E1001.kind)), None)); + /// ``` + #[inline] + pub fn add_diagnostic(&mut self, diagnostic: Diagnostic) -> &mut Self { + self.diagnostics.insert(diagnostic); + + self + } +} + +impl From for Diagnostic { + fn from(panic_info: PanicInfo) -> Self { + let panic_msg = if panic_info.kcl_arg_msg.is_empty() { + &panic_info.message + } else { + &panic_info.kcl_arg_msg + }; + + let mut diag = if panic_info.backtrace.is_empty() { + let pos = Position { + filename: panic_info.kcl_file.clone(), + line: panic_info.kcl_line as u64, + column: None, + }; + Diagnostic::new_with_code( + Level::Error, + panic_msg, + None, + (pos.clone(), pos), + None, + None, + ) + } else { + let mut backtrace_msg = "backtrace:\n".to_string(); + let mut backtrace = panic_info.backtrace.clone(); + backtrace.reverse(); + for (index, frame) in backtrace.iter().enumerate() { + backtrace_msg.push_str(&format!( + "\t{index}: {}\n\t\tat {}:{}", + frame.func, frame.file, frame.line + )); + if frame.col != 0 { + backtrace_msg.push_str(&format!(":{}", frame.col)) + } + backtrace_msg.push('\n') + } + let pos = Position { + filename: panic_info.kcl_file.clone(), + line: panic_info.kcl_line as u64, + column: None, + }; + Diagnostic::new_with_code( + Level::Error, + panic_msg, + Some(&backtrace_msg), + (pos.clone(), pos), + None, + None, + ) + }; + + if panic_info.kcl_config_meta_file.is_empty() { + return diag; + } + let pos = Position { + filename: panic_info.kcl_config_meta_file.clone(), + line: panic_info.kcl_config_meta_line as u64, + column: Some(panic_info.kcl_config_meta_col as u64), + }; + let mut config_meta_diag = Diagnostic::new_with_code( + Level::Error, + &panic_info.kcl_config_meta_arg_msg, + None, + (pos.clone(), pos), + None, + None, + ); + config_meta_diag.messages.append(&mut diag.messages); + config_meta_diag + } +} + +#[derive(Error, Debug, Clone)] +pub enum ParseErrorMessage { + #[error("invalid token '!', consider using 'not '")] + InvalidTokenNot, + #[error("'else if' here is invalid in KCL, consider using the 'elif' keyword")] + InvalidTokenElseIf, + #[error("unterminated string")] + UnterminatedString, + #[error("unexpected character after line continuation character")] + CharAfterLineContinuationToken, + #[error("the semicolon ';' here is unnecessary, please remove it")] + RedundantSemicolon, + #[error("expected expression, got {0}")] + ExpectExpr(String), + #[error("invalid string interpolation expression: '{0}'")] + InvalidStringInterpolationExpr(String), + #[error("invalid joined string spec without #")] + InvalidJoinedStringSpec, + #[error("invalid joined string")] + InvalidJoinedStringExpr, +} + +#[derive(Debug, Clone)] +pub enum ParseError { + UnexpectedToken { + expected: Vec, + got: String, + span: Span, + }, + Message { + message: ParseErrorMessage, + span: Span, + suggestions: Option>, + }, + String { + message: String, + span: Span, + }, +} + +/// A single string error. +pub struct StringError(pub String); + +impl ParseError { + /// New a unexpected token parse error with span and token information. + pub fn unexpected_token(expected: &[&str], got: &str, span: Span) -> Self { + ParseError::UnexpectedToken { + expected: expected + .iter() + .map(|v| v.to_string()) + .collect::>(), + got: got.to_string(), + span, + } + } + + /// New a message parse error with span. + pub fn message( + message: ParseErrorMessage, + span: Span, + suggestions: Option>, + ) -> Self { + ParseError::Message { + message, + span, + suggestions, + } + } +} + +impl ParseError { + /// Convert a parse error into an error diagnostic. + pub fn into_diag(self, sess: &Session) -> Result { + let span = match self { + ParseError::UnexpectedToken { span, .. } => span, + ParseError::Message { span, .. } => span, + ParseError::String { span, .. } => span, + }; + let start_pos = sess.sm.lookup_char_pos(span.lo()).into(); + let end_pos = sess.sm.lookup_char_pos(span.hi()).into(); + let suggestions = match &self { + ParseError::Message { suggestions, .. } => suggestions.clone(), + _ => None, + }; + Ok(Diagnostic::new_with_code( + Level::Error, + &self.to_string(), + None, + (start_pos, end_pos), + Some(DiagnosticId::Error(ErrorKind::InvalidSyntax)), + suggestions, + )) + } +} + +impl ToString for ParseError { + fn to_string(&self) -> String { + match self { + ParseError::UnexpectedToken { expected, got, .. } => { + format!("expected one of {expected:?} got {got}") + } + ParseError::Message { message, .. } => message.to_string(), + ParseError::String { message, .. } => message.to_string(), + } + } +} + +impl SessionDiagnostic for ParseError { + fn into_diagnostic(self, sess: &Session) -> Result> { + let mut diag = DiagnosticTrait::::new(); + diag.append_component(Box::new(Label::Error(E1001.code.to_string()))); + diag.append_component(Box::new(": invalid syntax\n".to_string())); + match self { + ParseError::UnexpectedToken { span, .. } => { + let code_snippet = CodeSnippet::new(span, Arc::clone(&sess.sm)); + diag.append_component(Box::new(code_snippet)); + diag.append_component(Box::new(format!(" {}\n", self.to_string()))); + Ok(diag) + } + ParseError::Message { message, span, .. } => { + let code_snippet = CodeSnippet::new(span, Arc::clone(&sess.sm)); + diag.append_component(Box::new(code_snippet)); + diag.append_component(Box::new(format!(" {message}\n"))); + Ok(diag) + } + ParseError::String { message, span } => { + let code_snippet = CodeSnippet::new(span, Arc::clone(&sess.sm)); + diag.append_component(Box::new(code_snippet)); + diag.append_component(Box::new(format!(" {message}\n"))); + Ok(diag) + } + } + } +} + +#[derive(Default)] +pub struct SuggestionsLabel; + +impl Component for SuggestionsLabel { + fn format(&self, sb: &mut StyledBuffer, _: &mut Vec) { + sb.appendl("suggestion: ", Some(DiagnosticStyle::NeedAttention)); + } +} + +impl SessionDiagnostic for Diagnostic { + fn into_diagnostic(self, _: &Session) -> Result> { + let mut diag = DiagnosticTrait::::new(); + match self.code { + Some(id) => match id { + DiagnosticId::Error(error) => { + diag.append_component(Box::new(Label::Error(error.code()))); + diag.append_component(Box::new(format!(": {}\n", error.name()))); + } + DiagnosticId::Warning(warning) => { + diag.append_component(Box::new(Label::Warning(warning.code()))); + diag.append_component(Box::new(format!(": {}\n", warning.name()))); + } + DiagnosticId::Suggestions => { + diag.append_component(Box::new(SuggestionsLabel)); + } + }, + None => match self.level { + Level::Error => { + diag.append_component(Box::new(format!("{}\n", ErrorKind::EvaluationError))); + } + Level::Warning => { + diag.append_component(Box::new(format!("{}\n", WarningKind::CompilerWarning))); + } + Level::Note => { + diag.append_component(Box::new(Label::Note)); + } + Level::Suggestions => { + diag.append_component(Box::new(SuggestionsLabel)); + } + }, + } + for msg in &self.messages { + match Session::new_with_file_and_code(&msg.range.0.filename, None) { + Ok(sess) => { + let source = sess.sm.lookup_source_file(new_byte_pos(0)); + let line = source.get_line( + (if msg.range.0.line >= 1 { + msg.range.0.line - 1 + } else { + 0 + }) as usize, + ); + match line.as_ref() { + Some(content) => { + let length = content.chars().count(); + let snippet = Snippet { + title: None, + footer: vec![], + slices: vec![Slice { + source: content, + line_start: msg.range.0.line as usize, + origin: Some(&msg.range.0.filename), + annotations: vec![SourceAnnotation { + range: match msg.range.0.column { + Some(column) if length >= 1 => { + let column = column as usize; + // If the position exceeds the length of the content, + // put the annotation at the end of the line. + if column >= length { + (length - 1, length) + } else { + (column, column + 1) + } + } + _ => (0, 0), + }, + label: &msg.message, + annotation_type: AnnotationType::Error, + }], + fold: true, + }], + opt: FormatOptions { + color: true, + anonymized_line_numbers: false, + margin: None, + }, + }; + let dl = DisplayList::from(snippet); + diag.append_component(Box::new(format!("{dl}\n"))); + } + None => { + let info = msg.range.0.info(); + if !info.is_empty() { + diag.append_component(Box::new(format!( + "{}: {}\n", + info, msg.message + ))); + } else { + diag.append_component(Box::new(format!("{}\n", msg.message))); + } + } + }; + } + Err(_) => { + let info = msg.range.0.info(); + if !info.is_empty() { + diag.append_component(Box::new(format!("{}: {}\n", info, msg.message))); + } else { + diag.append_component(Box::new(format!("{}\n", msg.message))); + } + } + }; + if let Some(note) = &msg.note { + diag.append_component(Box::new(Label::Note)); + diag.append_component(Box::new(format!(": {note}\n"))); + } + // Append a new line. + diag.append_component(Box::new(String::from("\n"))); + } + Ok(diag) + } +} + +impl SessionDiagnostic for StringError { + fn into_diagnostic(self, _: &Session) -> Result> { + let mut diag = DiagnosticTrait::::new(); + diag.append_component(Box::new(Label::Error(E3M38.code.to_string()))); + diag.append_component(Box::new(format!(": {}\n", self.0))); + Ok(diag) + } +} + +/// Convert an error to string. +/// +/// ``` +/// use kcl_error::err_to_str; +/// +/// assert_eq!(err_to_str(Box::new("error_string".to_string())), "error_string"); +/// ``` +pub fn err_to_str(err: Box) -> String { + if let Some(s) = err.downcast_ref::<&str>() { + s.to_string() + } else if let Some(s) = err.downcast_ref::<&String>() { + (*s).clone() + } else if let Some(s) = err.downcast_ref::() { + (*s).clone() + } else { + "".to_string() + } +} diff --git a/kclvm/error/src/warning_codes/W1001.md b/crates/error/src/warning_codes/W1001.md similarity index 100% rename from kclvm/error/src/warning_codes/W1001.md rename to crates/error/src/warning_codes/W1001.md diff --git a/crates/evaluator/Cargo.toml b/crates/evaluator/Cargo.toml new file mode 100644 index 000000000..718c66087 --- /dev/null +++ b/crates/evaluator/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "kcl-evaluator" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +anyhow = "1.0" +generational-arena = "0.2.9" +kcl-ast = { path = "../ast" } +kcl-sema = { path = "../sema" } +kcl-runtime = { path = "../runtime" } +kcl-error = { path = "../error" } +kcl-primitives = { path = "../primitives" } +scopeguard = "1.2.0" + +[dev-dependencies] +kcl-parser = { path = "../parser" } +kcl-loader = { path = "../loader" } +insta = "1.8.0" diff --git a/crates/evaluator/src/calculation.rs b/crates/evaluator/src/calculation.rs new file mode 100644 index 000000000..ccaead1de --- /dev/null +++ b/crates/evaluator/src/calculation.rs @@ -0,0 +1,327 @@ +/* Calculation methods */ + +use kcl_ast::ast; +use kcl_runtime::{ConfigEntryOperationKind, DictValue, UnionOptions, Value, ValueRef}; + +use crate::Evaluator; +use crate::ty::{resolve_schema, type_pack_and_check}; +use crate::union::union_entry; + +impl<'ctx> Evaluator<'ctx> { + /// lhs + rhs + #[inline] + pub(crate) fn add(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.bin_add(&mut self.runtime_ctx.borrow_mut(), &rhs) + } + /// lhs - rhs + #[inline] + pub(crate) fn sub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.bin_sub(&mut self.runtime_ctx.borrow_mut(), &rhs) + } + /// lhs * rhs + #[inline] + pub(crate) fn mul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.bin_mul(&mut self.runtime_ctx.borrow_mut(), &rhs) + } + /// lhs / rhs + #[inline] + pub(crate) fn div(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.bin_div(&rhs) + } + /// lhs // rhs + #[inline] + pub(crate) fn floor_div(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.bin_floor_div(&rhs) + } + /// lhs % rhs + #[inline] + pub(crate) fn r#mod(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.bin_mod(&rhs) + } + /// lhs ** rhs + #[inline] + pub(crate) fn pow(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.bin_pow(&mut self.runtime_ctx.borrow_mut(), &rhs) + } + /// lhs << rhs + #[inline] + pub(crate) fn bit_lshift(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.bin_bit_lshift(&mut self.runtime_ctx.borrow_mut(), &rhs) + } + /// lhs >> rhs + #[inline] + pub(crate) fn bit_rshift(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.bin_bit_rshift(&mut self.runtime_ctx.borrow_mut(), &rhs) + } + /// lhs & rhs + #[inline] + pub(crate) fn bit_and(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.bin_bit_and(&rhs) + } + /// lhs | rhs + #[inline] + pub(crate) fn bit_or(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + if let (Value::int_value(a), Value::int_value(b)) = (&*lhs.rc.borrow(), &*rhs.rc.borrow()) { + return ValueRef::int(*a | *b); + }; + union_entry( + self, + &mut lhs.deep_copy(), + &rhs, + true, + &UnionOptions::default(), + ) + } + /// lhs ^ rhs + #[inline] + pub(crate) fn bit_xor(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.bin_bit_xor(&rhs) + } + /// lhs and rhs + #[inline] + pub(crate) fn logic_and(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.logic_and(&rhs).into() + } + /// lhs or rhs + #[inline] + pub(crate) fn logic_or(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.logic_or(&rhs).into() + } + /// lhs == rhs + #[inline] + pub(crate) fn cmp_equal_to(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.cmp_equal(&rhs).into() + } + /// lhs != rhs + #[inline] + pub(crate) fn cmp_not_equal_to(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.cmp_not_equal(&rhs).into() + } + /// lhs > rhs + #[inline] + pub(crate) fn cmp_greater_than(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.cmp_greater_than(&rhs).into() + } + /// lhs >= rhs + #[inline] + pub(crate) fn cmp_greater_than_or_equal(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.cmp_greater_than_or_equal(&rhs).into() + } + /// lhs < rhs + #[inline] + pub(crate) fn cmp_less_than(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.cmp_less_than(&rhs).into() + } + /// lhs <= rhs + #[inline] + pub(crate) fn cmp_less_than_or_equal(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.cmp_less_than_or_equal(&rhs).into() + } + /// lhs as rhs + #[inline] + pub(crate) fn r#as(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + type_pack_and_check(self, &lhs, vec![&rhs.as_str()], true) + } + /// lhs is rhs + #[inline] + pub(crate) fn is(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + (lhs == rhs).into() + } + /// lhs is not rhs + #[inline] + pub(crate) fn is_not(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + (lhs != rhs).into() + } + /// lhs in rhs + #[inline] + pub(crate) fn r#in(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.r#in(&rhs).into() + } + /// lhs not in rhs + #[inline] + pub(crate) fn not_in(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { + lhs.not_in(&rhs).into() + } +} + +impl<'ctx> Evaluator<'ctx> { + /// Value is truth function, return i1 value. + #[inline] + pub(crate) fn value_is_truthy(&self, value: &ValueRef) -> bool { + value.is_truthy() + } + /// Value deep copy + #[inline] + pub(crate) fn value_deep_copy(&self, value: &ValueRef) -> ValueRef { + value.deep_copy() + } + /// value_union unions two collection elements. + pub(crate) fn value_union(&self, lhs: &mut ValueRef, rhs: &ValueRef) -> ValueRef { + let attr_map = match &*lhs.rc.borrow() { + Value::dict_value(dict) => dict.attr_map.clone(), + Value::schema_value(schema) => schema.config.attr_map.clone(), + _ => panic!("invalid object '{}' in attr_map", lhs.type_str()), + }; + let opts = UnionOptions { + list_override: false, + idempotent_check: false, + config_resolve: true, + }; + if rhs.is_config() { + let dict = rhs.as_dict_ref(); + for k in dict.values.keys() { + let entry = rhs.dict_get_entry(k).unwrap(); + union_entry(self, lhs, &entry, true, &opts); + // Has type annotation + if let Some(ty) = attr_map.get(k) { + let value = lhs.dict_get_value(k).unwrap(); + lhs.dict_update_key_value( + k, + type_pack_and_check(self, &value, vec![ty], false), + ); + } + } + lhs.clone() + } else { + union_entry(self, lhs, rhs, true, &opts) + } + } + /// Append a item into the list. + #[inline] + pub(crate) fn list_append(&self, list: &mut ValueRef, item: &ValueRef) { + list.list_append(item) + } + /// Append a list item and unpack it into the list. + #[inline] + pub(crate) fn list_append_unpack(&self, list: &mut ValueRef, item: &ValueRef) { + list.list_append_unpack(item) + } + #[inline] + pub(crate) fn dict_get_value(&self, dict: &ValueRef, key: &str) -> ValueRef { + dict.dict_get_value(key).unwrap_or(self.undefined_value()) + } + /// Insert a dict entry including key, value, op and insert_index into the dict, + /// and the type of key is `&str` + #[inline] + pub(crate) fn dict_insert( + &self, + dict: &mut ValueRef, + key: &str, + value: &ValueRef, + op: &ast::ConfigEntryOperation, + insert_index: Option, + ) { + let op = match op { + ast::ConfigEntryOperation::Union => ConfigEntryOperationKind::Union, + ast::ConfigEntryOperation::Override => ConfigEntryOperationKind::Override, + ast::ConfigEntryOperation::Insert => ConfigEntryOperationKind::Insert, + }; + self.dict_merge_key_value_pair(dict, key, value, op, insert_index, true); + } + + /// Insert a dict entry including key, value, op and insert_index into the dict, + /// and the type of key is `&str` + #[inline] + pub(crate) fn schema_dict_merge( + &self, + dict: &mut ValueRef, + key: &str, + value: &ValueRef, + op: &ast::ConfigEntryOperation, + insert_index: Option, + ) { + let op = match op { + ast::ConfigEntryOperation::Union => ConfigEntryOperationKind::Union, + ast::ConfigEntryOperation::Override => ConfigEntryOperationKind::Override, + ast::ConfigEntryOperation::Insert => ConfigEntryOperationKind::Insert, + }; + let attr_map = { + match &*dict.rc.borrow() { + Value::dict_value(dict) => dict.attr_map.clone(), + Value::schema_value(schema) => schema.config.attr_map.clone(), + _ => panic!("invalid object '{}' in attr_map", dict.type_str()), + } + }; + if attr_map.contains_key(key) { + let v = type_pack_and_check(self, value, vec![attr_map.get(key).unwrap()], false); + self.dict_merge_key_value_pair(dict, key, &v, op, insert_index, false); + } else { + self.dict_merge_key_value_pair(dict, key, value, op, insert_index, false); + } + } + + /// Insert an entry including key and value into the dict. + #[inline] + pub(crate) fn dict_insert_value(&self, dict: &mut ValueRef, key: &str, value: &ValueRef) { + dict.dict_update_key_value(key, value.clone()) + } + + /// Insert an entry including key and value into the dict, and merge the original entry. + #[inline] + pub(crate) fn dict_insert_merge_value(&self, dict: &mut ValueRef, key: &str, value: &ValueRef) { + self.dict_merge_key_value_pair( + dict, + key, + value, + ConfigEntryOperationKind::Union, + None, + true, + ); + } + + /// Set dict key with the value. When the dict is a schema and resolve schema validations. + pub(crate) fn dict_set_value(&self, p: &mut ValueRef, key: &str, val: &ValueRef) { + if p.is_config() { + p.dict_update_key_value(key, val.clone()); + if p.is_schema() { + let schema: ValueRef; + { + let schema_value = p.as_schema(); + let mut config_keys = schema_value.config_keys.clone(); + config_keys.push(key.to_string()); + schema = resolve_schema(self, p, &config_keys); + } + p.schema_update_with_schema(&schema); + } + } else { + panic!( + "failed to update the dict. An iterable of key-value pairs was expected, but got {}. Check if the syntax for updating the dictionary with the attribute '{}' is correct", + p.type_str(), + key + ); + } + } + + /// Private dict merge key value pair with the idempotent check option + pub(crate) fn dict_merge_key_value_pair( + &self, + p: &mut ValueRef, + key: &str, + v: &ValueRef, + op: ConfigEntryOperationKind, + insert_index: Option, + idempotent_check: bool, + ) { + if p.is_config() { + let mut dict: DictValue = Default::default(); + dict.values.insert(key.to_string(), v.clone()); + dict.ops.insert(key.to_string(), op); + if let Some(index) = insert_index { + dict.insert_indexs.insert(key.to_string(), index); + } + union_entry( + self, + p, + &ValueRef::from(Value::dict_value(Box::new(dict))), + true, + &UnionOptions { + config_resolve: false, + idempotent_check, + ..Default::default() + }, + ); + } else { + panic!("invalid dict insert value: {}", p.type_str()) + } + } +} diff --git a/crates/evaluator/src/context.rs b/crates/evaluator/src/context.rs new file mode 100644 index 000000000..a4f62f115 --- /dev/null +++ b/crates/evaluator/src/context.rs @@ -0,0 +1,320 @@ +use std::{collections::HashSet, rc::Rc}; + +use generational_arena::Index; +use kcl_ast::ast; +use kcl_runtime::{BacktraceFrame, MAIN_PKG_PATH}; + +use crate::{ + EvalContext, Evaluator, LambdaOrSchemaEvalContext, error as kcl_error, + func::{FunctionCaller, FunctionEvalContextRef}, + lazy::{BacktrackMeta, Setter, SetterKind}, + proxy::{Frame, Proxy}, + rule::RuleCaller, + schema::SchemaCaller, +}; + +impl<'ctx> Evaluator<'ctx> { + /// Current package path + #[inline] + pub(crate) fn current_pkgpath(&self) -> String { + self.pkgpath_stack + .borrow() + .last() + .expect(kcl_error::INTERNAL_ERROR_MSG) + .to_string() + } + + /// Last package path + #[inline] + pub(crate) fn last_pkgpath(&self) -> String { + let len = self.pkgpath_stack.borrow().len(); + self.pkgpath_stack + .borrow() + .get(if len > 2 { len - 2 } else { 2 - len }) + .unwrap_or(&MAIN_PKG_PATH.to_string()) + .to_string() + } + + /// Update current runtime context kcl filename and line + #[inline] + pub(crate) fn update_ctx_panic_info(&self, node: &'ctx ast::Node) { + let mut ctx = self.runtime_ctx.borrow_mut(); + ctx.panic_info.kcl_file = node.filename.clone(); + ctx.panic_info.kcl_line = node.line as i32; + } + + /// Update current AST index. + #[inline] + pub(crate) fn update_ast_id(&self, node: &'ctx ast::Node) { + *self.ast_id.borrow_mut() = node.id.clone(); + } + + /// Push a lambda definition scope into the lambda stack + #[inline] + pub fn push_lambda( + &self, + lambda_ctx: FunctionEvalContextRef, + current_pkgpath: &str, + frame_pkgpath: &str, + level: usize, + ) { + // Capture function schema this reference. + if let Some(this) = &lambda_ctx.this { + self.push_schema(this.eval_ctx()); + } + // Inner scope function calling. + // Note the minimum lambda.ctx.level is 2 for the top level lambda definitions. + if frame_pkgpath == current_pkgpath && level >= lambda_ctx.level { + // The scope cover is [lambda.ctx.level, self.scope_level()] + self.push_scope_cover(lambda_ctx.level, level); + } + self.lambda_stack.borrow_mut().push(lambda_ctx.clone()); + self.ctx_stack + .borrow_mut() + .push(LambdaOrSchemaEvalContext::Lambda(lambda_ctx)); + } + + /// Pop a lambda definition scope. + #[inline] + pub fn pop_lambda( + &self, + lambda_ctx: FunctionEvalContextRef, + current_pkgpath: &str, + frame_pkgpath: &str, + level: usize, + ) { + self.lambda_stack.borrow_mut().pop(); + self.ctx_stack.borrow_mut().pop(); + // Inner scope function calling. + if frame_pkgpath == current_pkgpath && level >= lambda_ctx.level { + self.pop_scope_cover(); + } + // Release function schema this reference. + if lambda_ctx.this.is_some() { + self.pop_schema() + } + } + + #[inline] + pub fn is_in_lambda(&self) -> bool { + !self.lambda_stack.borrow().is_empty() + } + + #[inline] + pub fn last_lambda_ctx(&self) -> Option { + self.lambda_stack.borrow().last().cloned() + } + + #[inline] + pub fn push_schema(&self, v: EvalContext) { + self.schema_stack.borrow_mut().push(v.clone()); + self.ctx_stack + .borrow_mut() + .push(LambdaOrSchemaEvalContext::Schema(v)); + } + + #[inline] + pub fn pop_schema(&self) { + self.schema_stack.borrow_mut().pop(); + self.ctx_stack.borrow_mut().pop(); + } + + #[inline] + pub fn is_in_schema(&self) -> bool { + !self.schema_stack.borrow().is_empty() + } + + #[inline] + pub fn push_schema_expr(&self) { + self.schema_expr_stack.borrow_mut().push(()); + } + + #[inline] + pub fn pop_schema_expr(&self) { + self.schema_expr_stack.borrow_mut().pop(); + } + + #[inline] + pub fn is_in_schema_expr(&self) -> bool { + !self.schema_expr_stack.borrow().is_empty() + } + + #[inline] + pub fn add_local_var(&self, name: &str) { + self.local_vars.borrow_mut().insert(name.to_string()); + } + + #[inline] + pub fn remove_local_var(&self, name: &str) { + self.local_vars.borrow_mut().remove(name); + } + + #[inline] + pub fn is_local_var(&self, name: &str) -> bool { + self.local_vars.borrow().contains(name) + } + + #[inline] + pub(crate) fn clear_local_vars(&self) { + self.local_vars.borrow_mut().clear(); + } + + #[inline] + pub(crate) fn clean_and_cloned_local_vars(&self) -> HashSet { + let mut local_vars = self.local_vars.borrow_mut(); + let r = local_vars.clone(); + local_vars.clear(); + r + } + + #[inline] + pub(crate) fn set_local_vars(&self, vars: HashSet) { + self.local_vars.borrow_mut().extend(vars); + } + + #[inline] + pub(crate) fn add_target_var(&self, name: &str) { + self.target_vars.borrow_mut().push(name.to_string()); + } + + #[inline] + pub(crate) fn pop_target_var(&self) { + self.target_vars.borrow_mut().pop(); + } + + #[inline] + pub(crate) fn get_target_var(&self) -> String { + self.target_vars + .borrow() + .last() + .cloned() + .unwrap_or_default() + } + + #[inline] + pub(crate) fn check_imported(&self, pkgpath: &str) -> bool { + let imported = &mut self.imported.borrow_mut(); + imported.contains(pkgpath) + } + + #[inline] + pub(crate) fn mark_imported(&self, pkgpath: &str) { + let imported = &mut self.imported.borrow_mut(); + (*imported).insert(pkgpath.to_string()); + } + + #[inline] + pub(crate) fn push_pkgpath(&self, pkgpath: &str) { + self.pkgpath_stack.borrow_mut().push(pkgpath.to_string()); + self.runtime_ctx.borrow_mut().set_kcl_pkgpath(pkgpath); + } + + #[inline] + pub(crate) fn pop_pkgpath(&self) { + if let Some(pkgpath) = self.pkgpath_stack.borrow_mut().pop() { + self.runtime_ctx.borrow_mut().set_kcl_pkgpath(&pkgpath); + } + } + + /// Append a global body into the scope. + #[inline] + pub(crate) fn add_global_body(&self, index: usize) -> Index { + let pkgpath = self.current_pkgpath(); + self.frames.borrow_mut().insert(Rc::new(Frame { + pkgpath, + proxy: Proxy::Global(index), + })) + } + + /// Append a function into the scope. + #[inline] + pub(crate) fn add_function(&self, function: FunctionCaller) -> Index { + let pkgpath = self.current_pkgpath(); + self.frames.borrow_mut().insert(Rc::new(Frame { + pkgpath, + proxy: Proxy::Lambda(function), + })) + } + + /// Append a schema into the scope. + #[inline] + pub(crate) fn add_schema(&self, schema: SchemaCaller) -> Index { + let pkgpath = self.current_pkgpath(); + self.frames.borrow_mut().insert(Rc::new(Frame { + pkgpath, + proxy: Proxy::Schema(schema), + })) + } + + /// Append a rule into the scope. + #[inline] + pub(crate) fn add_rule(&self, rule: RuleCaller) -> Index { + let pkgpath = self.current_pkgpath(); + self.frames.borrow_mut().insert(Rc::new(Frame { + pkgpath, + proxy: Proxy::Rule(rule), + })) + } + + pub(crate) fn push_backtrace(&self, frame: &Frame) { + let ctx = &mut self.runtime_ctx.borrow_mut(); + if ctx.cfg.debug_mode { + let backtrace_frame = BacktraceFrame::from_panic_info(&ctx.panic_info); + ctx.backtrace.push(backtrace_frame); + ctx.panic_info.kcl_func = frame.proxy.get_name(); + } + } + + pub(crate) fn pop_backtrace(&self) { + let ctx = &mut self.runtime_ctx.borrow_mut(); + if ctx.cfg.debug_mode { + if let Some(backtrace_frame) = ctx.backtrace.pop() { + ctx.panic_info.kcl_func = backtrace_frame.func; + ctx.panic_info.kcl_line = backtrace_frame.line; + ctx.panic_info.kcl_file = backtrace_frame.file; + } + } + } + + #[inline] + pub(crate) fn push_backtrack_meta(&self, setter: &Setter) { + let meta = &mut self.backtrack_meta.borrow_mut(); + meta.push(BacktrackMeta { + stopped: setter.stopped.clone(), + is_break: false, + kind: setter.kind.clone(), + }); + } + + #[inline] + pub(crate) fn pop_backtrack_meta(&self) { + let meta = &mut self.backtrack_meta.borrow_mut(); + meta.pop(); + } + + #[inline] + pub(crate) fn is_backtrack_only_if(&self) -> bool { + let meta = &mut self.backtrack_meta.borrow_mut(); + match meta.last().map(|m| matches!(m.kind, SetterKind::If)) { + Some(r) => r, + None => false, + } + } + + #[inline] + pub(crate) fn is_backtrack_only_or_else(&self) -> bool { + let meta = &mut self.backtrack_meta.borrow_mut(); + match meta.last().map(|m| matches!(m.kind, SetterKind::OrElse)) { + Some(r) => r, + None => false, + } + } + + pub(crate) fn push_scope_cover(&self, start: usize, stop: usize) { + self.scope_covers.borrow_mut().push((start, stop)); + } + + pub(crate) fn pop_scope_cover(&self) { + self.scope_covers.borrow_mut().pop(); + } +} diff --git a/kclvm/evaluator/src/error.rs b/crates/evaluator/src/error.rs similarity index 100% rename from kclvm/evaluator/src/error.rs rename to crates/evaluator/src/error.rs diff --git a/kclvm/evaluator/src/func.rs b/crates/evaluator/src/func.rs similarity index 97% rename from kclvm/evaluator/src/func.rs rename to crates/evaluator/src/func.rs index e43c67f7e..8f579f55a 100644 --- a/kclvm/evaluator/src/func.rs +++ b/crates/evaluator/src/func.rs @@ -2,15 +2,15 @@ use std::fmt::Debug; use std::sync::Arc; use generational_arena::Index; -use kclvm_ast::ast; -use kclvm_primitives::IndexMap; -use kclvm_runtime::ValueRef; +use kcl_ast::ast; +use kcl_primitives::IndexMap; +use kcl_runtime::ValueRef; use scopeguard::defer; +use crate::Evaluator; use crate::proxy::Proxy; use crate::ty::type_pack_and_check; -use crate::Evaluator; -use crate::{error as kcl_error, EvalContext}; +use crate::{EvalContext, error as kcl_error}; pub type FunctionHandler = Arc ValueRef>; diff --git a/kclvm/evaluator/src/lazy.rs b/crates/evaluator/src/lazy.rs similarity index 99% rename from kclvm/evaluator/src/lazy.rs rename to crates/evaluator/src/lazy.rs index fd0c46f42..7cc20b8d7 100644 --- a/kclvm/evaluator/src/lazy.rs +++ b/crates/evaluator/src/lazy.rs @@ -2,14 +2,14 @@ use std::cell::RefCell; use std::rc::Rc; use generational_arena::Index; -use kclvm_ast::ast; -use kclvm_ast::ast::AstIndex; -use kclvm_primitives::IndexMap; -use kclvm_runtime::ValueRef; +use kcl_ast::ast; +use kcl_ast::ast::AstIndex; +use kcl_primitives::IndexMap; +use kcl_runtime::ValueRef; +use crate::Evaluator; use crate::error as kcl_error; use crate::error::INTERNAL_ERROR_MSG; -use crate::Evaluator; pub type LazyEvalScopeRef = Rc>; #[macro_export] diff --git a/crates/evaluator/src/lib.rs b/crates/evaluator/src/lib.rs new file mode 100644 index 000000000..32332ae72 --- /dev/null +++ b/crates/evaluator/src/lib.rs @@ -0,0 +1,243 @@ +//! Copyright The KCL Authors. All rights reserved. + +#[cfg(test)] +mod tests; + +mod calculation; +mod context; +mod error; +mod func; +#[macro_use] +mod lazy; +mod module; +mod node; +mod proxy; +mod rule; +mod runtime; +mod schema; +mod scope; +mod ty; +mod union; +mod value; + +extern crate kcl_error; + +use func::FunctionEvalContextRef; +use generational_arena::{Arena, Index}; +use kcl_primitives::IndexMap; +use kcl_runtime::val_plan::KCL_PRIVATE_VAR_PREFIX; +use lazy::{BacktrackMeta, LazyEvalScope}; +use proxy::{Frame, Proxy}; +use rule::RuleEvalContextRef; +use schema::SchemaEvalContextRef; +use scope::Scope; +use std::collections::{HashMap, HashSet}; +use std::panic::RefUnwindSafe; +use std::rc::Rc; +use std::str; +use std::{cell::RefCell, panic::UnwindSafe}; + +use crate::error as eval_error; +use anyhow::Result; +use kcl_ast::ast::{self, AstIndex}; +use kcl_runtime::{Context, ValueRef}; + +/// SCALAR_KEY denotes the temp scalar key for the global variable json plan process. +const SCALAR_KEY: &str = ""; +/// Global level +const GLOBAL_LEVEL: usize = 1; +/// Inner level +const INNER_LEVEL: usize = 2; + +/// The evaluator function result +pub type EvalResult = Result; + +/// The evaluator for the program +pub struct Evaluator<'ctx> { + pub program: &'ctx ast::Program, + /// All frames including functions, schemas and rules + pub frames: RefCell>>, + /// All schema index in the package path, we can find the frame through the index. + pub schemas: RefCell>, + /// Runtime evaluation context. + pub runtime_ctx: Rc>, + /// Package path stack. + pub pkgpath_stack: RefCell>, + /// Filename stack. + pub filename_stack: RefCell>, + /// The names of possible assignment objects for the current instruction. + pub target_vars: RefCell>, + /// Imported package path set to judge is there a duplicate import. + pub imported: RefCell>, + /// The lambda stack index denotes the scope level of the lambda function. + pub lambda_stack: RefCell>, + /// To judge is in the schema statement. + pub schema_stack: RefCell>, + /// Order lambda and schema ctx vec + pub ctx_stack: RefCell>, + /// To judge is in the schema expression. + pub schema_expr_stack: RefCell>, + /// Import names mapping + pub import_names: RefCell>>, + /// Package scope to store variable values. + pub pkg_scopes: RefCell>>, + /// Package lazy scope to store variable cached values. + pub lazy_scopes: RefCell>, + /// Scope cover to block the acquisition of certain scopes. + pub scope_covers: RefCell>, + /// Local variables in the loop. + pub local_vars: RefCell>, + /// Schema attr backtrack meta. + pub backtrack_meta: RefCell>, + /// Current AST id for the evaluator walker. + pub ast_id: RefCell, +} + +#[derive(Clone)] +pub enum LambdaOrSchemaEvalContext { + Schema(EvalContext), + Lambda(FunctionEvalContextRef), +} + +#[derive(Clone)] +pub enum EvalContext { + Schema(SchemaEvalContextRef), + Rule(RuleEvalContextRef), +} + +impl EvalContext { + #[inline] + pub fn value(&self) -> ValueRef { + match self { + EvalContext::Schema(schema) => schema.borrow().value.clone(), + EvalContext::Rule(rule) => rule.borrow().value.clone(), + } + } + + #[inline] + pub fn config(&self) -> ValueRef { + match self { + EvalContext::Schema(schema) => schema.borrow().config.clone(), + EvalContext::Rule(rule) => rule.borrow().config.clone(), + } + } +} + +impl<'ctx> Evaluator<'ctx> { + /// New aa Evaluator using the AST program + #[inline] + pub fn new(program: &'ctx ast::Program) -> Evaluator<'ctx> { + Self::new_with_runtime_ctx(program, Rc::new(RefCell::new(Context::new()))) + } + + /// New aa Evaluator using the AST program and runtime context + #[inline] + pub fn new_with_runtime_ctx( + program: &'ctx ast::Program, + runtime_ctx: Rc>, + ) -> Evaluator<'ctx> { + Evaluator { + runtime_ctx, + program, + frames: RefCell::new(Arena::new()), + schemas: RefCell::new(Default::default()), + target_vars: RefCell::new(vec![]), + lambda_stack: RefCell::new(vec![]), + imported: RefCell::new(Default::default()), + schema_stack: RefCell::new(Default::default()), + schema_expr_stack: RefCell::new(Default::default()), + pkgpath_stack: RefCell::new(vec![kcl_ast::MAIN_PKG.to_string()]), + filename_stack: RefCell::new(Default::default()), + import_names: RefCell::new(Default::default()), + pkg_scopes: RefCell::new(Default::default()), + lazy_scopes: RefCell::new(Default::default()), + scope_covers: RefCell::new(Default::default()), + local_vars: RefCell::new(Default::default()), + backtrack_meta: RefCell::new(Default::default()), + ast_id: RefCell::new(AstIndex::default()), + ctx_stack: RefCell::new(Default::default()), + } + } + + /// Evaluate the program and return the JSON and YAML result. + pub fn run(self: &Evaluator<'ctx>) -> Result<(String, String)> { + let modules = self.program.get_modules_for_pkg(kcl_ast::MAIN_PKG); + self.init_scope(kcl_ast::MAIN_PKG); + self.compile_ast_modules(&modules); + Ok(self.plan_globals_to_string()) + } + + /// Evaluate the program with the function mode and return the JSON and YAML result, + /// which means treating the files in the entire main package as a function run to + /// return the result of the function run, rather than a dictionary composed of each + /// configuration attribute. + pub fn run_as_function(self: &Evaluator<'ctx>) -> ValueRef { + let modules = self.program.get_modules_for_pkg(kcl_ast::MAIN_PKG); + if modules.is_empty() { + ValueRef::undefined() + } else { + self.init_scope(kcl_ast::MAIN_PKG); + self.compile_ast_modules(&modules) + } + } + + /// Plan globals to a planed json and yaml string. + pub(crate) fn plan_globals_to_string(&self) -> (String, String) { + let current_pkgpath = self.current_pkgpath(); + let pkg_scopes = &self.pkg_scopes.borrow(); + let scopes = pkg_scopes + .get(¤t_pkgpath) + .unwrap_or_else(|| panic!("pkgpath {} is not found", current_pkgpath)); + // The global scope. + let scope = scopes.last().expect(eval_error::INTERNAL_ERROR_MSG); + let scalars = &scope.scalars; + let globals = &scope.variables; + // Construct a plan object. + let mut global_dict = self.dict_value(); + // Plan empty dict result. + if scalars.is_empty() && globals.is_empty() { + return self.plan_value(&global_dict); + } + // Deal scalars + for scalar in scalars.iter() { + self.dict_insert_merge_value(&mut global_dict, SCALAR_KEY, scalar); + } + // Deal global variables + for (name, value) in globals.iter() { + if name.starts_with(KCL_PRIVATE_VAR_PREFIX) + && !self.runtime_ctx.borrow().plan_opts.show_hidden + { + continue; + } + let mut value_dict = self.dict_value(); + self.dict_insert_merge_value(&mut value_dict, name.as_str(), value); + self.dict_insert_merge_value(&mut global_dict, SCALAR_KEY, &value_dict); + } + // Plan result to JSON and YAML string. + match global_dict.dict_get_value(SCALAR_KEY) { + Some(value) => self.plan_value(&value), + None => self.plan_value(&self.dict_value()), + } + } + + /// Get evaluator default ok result + #[inline] + pub fn ok_result(&self) -> EvalResult { + Ok(self.undefined_value()) + } + + pub fn plan_value(&self, value: &ValueRef) -> (String, String) { + let mut ctx = self.runtime_ctx.borrow_mut(); + let value = match ctx.buffer.custom_manifests_output.clone() { + Some(output) => ValueRef::from_yaml_stream(&mut ctx, &output).unwrap(), + None => value.clone(), + }; + let (json_string, yaml_string) = value.plan(&ctx); + ctx.json_result = json_string.clone(); + ctx.yaml_result = yaml_string.clone(); + (json_string, yaml_string) + } +} + +impl UnwindSafe for Evaluator<'_> {} +impl RefUnwindSafe for Evaluator<'_> {} diff --git a/crates/evaluator/src/module.rs b/crates/evaluator/src/module.rs new file mode 100644 index 000000000..fb46af7a6 --- /dev/null +++ b/crates/evaluator/src/module.rs @@ -0,0 +1,108 @@ +// Copyright The KCL Authors. All rights reserved. + +use std::sync::{Arc, RwLock}; + +use kcl_ast::ast; +use kcl_ast::walker::TypedResultWalker; +use kcl_runtime::ValueRef; + +use super::Evaluator; +use crate::error as kcl_error; + +impl<'ctx> Evaluator<'_> { + pub fn compile_module_import_and_types(&self, module: &'ctx ast::Module) { + for stmt in &module.body { + match &stmt.node { + ast::Stmt::Import(import_stmt) => { + self.walk_import_stmt(import_stmt) + .expect(kcl_error::RUNTIME_ERROR_MSG); + } + ast::Stmt::Schema(schema_stmt) => { + // Pre define global types with undefined values + self.predefine_global_types(&schema_stmt.name.node); + self.walk_schema_stmt(schema_stmt) + .expect(kcl_error::RUNTIME_ERROR_MSG); + } + ast::Stmt::Rule(rule_stmt) => { + // Pre define global types with undefined values + self.predefine_global_types(&rule_stmt.name.node); + self.walk_rule_stmt(rule_stmt) + .expect(kcl_error::RUNTIME_ERROR_MSG); + } + _ => {} + }; + } + } + + pub fn predefine_global_types(&self, name: &str) { + // Store or add the variable in the scope + let function = self.undefined_value(); + if !self.store_variable(name, function.clone()) { + self.add_variable(name, function); + } + } + + /// Predefine all global variables. + #[inline] + pub(crate) fn predefine_global_vars(&self, module: &'ctx ast::Module) { + self.emit_global_vars(&module.body); + } + + fn emit_global_vars(&self, body: &'ctx [Box>]) { + for stmt in body { + match &stmt.node { + ast::Stmt::Unification(unification_stmt) => { + let names = &unification_stmt.target.node.names; + if names.len() == 1 { + self.add_or_update_global_variable( + &names[0].node, + self.undefined_value(), + false, + ); + } + } + ast::Stmt::Assign(assign_stmt) => { + for target in &assign_stmt.targets { + self.add_or_update_global_variable( + &target.node.get_name(), + self.undefined_value(), + false, + ); + } + } + ast::Stmt::If(if_stmt) => { + self.emit_global_vars(&if_stmt.body); + self.emit_global_vars(&if_stmt.orelse); + } + _ => {} + } + } + } + + /// Compile AST Modules, which requires traversing three times. + /// 1. scan all possible global variables and allocate undefined values to global pointers. + /// 2. build all user-defined schema/rule types. + /// 3. evaluate all codes for the third time. + pub(crate) fn compile_ast_modules(&self, modules: &[Arc>]) -> ValueRef { + // Scan global variables + for ast_module in modules { + let ast_module = ast_module.read().expect("Failed to acquire module lock"); + // Pre define global variables with undefined values + self.predefine_global_vars(&ast_module); + } + // Scan global types + for ast_module in modules { + let ast_module = ast_module.read().expect("Failed to acquire module lock"); + self.compile_module_import_and_types(&ast_module); + } + let mut result = ValueRef::undefined(); + // Compile the ast module in the pkgpath. + for ast_module in modules { + let ast_module = ast_module.read().expect("Failed to acquire module lock"); + result = self + .walk_module(&ast_module) + .expect(kcl_error::RUNTIME_ERROR_MSG); + } + result + } +} diff --git a/crates/evaluator/src/node.rs b/crates/evaluator/src/node.rs new file mode 100644 index 000000000..49454faec --- /dev/null +++ b/crates/evaluator/src/node.rs @@ -0,0 +1,1667 @@ +// Copyright The KCL Authors. All rights reserved. + +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::{Arc, RwLock}; + +use anyhow::Ok; +use generational_arena::Index; +use kcl_ast::ast::{self, CallExpr, ConfigEntry, Module, NodeRef}; +use kcl_ast::walker::TypedResultWalker; +use kcl_runtime::{ + ConfigEntryOperationKind, DecoratorValue, PKG_PATH_PREFIX, RuntimeErrorType, UnionOptions, + ValueRef, schema_assert, schema_runtime_type, +}; +use kcl_sema::{builtin, pkgpath_without_prefix, plugin}; +use scopeguard::defer; + +use crate::error::INTERNAL_ERROR_MSG; +use crate::func::{FunctionCaller, FunctionEvalContext, FunctionEvalThis, func_body}; +use crate::lazy::Setter; +use crate::proxy::Proxy; +use crate::rule::{RuleCaller, RuleEvalContext, rule_body, rule_check}; +use crate::runtime::invoke_function; +use crate::schema::{SchemaCaller, SchemaEvalContext, schema_body, schema_check}; +use crate::ty::type_pack_and_check; +use crate::union::union_entry; +use crate::{EvalResult, Evaluator}; +use crate::{GLOBAL_LEVEL, INNER_LEVEL, error as kcl_error}; +use crate::{backtrack_break_here, backtrack_update_break}; + +/// Impl TypedResultWalker for Evaluator to visit AST nodes to evaluate the result. +impl<'ctx> TypedResultWalker<'ctx> for Evaluator<'ctx> { + type Result = EvalResult; + + /* + * Stmt + */ + + fn walk_stmt(&self, stmt: &'ctx ast::Node) -> Self::Result { + backtrack_break_here!(self, stmt); + self.update_ctx_panic_info(stmt); + self.update_ast_id(stmt); + let value = match &stmt.node { + ast::Stmt::TypeAlias(type_alias) => self.walk_type_alias_stmt(type_alias), + ast::Stmt::Expr(expr_stmt) => self.walk_expr_stmt(expr_stmt), + ast::Stmt::Unification(unification_stmt) => { + self.walk_unification_stmt(unification_stmt) + } + ast::Stmt::Assign(assign_stmt) => self.walk_assign_stmt(assign_stmt), + ast::Stmt::AugAssign(aug_assign_stmt) => self.walk_aug_assign_stmt(aug_assign_stmt), + ast::Stmt::Assert(assert_stmt) => self.walk_assert_stmt(assert_stmt), + ast::Stmt::If(if_stmt) => self.walk_if_stmt(if_stmt), + ast::Stmt::Import(import_stmt) => self.walk_import_stmt(import_stmt), + ast::Stmt::SchemaAttr(schema_attr) => self.walk_schema_attr(schema_attr), + ast::Stmt::Schema(schema_stmt) => self.walk_schema_stmt(schema_stmt), + ast::Stmt::Rule(rule_stmt) => self.walk_rule_stmt(rule_stmt), + }; + backtrack_update_break!(self, stmt); + value + } + + fn walk_expr_stmt(&self, expr_stmt: &'ctx ast::ExprStmt) -> Self::Result { + let mut result = self.ok_result(); + for expr in &expr_stmt.exprs { + let scalar = self.walk_expr(expr)?; + // Only non-call expressions are allowed to emit values because of the function void return type. + if !matches!(expr.node, ast::Expr::Call(_)) { + self.add_scalar(scalar.clone(), matches!(expr.node, ast::Expr::Schema(_))); + } + result = Ok(scalar); + } + result + } + + fn walk_unification_stmt(&self, unification_stmt: &'ctx ast::UnificationStmt) -> Self::Result { + self.clear_local_vars(); + let name = &unification_stmt.target.node.names[0].node; + self.add_target_var(name); + // The right value of the unification_stmt is a schema_expr. + let value = self.walk_schema_expr(&unification_stmt.value.node)?; + // Load the identifier value + let org_value = self + .walk_identifier_with_ctx(&unification_stmt.target.node, &ast::ExprContext::Load, None) + .unwrap_or(self.undefined_value()); + let value = self.bit_or(org_value, value); + // Store the identifier value + self.walk_identifier_with_ctx( + &unification_stmt.target.node, + &ast::ExprContext::Store, + Some(value.clone()), + )?; + self.pop_target_var(); + Ok(value) + } + + fn walk_type_alias_stmt(&self, _type_alias_stmt: &'ctx ast::TypeAliasStmt) -> Self::Result { + // Nothing to do, because all type aliases have been replaced at compile time + self.ok_result() + } + + fn walk_assign_stmt(&self, assign_stmt: &'ctx ast::AssignStmt) -> Self::Result { + self.clear_local_vars(); + // Set target vars. + for name in &assign_stmt.targets { + self.add_target_var(&name.node.name.node) + } + // Load the right value + let mut value = self.walk_expr(&assign_stmt.value)?; + // Runtime type cast if exists the type annotation. + if let Some(ty) = &assign_stmt.ty { + value = type_pack_and_check(self, &value, vec![&ty.node.to_string()], false); + } + if assign_stmt.targets.len() == 1 { + // Store the single target + let name = &assign_stmt.targets[0]; + self.walk_target_with_value(&name.node, value.clone())?; + } else { + // Store multiple targets + for name in &assign_stmt.targets { + let value = self.value_deep_copy(&value); + self.walk_target_with_value(&name.node, value.clone())?; + } + } + // Pop target vars. + for _ in &assign_stmt.targets { + self.pop_target_var(); + } + Ok(value) + } + + fn walk_aug_assign_stmt(&self, aug_assign_stmt: &'ctx ast::AugAssignStmt) -> Self::Result { + self.add_target_var(&aug_assign_stmt.target.node.name.node); + // Load the right value + let right_value = self.walk_expr(&aug_assign_stmt.value)?; + // Load the identifier value + let org_value = self.load_target(&aug_assign_stmt.target.node)?; + let value = match aug_assign_stmt.op { + ast::AugOp::Add => self.add(org_value, right_value), + ast::AugOp::Sub => self.sub(org_value, right_value), + ast::AugOp::Mul => self.mul(org_value, right_value), + ast::AugOp::Div => self.div(org_value, right_value), + ast::AugOp::Mod => self.r#mod(org_value, right_value), + ast::AugOp::Pow => self.pow(org_value, right_value), + ast::AugOp::LShift => self.bit_lshift(org_value, right_value), + ast::AugOp::RShift => self.bit_rshift(org_value, right_value), + ast::AugOp::BitOr => self.bit_or(org_value, right_value), + ast::AugOp::BitXor => self.bit_xor(org_value, right_value), + ast::AugOp::BitAnd => self.bit_and(org_value, right_value), + ast::AugOp::FloorDiv => self.floor_div(org_value, right_value), + ast::AugOp::Assign => { + return Err(anyhow::anyhow!(kcl_error::INVALID_OPERATOR_MSG)); + } + }; + // Store the target value + self.walk_target_with_value(&aug_assign_stmt.target.node, value.clone())?; + self.pop_target_var(); + Ok(value) + } + + fn walk_assert_stmt(&self, assert_stmt: &'ctx ast::AssertStmt) -> Self::Result { + let do_assert = || { + let assert_result = self + .walk_expr(&assert_stmt.test) + .expect(kcl_error::RUNTIME_ERROR_MSG); + // Assert statement error message. + let msg = { + if let Some(msg) = &assert_stmt.msg { + self.walk_expr(msg).expect(kcl_error::RUNTIME_ERROR_MSG) + } else { + self.string_value("") + } + }; + if !assert_result.is_truthy() { + let mut ctx = self.runtime_ctx.borrow_mut(); + ctx.set_err_type(&RuntimeErrorType::AssertionError); + let msg = msg.as_str(); + panic!("{}", msg); + } + }; + if let Some(if_cond) = &assert_stmt.if_cond { + let if_value = self.walk_expr(if_cond)?; + let is_truth = self.value_is_truthy(&if_value); + if is_truth { + do_assert() + } + } else { + do_assert() + } + self.ok_result() + } + + fn walk_if_stmt(&self, if_stmt: &'ctx ast::IfStmt) -> Self::Result { + let cond = self.walk_expr(&if_stmt.cond)?; + let is_truth = self.value_is_truthy(&cond); + // Is backtrack only orelse stmt? + if self.is_backtrack_only_or_else() { + if !is_truth { + self.walk_stmts(&if_stmt.orelse)?; + } + return self.ok_result(); + } + // Is backtrack only if stmt? + if self.is_backtrack_only_if() { + if is_truth { + self.walk_stmts(&if_stmt.body)?; + } + return self.ok_result(); + } + // Normal full if stmt. + if is_truth { + self.walk_stmts(&if_stmt.body)?; + } else { + self.walk_stmts(&if_stmt.orelse)?; + } + self.ok_result() + } + + fn walk_import_stmt(&self, import_stmt: &'ctx ast::ImportStmt) -> Self::Result { + let pkgpath = import_stmt.path.node.as_str(); + // Check if it has already been generated, there is no need to generate code + // for duplicate import statements. + if self.check_imported(pkgpath) { + return self.ok_result(); + } + // Standard or plugin modules. + if builtin::STANDARD_SYSTEM_MODULES.contains(&pkgpath) + || pkgpath.starts_with(plugin::PLUGIN_MODULE_PREFIX) + { + // Nothing to do on the builtin system module import because the check has been done. + return self.ok_result(); + } else { + let pkgpath = format!("{}{}", PKG_PATH_PREFIX, import_stmt.path.node); + if let Some(modules) = self.program.pkgs.get(&import_stmt.path.node) { + self.push_pkgpath(&pkgpath); + self.init_scope(&pkgpath); + let modules: Vec>> = modules + .iter() + .map(|m| { + let m = self + .program + .get_module_ref(&m) + .expect(&format!("module {:?} not found in program", m)); + m + }) + .collect(); + self.compile_ast_modules(&modules); + self.pop_pkgpath(); + } + } + self.mark_imported(pkgpath); + self.ok_result() + } + + fn walk_schema_stmt(&self, schema_stmt: &'ctx ast::SchemaStmt) -> Self::Result { + let body = Arc::new(schema_body); + let check = Arc::new(schema_check); + let caller = SchemaCaller { + ctx: Rc::new(RefCell::new(SchemaEvalContext::new_with_node( + schema_stmt.clone(), + Index::from_raw_parts(self.frames.borrow().len(), 0), + SchemaEvalContext::get_parent_schema(self, &schema_stmt.parent_name), + SchemaEvalContext::get_mixin_schemas(self, &schema_stmt.mixins), + ))), + body, + check, + }; + // Add function to the global state + let index = self.add_schema(caller); + let runtime_type = schema_runtime_type(&schema_stmt.name.node, &self.current_pkgpath()); + let function = self.proxy_function_value_with_type(index, &runtime_type); + // Store or add the variable in the scope + let name = &schema_stmt.name.node; + if !self.store_variable(name, function.clone()) { + self.add_variable(name, function.clone()); + } + self.schemas.borrow_mut().insert(runtime_type, index); + Ok(function) + } + + fn walk_rule_stmt(&self, rule_stmt: &'ctx ast::RuleStmt) -> Self::Result { + let body = Arc::new(rule_body); + let check = Arc::new(rule_check); + let caller = RuleCaller { + ctx: Rc::new(RefCell::new(RuleEvalContext::new_with_node( + rule_stmt.clone(), + ))), + body, + check, + }; + // Add function to the global state + let index = self.add_rule(caller); + let runtime_type = schema_runtime_type(&rule_stmt.name.node, &self.current_pkgpath()); + let function = self.proxy_function_value_with_type(index, &runtime_type); + // Store or add the variable in the scope + let name = &rule_stmt.name.node; + if !self.store_variable(name, function.clone()) { + self.add_variable(name, function.clone()); + } + Ok(function) + } + + /* + * Expr + */ + + fn walk_expr(&self, expr: &'ctx ast::Node) -> Self::Result { + self.update_ctx_panic_info(expr); + match &expr.node { + ast::Expr::Target(target) => self.walk_target(target), + ast::Expr::Identifier(identifier) => self.walk_identifier(identifier), + ast::Expr::Unary(unary_expr) => self.walk_unary_expr(unary_expr), + ast::Expr::Binary(binary_expr) => self.walk_binary_expr(binary_expr), + ast::Expr::If(if_expr) => self.walk_if_expr(if_expr), + ast::Expr::Selector(selector_expr) => self.walk_selector_expr(selector_expr), + ast::Expr::Call(call_expr) => self.walk_call_expr(call_expr), + ast::Expr::Paren(paren_expr) => self.walk_paren_expr(paren_expr), + ast::Expr::Quant(quant_expr) => self.walk_quant_expr(quant_expr), + ast::Expr::List(list_expr) => self.walk_list_expr(list_expr), + ast::Expr::ListIfItem(list_if_item_expr) => { + self.walk_list_if_item_expr(list_if_item_expr) + } + ast::Expr::ListComp(list_comp) => self.walk_list_comp(list_comp), + ast::Expr::Starred(starred_expr) => self.walk_starred_expr(starred_expr), + ast::Expr::DictComp(dict_comp) => self.walk_dict_comp(dict_comp), + ast::Expr::ConfigIfEntry(config_if_entry_expr) => { + self.walk_config_if_entry_expr(config_if_entry_expr) + } + ast::Expr::CompClause(comp_clause) => self.walk_comp_clause(comp_clause), + ast::Expr::Schema(schema_expr) => self.walk_schema_expr(schema_expr), + ast::Expr::Config(config_expr) => self.walk_config_expr(config_expr), + ast::Expr::Check(check) => self.walk_check_expr(check), + ast::Expr::Lambda(lambda) => self.walk_lambda_expr(lambda), + ast::Expr::Subscript(subscript) => self.walk_subscript(subscript), + ast::Expr::Keyword(keyword) => self.walk_keyword(keyword), + ast::Expr::Arguments(..) => self.ok_result(), + ast::Expr::Compare(compare) => self.walk_compare(compare), + ast::Expr::NumberLit(number_lit) => self.walk_number_lit(number_lit), + ast::Expr::StringLit(string_lit) => self.walk_string_lit(string_lit), + ast::Expr::NameConstantLit(name_constant_lit) => { + self.walk_name_constant_lit(name_constant_lit) + } + ast::Expr::JoinedString(joined_string) => self.walk_joined_string(joined_string), + ast::Expr::FormattedValue(formatted_value) => { + self.walk_formatted_value(formatted_value) + } + ast::Expr::Missing(missing_expr) => self.walk_missing_expr(missing_expr), + } + } + + fn walk_quant_expr(&self, quant_expr: &'ctx ast::QuantExpr) -> Self::Result { + let mut result = match quant_expr.op { + ast::QuantOperation::All => self.bool_value(true), + ast::QuantOperation::Any => self.bool_value(false), + ast::QuantOperation::Map => self.list_value(), + ast::QuantOperation::Filter => { + self.value_deep_copy(&self.walk_expr(&quant_expr.target)?) + } + }; + // Iterator + let iter_host_value = if let ast::QuantOperation::Filter = quant_expr.op { + self.value_deep_copy(&result) + } else { + self.walk_expr(&quant_expr.target)? + }; + let mut iter_value = iter_host_value.iter(); + // Start iteration and enter the loop scope for the loop variable. + self.enter_scope(); + defer! { + self.leave_scope(); + self.clear_local_vars(); + } + // Start block + while let Some((next_value, key, value)) = iter_value.next_with_key_value(&iter_host_value) + { + // Next value block + let variables = &quant_expr.variables; + for v in variables { + self.add_local_var(&v.node.names[0].node); + } + if variables.len() == 1 { + // Store the target + self.walk_identifier_with_ctx( + &variables.first().expect(kcl_error::INTERNAL_ERROR_MSG).node, + &ast::ExprContext::Store, + Some(next_value.clone()), + )?; + } else if variables.len() == 2 { + // Store the target + self.walk_identifier_with_ctx( + &variables.first().expect(kcl_error::INTERNAL_ERROR_MSG).node, + &ast::ExprContext::Store, + Some(key.clone()), + )?; + self.walk_identifier_with_ctx( + &variables.get(1).expect(kcl_error::INTERNAL_ERROR_MSG).node, + &ast::ExprContext::Store, + Some(value.clone()), + )?; + } else { + panic!( + "the number of loop variables is {}, which can only be 1 or 2", + variables.len() + ) + } + // Check the if filter condition + if let Some(if_expr) = &quant_expr.if_cond { + let value = self.walk_expr(if_expr)?; + // Skip the iteration + if !value.is_truthy() { + continue; + } + } + // Loop var generation body block + let test = &quant_expr.test; + let value = self.walk_expr(test)?; + let is_truth = self.value_is_truthy(&value); + match quant_expr.op { + ast::QuantOperation::All => { + if !is_truth { + return Ok(self.bool_value(false)); + } + } + ast::QuantOperation::Any => { + if is_truth { + return Ok(self.bool_value(true)); + } + } + ast::QuantOperation::Filter => { + if !is_truth { + if result.is_dict() { + result.dict_remove(&next_value.as_str()); + } else if result.is_list() { + result.list_remove(&next_value); + } else { + panic!("only list, dict and schema can be removed item"); + } + } + } + ast::QuantOperation::Map => { + self.list_append(&mut result, &value); + } + } + } + // End for block. + Ok(result) + } + + fn walk_schema_attr(&self, schema_attr: &'ctx ast::SchemaAttr) -> Self::Result { + self.clear_local_vars(); + let name = schema_attr.name.node.as_str(); + self.add_target_var(name); + for decorator in &schema_attr.decorators { + self.walk_decorator_with_name(&decorator.node, Some(name), false) + .expect(kcl_error::INTERNAL_ERROR_MSG); + } + let (mut schema_value, config_value, _) = self + .get_schema_or_rule_config_info() + .expect(kcl_error::INTERNAL_ERROR_MSG); + schema_value.update_attr_map(name, &schema_attr.ty.node.to_string()); + if let Some(entry) = config_value.dict_get_entry(name) { + let is_override_attr = { + let is_override_op = matches!( + config_value.dict_get_attr_operator(name), + Some(ConfigEntryOperationKind::Override) + ); + let without_index = matches!(config_value.dict_get_insert_index(name), None); + is_override_op && without_index + }; + if !is_override_attr { + let value = match &schema_attr.value { + Some(value) => self.walk_expr(value)?, + None => self.undefined_value(), + }; + if let Some(op) = &schema_attr.op { + match op { + // Union + ast::AugOp::BitOr => { + let org_value = schema_value + .dict_get_value(name) + .unwrap_or(self.undefined_value()); + let value = self.bit_or(org_value, value); + self.schema_dict_merge( + &mut schema_value, + name, + &value, + &ast::ConfigEntryOperation::Override, + None, + ); + } + // Assign + _ => self.schema_dict_merge( + &mut schema_value, + name, + &value, + &ast::ConfigEntryOperation::Override, + None, + ), + } + } + } + self.value_union(&mut schema_value, &entry); + } else { + // Lazy eval for the schema attribute. + let value = match &schema_attr.value { + Some(value) => self.walk_expr(value)?, + None => { + let value = self.undefined_value(); + // When the schema has no default value and config value, + // set it with a undefined value. + // Note that do not override the existed attribute value. + if schema_value.dict_get_entry(name).is_none() { + self.dict_insert_value(&mut schema_value, name, &value); + } + value + } + }; + if let Some(op) = &schema_attr.op { + match op { + // Union + ast::AugOp::BitOr => { + let org_value = schema_value + .dict_get_value(name) + .unwrap_or(self.undefined_value()); + let value = self.bit_or(org_value, value); + self.schema_dict_merge( + &mut schema_value, + name, + &value, + &ast::ConfigEntryOperation::Override, + None, + ); + } + // Assign + _ => self.schema_dict_merge( + &mut schema_value, + name, + &value, + &ast::ConfigEntryOperation::Override, + None, + ), + } + } + } + // Set config cache for the schema eval context. + if let Some(schema_ctx) = self.get_schema_eval_context() { + schema_ctx.borrow().set_value(self, name); + } + self.pop_target_var(); + Ok(schema_value) + } + + fn walk_if_expr(&self, if_expr: &'ctx ast::IfExpr) -> Self::Result { + let cond = self.walk_expr(&if_expr.cond)?; + let is_truth = self.value_is_truthy(&cond); + if is_truth { + self.walk_expr(&if_expr.body) + } else { + self.walk_expr(&if_expr.orelse) + } + } + + fn walk_unary_expr(&self, unary_expr: &'ctx ast::UnaryExpr) -> Self::Result { + let value = self.walk_expr(&unary_expr.operand)?; + Ok(match unary_expr.op { + ast::UnaryOp::UAdd => value.unary_plus(), + ast::UnaryOp::USub => value.unary_minus(), + ast::UnaryOp::Invert => value.unary_not(), + ast::UnaryOp::Not => value.unary_l_not(), + }) + } + + fn walk_binary_expr(&self, binary_expr: &'ctx ast::BinaryExpr) -> Self::Result { + let is_logic_op = matches!(binary_expr.op, ast::BinOp::And | ast::BinOp::Or); + let is_membership_as_op = matches!(binary_expr.op, ast::BinOp::As); + if !is_logic_op { + let left_value = self.walk_expr(&binary_expr.left)?; + let right_value = if is_membership_as_op { + match &binary_expr.right.node { + ast::Expr::Identifier(id) => { + let name = id.get_names().join("."); + self.string_value(&name) + } + _ => self.none_value(), + } + } else { + self.walk_expr(&binary_expr.right)? + }; + let value = match binary_expr.op { + ast::BinOp::Add => self.add(left_value, right_value), + ast::BinOp::Sub => self.sub(left_value, right_value), + ast::BinOp::Mul => self.mul(left_value, right_value), + ast::BinOp::Div => self.div(left_value, right_value), + ast::BinOp::FloorDiv => self.floor_div(left_value, right_value), + ast::BinOp::Mod => self.r#mod(left_value, right_value), + ast::BinOp::Pow => self.pow(left_value, right_value), + ast::BinOp::LShift => self.bit_lshift(left_value, right_value), + ast::BinOp::RShift => self.bit_rshift(left_value, right_value), + ast::BinOp::BitAnd => self.bit_and(left_value, right_value), + ast::BinOp::BitOr => self.bit_or(left_value, right_value), + ast::BinOp::BitXor => self.bit_xor(left_value, right_value), + ast::BinOp::And => self.logic_and(left_value, right_value), + ast::BinOp::Or => self.logic_or(left_value, right_value), + ast::BinOp::As => self.r#as(left_value, right_value), + }; + Ok(value) + } else { + // Short circuit operation of logical operators + let jump_if_false = matches!(binary_expr.op, ast::BinOp::And); + let left_value = self.walk_expr(&binary_expr.left)?; + let is_truth = self.value_is_truthy(&left_value); + if jump_if_false { + // Jump if false on logic and + if is_truth { + let right_value = self.walk_expr(&binary_expr.right)?; + return Ok(right_value); + } + } else { + // Jump if true on logic or + if !is_truth { + let right_value = self.walk_expr(&binary_expr.right)?; + return Ok(right_value); + } + }; + Ok(left_value) + } + } + + fn walk_selector_expr(&self, selector_expr: &'ctx ast::SelectorExpr) -> Self::Result { + let value = self.walk_expr(&selector_expr.value)?; + let key = selector_expr.attr.node.names[0].node.as_str(); + let mut value = if selector_expr.has_question { + if value.is_truthy() { + value.load_attr(key) + } else { + self.none_value() + } + } else { + value.load_attr(key) + }; + for name in &selector_expr.attr.node.names[1..] { + value = value.load_attr(&name.node) + } + Ok(value) + } + + fn walk_call_expr(&self, call_expr: &'ctx ast::CallExpr) -> Self::Result { + let func = self.walk_expr(&call_expr.func)?; + // args + let mut list_value = self.list_value(); + for arg in &call_expr.args { + let value = self.walk_expr(arg)?; + self.list_append(&mut list_value, &value); + } + let mut dict_value = self.dict_value(); + // keyword arguments + for keyword in &call_expr.keywords { + let name = &keyword.node.arg.node.names[0]; + let value = if let Some(value) = &keyword.node.value { + self.walk_expr(value)? + } else { + self.none_value() + }; + self.dict_insert_value(&mut dict_value, name.node.as_str(), &value); + } + let vars = self.clean_and_cloned_local_vars(); + let result = if let Some(proxy) = func.try_get_proxy() { + // Invoke user defined functions, schemas or rules. + Ok(self.invoke_proxy_function(proxy, &list_value, &dict_value)) + } else { + // Invoke runtime builtin functions or external plugin functions. + Ok(invoke_function(self, &func, &mut list_value, &dict_value)) + }; + self.set_local_vars(vars); + result + } + + fn walk_subscript(&self, subscript: &'ctx ast::Subscript) -> Self::Result { + let mut value = self.walk_expr(&subscript.value)?; + if let Some(index) = &subscript.index { + // index + let index = self.walk_expr(index)?; + value = if subscript.has_question { + value.bin_subscr_option(&index) + } else { + value.bin_subscr(&index) + }; + } else { + let lower = { + if let Some(lower) = &subscript.lower { + self.walk_expr(lower)? + } else { + self.none_value() + } + }; + let upper = { + if let Some(upper) = &subscript.upper { + self.walk_expr(upper)? + } else { + self.none_value() + } + }; + let step = { + if let Some(step) = &subscript.step { + self.walk_expr(step)? + } else { + self.none_value() + } + }; + value = if subscript.has_question { + if value.is_truthy() { + value.list_slice(&lower, &upper, &step) + } else { + self.none_value() + } + } else { + value.list_slice(&lower, &upper, &step) + }; + } + Ok(value) + } + + fn walk_paren_expr(&self, paren_expr: &'ctx ast::ParenExpr) -> Self::Result { + self.walk_expr(&paren_expr.expr) + } + + fn walk_list_expr(&self, list_expr: &'ctx ast::ListExpr) -> Self::Result { + let mut list_value = self.list_value(); + for item in &list_expr.elts { + let value = self.walk_expr(item)?; + match &item.node { + ast::Expr::Starred(_) | ast::Expr::ListIfItem(_) => { + self.list_append_unpack(&mut list_value, &value); + } + _ => self.list_append(&mut list_value, &value), + }; + } + Ok(list_value) + } + + fn walk_list_if_item_expr(&self, list_if_item_expr: &'ctx ast::ListIfItemExpr) -> Self::Result { + let cond = self.walk_expr(&list_if_item_expr.if_cond)?; + let is_truth = self.value_is_truthy(&cond); + Ok(if is_truth { + let mut then_value = self.list_value(); + for expr in &list_if_item_expr.exprs { + let value = self.walk_expr(expr)?; + match &expr.node { + ast::Expr::Starred(_) | ast::Expr::ListIfItem(_) => { + self.list_append_unpack(&mut then_value, &value) + } + _ => self.list_append(&mut then_value, &value), + }; + } + then_value + } else if let Some(orelse) = &list_if_item_expr.orelse { + self.walk_expr(orelse)? + } else { + self.none_value() + }) + } + + fn walk_starred_expr(&self, starred_expr: &'ctx ast::StarredExpr) -> Self::Result { + self.walk_expr(&starred_expr.value) + } + + fn walk_list_comp(&self, list_comp: &'ctx ast::ListComp) -> Self::Result { + let mut collection_value = self.list_value(); + self.enter_scope(); + defer! { + self.leave_scope(); + } + self.walk_generator( + &list_comp.generators, + &list_comp.elt, + None, + None, + 0, + &mut collection_value, + &ast::CompType::List, + ); + Ok(collection_value) + } + + fn walk_dict_comp(&self, dict_comp: &'ctx ast::DictComp) -> Self::Result { + let mut collection_value = self.dict_value(); + self.enter_scope(); + defer! { + self.leave_scope(); + } + let key = dict_comp + .entry + .key + .as_ref() + .expect(kcl_error::INTERNAL_ERROR_MSG); + self.walk_generator( + &dict_comp.generators, + key, + Some(&dict_comp.entry.value), + Some(&dict_comp.entry.operation), + 0, + &mut collection_value, + &ast::CompType::Dict, + ); + + Ok(collection_value) + } + + fn walk_config_if_entry_expr( + &self, + config_if_entry_expr: &'ctx ast::ConfigIfEntryExpr, + ) -> Self::Result { + let cond = self.walk_expr(&config_if_entry_expr.if_cond)?; + let is_truth = self.value_is_truthy(&cond); + Ok(if is_truth { + self.walk_config_entries(&config_if_entry_expr.items)? + } else if let Some(orelse) = &config_if_entry_expr.orelse { + // Config expr or config if entry expr. + if let ast::Expr::Config(config_expr) = &orelse.node { + self.walk_config_entries(&config_expr.items)? + } else { + self.walk_expr(orelse)? + } + } else { + self.none_value() + }) + } + + fn walk_comp_clause(&self, _comp_clause: &'ctx ast::CompClause) -> Self::Result { + // Nothing to do on this AST node + self.ok_result() + } + + fn walk_schema_expr(&self, schema_expr: &'ctx ast::SchemaExpr) -> Self::Result { + // Check the required attributes only when the values of all attributes + // in the final schema are solved. + self.push_schema_expr(); + defer! { + self.pop_schema_expr(); + } + let config_value = self.walk_expr(&schema_expr.config)?; + let schema_type = self.walk_identifier_with_ctx( + &schema_expr.name.node, + &schema_expr.name.node.ctx, + None, + )?; + let config_expr = match &schema_expr.config.node { + ast::Expr::Config(config_expr) => config_expr, + _ => panic!("invalid schema config expr"), + }; + let config_meta = self.construct_schema_config_meta(Some(&schema_expr.name), config_expr); + let mut list_value = self.list_value(); + for arg in &schema_expr.args { + let value = self.walk_expr(arg)?; + self.list_append(&mut list_value, &value); + } + let mut dict_value = self.dict_value(); + for keyword in &schema_expr.kwargs { + let name = &keyword.node.arg.node.names[0]; + let value = if let Some(value) = &keyword.node.value { + self.walk_expr(value)? + } else { + self.none_value() + }; + self.dict_insert_merge_value(&mut dict_value, name.node.as_str(), &value); + } + let schema = if let Some(index) = schema_type.try_get_proxy() { + let frame = { + let frames = self.frames.borrow(); + frames + .get(index) + .expect(kcl_error::INTERNAL_ERROR_MSG) + .clone() + }; + if let Proxy::Schema(schema) = &frame.proxy { + self.push_pkgpath(&frame.pkgpath); + self.push_backtrace(&frame); + defer! { + self.pop_backtrace(); + self.pop_pkgpath(); + } + let value = (schema.body)( + self, + &schema.ctx.borrow().snapshot(config_value, config_meta), + &list_value, + &dict_value, + ); + value + } else if let Proxy::Rule(rule) = &frame.proxy { + self.push_pkgpath(&frame.pkgpath); + self.push_backtrace(&frame); + defer! { + self.pop_backtrace(); + self.pop_pkgpath(); + } + let value = (rule.body)( + self, + &rule.ctx.borrow().snapshot(config_value, config_meta), + &list_value, + &dict_value, + ); + value + } else { + self.undefined_value() + } + } else { + union_entry( + self, + &mut schema_type.deep_copy(), + &config_value, + true, + &UnionOptions::default(), + ) + }; + Ok(schema) + } + + #[inline] + fn walk_config_expr(&self, config_expr: &'ctx ast::ConfigExpr) -> Self::Result { + self.enter_scope(); + defer! { + self.leave_scope(); + } + let result = self.walk_config_entries(&config_expr.items); + result + } + + fn walk_check_expr(&self, check_expr: &'ctx ast::CheckExpr) -> Self::Result { + if let Some(if_cond) = &check_expr.if_cond { + let if_value = self.walk_expr(if_cond)?; + let is_truth = self.value_is_truthy(&if_value); + if !is_truth { + return self.ok_result(); + } + } + let check_result = self.walk_expr(&check_expr.test)?; + let msg = { + if let Some(msg) = &check_expr.msg { + self.walk_expr(msg).expect(kcl_error::INTERNAL_ERROR_MSG) + } else { + self.string_value("") + } + } + .as_str(); + let (_, _, config_meta) = self + .get_schema_or_rule_config_info() + .expect(kcl_error::INTERNAL_ERROR_MSG); + schema_assert( + &mut self.runtime_ctx.borrow_mut(), + &check_result, + &msg, + &config_meta, + ); + self.ok_result() + } + + fn walk_lambda_expr(&self, lambda_expr: &'ctx ast::LambdaExpr) -> Self::Result { + let func = Arc::new(func_body); + // Capture schema self + let proxy = FunctionCaller::new( + FunctionEvalContext { + node: lambda_expr.clone(), + this: self + .schema_stack + .borrow() + .last() + .map(|ctx| FunctionEvalThis { + ctx: ctx.clone(), + value: ctx.value(), + config: ctx.config(), + }), + closure: self.get_current_closure_map(), + level: self.scope_level() + 1, + }, + func, + ); + // Add function to the global state + let index = self.add_function(proxy); + Ok(self.proxy_function_value(index)) + } + + fn walk_keyword(&self, _keyword: &'ctx ast::Keyword) -> Self::Result { + // Nothing to do + self.ok_result() + } + + fn walk_arguments(&self, _arguments: &'ctx ast::Arguments) -> Self::Result { + // Nothing to do + self.ok_result() + } + + fn walk_compare(&self, compare: &'ctx ast::Compare) -> Self::Result { + let mut left_value = self.walk_expr(&compare.left)?; + if compare.comparators.len() > 1 { + let mut result_value = self.undefined_value(); + for (i, op) in compare.ops.iter().enumerate() { + let has_next = i < (compare.ops.len() - 1); + let right_value = self.walk_expr(&compare.comparators[i])?; + result_value = match op { + ast::CmpOp::Eq => self.cmp_equal_to(left_value, right_value.clone()), + ast::CmpOp::NotEq => self.cmp_not_equal_to(left_value, right_value.clone()), + ast::CmpOp::Gt => self.cmp_greater_than(left_value, right_value.clone()), + ast::CmpOp::GtE => { + self.cmp_greater_than_or_equal(left_value, right_value.clone()) + } + ast::CmpOp::Lt => self.cmp_less_than(left_value, right_value.clone()), + ast::CmpOp::LtE => self.cmp_less_than_or_equal(left_value, right_value.clone()), + ast::CmpOp::Is => self.is(left_value, right_value.clone()), + ast::CmpOp::IsNot => self.is_not(left_value, right_value.clone()), + ast::CmpOp::Not => self.is_not(left_value, right_value.clone()), + ast::CmpOp::NotIn => self.not_in(left_value, right_value.clone()), + ast::CmpOp::In => self.r#in(left_value, right_value.clone()), + }; + left_value = right_value; + let is_truth = self.value_is_truthy(&result_value); + if has_next { + if !is_truth { + break; + } + } else { + break; + } + } + Ok(result_value) + } else { + let right_value = self.walk_expr(&compare.comparators[0])?; + Ok(match &compare.ops[0] { + ast::CmpOp::Eq => self.cmp_equal_to(left_value, right_value), + ast::CmpOp::NotEq => self.cmp_not_equal_to(left_value, right_value), + ast::CmpOp::Gt => self.cmp_greater_than(left_value, right_value), + ast::CmpOp::GtE => self.cmp_greater_than_or_equal(left_value, right_value), + ast::CmpOp::Lt => self.cmp_less_than(left_value, right_value), + ast::CmpOp::LtE => self.cmp_less_than_or_equal(left_value, right_value), + ast::CmpOp::Is => self.is(left_value, right_value), + ast::CmpOp::IsNot => self.is_not(left_value, right_value), + ast::CmpOp::Not => self.is_not(left_value, right_value), + ast::CmpOp::NotIn => self.not_in(left_value, right_value), + ast::CmpOp::In => self.r#in(left_value, right_value), + }) + } + } + + #[inline] + fn walk_identifier(&self, identifier: &'ctx ast::Identifier) -> Self::Result { + self.walk_identifier_with_ctx(identifier, &identifier.ctx, None) + } + + #[inline] + fn walk_target(&self, target: &'ctx ast::Target) -> Self::Result { + self.load_target(target) + } + + fn walk_number_lit(&self, number_lit: &'ctx ast::NumberLit) -> Self::Result { + match number_lit.value { + ast::NumberLitValue::Int(int_value) => match &number_lit.binary_suffix { + Some(binary_suffix) => { + let unit = binary_suffix.value(); + let value = kcl_runtime::cal_num(int_value, unit.as_str()); + Ok(self.unit_value(value, int_value, &unit)) + } + None => Ok(self.int_value(int_value)), + }, + ast::NumberLitValue::Float(float_value) => Ok(self.float_value(float_value)), + } + } + + #[inline] + fn walk_string_lit(&self, string_lit: &'ctx ast::StringLit) -> Self::Result { + Ok(ValueRef::str(string_lit.value.as_str())) + } + + #[inline] + fn walk_name_constant_lit( + &self, + name_constant_lit: &'ctx ast::NameConstantLit, + ) -> Self::Result { + match name_constant_lit.value { + ast::NameConstant::True => Ok(self.bool_value(true)), + ast::NameConstant::False => Ok(self.bool_value(false)), + ast::NameConstant::None => Ok(self.none_value()), + ast::NameConstant::Undefined => Ok(self.undefined_value()), + } + } + + fn walk_joined_string(&self, joined_string: &'ctx ast::JoinedString) -> Self::Result { + let mut result_value = self.string_value(""); + for value in &joined_string.values { + let value = &value.node; + let value = match value { + ast::Expr::FormattedValue(formatted_value) => self + .walk_formatted_value(formatted_value) + .expect(kcl_error::INTERNAL_ERROR_MSG), + ast::Expr::StringLit(string_lit) => self + .walk_string_lit(string_lit) + .expect(kcl_error::INTERNAL_ERROR_MSG), + _ => panic!("{}", kcl_error::INVALID_JOINED_STR_MSG), + }; + result_value = self.add(result_value, value) + } + Ok(result_value) + } + + fn walk_formatted_value(&self, formatted_value: &'ctx ast::FormattedValue) -> Self::Result { + let formatted_expr_value = self.walk_expr(&formatted_value.value)?; + let value = if let Some(spec) = &formatted_value.format_spec { + match spec.to_lowercase().as_str() { + "#json" => formatted_expr_value.to_json_string(), + "#yaml" => formatted_expr_value.to_yaml_string(), + _ => panic!("{}", kcl_error::INVALID_STR_INTERPOLATION_SPEC_MSG), + } + } else { + formatted_expr_value.to_string() + }; + Ok(ValueRef::str(&value)) + } + + fn walk_comment(&self, _comment: &'ctx ast::Comment) -> Self::Result { + // Nothing to do + self.ok_result() + } + + fn walk_missing_expr(&self, _missing_expr: &'ctx ast::MissingExpr) -> Self::Result { + Err(anyhow::anyhow!("compile error: missing expression",)) + } + + fn walk_module(&self, module: &'ctx ast::Module) -> Self::Result { + // Compile all statements of the module except all import statements + self.walk_stmts_except_import(&module.body) + } +} + +impl<'ctx> Evaluator<'ctx> { + pub fn walk_stmts_except_import(&self, stmts: &'ctx [Box>]) -> EvalResult { + let mut result = self.ok_result(); + for stmt in stmts { + if !matches!(&stmt.node, ast::Stmt::Import(..)) { + result = self.walk_stmt(stmt); + } + } + result + } + + pub fn walk_stmts(&self, stmts: &'ctx [Box>]) -> EvalResult { + // Empty statements return None value + let mut result = self.ok_result(); + for stmt in stmts { + result = self.walk_stmt(stmt); + } + result + } + + pub(crate) fn walk_stmts_with_setter(&self, setter: &Setter) { + if let Some(index) = setter.index { + let frame = { + let frames = self.frames.borrow(); + frames + .get(index) + .expect(kcl_error::INTERNAL_ERROR_MSG) + .clone() + }; + if let Proxy::Global(index) = &frame.proxy { + if let Some(module_list) = self + .program + .pkgs + .get(&pkgpath_without_prefix!(frame.pkgpath)) + { + if let Some(module) = module_list.get(*index) { + let module = self + .program + .get_module(module) + .expect("Failed to acquire module lock") + .expect(&format!("module {:?} not found in program", module)); + if let Some(stmt) = module.body.get(setter.stmt) { + self.push_backtrack_meta(setter); + self.walk_stmt(stmt).expect(INTERNAL_ERROR_MSG); + self.pop_backtrack_meta(); + } + } + } + } + } + } + + pub(crate) fn walk_schema_stmts_with_setter( + &self, + stmts: &'ctx [Box>], + setter: &Setter, + ) -> EvalResult { + if let Some(index) = setter.index { + let frame = { + let frames = self.frames.borrow(); + frames + .get(index) + .expect(kcl_error::INTERNAL_ERROR_MSG) + .clone() + }; + if let Proxy::Schema(schema) = &frame.proxy { + if let Some(stmt) = schema.ctx.borrow().node.body.get(setter.stmt) { + self.push_pkgpath(&frame.pkgpath); + self.enter_scope(); + self.push_backtrack_meta(setter); + defer! { + self.pop_backtrack_meta(); + self.leave_scope(); + self.pop_pkgpath(); + } + let value = self.walk_stmt(stmt); + value + } else { + self.ok_result() + } + } else { + self.ok_result() + } + } else if let Some(stmt) = stmts.get(setter.stmt) { + self.walk_stmt(stmt) + } else { + self.ok_result() + } + } + + pub fn walk_target_with_value( + &self, + target: &'ctx ast::Target, + right_value: ValueRef, + ) -> EvalResult { + let is_in_schema = self.is_in_schema(); + if target.paths.is_empty() { + let name = target.get_name(); + // Global variables + if self.scope_level() == GLOBAL_LEVEL { + self.add_or_update_global_variable(name, right_value.clone(), true); + // Lambda local variables. + } else if self.is_in_lambda() { + let value = right_value.clone(); + // schema frame in the lambda + if self.is_schema_scope() { + let is_local_var = self.is_local_var(name); + let value = right_value.clone(); + match (is_local_var, is_in_schema) { + (false, true) => self.update_schema_or_rule_scope_value(name, Some(&value)), + _ => self.add_variable(name, value), + } + } else { + // If variable exists in the scope and update it, if not, add it to the scope. + if !self.store_variable_in_current_scope(name, value.clone()) { + self.add_variable(name, self.undefined_value()); + self.store_variable(name, value); + } + } + } else { + let is_local_var = self.is_local_var(name); + let value = right_value.clone(); + match (is_local_var, is_in_schema) { + (false, true) => self.update_schema_or_rule_scope_value(name, Some(&value)), + _ => self.add_variable(name, value), + } + } + } else { + let name = target.get_name(); + // In KCL, we cannot modify global variables in other packages, + // so pkgpath is empty here. + let mut value = self.load_value("", &[name]); + // Convert `store a.b.c = 1` -> `%t = load &a; %t = load_attr %t %b; store_attr %t %c with 1` + for (i, path) in target.paths.iter().enumerate() { + let ctx = if i < target.paths.len() - 1 { + ast::ExprContext::Load + } else { + ast::ExprContext::Store + }; + match ctx { + ast::ExprContext::Load => { + value = self.load_target_path(&value, path)?; + } + ast::ExprContext::Store => { + self.store_target_path(&mut value, path, &right_value)?; + let is_local_var = self.is_local_var(name); + let is_in_lambda = self.is_in_lambda(); + // Set config value for the schema attribute if the attribute is in the schema and + // it is not a local variable in the lambda function. + if self.scope_level() >= INNER_LEVEL + && is_in_schema + && !is_in_lambda + && !is_local_var + { + self.update_schema_or_rule_scope_value(name, None); + } + } + } + } + } + Ok(right_value) + } + + pub fn walk_identifier_with_ctx( + &self, + identifier: &'ctx ast::Identifier, + identifier_ctx: &ast::ExprContext, + right_value: Option, + ) -> EvalResult { + let is_in_schema = self.is_in_schema(); + match identifier_ctx { + // Store a.b.c = 1 + ast::ExprContext::Store => { + if identifier.names.len() == 1 { + let name = identifier.names[0].node.as_str(); + // Global variables + if self.scope_level() == GLOBAL_LEVEL { + self.add_or_update_global_variable( + name, + right_value.clone().expect(kcl_error::INTERNAL_ERROR_MSG), + true, + ); + // Lambda local variables. + } else if self.is_in_lambda() { + let value = right_value.clone().expect(kcl_error::INTERNAL_ERROR_MSG); + // schema frame in the lambda + if self.is_schema_scope() { + let is_local_var = self.is_local_var(name); + let value = right_value.clone().expect(kcl_error::INTERNAL_ERROR_MSG); + match (is_local_var, is_in_schema) { + (false, true) => { + self.update_schema_or_rule_scope_value(name, Some(&value)) + } + _ => self.add_variable(name, value), + } + } else { + // If variable exists in the scope and update it, if not, add it to the scope. + if !self.store_variable_in_current_scope(name, value.clone()) { + self.add_variable(name, self.undefined_value()); + self.store_variable(name, value); + } + } + } else { + let is_local_var = self.is_local_var(name); + let value = right_value.clone().expect(kcl_error::INTERNAL_ERROR_MSG); + match (is_local_var, is_in_schema) { + (false, true) => { + self.update_schema_or_rule_scope_value(name, Some(&value)) + } + _ => self.add_variable(name, value), + } + } + } else { + let names = &identifier.names; + let name = names[0].node.as_str(); + // In KCL, we cannot modify global variables in other packages, + // so pkgpath is empty here. + let mut value = self.load_value("", &[name]); + // Convert `store a.b.c = 1` -> `%t = load &a; %t = load_attr %t %b; store_attr %t %c with 1` + for i in 0..names.len() - 1 { + let attr = names[i + 1].node.as_str(); + let ctx = if matches!(identifier_ctx, ast::ExprContext::Store) + && i != names.len() - 2 + && names.len() > 2 + { + &ast::ExprContext::Load + } else { + identifier_ctx + }; + match ctx { + ast::ExprContext::Load => { + value = value.load_attr(attr); + } + ast::ExprContext::Store => { + self.dict_set_value( + &mut value, + attr, + &right_value.clone().expect(kcl_error::INTERNAL_ERROR_MSG), + ); + let is_local_var = self.is_local_var(name); + let is_in_lambda = self.is_in_lambda(); + // Set config value for the schema attribute if the attribute is in the schema and + // it is not a local variable in the lambda function. + if self.scope_level() >= INNER_LEVEL + && is_in_schema + && !is_in_lambda + && !is_local_var + { + self.update_schema_or_rule_scope_value(name, None); + } + } + } + } + } + Ok(right_value.expect(kcl_error::INTERNAL_ERROR_MSG)) + } + // Load .a.b.c + ast::ExprContext::Load => Ok(self.load_value( + &identifier.pkgpath, + &identifier + .names + .iter() + .map(|n| n.node.as_str()) + .collect::>(), + )), + } + } + + pub fn walk_decorator_with_name( + &self, + decorator: &'ctx CallExpr, + attr_name: Option<&str>, + is_schema_target: bool, + ) -> EvalResult { + let mut list_value = self.list_value(); + let mut dict_value = self.dict_value(); + let (_, config_value, config_meta) = self + .get_schema_or_rule_config_info() + .expect(kcl_error::INTERNAL_ERROR_MSG); + for arg in &decorator.args { + let value = self.walk_expr(arg)?; + self.list_append(&mut list_value, &value); + } + for keyword in &decorator.keywords { + let name = &keyword.node.arg.node.names[0]; + let value = if let Some(value) = &keyword.node.value { + self.walk_expr(value)? + } else { + self.none_value() + }; + self.dict_insert_value(&mut dict_value, name.node.as_str(), &value); + } + let name = match &decorator.func.node { + ast::Expr::Identifier(ident) if ident.names.len() == 1 => ident.names[0].clone(), + _ => panic!("invalid decorator name, expect single identifier"), + }; + let attr_name = if let Some(v) = attr_name { v } else { "" }; + DecoratorValue::new(&name.node, &list_value, &dict_value).run( + &mut self.runtime_ctx.borrow_mut(), + attr_name, + is_schema_target, + &config_value, + &config_meta, + ); + self.ok_result() + } + + pub fn walk_arguments( + &self, + arguments: &'ctx Option>, + args: &ValueRef, + kwargs: &ValueRef, + ) { + // Arguments names and defaults + let (arg_names, arg_types, arg_defaults) = if let Some(args) = &arguments { + let names = &args.node.args; + let types = &args.node.ty_list; + let defaults = &args.node.defaults; + ( + names.iter().map(|identifier| &identifier.node).collect(), + types.iter().collect(), + defaults.iter().collect(), + ) + } else { + (vec![], vec![], vec![]) + }; + // Default parameter values + for ((arg_name, arg_type), value) in + arg_names.iter().zip(&arg_types).zip(arg_defaults.iter()) + { + let mut arg_value = if let Some(value) = value { + self.walk_expr(value).expect(kcl_error::RUNTIME_ERROR_MSG) + } else { + self.none_value() + }; + if let Some(ty) = arg_type { + arg_value = + type_pack_and_check(self, &arg_value, vec![&ty.node.to_string()], false); + } + // Arguments are immutable, so we place them in different scopes. + let name = arg_name.get_name(); + self.store_argument_in_current_scope(&name); + // Argument is a local variable instead of a global variable or schema attribute. + self.add_local_var(&name); + self.walk_identifier_with_ctx(arg_name, &ast::ExprContext::Store, Some(arg_value)) + .expect(kcl_error::RUNTIME_ERROR_MSG); + self.remove_local_var(&name); + } + // Positional arguments + let argument_len = args.len(); + for (i, (arg_name, arg_type)) in arg_names.iter().zip(arg_types).enumerate() { + // Positional arguments + let is_in_range = i < argument_len; + if is_in_range { + let mut arg_value = match args.list_get_option(i as isize) { + Some(v) => v, + None => self.undefined_value(), + }; + if let Some(ty) = arg_type { + arg_value = + type_pack_and_check(self, &arg_value, vec![&ty.node.to_string()], false); + } + self.store_variable(&arg_name.names[0].node, arg_value); + } else { + break; + } + } + // Keyword arguments + for arg_name in arg_names.iter() { + let name = &arg_name.names[0].node; + if let Some(arg) = kwargs.dict_get_value(name) { + // Find argument name in the scope + self.store_variable(&arg_name.names[0].node, arg); + } + } + } + + pub fn walk_generator( + &self, + generators: &'ctx [Box>], + elt: &'ctx ast::Node, + val: Option<&'ctx ast::Node>, + op: Option<&'ctx ast::ConfigEntryOperation>, + gen_index: usize, + collection_value: &mut ValueRef, + comp_type: &ast::CompType, + ) { + // Start block + let generator = &generators[gen_index]; + let iter_host_value = self + .walk_expr(&generator.node.iter) + .expect(kcl_error::RUNTIME_ERROR_MSG); + let mut iter_value = iter_host_value.iter(); + let targets = &generator.node.targets; + + while let Some((next_value, key, value)) = iter_value.next_with_key_value(&iter_host_value) + { + for v in targets { + self.add_local_var(&v.node.names[0].node) + } + if targets.len() == 1 { + // Store the target + self.walk_identifier_with_ctx( + &targets.first().expect(kcl_error::INTERNAL_ERROR_MSG).node, + &ast::ExprContext::Store, + Some(next_value), + ) + .expect(kcl_error::RUNTIME_ERROR_MSG); + } else if targets.len() == 2 { + // Store the target + self.walk_identifier_with_ctx( + &targets.first().expect(kcl_error::INTERNAL_ERROR_MSG).node, + &ast::ExprContext::Store, + Some(key), + ) + .expect(kcl_error::RUNTIME_ERROR_MSG); + self.walk_identifier_with_ctx( + &targets.get(1).expect(kcl_error::INTERNAL_ERROR_MSG).node, + &ast::ExprContext::Store, + Some(value), + ) + .expect(kcl_error::RUNTIME_ERROR_MSG); + } else { + panic!( + "the number of loop variables is {}, which can only be 1 or 2", + generator.node.targets.len() + ) + } + // Check the if filter + let mut skip = false; + for if_expr in &generator.node.ifs { + let value = self.walk_expr(if_expr).expect(kcl_error::RUNTIME_ERROR_MSG); + // Skip the iteration + if !value.is_truthy() { + skip = true; + } + } + if skip { + continue; + } + let next_gen_index = gen_index + 1; + if next_gen_index >= generators.len() { + match comp_type { + ast::CompType::List => { + let item = self.walk_expr(elt).expect(kcl_error::RUNTIME_ERROR_MSG); + self.list_append(collection_value, &item); + } + ast::CompType::Dict => { + let value = self + .walk_expr(val.expect(kcl_error::INTERNAL_ERROR_MSG)) + .expect(kcl_error::RUNTIME_ERROR_MSG); + let key = self.walk_expr(elt).expect(kcl_error::RUNTIME_ERROR_MSG); + let op = op.expect(kcl_error::INTERNAL_ERROR_MSG); + self.dict_insert( + collection_value, + &key.as_str(), + &value.deep_copy(), + op, + None, + ); + } + } + } else { + self.walk_generator( + generators, + elt, + val, + op, + next_gen_index, + collection_value, + comp_type, + ); + } + } + for v in targets { + self.remove_local_var(&v.node.names[0].node) + } + } + + pub(crate) fn walk_config_entries(&self, items: &'ctx [NodeRef]) -> EvalResult { + let mut config_value = self.dict_value(); + for item in items { + let value = self.walk_expr(&item.node.value)?; + if let Some(key_node) = &item.node.key { + let mut insert_index = None; + let optional_name = match &key_node.node { + ast::Expr::Identifier(identifier) => Some(identifier.names[0].node.clone()), + ast::Expr::StringLit(string_lit) => Some(string_lit.value.clone()), + ast::Expr::Subscript(subscript) => { + let mut name = None; + if let ast::Expr::Identifier(identifier) = &subscript.value.node { + if let Some(index_node) = &subscript.index { + // Insert index + if let ast::Expr::NumberLit(number) = &index_node.node { + if let ast::NumberLitValue::Int(v) = number.value { + insert_index = Some(v as i32); + name = Some(identifier.names[0].node.clone()) + } + } else if let ast::Expr::Unary(unary_expr) = &index_node.node { + // Negative insert index + if let ast::Expr::NumberLit(number) = &unary_expr.operand.node { + if let ast::NumberLitValue::Int(v) = number.value { + insert_index = Some(-v as i32); + name = Some(identifier.names[0].node.clone()) + } + } + } + } + } + name + } + _ => None, + }; + // Store a local variable for every entry key. + let key = match &optional_name { + Some(name) if !self.is_local_var(name) => self.string_value(name), + _ => self.walk_expr(key_node)?, + }; + self.dict_insert( + &mut config_value, + &key.as_str(), + &value, + &item.node.operation, + insert_index, + ); + if let Some(name) = &optional_name { + let value = self.dict_get_value(&config_value, name); + self.add_or_update_local_variable_within_scope(name, value); + } + } else { + // If the key does not exist, execute the logic of unpacking expression `**expr` here. + config_value.dict_insert_unpack(&mut self.runtime_ctx.borrow_mut(), &value) + } + } + Ok(config_value) + } +} diff --git a/kclvm/evaluator/src/proxy.rs b/crates/evaluator/src/proxy.rs similarity index 99% rename from kclvm/evaluator/src/proxy.rs rename to crates/evaluator/src/proxy.rs index 7f5524493..932b5b424 100644 --- a/kclvm/evaluator/src/proxy.rs +++ b/crates/evaluator/src/proxy.rs @@ -1,11 +1,11 @@ -use kclvm_runtime::ValueRef; +use kcl_runtime::ValueRef; use scopeguard::defer; +use crate::Evaluator; use crate::error as kcl_error; use crate::func::FunctionCaller; use crate::rule::{RuleCaller, RuleEvalContextRef}; use crate::schema::{SchemaCaller, SchemaEvalContextRef}; -use crate::Evaluator; /// Caller frame with the package path. When a caller occurs, /// it is necessary to switch the frame to ensure that a suitable diff --git a/kclvm/evaluator/src/rule.rs b/crates/evaluator/src/rule.rs similarity index 98% rename from kclvm/evaluator/src/rule.rs rename to crates/evaluator/src/rule.rs index 756ead23b..2299bcf93 100644 --- a/kclvm/evaluator/src/rule.rs +++ b/crates/evaluator/src/rule.rs @@ -2,15 +2,15 @@ use std::cell::RefCell; use std::rc::Rc; use std::sync::Arc; -use kclvm_ast::ast; -use kclvm_ast::walker::TypedResultWalker; -use kclvm_runtime::ValueRef; +use kcl_ast::ast; +use kcl_ast::walker::TypedResultWalker; +use kcl_runtime::ValueRef; use scopeguard::defer; use crate::error as kcl_error; -use crate::proxy::{call_rule_check, call_schema_body_from_rule}; use crate::Evaluator; +use crate::proxy::{call_rule_check, call_schema_body_from_rule}; pub type RuleBodyHandler = Arc ValueRef>; diff --git a/kclvm/evaluator/src/runtime.rs b/crates/evaluator/src/runtime.rs similarity index 85% rename from kclvm/evaluator/src/runtime.rs rename to crates/evaluator/src/runtime.rs index fd90d95d9..efe093d2a 100644 --- a/kclvm/evaluator/src/runtime.rs +++ b/crates/evaluator/src/runtime.rs @@ -1,12 +1,12 @@ use std::os::raw::c_char; use std::{ mem::transmute_copy, - panic::{catch_unwind, AssertUnwindSafe}, + panic::{AssertUnwindSafe, catch_unwind}, }; -use kclvm_runtime::{ - get_call_arg, is_runtime_catch_function, kclvm_plugin_invoke, ptr_as_ref, Context, - SchemaTypeFunc, UnsafeWrapper, ValueRef, +use kcl_runtime::{ + Context, SchemaTypeFunc, UnsafeWrapper, ValueRef, get_call_arg, is_runtime_catch_function, + kcl_plugin_invoke, ptr_as_ref, }; use crate::Evaluator; @@ -31,7 +31,7 @@ pub fn invoke_function( // Call schema constructor twice let value = if func.is_external { let name = format!("{}\0", func.name); - kclvm_plugin_invoke(ctx, name.as_ptr() as *const c_char, args, kwargs) + kcl_plugin_invoke(ctx, name.as_ptr() as *const c_char, args, kwargs) } else { let call_fn: SchemaTypeFunc = transmute_copy(&fn_ptr); args.list_append_unpack_first(closure); @@ -64,7 +64,7 @@ pub fn runtime_catch(s: &Evaluator, args: &ValueRef, kwargs: &ValueRef) -> Value })); return match result { Ok(_) => ValueRef::undefined(), - Err(err) => ValueRef::str(&kclvm_error::err_to_str(err)), + Err(err) => ValueRef::str(&kcl_error::err_to_str(err)), }; } panic!("catch() takes exactly one argument (0 given)"); diff --git a/crates/evaluator/src/schema.rs b/crates/evaluator/src/schema.rs new file mode 100644 index 000000000..ad9797faa --- /dev/null +++ b/crates/evaluator/src/schema.rs @@ -0,0 +1,911 @@ +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; + +use generational_arena::Index; +use kcl_ast::ast; +use kcl_ast::walker::TypedResultWalker; +use kcl_primitives::{DefaultHashBuilder, IndexMap}; +use kcl_runtime::{ConfigEntryOperationKind, ValueRef, schema_runtime_type}; +use scopeguard::defer; + +use crate::lazy::{LazyEvalScope, LazyEvalScopeRef, merge_variables_and_setters}; +use crate::proxy::{call_schema_body, call_schema_check}; +use crate::rule::RuleEvalContext; +use crate::ty::type_pack_and_check; +use crate::{Evaluator, INNER_LEVEL}; +use crate::{Proxy, error as kcl_error}; + +pub type SchemaBodyHandler = + Arc ValueRef>; + +pub type SchemaCheckHandler = + Arc ()>; + +pub type SchemaEvalContextRef = Rc>; + +/// Proxy functions represent the saved functions of the runtime its, +/// rather than executing KCL defined functions or plugin functions. +#[derive(Clone, Debug)] +pub struct SchemaEvalContext { + pub node: Rc, + pub scope: Option, + pub index: Index, + pub parent: Option, + pub mixins: Vec, + pub value: ValueRef, + pub config: ValueRef, + pub config_meta: ValueRef, + pub optional_mapping: ValueRef, + pub is_sub_schema: bool, +} + +impl SchemaEvalContext { + #[inline] + pub fn new_with_node( + node: ast::SchemaStmt, + index: Index, + parent: Option, + mixins: Vec, + ) -> Self { + Self { + node: Rc::new(node), + scope: None, + index, + parent, + mixins, + value: ValueRef::dict(None), + config: ValueRef::dict(None), + config_meta: ValueRef::dict(None), + optional_mapping: ValueRef::dict(None), + is_sub_schema: true, + } + } + + /// Reset schema evaluation context state. + #[inline] + pub fn snapshot(&self, config: ValueRef, config_meta: ValueRef) -> SchemaEvalContextRef { + Rc::new(RefCell::new(Self { + node: self.node.clone(), + index: self.index, + parent: self.parent, + mixins: self.mixins.clone(), + scope: None, + value: ValueRef::dict(None), + config, + config_meta, + optional_mapping: ValueRef::dict(None), + is_sub_schema: true, + })) + } + + /// New a schema evaluation context with schema value and config. + #[inline] + pub fn new_with_value(&self, value: &ValueRef, config: &ValueRef) -> SchemaEvalContextRef { + Rc::new(RefCell::new(Self { + node: self.node.clone(), + index: self.index, + parent: self.parent, + mixins: self.mixins.clone(), + scope: None, + value: value.clone(), + config: config.clone(), + config_meta: ValueRef::dict(None), + optional_mapping: ValueRef::dict(None), + is_sub_schema: true, + })) + } + + /// Pass value references from other schema eval context. + /// Note that do not change the schema node. + pub fn set_info_with_schema(&mut self, other: &SchemaEvalContext) { + self.config = other.config.clone(); + self.config_meta = other.config_meta.clone(); + self.value = other.value.clone(); + self.optional_mapping = other.optional_mapping.clone(); + self.is_sub_schema = false; + // Set lazy eval scope. + if let Some(other) = &other.scope { + if let Some(scope) = &self.scope { + let mut scope = scope.borrow_mut(); + let other = other.borrow(); + scope.cache = other.cache.clone(); + scope.levels = other.levels.clone(); + scope.cal_times = other.cal_times.clone(); + scope.setters = other.setters.clone(); + } else { + let other = other.borrow(); + self.scope = Some(Rc::new(RefCell::new(LazyEvalScope { + cache: other.cache.clone(), + levels: other.levels.clone(), + cal_times: other.cal_times.clone(), + setters: other.setters.clone(), + }))) + } + } + } + + /// Pass value references from other rule eval context. + /// Note that do not change the schema node. + pub fn set_info_with_rule(&mut self, other: &RuleEvalContext) { + self.config = other.config.clone(); + self.config_meta = other.config_meta.clone(); + self.value = other.value.clone(); + self.optional_mapping = other.optional_mapping.clone(); + // Note that for the host schema, it will evaluate the final value. + self.is_sub_schema = true; + } + + /// Update parent schema and mixin schema information in the current scope. + pub fn get_parent_schema( + s: &Evaluator, + parent: &Option>>, + ) -> Option { + if let Some(parent) = parent { + let func = s + .walk_identifier_with_ctx(&parent.node, &ast::ExprContext::Load, None) + .expect(kcl_error::RUNTIME_ERROR_MSG); + if let Some(index) = func.try_get_proxy() { + Some(index) + } else { + None + } + } else { + None + } + } + + /// Update parent schema and mixin schema information + pub fn get_mixin_schemas( + s: &Evaluator, + mixins: &[Box>], + ) -> Vec { + let mut results = vec![]; + for mixin in mixins { + let func = s + .walk_identifier_with_ctx(&mixin.node, &ast::ExprContext::Load, None) + .expect(kcl_error::RUNTIME_ERROR_MSG); + if let Some(index) = func.try_get_proxy() { + let frame = { + let frames = s.frames.borrow(); + frames + .get(index) + .expect(kcl_error::INTERNAL_ERROR_MSG) + .clone() + }; + if let Proxy::Schema(_) = &frame.proxy { + results.push(index); + } + } + } + results + } + + /// Whether the attribute is the schema context. + pub fn has_attr(s: &Evaluator, ctx: &SchemaEvalContextRef, name: &str) -> bool { + for stmt in &ctx.borrow().node.body { + if let ast::Stmt::SchemaAttr(attr) = &stmt.node { + if attr.name.node == name { + return true; + } + } + } + if let Some(index) = ctx.borrow().parent { + let frame = { + let frames = s.frames.borrow(); + frames + .get(index) + .expect(kcl_error::INTERNAL_ERROR_MSG) + .clone() + }; + if let Proxy::Schema(schema) = &frame.proxy { + return SchemaEvalContext::has_attr(s, &schema.ctx, name); + } + } + false + } + + /// Get all attribute from schema + pub fn get_attrs(s: &Evaluator, ctx: &SchemaEvalContextRef) -> Vec<(String, bool)> { + let mut attrs = vec![]; + for stmt in &ctx.borrow().node.body { + if let ast::Stmt::SchemaAttr(attr) = &stmt.node { + attrs.push((attr.name.node.clone(), attr.is_optional)); + } + } + if let Some(index) = ctx.borrow().parent { + let frame = { + let frames = s.frames.borrow(); + frames + .get(index) + .expect(kcl_error::INTERNAL_ERROR_MSG) + .clone() + }; + if let Proxy::Schema(schema) = &frame.proxy { + attrs.extend(SchemaEvalContext::get_attrs(s, &schema.ctx)); + } + } + attrs + } + + /// Whether the index signature is the schema context. + pub fn has_index_signature(s: &Evaluator, ctx: &SchemaEvalContextRef) -> bool { + if ctx.borrow().node.index_signature.is_some() { + return true; + } + + if let Some(index) = ctx.borrow().parent { + let frame = { + let frames = s.frames.borrow(); + frames + .get(index) + .expect(kcl_error::INTERNAL_ERROR_MSG) + .clone() + }; + if let Proxy::Schema(schema) = &frame.proxy { + return SchemaEvalContext::has_index_signature(s, &schema.ctx); + } + } + false + } + + #[inline] + pub fn is_fit_config(s: &Evaluator, ctx: &SchemaEvalContextRef, value: &ValueRef) -> bool { + if value.is_config() { + let config = value.as_dict_ref(); + for (key, _) in &config.values { + let no_such_attr = + !SchemaEvalContext::has_attr(s, ctx, key) && !key.starts_with('_'); + let has_index_signature = SchemaEvalContext::has_index_signature(s, ctx); + if !has_index_signature && no_such_attr { + return false; + } + } + true + } else { + false + } + } + + /// Init the lazy scope used to cache the lazy evaluation result. + pub fn init_lazy_scope(&mut self, s: &Evaluator, index: Option) { + // TODO: cache the lazy scope cross different schema instances. + let mut setters = IndexMap::with_hasher(DefaultHashBuilder::default()); + // Parent schema setters + if let Some(idx) = self.parent { + let frame = { + let frames = s.frames.borrow(); + frames + .get(idx) + .expect(kcl_error::INTERNAL_ERROR_MSG) + .clone() + }; + if let Proxy::Schema(schema) = &frame.proxy { + let mut parent = schema.ctx.borrow_mut(); + parent.init_lazy_scope(s, Some(idx)); + if let Some(scope) = &parent.scope { + merge_variables_and_setters( + &mut self.value, + &mut setters, + &scope.borrow().setters, + ); + } + } + } + // Self setters + merge_variables_and_setters( + &mut self.value, + &mut setters, + &s.emit_setters(&self.node.body, index), + ); + // Mixin schema setters + for idx in &self.mixins { + let frame = { + let frames = s.frames.borrow(); + frames + .get(*idx) + .expect(kcl_error::INTERNAL_ERROR_MSG) + .clone() + }; + if let Proxy::Schema(schema) = &frame.proxy { + let mut mixin = schema.ctx.borrow_mut(); + mixin.init_lazy_scope(s, Some(*idx)); + if let Some(scope) = &mixin.scope { + merge_variables_and_setters( + &mut self.value, + &mut setters, + &scope.borrow().setters, + ); + } + } + } + self.scope = Some(Rc::new(RefCell::new(LazyEvalScope { + setters, + ..Default::default() + }))) + } + + /// Get the value from the context. + pub fn get_value(&self, s: &Evaluator, key: &str, pkgpath: &str, target: &str) -> ValueRef { + if let Some(scope) = &self.scope { + let value = { + match self.value.get_by_key(key) { + Some(value) => value.clone(), + None => s.get_variable_in_pkgpath(key, pkgpath), + } + }; + // Deal in-place modify and return it self immediately. + if key == target && { + let scope = scope.borrow(); + !scope.is_backtracking(key) || scope.setter_len(key) <= 1 + } { + value + } else { + let cached_value = { + let scope = scope.borrow(); + scope.cache.get(key).cloned() + }; + match cached_value { + Some(value) => value.clone(), + None => { + let setters = { + let scope = scope.borrow(); + scope.setters.get(key).cloned() + }; + match &setters { + Some(setters) if !setters.is_empty() => { + // Call all setters function to calculate the value recursively. + let level = { + let scope = scope.borrow(); + *scope.levels.get(key).unwrap_or(&0) + }; + let next_level = level + 1; + { + let mut scope = scope.borrow_mut(); + scope.levels.insert(key.to_string(), next_level); + } + let n = setters.len(); + let index = n - next_level; + if index >= n { + value + } else { + // Call setter function + s.walk_schema_stmts_with_setter( + &self.node.body, + &setters[index], + ) + .expect(kcl_error::INTERNAL_ERROR_MSG); + { + let mut scope = scope.borrow_mut(); + scope.levels.insert(key.to_string(), level); + let value = match self.value.get_by_key(key) { + Some(value) => value.clone(), + None => s.undefined_value(), + }; + scope.cache.insert(key.to_string(), value.clone()); + value + } + } + } + _ => value, + } + } + } + } + } else if let Some(value) = self.value.dict_get_value(key) { + value + } else { + s.get_variable_in_pkgpath(key, pkgpath) + } + } + + /// Set value to the context. + #[inline] + pub fn set_value(&self, s: &Evaluator, key: &str) { + if let Some(scope) = &self.scope { + let mut scope = scope.borrow_mut(); + if (scope.cal_increment(key) || scope.is_last_setter_ast_index(key, &s.ast_id.borrow())) + && scope.cache.get(key).is_none() + { + scope + .cache + .insert(key.to_string(), s.dict_get_value(&self.value, key)); + } + } + } +} + +#[derive(Clone)] +pub struct SchemaCaller { + pub ctx: SchemaEvalContextRef, + pub body: SchemaBodyHandler, + pub check: SchemaCheckHandler, +} + +/// Init or reset the schema lazy eval scope. +pub(crate) fn init_lazy_scope(s: &Evaluator, ctx: &mut SchemaEvalContext) { + let is_sub_schema = { ctx.is_sub_schema }; + let index = { ctx.index }; + if is_sub_schema { + ctx.init_lazy_scope(s, Some(index)); + } +} + +/// Schema body function +pub(crate) fn schema_body( + s: &Evaluator, + ctx: &SchemaEvalContextRef, + args: &ValueRef, + kwargs: &ValueRef, +) -> ValueRef { + init_lazy_scope(s, &mut ctx.borrow_mut()); + // Schema self value or parent schema value; + let mut schema_ctx_value = if let Some(parent_name) = &ctx.borrow().node.parent_name { + let base_constructor_func = s.load_global_value( + &parent_name.node.pkgpath, + &parent_name + .node + .names + .iter() + .map(|n| n.node.as_str()) + .collect::>(), + ); + // Call base schema function + call_schema_body(s, &base_constructor_func, args, kwargs, ctx) + } else { + ctx.borrow().value.clone() + }; + let schema_name = { ctx.borrow().node.name.node.to_string() }; + s.push_schema(crate::EvalContext::Schema(ctx.clone())); + s.enter_schema_scope(true); + defer! { + s.leave_scope(); + s.pop_schema(); + } + // Evaluate arguments and keyword arguments and store values to local variables. + s.walk_arguments(&ctx.borrow().node.args, args, kwargs); + // Eval schema body and record schema instances. + { + let schema_pkgpath = &s.current_pkgpath(); + // To prevent schema recursive calling, thus clone the AST here. + let node = { + let ctx = ctx.borrow(); + ctx.node.clone() + }; + // Run schema compiled function + for stmt in &node.body { + s.walk_stmt(stmt).expect(kcl_error::RUNTIME_ERROR_MSG); + } + // Schema decorators check + for decorator in &node.decorators { + s.walk_decorator_with_name(&decorator.node, Some(&schema_name), true) + .expect(kcl_error::RUNTIME_ERROR_MSG); + } + let runtime_type = kcl_runtime::schema_runtime_type(&schema_name, schema_pkgpath); + schema_ctx_value.set_potential_schema_type(&runtime_type); + // Set schema arguments and keyword arguments + schema_ctx_value.set_schema_args(args, kwargs); + } + // Schema Mixins + { + let ctx_ref = ctx.borrow(); + for mixin in &ctx_ref.node.mixins { + let mixin_func = s.load_global_value( + &mixin.node.pkgpath, + &mixin + .node + .names + .iter() + .map(|n| n.node.as_str()) + .collect::>(), + ); + schema_ctx_value = call_schema_body(s, &mixin_func, args, kwargs, ctx); + } + } + // Schema Attribute optional check + let mut optional_mapping = { ctx.borrow().optional_mapping.clone() }; + { + let ctx = ctx.borrow(); + for stmt in &ctx.node.body { + if let ast::Stmt::SchemaAttr(schema_attr) = &stmt.node { + s.dict_insert_value( + &mut optional_mapping, + &schema_attr.name.node, + &s.bool_value(schema_attr.is_optional), + ) + } + } + } + // Do schema check for the sub schema. + let is_sub_schema = { ctx.borrow().is_sub_schema }; + let schema = if is_sub_schema { + let index_sign_key_name = if let Some(index_signature) = &ctx.borrow().node.index_signature + { + if let Some(key_name) = &index_signature.node.key_name { + key_name.node.clone() + } else { + "".to_string() + } + } else { + "".to_string() + }; + if index_sign_key_name.is_empty() { + // Update schema relaxed attribute + update_schema_relaxed_attr(s, ctx, &mut schema_ctx_value); + // Construct schema instance + let schema = schema_with_config(s, ctx, &schema_ctx_value, args, kwargs); + // Do schema optional attribute check recursively before evaluate check expressions. + check_schema_optional_attr(s, &schema); + // Call schema check block function + schema_check(s, ctx, &schema, args, kwargs); + schema + } else { + // Do check function for every index signature key + let config = { + let ctx = ctx.borrow(); + ctx.config.clone() + }; + for (k, _) in &config.as_dict_ref().values { + // relaxed keys + if schema_ctx_value.attr_map_get(k).is_none() { + // Update index signature key value + let value = ValueRef::str(k); + schema_ctx_value.dict_update_key_value(&index_sign_key_name, value.clone()); + // Update schema relaxed attribute + update_schema_relaxed_attr(s, ctx, &mut schema_ctx_value); + // Call schema check block function + schema_check(s, ctx, &schema_ctx_value, args, kwargs); + } + } + schema_ctx_value.dict_remove(&index_sign_key_name); + // Construct schema instance + let schema = schema_with_config(s, ctx, &schema_ctx_value, args, kwargs); + // Do schema optional attribute check recursively before evaluate check expressions. + check_schema_optional_attr(s, &schema); + schema + } + } else { + // Record base schema instances. + schema_with_config(s, ctx, &schema_ctx_value, args, kwargs) + }; + schema +} + +// Schema check and index sign value update function +pub(crate) fn schema_check( + s: &Evaluator, + ctx: &SchemaEvalContextRef, + schema_value: &ValueRef, + args: &ValueRef, + kwargs: &ValueRef, +) { + // Call base check function + { + let ctx_ref = ctx.borrow(); + if let Some(parent_name) = &ctx_ref.node.parent_name { + let base_constructor_func = s + .walk_identifier_with_ctx(&parent_name.node, &ast::ExprContext::Load, None) + .expect(kcl_error::RUNTIME_ERROR_MSG); + call_schema_check( + s, + &base_constructor_func, + schema_value, + args, + kwargs, + Some(ctx), + ) + } + } + // Call self check function + { + let ctx = ctx.borrow(); + for check_expr in &ctx.node.checks { + s.walk_check_expr(&check_expr.node) + .expect(kcl_error::RUNTIME_ERROR_MSG); + } + } + + // Call mixin check functions + { + let ctx = ctx.borrow(); + for mixin in &ctx.node.mixins { + let mixin_func = s + .walk_identifier_with_ctx(&mixin.node, &ast::ExprContext::Load, None) + .expect(kcl_error::RUNTIME_ERROR_MSG); + if let Some(index) = mixin_func.try_get_proxy() { + let frame = { + let frames = s.frames.borrow(); + frames + .get(index) + .expect(kcl_error::INTERNAL_ERROR_MSG) + .clone() + }; + if let Proxy::Schema(schema) = &frame.proxy { + s.push_pkgpath(&frame.pkgpath); + s.push_backtrace(&frame); + defer! { + s.pop_backtrace(); + s.pop_pkgpath(); + } + (schema.check)(s, &schema.ctx, schema_value, args, kwargs); + } + } + } + } +} + +pub(crate) fn schema_with_config( + s: &Evaluator, + ctx: &SchemaEvalContextRef, + schema_ctx_value: &ValueRef, + args: &ValueRef, + kwargs: &ValueRef, +) -> ValueRef { + let name = { ctx.borrow().node.name.node.to_string() }; + let pkgpath = s.current_pkgpath(); + let config_keys: Vec = { + ctx.borrow() + .config + .as_dict_ref() + .values + .keys() + .cloned() + .collect() + }; + let runtime_type = schema_runtime_type(&name, &pkgpath); + // Instance package path is the last frame calling package path. + let instance_pkgpath = s.last_pkgpath(); + // Currently, `MySchema.instances()` it is only valid for files in the main package to + // avoid unexpected non idempotent calls. For example, I instantiated a MySchema in pkg1, + // but the length of the list returned by calling the instances method in other packages + // is uncertain. + { + let mut ctx = s.runtime_ctx.borrow_mut(); + // Record schema instance in the context + if !ctx.instances.contains_key(&runtime_type) { + ctx.instances + .insert(runtime_type.clone(), IndexMap::default()); + } + let pkg_instance_map = ctx.instances.get_mut(&runtime_type).unwrap(); + if !pkg_instance_map.contains_key(&instance_pkgpath) { + pkg_instance_map.insert(instance_pkgpath.clone(), vec![]); + } + pkg_instance_map + .get_mut(&instance_pkgpath) + .unwrap() + .push(schema_ctx_value.clone()); + } + // Dict to schema + let is_sub_schema = { ctx.borrow().is_sub_schema }; + if is_sub_schema { + let ctx = ctx.borrow(); + // Record instance copy and convert it to schema value. + schema_ctx_value.dict_to_schema( + &name, + &pkgpath, + &config_keys, + &ctx.config_meta, + &ctx.optional_mapping, + Some(args.clone()), + Some(kwargs.clone()), + ) + } else { + schema_ctx_value.clone() + } +} + +fn update_schema_relaxed_attr( + s: &Evaluator, + ctx: &SchemaEvalContextRef, + schema_value: &mut ValueRef, +) { + let schema_name = { ctx.borrow().node.name.node.to_string() }; + // Do check function + // Schema runtime index signature and relaxed check + { + let ctx = ctx.borrow(); + if let Some(index_signature) = &ctx.node.index_signature { + let index_sign_value = if let Some(value) = &index_signature.node.value { + s.walk_expr(value).expect(kcl_error::RUNTIME_ERROR_MSG) + } else { + s.undefined_value() + }; + let key_name = if let Some(key_name) = &index_signature.node.key_name { + key_name.node.as_str() + } else { + "" + }; + schema_relaxed_attr_update_and_check( + s, + schema_value, + &ctx.config, + &schema_name, + &index_sign_value, + key_name, + index_signature.node.key_ty.node.to_string().as_str(), + index_signature.node.value_ty.node.to_string().as_str(), + ); + } else { + schema_relaxed_attr_update_and_check( + s, + schema_value, + &ctx.config, + &schema_name, + &s.undefined_value(), + "", + "", + "", + ); + } + } +} + +fn check_schema_optional_attr(s: &Evaluator, schema_value: &ValueRef) { + if is_top_level_schema_instance(s) { + schema_value.schema_check_attr_optional(&mut s.runtime_ctx.borrow_mut(), true); + } +} + +/// Schema additional value check +fn schema_relaxed_attr_update_and_check( + s: &Evaluator, + schema_value: &mut ValueRef, + schema_config: &ValueRef, + schema_name: &str, + index_sign_value: &ValueRef, + index_key_name: &str, + key_type: &str, + value_type: &str, +) { + let has_index_signature = !key_type.is_empty(); + let config = schema_config.as_dict_ref(); + for (key, value) in &config.values { + let no_such_attr = schema_value.dict_get_value(key).is_none(); + if has_index_signature && no_such_attr { + // Allow index signature value has different values + // related to the index signature key name. + let should_update = + if let Some(index_key_value) = schema_value.dict_get_value(index_key_name) { + index_key_value.is_str() && key == &index_key_value.as_str() + } else { + true + }; + if should_update { + let op = config + .ops + .get(key) + .unwrap_or(&ConfigEntryOperationKind::Union); + schema_value.dict_update_entry( + key.as_str(), + &index_sign_value.deep_copy(), + &ConfigEntryOperationKind::Override, + None, + ); + s.dict_merge_key_value_pair( + schema_value, + key.as_str(), + value, + op.clone(), + None, + false, + ); + let value = schema_value.dict_get_value(key).unwrap(); + schema_value.dict_update_key_value( + key.as_str(), + type_pack_and_check(s, &value, vec![value_type], false), + ); + } + } else if !has_index_signature && no_such_attr { + panic!("No attribute named '{key}' in the schema '{schema_name}'"); + } + } +} + +/// For a schema instance returned by the schema body. Its schema and schema expr stack +/// length are both 1, if > 1, it's not a top level schema instance. +#[inline] +fn is_top_level_schema_instance(s: &Evaluator) -> bool { + !(s.schema_stack.borrow().len() > 1 || s.schema_expr_stack.borrow().len() > 1) +} + +impl<'ctx> Evaluator<'ctx> { + pub(crate) fn construct_schema_config_meta( + &self, + n: Option<&'ctx ast::Node>, + t: &'ctx ast::ConfigExpr, + ) -> ValueRef { + let mut config_meta = self.dict_value(); + if let Some(n) = n { + let value = self.string_value(&n.filename); + self.dict_insert_value(&mut config_meta, kcl_runtime::CONFIG_META_FILENAME, &value); + let value = self.int_value(n.line as i64); + self.dict_insert_value(&mut config_meta, kcl_runtime::CONFIG_META_LINE, &value); + let value = self.int_value(n.column as i64); + self.dict_insert_value(&mut config_meta, kcl_runtime::CONFIG_META_COLUMN, &value); + } + for item in &t.items { + if let Some(key) = &item.node.key { + let name = match &key.node { + ast::Expr::Identifier(t) => t.names[0].node.clone(), + ast::Expr::NumberLit(t) => match t.value { + ast::NumberLitValue::Int(i) => i.to_string(), + ast::NumberLitValue::Float(f) => f.to_string(), + }, + ast::Expr::StringLit(t) => t.value.clone(), + ast::Expr::NameConstantLit(t) => match t.value { + ast::NameConstant::True => kcl_runtime::KCL_NAME_CONSTANT_TRUE.to_string(), + ast::NameConstant::False => { + kcl_runtime::KCL_NAME_CONSTANT_FALSE.to_string() + } + ast::NameConstant::None => kcl_runtime::KCL_NAME_CONSTANT_NONE.to_string(), + ast::NameConstant::Undefined => { + kcl_runtime::KCL_NAME_CONSTANT_UNDEFINED.to_string() + } + }, + _ => format!("{:?}", key.node), + }; + let mut config_item_meta = self.dict_value(); + let value = self.string_value(&key.filename); + self.dict_insert_value( + &mut config_item_meta, + kcl_runtime::CONFIG_ITEM_META_FILENAME, + &value, + ); + let value = self.int_value(key.line as i64); + self.dict_insert_value( + &mut config_item_meta, + kcl_runtime::CONFIG_ITEM_META_LINE, + &value, + ); + let value = self.int_value(key.column as i64); + self.dict_insert_value( + &mut config_item_meta, + kcl_runtime::CONFIG_ITEM_META_COLUMN, + &value, + ); + let value = match &item.node.value.node { + ast::Expr::Config(config_expr) => { + self.construct_schema_config_meta(None, config_expr) + } + _ => self.dict_value(), + }; + self.dict_insert_value( + &mut config_item_meta, + kcl_runtime::CONFIG_ITEM_META, + &value, + ); + self.dict_insert_value(&mut config_meta, &name, &config_item_meta) + } + } + config_meta + } + + pub(crate) fn update_schema_or_rule_scope_value( + &self, + name: &str, // Schema attribute name + value: Option<&ValueRef>, // Optional right override value + ) { + let (mut schema_value, config_value, _) = self + .get_schema_or_rule_config_info() + .expect(kcl_error::INTERNAL_ERROR_MSG); + let config_value = config_value + .dict_get_entry(name) + .unwrap_or(self.undefined_value()); + if self.scope_level() >= INNER_LEVEL && !self.is_local_var(name) { + if let Some(value) = value { + self.schema_dict_merge( + &mut schema_value, + name, + value, + &ast::ConfigEntryOperation::Override, + None, + ); + } + self.value_union(&mut schema_value, &config_value); + // Set config cache for the schema eval context. + if let Some(schema_ctx) = self.get_schema_eval_context() { + schema_ctx.borrow().set_value(self, name); + } + } + } +} diff --git a/crates/evaluator/src/scope.rs b/crates/evaluator/src/scope.rs new file mode 100644 index 000000000..a878d50a8 --- /dev/null +++ b/crates/evaluator/src/scope.rs @@ -0,0 +1,746 @@ +use std::sync::{Arc, RwLock}; + +use crate::func::ClosureMap; +use crate::lazy::merge_setters; +use crate::{ + error as kcl_error, lazy::LazyEvalScope, rule::RuleEvalContextRef, schema::SchemaEvalContextRef, +}; +use kcl_ast::ast; +use kcl_ast::walker::TypedResultWalker; +use kcl_primitives::{DefaultHashBuilder, IndexMap, IndexSet}; +use kcl_runtime::{_kcl_get_fn_ptr_by_name, MAIN_PKG_PATH, ValueRef}; +use kcl_sema::{builtin, plugin}; + +use crate::{EvalResult, Evaluator, GLOBAL_LEVEL, INNER_LEVEL}; + +/// The evaluator scope. +#[derive(Debug, Default)] +pub struct Scope { + /// Scalars denotes the expression statement values without attribute. + pub scalars: Vec, + /// schema_scalar_idx denotes whether a schema exists in the scalar list. + pub schema_scalar_idx: usize, + /// is_schema denotes whether the scope is a schema. + pub is_schema: bool, + /// Scope normal variables + pub variables: IndexMap, + /// Potential arguments in the current scope, such as schema/lambda arguments. + pub arguments: IndexSet, +} + +impl<'ctx> Evaluator<'ctx> { + /// Init a scope named `pkgpath` with all builtin functions + pub(crate) fn init_scope(&self, pkgpath: &str) { + { + let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); + if pkg_scopes.contains_key(pkgpath) { + return; + } + let scopes = vec![Scope::default()]; + pkg_scopes.insert(String::from(pkgpath), scopes); + } + // Get the AST module list in the package path. + let module_list: Vec>> = if self.program.pkgs.contains_key(pkgpath) + { + self.program.get_modules_for_pkg(pkgpath) + } else if pkgpath.starts_with(kcl_runtime::PKG_PATH_PREFIX) + && self.program.pkgs.contains_key(&pkgpath[1..]) + { + self.program.get_modules_for_pkg(&pkgpath[1..]) + } else { + panic!("pkgpath {} not found", pkgpath); + }; + // Init all global types including schema and rule. + for module in &module_list { + let module = module.read().expect("Failed to acquire module lock"); + for stmt in &module.body { + let name = match &stmt.node { + ast::Stmt::Schema(schema_stmt) => schema_stmt.name.node.clone(), + ast::Stmt::Rule(rule_stmt) => rule_stmt.name.node.clone(), + _ => "".to_string(), + }; + if !name.is_empty() { + self.add_variable(&name, self.undefined_value()); + } + } + } + // Init all builtin functions + for symbol in builtin::BUILTIN_FUNCTION_NAMES { + let function_name = + format!("{}_{}", builtin::KCL_BUILTIN_FUNCTION_MANGLE_PREFIX, symbol); + let function_ptr = _kcl_get_fn_ptr_by_name(&function_name); + self.add_variable(symbol, self.function_value_with_ptr(function_ptr)); + } + // Init lazy scopes. + { + let mut lazy_scopes = self.lazy_scopes.borrow_mut(); + let mut setters = IndexMap::with_hasher(DefaultHashBuilder::default()); + for (index, module) in module_list.iter().enumerate() { + let index = self.add_global_body(index); + let module = module.read().expect("Failed to acquire module lock"); + merge_setters(&mut setters, &self.emit_setters(&module.body, Some(index))) + } + if !lazy_scopes.contains_key(pkgpath) { + lazy_scopes.insert( + pkgpath.to_string(), + LazyEvalScope { + setters, + ..Default::default() + }, + ); + } + } + // Enter the global scope. + self.enter_scope(); + } + + /// Get the scope level + pub(crate) fn scope_level(&self) -> usize { + let current_pkgpath = self.current_pkgpath(); + let pkg_scopes = &self.pkg_scopes.borrow(); + let msg = format!("pkgpath {} is not found", current_pkgpath); + let scopes = pkg_scopes.get(¤t_pkgpath).expect(&msg); + // Sub the builtin global scope + scopes.len() - 1 + } + + /// Get the scope level + pub(crate) fn is_schema_scope(&self) -> bool { + let current_pkgpath = self.current_pkgpath(); + let pkg_scopes = &self.pkg_scopes.borrow(); + let msg = format!("pkgpath {} is not found", current_pkgpath); + let scopes = pkg_scopes.get(¤t_pkgpath).expect(&msg); + if let Some(last_scope) = scopes.last() { + last_scope.is_schema + } else { + false + } + } + + /// Enter a schema scope + pub(crate) fn enter_schema_scope(&self, is_schema: bool) { + let current_pkgpath = self.current_pkgpath(); + let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); + let msg = format!("pkgpath {} is not found", current_pkgpath); + let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); + let mut scope = Scope::default(); + scope.is_schema = is_schema; + scopes.push(scope); + } + + /// Enter scope + #[inline] + pub(crate) fn enter_scope(&self) { + self.enter_schema_scope(false); + } + + /// Leave scope + pub(crate) fn leave_scope(&self) { + let current_pkgpath = self.current_pkgpath(); + let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); + let msg = format!("pkgpath {} is not found", current_pkgpath); + let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); + scopes.pop(); + } + + pub(crate) fn get_schema_eval_context(&self) -> Option { + match self.schema_stack.borrow().last() { + Some(ctx) => match ctx { + crate::EvalContext::Schema(schema) => Some(schema.clone()), + crate::EvalContext::Rule(_) => None, + }, + None => None, + } + } + + pub(crate) fn get_rule_eval_context(&self) -> Option { + match self.schema_stack.borrow().last() { + Some(ctx) => match ctx { + crate::EvalContext::Schema(_) => None, + crate::EvalContext::Rule(rule) => Some(rule.clone()), + }, + None => None, + } + } + + /// Returns (value, config, config_meta) + #[inline] + pub(crate) fn get_schema_or_rule_config_info(&self) -> Option<(ValueRef, ValueRef, ValueRef)> { + match self.get_schema_eval_context() { + Some(v) => Some(( + v.borrow().value.clone(), + v.borrow().config.clone(), + v.borrow().config_meta.clone(), + )), + None => self.get_rule_eval_context().map(|v| { + ( + v.borrow().value.clone(), + v.borrow().config.clone(), + v.borrow().config_meta.clone(), + ) + }), + } + } + + /// Append a scalar value into the scope. + pub fn add_scalar(&self, scalar: ValueRef, is_schema: bool) { + let current_pkgpath = self.current_pkgpath(); + let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); + let scopes = pkg_scopes + .get_mut(¤t_pkgpath) + .unwrap_or_else(|| panic!("pkgpath {} is not found", current_pkgpath)); + if let Some(last) = scopes.last_mut() { + let scalars = &mut last.scalars; + let schema_scalar_idx = &mut last.schema_scalar_idx; + if is_schema { + // Remove the last schema scalar. + if *schema_scalar_idx < scalars.len() { + scalars.remove(*schema_scalar_idx); + } + // Override the last schema scalar. + scalars.push(scalar); + *schema_scalar_idx = scalars.len() - 1; + } else { + scalars.push(scalar); + } + } + } + + /// Append a variable into the scope + pub fn add_variable(&self, name: &str, pointer: ValueRef) { + let current_pkgpath = self.current_pkgpath(); + let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); + let msg = format!("pkgpath {} is not found", current_pkgpath); + let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); + if let Some(last) = scopes.last_mut() { + let variables = &mut last.variables; + variables.insert(name.to_string(), pointer); + } + } + + /// Store the argument named `name` in the current scope. + pub(crate) fn store_argument_in_current_scope(&self, name: &str) { + // Find argument name in the scope + let current_pkgpath = self.current_pkgpath(); + let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); + let msg = format!("pkgpath {} is not found", current_pkgpath); + let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); + let index = scopes.len() - 1; + let arguments_mut = &mut scopes[index].arguments; + arguments_mut.insert(name.to_string()); + } + + /// Store the variable named `name` with `value` from the current scope, return false when not found + pub fn store_variable_in_current_scope(&self, name: &str, value: ValueRef) -> bool { + // Find argument name in the scope + let current_pkgpath = self.current_pkgpath(); + let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); + let msg = format!("pkgpath {} is not found", current_pkgpath); + let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); + let index = scopes.len() - 1; + let variables = &mut scopes[index].variables; + // If exists and update it + if variables.get(&name.to_string()).is_some() { + variables.insert(name.to_string(), value); + return true; + } + false + } + + /// Store the variable named `name` with `value` from the scope, return false when not found + pub fn store_variable(&self, name: &str, value: ValueRef) -> bool { + // Find argument name in the scope + let current_pkgpath = self.current_pkgpath(); + let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); + let msg = format!("pkgpath {} is not found", current_pkgpath); + let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); + for i in 0..scopes.len() { + let index = scopes.len() - i - 1; + let variables = &mut scopes[index].variables; + // If exists and update it + if variables.get(&name.to_string()).is_some() { + variables.insert(name.to_string(), value); + return true; + } + } + false + } + + /// Resolve variable in scope, return false when not found. + #[inline] + pub fn resolve_variable(&self, name: &str) -> bool { + self.resolve_variable_level(name).is_some() + } + + /// Resolve variable level in scope, return None when not found. + pub fn resolve_variable_level(&self, name: &str) -> Option { + // Find argument name in the scope + let current_pkgpath = self.current_pkgpath(); + let pkg_scopes = &self.pkg_scopes.borrow(); + let msg = format!("pkgpath {} is not found", current_pkgpath); + let scopes = pkg_scopes.get(¤t_pkgpath).expect(&msg); + let mut level = None; + for i in 0..scopes.len() { + let index = scopes.len() - i - 1; + let variables = &scopes[index].variables; + let arguments = &scopes[index].arguments; + if variables.get(name).is_some() { + level = Some(index); + break; + } + if arguments.contains(name) { + level = Some(index); + break; + } + } + level + } + + /// Append a variable or update the existed local variable within the current scope. + pub(crate) fn add_or_update_local_variable_within_scope(&self, name: &str, value: ValueRef) { + let current_pkgpath = self.current_pkgpath(); + let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); + let msg = format!("pkgpath {} is not found", current_pkgpath); + let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); + let index = scopes.len() - 1; + if let Some(scope) = scopes.last_mut() { + let variables_mut = &mut scope.variables; + if index > GLOBAL_LEVEL { + variables_mut.insert(name.to_string(), value.clone()); + } + } + } + + /// Append a variable or update the existed variable + pub fn add_or_update_global_variable( + &self, + name: &str, + value: ValueRef, + save_lazy_scope: bool, + ) { + // Find argument name in the scope + let current_pkgpath = self.current_pkgpath(); + let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); + let msg = format!("pkgpath {} is not found", current_pkgpath); + let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); + let mut existed = false; + if let Some(last) = scopes.last_mut() { + let variables = &mut last.variables; + if variables.get(&name.to_string()).is_some() { + variables.insert(name.to_string(), value.clone()); + if save_lazy_scope { + self.set_value_to_lazy_scope(¤t_pkgpath, name, &value) + } + existed = true; + } + } + if !existed { + if let Some(last) = scopes.last_mut() { + let variables = &mut last.variables; + if !variables.contains_key(name) { + variables.insert(name.to_string(), value.clone()); + if save_lazy_scope { + self.set_value_to_lazy_scope(¤t_pkgpath, name, &value) + } + } + } + } + } + + /// Get the variable value named `name` from the scope, return Err when not found + pub fn get_variable(&self, name: &str) -> ValueRef { + let current_pkgpath = self.current_pkgpath(); + self.get_variable_in_pkgpath(name, ¤t_pkgpath) + } + + /// Get the variable value named `name` from the scope, return Err when not found + pub fn get_variable_in_schema_or_rule(&self, name: &str) -> ValueRef { + let pkgpath = self.current_pkgpath(); + if let Some(schema_ctx) = self.get_schema_eval_context() { + return schema_ctx + .borrow() + .get_value(self, name, &pkgpath, &self.get_target_var()); + } else if let Some(rule_ctx) = self.get_rule_eval_context() { + let rule_value: ValueRef = rule_ctx.borrow().value.clone(); + return if let Some(value) = rule_value.dict_get_value(name) { + value + } else { + self.get_variable_in_pkgpath(name, &pkgpath) + }; + } else { + self.get_variable_in_pkgpath(name, &pkgpath) + } + } + + /// Get the variable value named `name` from the scope named `pkgpath`, return Err when not found + pub fn get_variable_in_pkgpath(&self, name: &str, pkgpath: &str) -> ValueRef { + let pkg_scopes = self.pkg_scopes.borrow(); + let pkgpath = + if !pkgpath.starts_with(kcl_runtime::PKG_PATH_PREFIX) && pkgpath != MAIN_PKG_PATH { + format!("{}{}", kcl_runtime::PKG_PATH_PREFIX, pkgpath) + } else { + pkgpath.to_string() + }; + let mut result = self.undefined_value(); + // System module + if builtin::STANDARD_SYSTEM_MODULE_NAMES_WITH_AT.contains(&pkgpath.as_str()) { + let pkgpath = &pkgpath[1..]; + + if pkgpath == builtin::system_module::UNITS + && builtin::system_module::UNITS_FIELD_NAMES.contains(&name) + { + let value_float: f64 = kcl_runtime::f64_unit_value(name); + let value_int: u64 = kcl_runtime::u64_unit_value(name); + if value_int != 1 { + self.int_value(value_int as i64) + } else { + self.float_value(value_float) + } + } else { + let func_name = format!( + "{}{}_{}", + builtin::KCL_SYSTEM_MODULE_MANGLE_PREFIX, + pkgpath, + name + ); + let function_ptr = _kcl_get_fn_ptr_by_name(&func_name); + self.function_value_with_ptr(function_ptr) + } + } + // Plugin pkgpath + else if pkgpath.starts_with(plugin::PLUGIN_PREFIX_WITH_AT) { + // Strip the @kcl_plugin to kcl_plugin. + let name = format!("{}.{}", &pkgpath[1..], name); + ValueRef::func(0, 0, self.undefined_value(), &name, "", true) + // User pkgpath + } else { + // Global or local variables. + let scopes = pkg_scopes + .get(&pkgpath) + .unwrap_or_else(|| panic!("package {} is not found", pkgpath)); + // Scopes 0 is builtin scope, Scopes 1 is the global scope, Scopes 2~ are the local scopes + let scopes_len = scopes.len(); + let mut found = false; + for i in 0..scopes_len { + let index = scopes_len - i - 1; + let variables = &scopes[index].variables; + + if let Some(var) = variables.get(name) { + // Closure vars, 2 denotes the builtin scope and the global scope, here is a closure scope. + result = if let Some(lambda_ctx) = self.last_lambda_ctx() { + let last_lambda_scope = lambda_ctx.level; + // Local scope variable or lambda closure variable. + let ignore = if let Some((start, end)) = self.scope_covers.borrow().last() { + *start <= index && index <= *end + } else { + false + }; + if index >= last_lambda_scope && !ignore { + var.clone() + } else { + lambda_ctx.closure.get(name).unwrap_or(var).clone() + } + } else { + // Not in the lambda, maybe a local variable. + var.clone() + }; + found = true; + break; + } + } + if found { + result + } else { + // Not found variable in the scope, maybe lambda closures captured in other package scopes. + self.last_lambda_ctx() + .map(|ctx| ctx.closure.get(name).cloned().unwrap_or(result.clone())) + .unwrap_or(result) + } + } + } + + fn get_variable_in_pkgpath_from_last_scope(&self, name: &str, pkgpath: &str) -> ValueRef { + let pkg_scopes = self.pkg_scopes.borrow(); + let pkgpath = + if !pkgpath.starts_with(kcl_runtime::PKG_PATH_PREFIX) && pkgpath != MAIN_PKG_PATH { + format!("{}{}", kcl_runtime::PKG_PATH_PREFIX, pkgpath) + } else { + pkgpath.to_string() + }; + let mut result = self.undefined_value(); + // System module + if builtin::STANDARD_SYSTEM_MODULE_NAMES_WITH_AT.contains(&pkgpath.as_str()) { + let pkgpath = &pkgpath[1..]; + + if pkgpath == builtin::system_module::UNITS + && builtin::system_module::UNITS_FIELD_NAMES.contains(&name) + { + let value_float: f64 = kcl_runtime::f64_unit_value(name); + let value_int: u64 = kcl_runtime::u64_unit_value(name); + if value_int != 1 { + self.int_value(value_int as i64) + } else { + self.float_value(value_float) + } + } else { + let func_name = format!( + "{}{}_{}", + builtin::KCL_SYSTEM_MODULE_MANGLE_PREFIX, + pkgpath, + name + ); + let function_ptr = _kcl_get_fn_ptr_by_name(&func_name); + self.function_value_with_ptr(function_ptr) + } + } + // Plugin pkgpath + else if pkgpath.starts_with(plugin::PLUGIN_PREFIX_WITH_AT) { + // Strip the @kcl_plugin to kcl_plugin. + let name = format!("{}.{}", &pkgpath[1..], name); + ValueRef::func(0, 0, self.undefined_value(), &name, "", true) + // User pkgpath + } else { + // Global or local variables. + let scopes = pkg_scopes + .get(&pkgpath) + .unwrap_or_else(|| panic!("package {} is not found", pkgpath)); + // Scopes 0 is builtin scope, Scopes 1 is the global scope, Scopes 2~ are the local scopes + let scopes_len = scopes.len(); + + let index = scopes_len - 1; + let variables = &scopes[index].variables; + + if let Some(var) = variables.get(name) { + // Closure vars, 2 denotes the builtin scope and the global scope, here is a closure scope. + result = if let Some(lambda_ctx) = self.last_lambda_ctx() { + let last_lambda_scope = lambda_ctx.level; + // Local scope variable or lambda closure variable. + let ignore = if let Some((start, end)) = self.scope_covers.borrow().last() { + *start <= index && index <= *end + } else { + false + }; + if index >= last_lambda_scope && !ignore { + var.clone() + } else { + lambda_ctx.closure.get(name).unwrap_or(var).clone() + } + } else { + // Not in the lambda, maybe a local variable. + var.clone() + }; + } + result + } + } + + /// Get closure map in the current inner scope. + pub(crate) fn get_current_closure_map(&self) -> ClosureMap { + // Get variable map in the current scope. + let pkgpath = self.current_pkgpath(); + let pkg_scopes = self.pkg_scopes.borrow(); + let scopes = pkg_scopes + .get(&pkgpath) + .unwrap_or_else(|| panic!("package {} is not found", pkgpath)); + let last_lambda_ctx = self.last_lambda_ctx(); + // Get current closure map. + let mut closure_map = last_lambda_ctx + .as_ref() + .map(|ctx| ctx.closure.clone()) + .unwrap_or_default(); + // Get variable map including schema in the current scope. + for i in INNER_LEVEL..scopes.len() { + let variables = &scopes + .get(i) + .expect(kcl_error::INTERNAL_ERROR_MSG) + .variables; + for (k, v) in variables { + closure_map.insert(k.to_string(), v.clone()); + } + } + closure_map + } + + /// Load value from name. + pub fn load_value(&self, pkgpath: &str, names: &[&str]) -> ValueRef { + if names.is_empty() { + return self.undefined_value(); + } + let name = names[0]; + if names.len() == 1 { + self.load_name(name) + } else { + let mut value = if pkgpath.is_empty() { + self.load_name(name) + } else { + self.undefined_value() + }; + for i in 0..names.len() - 1 { + let attr = names[i + 1]; + if i == 0 && !pkgpath.is_empty() { + value = self.get_variable_in_pkgpath(attr, pkgpath); + } else { + value = value.load_attr(attr) + } + } + value + } + } + + /// Load global value from name. + pub fn load_global_value(&self, pkgpath: &str, names: &[&str]) -> ValueRef { + if names.is_empty() { + return self.undefined_value(); + } + let name = names[0]; + if names.len() == 1 { + self.get_variable(name) + } else { + let mut value = if pkgpath.is_empty() { + self.get_variable(name) + } else { + self.undefined_value() + }; + for i in 0..names.len() - 1 { + let attr = names[i + 1]; + if i == 0 && !pkgpath.is_empty() { + value = self.get_variable_in_pkgpath(attr, pkgpath); + } else { + value = value.load_attr(attr) + } + } + value + } + } + + /// Load global or local value from name. + pub fn load_name(&self, name: &str) -> ValueRef { + match ( + self.is_in_schema(), + self.is_in_lambda(), + self.is_local_var(name), + ) { + // Get variable from the global lazy scope. + (false, _, false) => { + let variable = self.get_variable(name); + match self.resolve_variable_level(name) { + // Closure variable or local variables + Some(level) if level <= GLOBAL_LEVEL => self.get_value_from_lazy_scope( + &self.current_pkgpath(), + name, + &self.get_target_var(), + variable, + ), + // Schema closure or global variables + _ => variable, + } + } + // Get variable from the local or global scope. + (false, _, _) | (_, _, true) => self.get_variable(name), + // Get variable from the current schema scope. + (true, false, false) => self.get_variable_in_schema_or_rule(name), + // Get from local scope including lambda arguments, lambda variables, + // loop variables or global variables. + (true, true, _) => + // Get from local scope including lambda arguments, lambda variables, + // loop variables or global variables. + { + match self.resolve_variable_level(name) { + // Closure variable or local variables + Some(level) if level > GLOBAL_LEVEL => { + let ctx_stack = self.ctx_stack.borrow(); + let mut result = self.undefined_value(); + let mut found = false; + for i in 0..ctx_stack.len() { + let index = ctx_stack.len() - i - 1; + match &ctx_stack[index] { + crate::LambdaOrSchemaEvalContext::Schema(_) => { + let res = self.get_variable_in_schema_or_rule(name); + + if !res.is_undefined() { + result = res; + found = true; + break; + } + } + crate::LambdaOrSchemaEvalContext::Lambda(_) => { + let current_pkgpath = self.current_pkgpath(); + let res = self.get_variable_in_pkgpath_from_last_scope( + name, + ¤t_pkgpath, + ); + if !res.is_undefined() { + result = res; + found = true; + break; + } + } + } + } + if found { + result + } else { + // Not found variable in the scope, maybe lambda closures captured in other package scopes. + self.last_lambda_ctx() + .map(|ctx| ctx.closure.get(name).cloned().unwrap_or(result.clone())) + .unwrap_or(result) + } + } + // Schema closure or global variables + _ => self.get_variable_in_schema_or_rule(name), + } + } + } + } + + /// Load assignment target value. + pub fn load_target(&self, target: &'ctx ast::Target) -> EvalResult { + let mut value = self.load_name(target.get_name()); + for path in &target.paths { + match path { + ast::MemberOrIndex::Member(member) => { + let attr = &member.node; + value = value.load_attr(attr); + } + ast::MemberOrIndex::Index(index) => { + let index = self.walk_expr(index)?; + value = value.bin_subscr(&index); + } + } + } + Ok(value) + } + + /// Load value from assignment target path. + pub fn load_target_path(&self, value: &ValueRef, path: &'ctx ast::MemberOrIndex) -> EvalResult { + Ok(match path { + ast::MemberOrIndex::Member(member) => { + let attr = &member.node; + value.load_attr(attr) + } + ast::MemberOrIndex::Index(index) => { + let index = self.walk_expr(index)?; + value.bin_subscr(&index) + } + }) + } + + pub fn store_target_path( + &self, + value: &mut ValueRef, + path: &'ctx ast::MemberOrIndex, + right_value: &ValueRef, + ) -> EvalResult { + match path { + ast::MemberOrIndex::Member(member) => { + let attr = &member.node; + self.dict_set_value(value, attr, &right_value); + } + ast::MemberOrIndex::Index(index) => { + let index = self.walk_expr(index)?; + value.bin_subscr_set(&mut self.runtime_ctx.borrow_mut(), &index, &right_value); + } + } + self.ok_result() + } +} diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__assert_stmt_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assert_stmt_0.snap new file mode 100644 index 000000000..38cba4d70 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assert_stmt_0.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__assert_stmt_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assert_stmt_1.snap new file mode 100644 index 000000000..38cba4d70 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assert_stmt_1.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_0.snap new file mode 100644 index 000000000..38cba4d70 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_0.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_1.snap new file mode 100644 index 000000000..4a24927e4 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_1.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_2.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_2.snap new file mode 100644 index 000000000..f532ec1c6 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_2.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 3 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_3.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_3.snap new file mode 100644 index 000000000..f762205c0 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_3.snap @@ -0,0 +1,6 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1 +b: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_4.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_4.snap new file mode 100644 index 000000000..f762205c0 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_4.snap @@ -0,0 +1,6 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1 +b: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_5.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_5.snap new file mode 100644 index 000000000..9cc8f3b1c --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_5.snap @@ -0,0 +1,7 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: +- 1 +- 0 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_6.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_6.snap new file mode 100644 index 000000000..117d20086 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_6.snap @@ -0,0 +1,7 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: +- key: 1 +- key: 0 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_7.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_7.snap new file mode 100644 index 000000000..4106f1621 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__assign_stmt_7.snap @@ -0,0 +1,13 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: +- key: + key: + - 1 + - 0 +- key: + key: + - 0 + - 0 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_0.snap new file mode 100644 index 000000000..4a24927e4 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_0.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_1.snap new file mode 100644 index 000000000..4f90c9ccb --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_1.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 0 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_10.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_10.snap new file mode 100644 index 000000000..38cba4d70 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_10.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_11.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_11.snap new file mode 100644 index 000000000..38cba4d70 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_11.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_12.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_12.snap new file mode 100644 index 000000000..a5af39b16 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_12.snap @@ -0,0 +1,10 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: +- 1 +- 0 +- 0 +- 0 +- 0 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_13.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_13.snap new file mode 100644 index 000000000..8ce0fb58b --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_13.snap @@ -0,0 +1,10 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: +- key: 2 +- key: 1 +- key: 1 +- key: 1 +- key: 1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_14.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_14.snap new file mode 100644 index 000000000..fd440dabd --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_14.snap @@ -0,0 +1,25 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: +- key: + key: + - 1 + - 0 +- key: + key: + - 0 + - 0 +- key: + key: + - 0 + - 0 +- key: + key: + - 0 + - 0 +- key: + key: + - 0 + - 0 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_2.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_2.snap new file mode 100644 index 000000000..4a24927e4 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_2.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_3.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_3.snap new file mode 100644 index 000000000..98edbb5df --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_3.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1.0 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_4.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_4.snap new file mode 100644 index 000000000..38cba4d70 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_4.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_5.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_5.snap new file mode 100644 index 000000000..7b823ca21 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_5.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 9 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_6.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_6.snap new file mode 100644 index 000000000..0a51c6406 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_6.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 6 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_7.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_7.snap new file mode 100644 index 000000000..38cba4d70 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_7.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_8.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_8.snap new file mode 100644 index 000000000..f532ec1c6 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_8.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 3 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_9.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_9.snap new file mode 100644 index 000000000..4a24927e4 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__aug_assign_stmt_9.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__binary_expr_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__binary_expr_0.snap new file mode 100644 index 000000000..1803e044c --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__binary_expr_0.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: -1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__binary_expr_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__binary_expr_1.snap new file mode 100644 index 000000000..f4e9800fa --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__binary_expr_1.snap @@ -0,0 +1,6 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: {} +b: [] diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__compare_expr_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__compare_expr_0.snap new file mode 100644 index 000000000..12b9cba49 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__compare_expr_0.snap @@ -0,0 +1,8 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: true +b: true +c: false +d: false diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__dict_expr_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__dict_expr_0.snap new file mode 100644 index 000000000..875ec7cf9 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__dict_expr_0.snap @@ -0,0 +1,15 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: + k1: v1 + k2: v2 +b: + k1: v1 + k2: v2 +c: + k1: v1 +d: + k1: v1 + k2: v2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__exec_with_plugin.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__exec_with_plugin.snap new file mode 100644 index 000000000..55b50d7f9 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__exec_with_plugin.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format!(\"{}\", evaluator.run().unwrap().1)" +--- +sum: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_0.snap new file mode 100644 index 000000000..360b2de41 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_0.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_1.snap new file mode 100644 index 000000000..a7464b9e9 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_1.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +2.0 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_2.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_2.snap new file mode 100644 index 000000000..55557fe37 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_2.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +true diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_3.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_3.snap new file mode 100644 index 000000000..13870a14e --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_3.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +null diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_4.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_4.snap new file mode 100644 index 000000000..feecde25c --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_4.snap @@ -0,0 +1,9 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +1 +--- +2 +--- +3 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_5.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_5.snap new file mode 100644 index 000000000..6553a7b19 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__expr_stmt_5.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +k: v diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__function_stmt_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__function_stmt_0.snap new file mode 100644 index 000000000..be78b169e --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__function_stmt_0.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run_as_function().to_string())" +--- +"bar" diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_expr_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_expr_0.snap new file mode 100644 index 000000000..38cba4d70 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_expr_0.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_expr_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_expr_1.snap new file mode 100644 index 000000000..4f90c9ccb --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_expr_1.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 0 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_expr_2.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_expr_2.snap new file mode 100644 index 000000000..4a24927e4 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_expr_2.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_0.snap new file mode 100644 index 000000000..38cba4d70 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_0.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_1.snap new file mode 100644 index 000000000..087a0febb --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_1.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +b: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_3.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_3.snap new file mode 100644 index 000000000..087a0febb --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_3.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +b: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_4.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_4.snap new file mode 100644 index 000000000..13e166f05 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_4.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +c: 3 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_5.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_5.snap new file mode 100644 index 000000000..087a0febb --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_5.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +b: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_6.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_6.snap new file mode 100644 index 000000000..d238c32da --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_6.snap @@ -0,0 +1,6 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +b: 1 +c: 1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_7.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_7.snap new file mode 100644 index 000000000..59a8c485e --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_7.snap @@ -0,0 +1,7 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 3 +c: + a: 3 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_8.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_8.snap new file mode 100644 index 000000000..16c32e67b --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__if_stmt_8.snap @@ -0,0 +1,9 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +items: +- key2: value2 +c: + items: + - key2: value2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__import_stmt_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__import_stmt_0.snap new file mode 100644 index 000000000..38cba4d70 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__import_stmt_0.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__import_stmt_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__import_stmt_1.snap new file mode 100644 index 000000000..087a0febb --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__import_stmt_1.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +b: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__import_stmt_2.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__import_stmt_2.snap new file mode 100644 index 000000000..9732c33c6 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__import_stmt_2.snap @@ -0,0 +1,6 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +v: null +x: true diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__import_stmt_3.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__import_stmt_3.snap new file mode 100644 index 000000000..fc8e9b629 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__import_stmt_3.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +x: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_0.snap new file mode 100644 index 000000000..f50912f5c --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_0.snap @@ -0,0 +1,6 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 2 +b: 4 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_1.snap new file mode 100644 index 000000000..f50912f5c --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_1.snap @@ -0,0 +1,6 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 2 +b: 4 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_2.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_2.snap new file mode 100644 index 000000000..e29eca25d --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_2.snap @@ -0,0 +1,7 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 2 +b: 3 +c: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_3.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_3.snap new file mode 100644 index 000000000..fc8e9b629 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_3.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +x: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_4.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_4.snap new file mode 100644 index 000000000..258b726cf --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_4.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +x: 6 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_5.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_5.snap new file mode 100644 index 000000000..b09b38c83 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_5.snap @@ -0,0 +1,6 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +x: + value: 4 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_6.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_6.snap new file mode 100644 index 000000000..bf84aa762 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lambda_6.snap @@ -0,0 +1,7 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +my_dict: + my_field: 1 + x: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__lazy_scope_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lazy_scope_0.snap new file mode 100644 index 000000000..812039b6a --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lazy_scope_0.snap @@ -0,0 +1,7 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +b: 3 +a: 1 +c: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__lazy_scope_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lazy_scope_1.snap new file mode 100644 index 000000000..83f614d8b --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lazy_scope_1.snap @@ -0,0 +1,8 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +data: + b: 3 + a: 1 + c: 2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__lazy_scope_2.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lazy_scope_2.snap new file mode 100644 index 000000000..faaedc96f --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__lazy_scope_2.snap @@ -0,0 +1,10 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +data1: + name: '1' +data2: + name: '1' + version: v0.1.0 +version: v0.1.0 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__list_comp1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__list_comp1.snap new file mode 100644 index 000000000..f805e5807 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__list_comp1.snap @@ -0,0 +1,7 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: +- 你 +- 好 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__list_expr_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__list_expr_0.snap new file mode 100644 index 000000000..41abbcef4 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__list_expr_0.snap @@ -0,0 +1,19 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: +- 1 +- 2 +- 3 +b: +- 1 +- 2 +- 3 +c: +- 1 +- 3 +d: +- 1 +- 2 +- 3 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__literal_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__literal_0.snap new file mode 100644 index 000000000..d29dde747 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__literal_0.snap @@ -0,0 +1,7 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +longStringStartWithNewline: | + This is the second line + This is the third line diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__literal_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__literal_1.snap new file mode 100644 index 000000000..27c1663bb --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__literal_1.snap @@ -0,0 +1,7 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: + k: v +b: '{"k": "v"}' diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__literal_2.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__literal_2.snap new file mode 100644 index 000000000..260dcbb4a --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__literal_2.snap @@ -0,0 +1,6 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1048576.0 +b: 2000.0 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__loop_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__loop_0.snap new file mode 100644 index 000000000..4a33448ad --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__loop_0.snap @@ -0,0 +1,8 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: +- 1 +- 4 +- 9 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__loop_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__loop_1.snap new file mode 100644 index 000000000..eba3a0219 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__loop_1.snap @@ -0,0 +1,8 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: +- 3 +- 4 +- 5 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__paren_expr_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__paren_expr_0.snap new file mode 100644 index 000000000..d8a9cbd95 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__paren_expr_0.snap @@ -0,0 +1,6 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 4 +b: 4 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_0.snap new file mode 100644 index 000000000..8ea07900d --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_0.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +b: true diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_1.snap new file mode 100644 index 000000000..8ea07900d --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_1.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +b: true diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_2.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_2.snap new file mode 100644 index 000000000..32f998f7f --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_2.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +b: false diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_3.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_3.snap new file mode 100644 index 000000000..32f998f7f --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_3.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +b: false diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_4.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_4.snap new file mode 100644 index 000000000..58da5aa5f --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_4.snap @@ -0,0 +1,8 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +b: +- 2 +- 3 +- 4 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_5.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_5.snap new file mode 100644 index 000000000..2a9e63492 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_5.snap @@ -0,0 +1,7 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +b: +- 2 +- 3 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_6.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_6.snap new file mode 100644 index 000000000..02b243d12 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_6.snap @@ -0,0 +1,8 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +b: +- 1 +- 4 +- 9 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_7.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_7.snap new file mode 100644 index 000000000..b9865edee --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__quant_expr_7.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +b: [] diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__schema_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__schema_0.snap new file mode 100644 index 000000000..bedbf8691 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__schema_0.snap @@ -0,0 +1,10 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +alice: + name: Alice + age: 10 +bob: + name: Bob + age: 18 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__schema_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__schema_1.snap new file mode 100644 index 000000000..bedbf8691 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__schema_1.snap @@ -0,0 +1,10 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +alice: + name: Alice + age: 10 +bob: + name: Bob + age: 18 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__schema_2.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__schema_2.snap new file mode 100644 index 000000000..fbea082ba --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__schema_2.snap @@ -0,0 +1,15 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +VALUES_MAP: + '1': + attr1: foobar + '2': + attr2: bar +config: + provider: '1' + values: + attr1: foobar + provider_values: + attr1: foobar diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__selector_expr_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__selector_expr_0.snap new file mode 100644 index 000000000..c1e1ca900 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__selector_expr_0.snap @@ -0,0 +1,7 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: v +b: v +c: null diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__selector_expr_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__selector_expr_1.snap new file mode 100644 index 000000000..39ddd9b0d --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__selector_expr_1.snap @@ -0,0 +1,11 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: +- 3 +- 2 +- 1 +b: 1 +c: 3 +d: null diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__subscript_expr_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__subscript_expr_0.snap new file mode 100644 index 000000000..e6a93a4f2 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__subscript_expr_0.snap @@ -0,0 +1,10 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: +- 3 +- 2 +- 1 +b: 1 +c: 3 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__subscript_expr_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__subscript_expr_1.snap new file mode 100644 index 000000000..39ddd9b0d --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__subscript_expr_1.snap @@ -0,0 +1,11 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: +- 3 +- 2 +- 1 +b: 1 +c: 3 +d: null diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__unary_expr_0.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__unary_expr_0.snap new file mode 100644 index 000000000..38cba4d70 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__unary_expr_0.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: 1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__unary_expr_1.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__unary_expr_1.snap new file mode 100644 index 000000000..1803e044c --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__unary_expr_1.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: -1 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__unary_expr_2.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__unary_expr_2.snap new file mode 100644 index 000000000..34a0d809d --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__unary_expr_2.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: -2 diff --git a/crates/evaluator/src/snapshots/kcl_evaluator__tests__unary_expr_3.snap b/crates/evaluator/src/snapshots/kcl_evaluator__tests__unary_expr_3.snap new file mode 100644 index 000000000..46f6f3d24 --- /dev/null +++ b/crates/evaluator/src/snapshots/kcl_evaluator__tests__unary_expr_3.snap @@ -0,0 +1,5 @@ +--- +source: crates/evaluator/src/tests.rs +expression: "format! (\"{}\", evaluator.run().unwrap().1)" +--- +a: true diff --git a/crates/evaluator/src/tests.rs b/crates/evaluator/src/tests.rs new file mode 100644 index 000000000..3e6dd5bac --- /dev/null +++ b/crates/evaluator/src/tests.rs @@ -0,0 +1,623 @@ +use crate::Evaluator; +use kcl_ast::MAIN_PKG; +use kcl_loader::{LoadPackageOptions, load_packages}; +use kcl_parser::LoadProgramOptions; +use kcl_runtime::{Context, ValueRef}; + +#[macro_export] +macro_rules! evaluator_snapshot { + ($name:ident, $src:expr) => { + #[test] + fn $name() { + let p = load_packages(&LoadPackageOptions { + paths: vec!["test.k".to_string()], + load_opts: Some(LoadProgramOptions { + k_code_list: vec![$src.to_string()], + ..Default::default() + }), + load_builtin: false, + ..Default::default() + }) + .unwrap(); + let evaluator = Evaluator::new(&p.program); + insta::assert_snapshot!(format!("{}", evaluator.run().unwrap().1)); + } + }; +} + +#[macro_export] +macro_rules! evaluator_function_snapshot { + ($name:ident, $src:expr) => { + #[test] + fn $name() { + let p = load_packages(&LoadPackageOptions { + paths: vec!["test.k".to_string()], + load_opts: Some(LoadProgramOptions { + k_code_list: vec![$src.to_string()], + ..Default::default() + }), + load_builtin: false, + ..Default::default() + }) + .unwrap(); + let evaluator = Evaluator::new(&p.program); + insta::assert_snapshot!(format!("{}", evaluator.run_as_function().to_string())); + } + }; +} + +evaluator_function_snapshot! {function_stmt_0, r#" +import json + +config = { + foo: "bar" +} + +json.encode("${config.foo}") +"#} + +evaluator_snapshot! {expr_stmt_0, "1"} +evaluator_snapshot! {expr_stmt_1, "2.0"} +evaluator_snapshot! {expr_stmt_2, "True"} +evaluator_snapshot! {expr_stmt_3, r#"None"#} +evaluator_snapshot! {expr_stmt_4, r#"[1, 2, 3]"#} +evaluator_snapshot! {expr_stmt_5, r#"{k = "v"}"#} + +evaluator_snapshot! {assign_stmt_0, "a = 1"} +evaluator_snapshot! {assign_stmt_1, "a = 1 + 1"} +evaluator_snapshot! {assign_stmt_2, "a = (1 + 2)"} +evaluator_snapshot! {assign_stmt_3, r#"a = 1 +b = a + 1 +"#} +evaluator_snapshot! {assign_stmt_4, r#"a: int = 1 +b: int = a + 1 +"#} +evaluator_snapshot! {assign_stmt_5, r#"_a = [0] * 2 +_a[0] = 1 +a = _a +"#} +evaluator_snapshot! {assign_stmt_6, r#"_a = [{"key": 0}] * 2 +_a[0].key = 1 +a = _a +"#} +evaluator_snapshot! {assign_stmt_7, r#"_a = [{key.key = [0] * 2}] * 2 +_a[0].key.key[0] = 1 +a = _a +"#} + +evaluator_snapshot! {aug_assign_stmt_0, r#"_a = 1 +_a += 1 +a = _a +"#} +evaluator_snapshot! {aug_assign_stmt_1, r#"_a = 1 +_a -= 1 +a = _a +"#} +evaluator_snapshot! {aug_assign_stmt_2, r#"_a = 1 +_a *= 2 +a = _a +"#} +evaluator_snapshot! {aug_assign_stmt_3, r#"_a = 2 +_a /= 2 +a = _a +"#} +evaluator_snapshot! {aug_assign_stmt_4, r#"_a = 3 +_a %= 2 +a = _a +"#} +evaluator_snapshot! {aug_assign_stmt_5, r#"_a = 3 +_a **= 2 +a = _a +"#} +evaluator_snapshot! {aug_assign_stmt_6, r#"_a = 3 +_a <<= 1 +a = _a +"#} +evaluator_snapshot! {aug_assign_stmt_7, r#"_a = 3 +_a >>= 1 +a = _a +"#} +evaluator_snapshot! {aug_assign_stmt_8, r#"_a = 3 +_a |= 1 +a = _a +"#} +evaluator_snapshot! {aug_assign_stmt_9, r#"_a = 3 +_a ^= 1 +a = _a +"#} +evaluator_snapshot! {aug_assign_stmt_10, r#"_a = 3 +_a &= 1 +a = _a +"#} +evaluator_snapshot! {aug_assign_stmt_11, r#"_a = 3 +_a //= 2 +a = _a +"#} +evaluator_snapshot! {aug_assign_stmt_12, r#"_a = [0] * 5 +_a[0] += 1 +a = _a +"#} +evaluator_snapshot! {aug_assign_stmt_13, r#"_a = [{"key": 1}] * 5 +_a[0].key += 1 +a = _a +"#} +evaluator_snapshot! {aug_assign_stmt_14, r#"_a = [{key.key = [0, 0]}] * 5 +_a[0].key.key[0] += 1 +a = _a +"#} + +evaluator_snapshot! {assert_stmt_0, r#"assert True, "msg" +a = 1 +"#} + +evaluator_snapshot! {assert_stmt_1, r#"assert False if False, "msg" +a = 1 +"#} + +evaluator_snapshot! {if_stmt_0, r#"if True: + a = 1 +else: + b = 2 +"#} +evaluator_snapshot! {if_stmt_1, r#"if False: + a = 1 +else: + b = 2 +"#} +evaluator_snapshot! {if_stmt_3, r#"if False: + a = 1 +elif True: + b = 2 +else: + c = 3 +"#} +evaluator_snapshot! {if_stmt_4, r#"if False: + a = 1 +elif False: + b = 2 +else: + c = 3 +"#} +evaluator_snapshot! {if_stmt_5, r#"if False: + a = 1 +else: + if True: + b = 2 + else: + c = 3 +"#} +evaluator_snapshot! {if_stmt_6, r#" +if False: + a = 1 +else: + if True: + b = 1 + if True: + c = 1 +"#} +evaluator_snapshot! {if_stmt_7, r#" +_a = 1 +if True: + _a = 2 + _a += 1 +a = _a + +schema Config: + _a = 1 + if True: + _a = 2 + _a += 1 + a = _a + +c = Config {} +"#} +evaluator_snapshot! {if_stmt_8, r#" +_items = [] +if False: + _items += [ {key1 = "value1"} ] +if True: + _items += [ {key2 = "value2"} ] +items = _items + +schema Config: + _items = [] + if False: + _items += [ {key1 = "value1"} ] + if True: + _items += [ {key2 = "value2"} ] + items = _items + +c = Config {} +"#} + +evaluator_snapshot! {import_stmt_0, r#"import math +a = 1 +"#} +evaluator_snapshot! {import_stmt_1, r#"import math +import math +b = 2 +"#} +evaluator_snapshot! {import_stmt_2, r#" +import regex + +v = option("foo") +x = regex.match("foo", "^\\w+$") +"#} +evaluator_snapshot! {import_stmt_3, r#"import math + +x = math.log(10) +"#} + +evaluator_snapshot! {quant_expr_0, r#"b = all a in [1, 2, 3] { + a > 0 +} +"#} +evaluator_snapshot! {quant_expr_1, r#"b = any a in [1, 2, 3] { + a > 2 +} +"#} +evaluator_snapshot! {quant_expr_2, r#"b = all a in [1, 2, 3] { + a > 5 +} +"#} +evaluator_snapshot! {quant_expr_3, r#"b = any a in [1, 2, 3] { + a > 5 +} +"#} +evaluator_snapshot! {quant_expr_4, r#"b = map a in [1, 2, 3] { + a + 1 +} +"#} +evaluator_snapshot! {quant_expr_5, r#"b = filter a in [1, 2, 3] { + a > 1 +} +"#} +evaluator_snapshot! {quant_expr_6, r#"b = map a in [1, 2, 3] { + a ** 2 +} +"#} +evaluator_snapshot! {quant_expr_7, r#"b = filter a in [1, 2, 3] { + a == 0 +} +"#} + +evaluator_snapshot! {if_expr_0, r#"a = 1 if True else 0"#} +evaluator_snapshot! {if_expr_1, r#"a = 1 if False else 0"#} +evaluator_snapshot! {if_expr_2, r#"a = 1 if False else 0 if False else 2"#} + +evaluator_snapshot! {unary_expr_0, r#"a = +1"#} +evaluator_snapshot! {unary_expr_1, r#"a = -1"#} +evaluator_snapshot! {unary_expr_2, r#"a = ~1"#} +evaluator_snapshot! {unary_expr_3, r#"a = not None"#} + +evaluator_snapshot! {binary_expr_0, r#"a = 1 + 1 * 2 - 4"#} +evaluator_snapshot! {binary_expr_1, r#"a = None or {} +b = [] and {} +"#} + +evaluator_snapshot! {selector_expr_0, r#"a = {k = "v"}.k +b = {k = "v"}?.k +c = None?.k +"#} +evaluator_snapshot! {selector_expr_1, r#"a = [1, 2, 3]?[::-1] +b = a?[-1] +c = a?[0] +d = None?[1] +"#} + +evaluator_snapshot! {subscript_expr_0, r#"a = [1, 2, 3][::-1] +b = a[-1] +c = a[0] +"#} +evaluator_snapshot! {subscript_expr_1, r#"a = [1, 2, 3]?[::-1] +b = a?[-1] +c = a?[0] +d = None?[1] +"#} + +evaluator_snapshot! {compare_expr_0, r#"a = 1 < 10 +b = 1 < 10 < 100 +c = 1 > 10 > 100 +d = 1 < 10 > 100 +"#} + +evaluator_snapshot! {paren_expr_0, r#"a = 2 * (1 + 1) +b = (((1 + 1))) * 2 +"#} + +evaluator_snapshot! {list_expr_0, r#"a = [1, 2, 3] +b = [1, if True: 2, 3] +c = [1, if False: 2, 3] +d = [1, *[2, 3]] +"#} + +evaluator_snapshot! {dict_expr_0, r#"a = {k1 = "v1", k2 = "v2"} +b = {k1 = "v1", if True: k2 = "v2"} +c = {k1 = "v1", if False: k2 = "v2"} +d = {k1 = "v1", **{k2 = "v2"}} +"#} + +evaluator_snapshot! {loop_0, r#"a = [i ** 2 for i in [1, 2, 3]]"#} +evaluator_snapshot! {loop_1, r#"a = [i + j for i in [1, 2, 3] for j in [1, 2, 3] if i < j]"#} + +evaluator_snapshot! {literal_0, r#"longStringStartWithNewline = """\ +This is the second line +This is the third line +""" +"#} +evaluator_snapshot! {literal_1, r#"a = {k = "v"} +b = "${a: #json}" +"#} +evaluator_snapshot! {literal_2, r#"a = 1Mi +b = 2K +"#} + +evaluator_snapshot! {lambda_0, r#"f = lambda x {x * 2} +a = f(1) +b = f(2) +"#} +evaluator_snapshot! {lambda_1, r#"a = lambda x {x * 2}(1) +b = lambda x {x * 2}(2) +"#} +evaluator_snapshot! {lambda_2, r#"import math +a = math.log(10) +b = len("abc") +c = len([1, 2]) +"#} +evaluator_snapshot! {lambda_3, r#" +x = lambda { + a = 1 + lambda { + a + 1 + }() +}() +"#} +evaluator_snapshot! {lambda_4, r#" +x = lambda { + a = 1 + b = 2 + lambda x { + a + b + x + }(3) +}() +"#} +evaluator_snapshot! {lambda_5, r#" +func = lambda config: {str:} { + x = 1 + lambda { + y = 1 + lambda { + z = 1 + lambda { + {value = x + y + z + config.key} + }() + }() + }() +} + +x = func({key = 1}) +"#} + +evaluator_snapshot! {lambda_6, r#" +schema A: + my_field: int + + get_field: () -> int = lambda { + my_field + } + +_a = A{my_field = 2} +my_dict = { + my_field = 1 + x = _a.get_field() +} +"#} + +evaluator_snapshot! {schema_0, r#" +schema Person: + name: str = "Alice" + age: int = 10 + +alice = Person {} +bob = Person { + name = "Bob" + age = 18 +} +"#} +evaluator_snapshot! {schema_1, r#" +schema Person: + name: str = "Alice" + age: int = 10 + +alice: Person {} +bob: Person { + name: "Bob" + age: 18 +} +"#} +evaluator_snapshot! {schema_2, r#" +VALUES_MAP = { + "1": Values1{ + attr1 = "foo" + } + "2": Values2 { + attr2 = "bar" + } +} + +schema Config: + provider: "1" | "2" + values = VALUES_MAP[provider] + provider_values: Values1 | Values2 = values + +schema CommonValues: + +schema Values1(CommonValues): + attr1: str + +schema Values2(CommonValues): + attr2: str + +config: Config { + provider = "1" + provider_values.attr1 = "foobar" +} +"#} +evaluator_snapshot! {lazy_scope_0, r#" +b = a + c +a = 1 +c = a + 1 +"#} +evaluator_snapshot! {lazy_scope_1, r#" +schema Data: + b = a + c + a = 1 + c = a + 1 + +data = Data {} +"#} +evaluator_snapshot! {lazy_scope_2, r#" +schema Data: + name: str + version?: str + +data1 = Data { + name = data2.name +} + +data2 = Data { + name = "1" + version = version +} + +version = "v0.1.0" +"#} + +evaluator_snapshot! {list_comp1, r#" +a = [ x for x in "你好"] +"#} + +#[test] +fn test_if_stmt_setters() { + let p = load_packages(&LoadPackageOptions { + paths: vec!["test.k".to_string()], + load_opts: Some(LoadProgramOptions { + k_code_list: vec![ + r#" + _a = 1 + if True: + _a += 1 + elif False: + _a += 1 + a=_a + "# + .to_string(), + ], + ..Default::default() + }), + load_builtin: false, + ..Default::default() + }) + .unwrap(); + let evaluator = Evaluator::new(&p.program); + evaluator.run().unwrap(); + let scopes = evaluator.lazy_scopes.borrow(); + let var_setters = scopes.get(MAIN_PKG).unwrap().setters.get("_a").unwrap(); + assert_eq!(var_setters.len(), 3); +} + +use std::cell::RefCell; +use std::rc::Rc; +use std::sync::Arc; +use std::thread; + +const MULTI_THREAD_SOURCE: &str = r#" +import regex +foo = option("foo") +bar = option("bar") +x = regex.match("", "") +"#; + +#[test] +fn test_multithread_exec() { + let threads = 10; + multithread_check(threads, |thread| { + println!("run: {}", thread); + for _ in 0..1000 { + run_code(MULTI_THREAD_SOURCE); + } + println!("done: {}", thread); + }); +} + +fn multithread_check(threads: i32, check: impl Fn(i32) + Send + Sync + 'static) { + let check_shared = Arc::new(check); + let mut handles = vec![]; + for thread in 0..threads { + let check_shared = Arc::clone(&check_shared); + let handle = thread::spawn(move || { + check_shared(thread); + }); + handles.push(handle); + } + for handle in handles { + handle.join().unwrap(); + } +} + +fn run_code(source: &str) -> (String, String) { + let p = load_packages(&LoadPackageOptions { + paths: vec!["test.k".to_string()], + load_opts: Some(LoadProgramOptions { + k_code_list: vec![source.to_string()], + ..Default::default() + }), + load_builtin: false, + ..Default::default() + }) + .unwrap(); + let evaluator = Evaluator::new(&p.program); + evaluator.run().unwrap() +} + +fn testing_sum(_: &Context, args: &ValueRef, _: &ValueRef) -> anyhow::Result { + let a = args + .arg_i_int(0, Some(0)) + .ok_or(anyhow::anyhow!("expect int value for the first param"))?; + let b = args + .arg_i_int(1, Some(0)) + .ok_or(anyhow::anyhow!("expect int value for the second param"))?; + Ok((a + b).into()) +} + +fn context_with_plugin() -> Rc> { + let mut plugin_functions: kcl_primitives::IndexMap = + Default::default(); + let func = Arc::new(testing_sum); + plugin_functions.insert("testing.add".to_string(), func); + let mut ctx = Context::new(); + ctx.plugin_functions = plugin_functions; + Rc::new(RefCell::new(ctx)) +} + +#[test] +fn test_exec_with_plugin() { + let src = r#" +import kcl_plugin.testing + +sum = testing.add(1, 1) +"#; + let p = load_packages(&LoadPackageOptions { + paths: vec!["test.k".to_string()], + load_opts: Some(LoadProgramOptions { + load_plugins: true, + k_code_list: vec![src.to_string()], + ..Default::default() + }), + load_builtin: false, + ..Default::default() + }) + .unwrap(); + let evaluator = Evaluator::new_with_runtime_ctx(&p.program, context_with_plugin()); + insta::assert_snapshot!(format!("{}", evaluator.run().unwrap().1)); +} diff --git a/crates/evaluator/src/ty.rs b/crates/evaluator/src/ty.rs new file mode 100644 index 000000000..1d3bd9ef5 --- /dev/null +++ b/crates/evaluator/src/ty.rs @@ -0,0 +1,277 @@ +use kcl_runtime::{ + BUILTIN_TYPES, ConfigEntryOperationKind, KCL_TYPE_ANY, PKG_PATH_PREFIX, ValueRef, check_type, + dereference_type, is_dict_type, is_list_type, is_schema_type, is_type_union, + schema_config_meta, schema_runtime_type, separate_kv, split_type_union, val_plan, +}; +use scopeguard::defer; + +use crate::error as kcl_error; +use crate::schema::SchemaEvalContext; +use crate::{Evaluator, proxy::Proxy}; + +/// Use the schema instance to build a new schema instance using the schema construct function +pub fn resolve_schema(s: &Evaluator, schema: &ValueRef, keys: &[String]) -> ValueRef { + if !schema.is_schema() { + return schema.clone(); + } + let schema_value = schema.as_schema(); + let schema_type_name = schema_runtime_type(&schema_value.name, &schema_value.pkgpath); + if let Some(index) = s.schemas.borrow().get(&schema_type_name) { + let keys = keys.iter().map(|v| v.as_str()).collect(); + let config_value = + schema.dict_get_entries_with_op(keys, &ConfigEntryOperationKind::Override); + let config_meta = { + let ctx = s.runtime_ctx.borrow(); + schema_config_meta( + &ctx.panic_info.kcl_file, + ctx.panic_info.kcl_line as u64, + ctx.panic_info.kcl_col as u64, + ) + }; + + let frame = { + let frames = s.frames.borrow(); + frames + .get(*index) + .expect(kcl_error::INTERNAL_ERROR_MSG) + .clone() + }; + let schema = if let Proxy::Schema(caller) = &frame.proxy { + s.push_pkgpath(&frame.pkgpath); + s.push_backtrace(&frame); + defer! { + s.pop_backtrace(); + s.pop_pkgpath(); + } + let value = (caller.body)( + s, + &caller.ctx.borrow().snapshot(config_value, config_meta), + &schema_value.args, + &schema_value.kwargs, + ); + value + } else { + schema.clone() + }; + return schema; + } + schema.clone() +} + +/// Type pack and check ValueRef with the expected type vector +pub fn type_pack_and_check( + s: &Evaluator, + value: &ValueRef, + expected_types: Vec<&str>, + strict: bool, +) -> ValueRef { + if value.is_none_or_undefined() || expected_types.is_empty() { + return value.clone(); + } + let is_schema = value.is_schema(); + let mut checked = false; + let mut converted_value = value.clone(); + let expected_type = &expected_types.join(" | ").replace('@', ""); + for tpe in &expected_types { + if !is_schema { + converted_value = convert_collection_value(s, value, tpe); + } + // Runtime type check + checked = check_type( + &converted_value, + &s.runtime_ctx.borrow().panic_info.kcl_pkgpath, + tpe, + strict, + ); + if checked { + break; + } + } + if !checked { + let mut error_msgs = vec![]; + for tpe in &expected_types { + if is_schema_type(tpe) { + let schema_type_name = if tpe.contains('.') { + if tpe.starts_with(PKG_PATH_PREFIX) { + tpe.to_string() + } else { + format!("{PKG_PATH_PREFIX}{tpe}") + } + } else { + format!("{}.{}", s.current_pkgpath(), tpe) + }; + + if let Some(index) = s.schemas.borrow().get(&schema_type_name) { + let frame = { + let frames = s.frames.borrow(); + frames + .get(*index) + .expect(kcl_error::INTERNAL_ERROR_MSG) + .clone() + }; + if let Proxy::Schema(caller) = &frame.proxy { + if value.is_config() { + let config = value.as_dict_ref(); + for (key, _) in &config.values { + let no_such_attr = + !SchemaEvalContext::has_attr(s, &caller.ctx, key) + && !key.starts_with('_'); + let has_index_signature = + SchemaEvalContext::has_index_signature(s, &caller.ctx); + if !has_index_signature && no_such_attr { + error_msgs.push(format!( + "Schema {} does not contain attribute {}", + tpe, key + )); + } + } + + for (attr, is_optional) in SchemaEvalContext::get_attrs(s, &caller.ctx) + { + if !config.values.contains_key(&attr) && !is_optional { + error_msgs.push(format!( + "Schema {}'s attribute {} is missing", + tpe, attr + )); + } + } + } + } + } + } + } + panic!( + "expect {expected_type}, got {}{}", + val_plan::type_of(value, true), + if error_msgs.is_empty() { + "".to_string() + } else { + format!(". For details:\n{}", error_msgs.join("\n")) + } + ); + } + converted_value +} + +/// Convert collection value including dict/list to the potential schema +pub fn convert_collection_value(s: &Evaluator, value: &ValueRef, tpe: &str) -> ValueRef { + if tpe.is_empty() || tpe == KCL_TYPE_ANY { + return value.clone(); + } + let is_collection = value.is_list() || value.is_dict(); + let invalid_match_dict = is_dict_type(tpe) && !value.is_dict(); + let invalid_match_list = is_list_type(tpe) && !value.is_list(); + let invalid_match = invalid_match_dict || invalid_match_list; + if !is_collection || invalid_match { + return value.clone(); + } + // Convert a value to union types e.g., {a: 1} => A | B + if is_type_union(tpe) { + let types = split_type_union(tpe); + convert_collection_value_with_union_types(s, value, &types) + } else if is_dict_type(tpe) { + //let (key_tpe, value_tpe) = separate_kv(tpe); + let (_, value_tpe) = separate_kv(&dereference_type(tpe)); + let mut expected_dict = ValueRef::dict(None); + let dict_ref = value.as_dict_ref(); + expected_dict + .set_potential_schema_type(&dict_ref.potential_schema.clone().unwrap_or_default()); + for (k, v) in &dict_ref.values { + let expected_value = convert_collection_value(s, v, &value_tpe); + let op = dict_ref + .ops + .get(k) + .unwrap_or(&ConfigEntryOperationKind::Union); + let index = dict_ref.insert_indexs.get(k); + expected_dict.dict_update_entry(k, &expected_value, op, index) + } + expected_dict + } else if is_list_type(tpe) { + let expected_type = dereference_type(tpe); + let mut expected_list = ValueRef::list(None); + let list_ref = value.as_list_ref(); + for v in &list_ref.values { + let expected_value = convert_collection_value(s, v, &expected_type); + expected_list.list_append(&expected_value) + } + expected_list + } else if BUILTIN_TYPES.contains(&tpe) { + value.clone() + } else { + // Get the type form @pkg.Schema + let schema_type_name = if tpe.contains('.') { + if tpe.starts_with(PKG_PATH_PREFIX) { + tpe.to_string() + } else { + format!("{PKG_PATH_PREFIX}{tpe}") + } + } else { + format!("{}.{}", s.current_pkgpath(), tpe) + }; + if let Some(index) = s.schemas.borrow().get(&schema_type_name) { + let config_meta = { + let ctx = s.runtime_ctx.borrow(); + schema_config_meta( + &ctx.panic_info.kcl_file, + ctx.panic_info.kcl_line as u64, + ctx.panic_info.kcl_col as u64, + ) + }; + let frame = { + let frames = s.frames.borrow(); + frames + .get(*index) + .expect(kcl_error::INTERNAL_ERROR_MSG) + .clone() + }; + let schema = if let Proxy::Schema(caller) = &frame.proxy { + // Try convert the config to schema, if failed, return the config directly. + if !SchemaEvalContext::is_fit_config(s, &caller.ctx, value) { + return value.clone(); + } + s.push_pkgpath(&frame.pkgpath); + s.push_backtrace(&frame); + let value = (caller.body)( + s, + &caller.ctx.borrow().snapshot(value.clone(), config_meta), + &s.list_value(), + &s.dict_value(), + ); + s.pop_backtrace(); + s.pop_pkgpath(); + value + } else { + value.clone() + }; + // ctx.panic_info = now_panic_info; + return schema.clone(); + } + // ctx.panic_info = now_meta_info; + value.clone() + } +} + +/// Convert collection value including dict/list to the potential schema and return errors. +pub fn convert_collection_value_with_union_types( + s: &Evaluator, + value: &ValueRef, + types: &[&str], +) -> ValueRef { + if value.is_schema() { + value.clone() + } else { + for tpe in types { + // Try match every type and convert the value, if matched, return the value. + let value = convert_collection_value(s, value, tpe); + if check_type( + &value, + &s.runtime_ctx.borrow().panic_info.kcl_pkgpath, + tpe, + false, + ) { + return value; + } + } + value.clone() + } +} diff --git a/kclvm/evaluator/src/union.rs b/crates/evaluator/src/union.rs similarity index 85% rename from kclvm/evaluator/src/union.rs rename to crates/evaluator/src/union.rs index 81cda4056..708d449bc 100644 --- a/kclvm/evaluator/src/union.rs +++ b/crates/evaluator/src/union.rs @@ -1,9 +1,9 @@ //! Copyright The KCL Authors. All rights reserved. use crate::*; -use kclvm_runtime::unification::value_subsume; -use kclvm_runtime::{ - must_normalize_index, ConfigEntryOperationKind, DictValue, UnionContext, UnionOptions, Value, +use kcl_runtime::unification::value_subsume; +use kcl_runtime::{ + ConfigEntryOperationKind, DictValue, UnionContext, UnionOptions, Value, must_normalize_index, }; use self::ty::resolve_schema; @@ -85,10 +85,16 @@ fn do_union( let index = must_normalize_index(index, origin_value.len()); origin_value.list_set(index, &union_value); } else { - panic!("only non-empty list attribute can be union value with the index {}", index); + panic!( + "only non-empty list attribute can be union value with the index {}", + index + ); } } else { - panic!("only non-empty list attribute can be union value with the index {}", index); + panic!( + "only non-empty list attribute can be union value with the index {}", + index + ); } } None => { @@ -123,30 +129,34 @@ fn do_union( } } }, - ConfigEntryOperationKind::Override => { - match index { - Some(index) => { - let index = *index; - let origin_value = obj.values.get_mut(k); - if let Some(origin_value) = origin_value { - if !origin_value.is_list() { - panic!("only list attribute can be override value with the index {}", index); - } - let index = must_normalize_index(index, origin_value.len()); - if v.is_undefined() { - origin_value.list_remove_at(index as usize); - } else { - origin_value.list_must_set(index as usize, v); - } + ConfigEntryOperationKind::Override => match index { + Some(index) => { + let index = *index; + let origin_value = obj.values.get_mut(k); + if let Some(origin_value) = origin_value { + if !origin_value.is_list() { + panic!( + "only list attribute can be override value with the index {}", + index + ); + } + let index = must_normalize_index(index, origin_value.len()); + if v.is_undefined() { + origin_value.list_remove_at(index as usize); } else { - panic!("only list attribute can be override value with the index {}", index); + origin_value.list_must_set(index as usize, v); } - } - None => { - obj.values.insert(k.clone(), v.clone()); + } else { + panic!( + "only list attribute can be override value with the index {}", + index + ); } } - } + None => { + obj.values.insert(k.clone(), v.clone()); + } + }, ConfigEntryOperationKind::Insert => { let origin_value = obj.values.get_mut(k); if origin_value.is_none() || origin_value.unwrap().is_none_or_undefined() { @@ -178,7 +188,8 @@ fn do_union( } _ => panic!( "only list attribute can be inserted value, the origin value type is {} and got value type is {}", - origin_value.type_str(), v.type_str() + origin_value.type_str(), + v.type_str() ), }; } @@ -371,13 +382,9 @@ pub fn union_entry( ); } else { panic!( - "conflicting values on the attribute '{}' between :\n {}\nand\n {}\nwith union path :\n {}\ntry operator '=' to override the attribute, like:\n{}", - conflict_key, - union_context.obj_json, - union_context.delta_json, - path_string, - note, - ); + "conflicting values on the attribute '{}' between :\n {}\nand\n {}\nwith union path :\n {}\ntry operator '=' to override the attribute, like:\n{}", + conflict_key, union_context.obj_json, union_context.delta_json, path_string, note, + ); } } ret diff --git a/kclvm/evaluator/src/value.rs b/crates/evaluator/src/value.rs similarity index 98% rename from kclvm/evaluator/src/value.rs rename to crates/evaluator/src/value.rs index 90ca7bb0b..2b25661a4 100644 --- a/kclvm/evaluator/src/value.rs +++ b/crates/evaluator/src/value.rs @@ -1,7 +1,7 @@ /* Value methods */ use generational_arena::Index; -use kclvm_runtime::ValueRef; +use kcl_runtime::ValueRef; use crate::Evaluator; diff --git a/crates/lexer/Cargo.toml b/crates/lexer/Cargo.toml new file mode 100644 index 000000000..62f2b318f --- /dev/null +++ b/crates/lexer/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "kcl-lexer" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +rustc_lexer = "0.1.0" +unic-emoji-char = "0.9.0" +kcl-error.workspace = true + +[dev-dependencies] +expect-test = "1.0" diff --git a/kclvm/lexer/src/cursor.rs b/crates/lexer/src/cursor.rs similarity index 96% rename from kclvm/lexer/src/cursor.rs rename to crates/lexer/src/cursor.rs index 0bf51e0e6..7d5474f9e 100644 --- a/kclvm/lexer/src/cursor.rs +++ b/crates/lexer/src/cursor.rs @@ -85,8 +85,7 @@ impl<'a> Cursor<'a> { /// Eats symbols while predicate returns true or until the end of file is reached. pub fn eat_while(&mut self, mut predicate: impl FnMut(char) -> bool) { - // It was tried making optimized version of this for eg. line comments, but - // LLVM can inline all of this and compile it down to fast iteration over bytes. + // It was tried making optimized version of this for eg. line comments while predicate(self.peek()) && !self.is_eof() { self.bump(); } diff --git a/kclvm/lexer/src/kcl_cursor.rs b/crates/lexer/src/kcl_cursor.rs similarity index 100% rename from kclvm/lexer/src/kcl_cursor.rs rename to crates/lexer/src/kcl_cursor.rs index 5731c1d07..75cd64e52 100644 --- a/kclvm/lexer/src/kcl_cursor.rs +++ b/crates/lexer/src/kcl_cursor.rs @@ -5,8 +5,6 @@ //! To do that, we should make IABCCursor as dynamic traits //! and enable implemente Cursor structs in different crate. -use crate::cursor::DOLLAR_CHAR; -use crate::cursor::EOF_CHAR; use crate::Cursor; use crate::DocStyle; use crate::ICommentCursor; @@ -16,6 +14,8 @@ use crate::Literal; use crate::LiteralKind::*; use crate::TokenKind; use crate::TokenKind::*; +use crate::cursor::DOLLAR_CHAR; +use crate::cursor::EOF_CHAR; impl<'a> ICommentCursor for Cursor<'a> { fn try_comment_magic(&self, c: char) -> bool { diff --git a/crates/lexer/src/lib.rs b/crates/lexer/src/lib.rs new file mode 100644 index 000000000..577722d81 --- /dev/null +++ b/crates/lexer/src/lib.rs @@ -0,0 +1,618 @@ +//! Low-level token stream lexer. +//! +//! The purpose of `kcl_lexer` is similar to [`rustc_lexer`] crate, +//! which separates out pure lexing and language-specific designs. +//! +//! The difference with [`rustc_lexer`] is that here we want to define +//! a more general and wider range of tokens used by more languages. +//! +//! A language-specific lexer is needed to convert the basic token stream +//! into wide tokens consumed by the parser. +//! +//! The purpose of the lexer is to convert raw sources into a labeled sequence +//! of well-known token types. No error reporting on obvious error(e.g., string-not-closed error), +//! instead storing them as flags on the token. Checking of literal content is +//! not performed in this lexer. +//! +//! The main entity of this crate is the [`TokenKind`] enum which represents common +//! lexeme types. +//! +//! [`parser::lexer`]: ../parser/lexer/index.html +//! We want to be able to build this crate with a stable compiler, so no +//! `#![feature]` attributes should be added. + +mod cursor; +mod kcl_cursor; +mod number; + +#[cfg(test)] +mod tests; + +extern crate kcl_error; + +use cursor::EOF_CHAR; + +use self::TokenKind::*; +pub use crate::cursor::Cursor; + +/// Parsed token. +#[derive(Debug)] +pub struct Token { + pub kind: TokenKind, + pub len: usize, +} + +impl Token { + fn new(kind: TokenKind, len: usize) -> Self { + Token { kind, len } + } +} + +/// Enum representing common lexeme types. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum TokenKind { + /// "# comment" or "// comment" + LineComment { doc_style: Option }, + + /// `/* block comment */` + /// + /// Block comments can be recursive, so the sequence like `/* /* */` + /// will not be considered terminated and will result in a parsing error. + BlockComment { + doc_style: Option, + terminated: bool, + }, + + /// "\t" + Tab, + + /// " " + Space, + + /// "\r" + CarriageReturn, + + /// "\n" + Newline, + + /// Any other whitespace characters sequence. + Whitespace, + + /// "ident" + Ident, + + /// Like the above, but containing invalid unicode codepoints. + InvalidIdent, + + /// Invalid line continue symbol `\\` without the `\n` followed. + InvalidLineContinue, + + /// Valid Line continue '\\' + LineContinue, + + /// "12_u8", "1.0e-40", "b"123"". See `LiteralKind` for more details. + Literal { + kind: LiteralKind, + suffix_start: usize, + }, + + /// ";" + Semi, + + /// "," + Comma, + + /// "." + Dot, + + /// ".." + DotDot, + + /// "..." + DotDotDot, + + /// "(" + OpenParen, + + /// ")" + CloseParen, + + /// "{" + OpenBrace, + + /// "}" + CloseBrace, + + /// "[" + OpenBracket, + + /// "]" + CloseBracket, + + /// "@" + At, + + /// "#" + Pound, + + /// "~" + Tilde, + + /// "?" + Question, + + /// ":" + Colon, + + /// "$" + Dollar, + + /// "=" + Eq, + + /// "!" + Bang, + + /// "<" + Lt, + + /// ">" + Gt, + + /// "==" + EqEq, + + /// "!=" + BangEq, + + /// ">=" + GtEq, + + /// "<=" + LtEq, + + /// "-" + Minus, + + /// "&" + And, + + /// "|" + Or, + + /// "+" + Plus, + + /// "*" + Star, + + /// "/" + Slash, + + /// "^" + Caret, + + /// "%" + Percent, + + /// "**" + StarStar, + + /// "//" + SlashSlash, + + /// "<<" + LtLt, + + /// ">>" + GtGt, + + /// "+=" + PlusEq, + + /// "-=" + MinusEq, + + /// "*=" + StarEq, + + /// "/=" + SlashEq, + + /// "%=" + PercentEq, + + /// "&=" + AndEq, + + /// "|=" + OrEq, + + /// "^=" + CaretEq, + + /// "**=" + StarStarEq, + + /// "//=" + SlashSlashEq, + + /// "<<=" + LtLtEq, + + /// ">>=" + GtGtEq, + + /// Unknown token, not expected by the lexer, e.g. "№" + Unknown, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum DocStyle { + Outer, + Inner, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum LiteralKind { + /// "12", "0o100", "0b120199" + Int { base: Base, empty_int: bool }, + /// "12.34", "0b100.100" + Float { base: Base, empty_exponent: bool }, + /// ""abc"", "'abc'", "'''abc'''" + Str { + terminated: bool, + triple_quoted: bool, + }, + /// True, False + Bool { terminated: bool }, +} + +/// Base of numeric literal encoding according to its prefix. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum Base { + /// Literal starts with "0b". + Binary, + /// Literal starts with "0o". + Octal, + /// Literal starts with "0x". + Hexadecimal, + /// Literal doesn't contain a prefix. + Decimal, +} + +impl Base { + /// Returns the description string of the numeric literal base. + pub fn describe(&self) -> &'static str { + match self { + Base::Binary => "binary", + Base::Octal => "octal", + Base::Hexadecimal => "hexadecimal", + Base::Decimal => "decimal", + } + } +} + +/// Parses the first token from the provided input string. +pub fn first_token(input: &str) -> Token { + debug_assert!(!input.is_empty()); + Cursor::new(input).token() +} + +/// Creates an iterator that produces tokens from the input string. +pub fn tokenize(input: &str) -> impl Iterator + '_ { + let mut cursor = Cursor::new(input); + std::iter::from_fn(move || { + if cursor.is_eof() { + None + } else { + cursor.reset_len_consumed(); + Some(cursor.token()) + } + }) +} + +pub trait ICursor: ITokenCursor + ICommentCursor {} + +// Cursor trait to read one token from char stream. +pub trait ITokenCursor { + fn token(&mut self) -> Token; +} + +// Cursor trait to read comment. +// Line comment and block comment should be considered here. +pub trait ICommentCursor { + // If we encounter a comment. + // Returns true if exists, otherwise returns false. + fn try_comment_magic(&self, _c: char) -> bool { + false + } + + // Eat it if so. + // This mehod **MUST** be called after 'try_comment_magic'. + // No gurantee to ensure the correctness if no comment here, + // and return 'Unknown' if it happens. + fn eat_comment(&mut self) -> TokenKind { + Unknown + } +} + +// Cursor trait to read string. +// Simple string, raw string, unicode string, multi-lines string, +// and more string cases should be considered here. +pub trait IStringCursor { + // If we encounter a string. + // Returns true if exists, otherwise returns false. + fn try_string_magic(&self, _c: char) -> bool { + false + } + + // Eat it if so. + // This mehod **MUST** be called after 'try_string_magic'. + // No gurantee to ensure the correctness if no string here, + // and return 'Unknown' if it happens. + // For example, no identifier check if no string found. + fn eat_string(&mut self, _c: char) -> TokenKind { + Unknown + } +} + +// Cursor trait to read identifier. +// Simple identifier, raw identifier, and more identifier cases should be considered here. +pub trait IIdentCursor { + // If we encounter a identifier. + // Returns true if exists, otherwise returns false. + fn try_ident_magic(&self, _c: char) -> bool { + false + } + + // Eat it if so. + // This method **MUST** be called after 'try_ident_magic'. + // No guarantee to ensure the correctness if no identifier here, + // and return 'Unknown' if it happens. + fn eat_ident(&mut self) -> TokenKind { + Unknown + } +} + +/// True if `c` is considered a whitespace. +pub fn is_whitespace(c: char) -> bool { + match c { + // Usual ASCII suspects + | '\u{000B}' // vertical tab + | '\u{000C}' // form feed + | '\u{000D}' // \r + // NEXT LINE from latin1 + | '\u{0085}' + + // Bidi markers + | '\u{200E}' // LEFT-TO-RIGHT MARK + | '\u{200F}' // RIGHT-TO-LEFT MARK + + // Dedicated whitespace characters from Unicode + | '\u{2028}' // LINE SEPARATOR + | '\u{2029}' // PARAGRAPH SEPARATOR + => true, + _ => false, + } +} + +impl<'a> ITokenCursor for Cursor<'a> { + fn token(&mut self) -> Token { + let char = self.bump().unwrap_or(EOF_CHAR); + + let token_kind = match char { + // Comment or block comment, or a simple token + c if self.try_comment_magic(c) => self.eat_comment(), + + // Whitespace sequence. + c if is_whitespace(c) => Whitespace, + + // Various of string. E.g., quoted string, raw string. + c if self.try_string_magic(c) => self.eat_string(c), + + // Identifier (this should be checked after other variant that can + // start as identifier). + c if self.try_ident_magic(c) => self.eat_ident(), + + // Numeric literal. + c @ '0'..='9' => { + let kind = self.number(c); + let suffix_start = self.len_consumed(); + self.eat_lit_suffix(); // In case we have some suffix + + TokenKind::Literal { kind, suffix_start } + } + + // '\r' will be considered as a 'WhiteSpace'. + '\u{0009}' => Tab, + '\u{0020}' => Space, + '\u{000A}' => Newline, + + ';' => Semi, + ',' => Comma, + '.' => match (self.peek(), self.peek1th()) { + ('.', '.') => { + self.bump(); + self.bump(); + DotDotDot + } + _ => Dot, + }, + '(' => OpenParen, + ')' => CloseParen, + '{' => OpenBrace, + '}' => CloseBrace, + '[' => OpenBracket, + ']' => CloseBracket, + '@' => At, + '#' => Pound, + '~' => Tilde, + '?' => Question, + ':' => Colon, + '$' => Dollar, + '=' => match self.peek() { + '=' => { + self.bump(); + EqEq + } + _ => Eq, + }, + '!' => match self.peek() { + '=' => { + self.bump(); + BangEq + } + _ => Bang, + }, + '<' => match self.peek() { + '=' => { + self.bump(); + LtEq + } + '<' => { + self.bump(); + match self.peek() { + '=' => { + self.bump(); + LtLtEq + } + _ => LtLt, + } + } + _ => Lt, + }, + '>' => match self.peek() { + '=' => { + self.bump(); + GtEq + } + '>' => { + self.bump(); + match self.peek() { + '=' => { + self.bump(); + GtGtEq + } + _ => GtGt, + } + } + _ => Gt, + }, + '-' => match self.peek() { + '=' => { + self.bump(); + MinusEq + } + _ => Minus, + }, + '&' => match self.peek() { + '=' => { + self.bump(); + AndEq + } + _ => And, + }, + '|' => match self.peek() { + '=' => { + self.bump(); + OrEq + } + _ => Or, + }, + '+' => match self.peek() { + '=' => { + self.bump(); + PlusEq + } + _ => Plus, + }, + '*' => match self.peek() { + '*' => { + self.bump(); + match self.peek() { + '=' => { + self.bump(); + StarStarEq + } + _ => StarStar, + } + } + '=' => { + self.bump(); + StarEq + } + _ => Star, + }, + '/' => match self.peek() { + '/' => { + self.bump(); + match self.peek() { + '=' => { + self.bump(); + SlashSlashEq + } + _ => SlashSlash, + } + } + '=' => { + self.bump(); + SlashEq + } + _ => Slash, + }, + '^' => match self.peek() { + '=' => { + self.bump(); + CaretEq + } + _ => Caret, + }, + '%' => match self.peek() { + '=' => { + self.bump(); + PercentEq + } + _ => Percent, + }, + '\\' => match self.peek() { + '\n' => { + self.bump(); + LineContinue + } + EOF_CHAR => LineContinue, + _ => InvalidLineContinue, + }, + // Identifier starting with an emoji. Only lexed for graceful error recovery. + c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { + self.fake_ident_or_unknown_prefix() + } + _ => Unknown, + }; + Token::new(token_kind, self.len_consumed()) + } +} + +impl<'a> Cursor<'a> { + // Eats the suffix of the literal, e.g. 'Ki', 'M', etc. + fn eat_lit_suffix(&mut self) { + if !rustc_lexer::is_id_start(self.peek()) { + return; + } + self.bump(); + + self.eat_while(rustc_lexer::is_id_continue); + } + + fn fake_ident_or_unknown_prefix(&mut self) -> TokenKind { + // Start is already eaten, eat the rest of identifier. + self.eat_while(|c| { + rustc_lexer::is_id_continue(c) + || (!c.is_ascii() && unic_emoji_char::is_emoji(c)) + || c == '\u{200d}' + }); + // Known prefixes must have been handled earlier. So if + // we see a prefix here, it is definitely an unknown prefix. + InvalidIdent + } +} diff --git a/kclvm/lexer/src/number.rs b/crates/lexer/src/number.rs similarity index 99% rename from kclvm/lexer/src/number.rs rename to crates/lexer/src/number.rs index 0458b1fd1..b31edf295 100644 --- a/kclvm/lexer/src/number.rs +++ b/crates/lexer/src/number.rs @@ -3,10 +3,10 @@ //! poor reusability and extensibility. //! Rust specific literal suffix(e.g. _u8, 2us) is not supported. -use crate::cursor::Cursor; use crate::Base; use crate::LiteralKind; use crate::LiteralKind::*; +use crate::cursor::Cursor; impl<'a> Cursor<'a> { pub(crate) fn number(&mut self, first_digit: char) -> LiteralKind { @@ -41,7 +41,7 @@ impl<'a> Cursor<'a> { return Int { base, empty_int: false, - } + }; } }; // Base prefix was provided, but there were no digits diff --git a/crates/lexer/src/tests.rs b/crates/lexer/src/tests.rs new file mode 100644 index 000000000..0d9bd3d14 --- /dev/null +++ b/crates/lexer/src/tests.rs @@ -0,0 +1,369 @@ +use super::*; +use expect_test::{Expect, expect}; +use std::fmt::Write; + +fn check_lexing(src: &str, expect: Expect) { + let actual: String = tokenize(src).fold(String::new(), |mut acc, token| { + writeln!(acc, "{:?}", token).expect("Failed to write to string"); + acc + }); + expect.assert_eq(&actual) +} + +#[test] +fn smoke_test() { + check_lexing( + " lambda { println(\"kcl\"); }\n", + expect![[r#" + Token { kind: Space, len: 1 } + Token { kind: Space, len: 1 } + Token { kind: Ident, len: 6 } + Token { kind: Space, len: 1 } + Token { kind: OpenBrace, len: 1 } + Token { kind: Space, len: 1 } + Token { kind: Ident, len: 7 } + Token { kind: OpenParen, len: 1 } + Token { kind: Literal { kind: Str { terminated: true, triple_quoted: false }, suffix_start: 5 }, len: 5 } + Token { kind: CloseParen, len: 1 } + Token { kind: Semi, len: 1 } + Token { kind: Space, len: 1 } + Token { kind: CloseBrace, len: 1 } + Token { kind: Newline, len: 1 } + "#]], + ) +} + +#[test] +fn comment_flavors() { + check_lexing( + r" +# +# line +", + expect![[r#" + Token { kind: Newline, len: 1 } + Token { kind: LineComment { doc_style: Some(Inner) }, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: LineComment { doc_style: Some(Inner) }, len: 6 } + Token { kind: Newline, len: 1 } +"#]], + ) +} + +#[test] +fn simple_tokens() { + check_lexing( + r####" +; +, +. +( +) +{ +} +[ +] +@ +# +~ +? +: +$ += +! +< +> +== +!= +>= +<= +- +& +| ++ +* +/ +^ +% +** +// +<< +>> +... ++= +-= +*= +/= +%= +&= +|= +^= +**= +//= +<<= +>>= +"####, + expect![[r#" + Token { kind: Newline, len: 1 } + Token { kind: Semi, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Comma, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Dot, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: OpenParen, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: CloseParen, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: OpenBrace, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: CloseBrace, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: OpenBracket, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: CloseBracket, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: At, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: LineComment { doc_style: Some(Inner) }, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Tilde, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Question, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Colon, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Dollar, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Eq, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Bang, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Lt, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Gt, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: EqEq, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: BangEq, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: GtEq, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: LtEq, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: Minus, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: And, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Or, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Plus, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Star, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Slash, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Caret, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Percent, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: StarStar, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: SlashSlash, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: LtLt, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: GtGt, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: DotDotDot, len: 3 } + Token { kind: Newline, len: 1 } + Token { kind: PlusEq, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: MinusEq, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: StarEq, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: SlashEq, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: PercentEq, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: AndEq, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: OrEq, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: CaretEq, len: 2 } + Token { kind: Newline, len: 1 } + Token { kind: StarStarEq, len: 3 } + Token { kind: Newline, len: 1 } + Token { kind: SlashSlashEq, len: 3 } + Token { kind: Newline, len: 1 } + Token { kind: LtLtEq, len: 3 } + Token { kind: Newline, len: 1 } + Token { kind: GtGtEq, len: 3 } + Token { kind: Newline, len: 1 } + "#]], + ) +} + +#[test] +fn nonstring_literal() { + check_lexing( + r####" +1234 +0b101 +0xABC +1.0 +1.0e10 +0777 +0077 +1Ki +"####, + expect![[r#" + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Int { base: Decimal, empty_int: false }, suffix_start: 4 }, len: 4 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Int { base: Binary, empty_int: false }, suffix_start: 5 }, len: 5 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Int { base: Hexadecimal, empty_int: false }, suffix_start: 5 }, len: 5 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Float { base: Decimal, empty_exponent: false }, suffix_start: 3 }, len: 3 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Float { base: Decimal, empty_exponent: false }, suffix_start: 6 }, len: 6 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Int { base: Octal, empty_int: false }, suffix_start: 4 }, len: 4 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Int { base: Octal, empty_int: false }, suffix_start: 4 }, len: 4 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Int { base: Decimal, empty_int: false }, suffix_start: 1 }, len: 3 } + Token { kind: Newline, len: 1 } + "#]], + ) +} + +#[test] +fn string_literal() { + check_lexing( + r####" +'a' +"a" +'''a''' +"""a""" +r'a' +r"a" +r'''a''' +r"""a""" +R'a' +R"a" +R'''a''' +R"""a""" +"####, + expect![[r#" + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Str { terminated: true, triple_quoted: false }, suffix_start: 3 }, len: 3 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Str { terminated: true, triple_quoted: false }, suffix_start: 3 }, len: 3 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Str { terminated: true, triple_quoted: true }, suffix_start: 7 }, len: 7 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Str { terminated: true, triple_quoted: true }, suffix_start: 7 }, len: 7 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Str { terminated: true, triple_quoted: false }, suffix_start: 4 }, len: 4 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Str { terminated: true, triple_quoted: false }, suffix_start: 4 }, len: 4 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Str { terminated: true, triple_quoted: true }, suffix_start: 8 }, len: 8 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Str { terminated: true, triple_quoted: true }, suffix_start: 8 }, len: 8 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Str { terminated: true, triple_quoted: false }, suffix_start: 4 }, len: 4 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Str { terminated: true, triple_quoted: false }, suffix_start: 4 }, len: 4 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Str { terminated: true, triple_quoted: true }, suffix_start: 8 }, len: 8 } + Token { kind: Newline, len: 1 } + Token { kind: Literal { kind: Str { terminated: true, triple_quoted: true }, suffix_start: 8 }, len: 8 } + Token { kind: Newline, len: 1 } + "#]], + ) +} + +#[test] +fn identifier() { + check_lexing( + r####" +a +abc +$schema +"####, + expect![[r#" + Token { kind: Newline, len: 1 } + Token { kind: Ident, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Ident, len: 3 } + Token { kind: Newline, len: 1 } + Token { kind: Ident, len: 7 } + Token { kind: Newline, len: 1 } + "#]], + ) +} + +#[test] +fn line_continue() { + check_lexing( + r####" +\ +\ +"####, + expect![[r#" + Token { kind: Newline, len: 1 } + Token { kind: LineContinue, len: 2 } + Token { kind: LineContinue, len: 2 } + "#]], + ) +} + +#[test] +fn newline_r_n() { + check_lexing( + "\r\n", + expect![[r#" + Token { kind: Whitespace, len: 1 } + Token { kind: Newline, len: 1 } + "#]], + ) +} + +#[test] +fn newline_r_n_r_n() { + check_lexing( + "\r\n\r\n", + expect![[r#" + Token { kind: Whitespace, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Whitespace, len: 1 } + Token { kind: Newline, len: 1 } + "#]], + ) +} + +#[test] +fn newline_r() { + check_lexing( + "\r", + expect![[r#" + Token { kind: Whitespace, len: 1 } + "#]], + ) +} + +#[test] +fn newline_r_n_n() { + check_lexing( + "\r\n\n", + expect![[r#" + Token { kind: Whitespace, len: 1 } + Token { kind: Newline, len: 1 } + Token { kind: Newline, len: 1 } + "#]], + ) +} diff --git a/crates/lib/Cargo.toml b/crates/lib/Cargo.toml new file mode 100644 index 000000000..9b384c2f8 --- /dev/null +++ b/crates/lib/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "kcl-lib" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[lib] +crate-type = ["cdylib", "staticlib"] +path = "src/lib.rs" +name = "kcl" + +[dependencies] +kcl-api.workspace = true +kcl-cmd.workspace = true +kcl-ast.workspace = true +kcl-runner.workspace = true +kcl-parser.workspace = true +kcl-compiler.workspace = true +kcl-config.workspace = true +kcl-loader.workspace = true +kcl-runtime.workspace = true +kcl-sema.workspace = true +kcl-tools.workspace = true +kcl-version.workspace = true +kcl-error.workspace = true +kcl-evaluator.workspace = true +kcl-query.workspace = true +kcl-driver.workspace = true +kcl-primitives.workspace = true diff --git a/crates/lib/src/capi.rs b/crates/lib/src/capi.rs new file mode 100644 index 000000000..fa00f994f --- /dev/null +++ b/crates/lib/src/capi.rs @@ -0,0 +1,261 @@ +#![allow(clippy::missing_safety_doc)] + +use kcl_runner::runner::KCL_RUNTIME_PANIC_RECORD; +use std::alloc::{Layout, alloc, dealloc}; +use std::ffi::c_char; +use std::ffi::{CStr, CString}; +use std::{mem, ptr}; + +use crate::{intern_fmt, intern_run}; + +/// Exposes an allocation function to the WASM host. +/// +/// _This implementation is copied from wasm-bindgen_ +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_malloc(size: usize) -> *mut u8 { + let align = mem::align_of::(); + let layout = Layout::from_size_align(size, align).expect("Invalid layout"); + if layout.size() > 0 { + let ptr = unsafe { alloc(layout) }; + if !ptr.is_null() { + unsafe { ptr::write_bytes(ptr, 0, size) }; + ptr + } else { + std::alloc::handle_alloc_error(layout); + } + } else { + align as *mut u8 + } +} + +/// Expose a deallocation function to the WASM host. +/// +/// _This implementation is copied from wasm-bindgen_ +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_free(ptr: *mut u8, size: usize) { + // This happens for zero-length slices, and in that case `ptr` is + // likely bogus so don't actually send this to the system allocator + if size == 0 { + return; + } + let align = mem::align_of::(); + let layout = unsafe { Layout::from_size_align_unchecked(size, align) }; + unsafe { dealloc(ptr, layout) }; +} + +#[repr(C)] +pub struct ExecProgramResult { + json_result: *const c_char, + yaml_result: *const c_char, + log_message: *const c_char, + err_message: *const c_char, +} + +/// Execute KCL file with arguments and return the JSON/YAML result. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_exec_program( + filename_ptr: *const c_char, + src_ptr: *const c_char, +) -> *const ExecProgramResult { + if filename_ptr.is_null() || src_ptr.is_null() { + return std::ptr::null(); + } + let filename = unsafe { CStr::from_ptr(filename_ptr).to_str().unwrap() }; + let src = unsafe { CStr::from_ptr(src_ptr).to_str().unwrap() }; + + match intern_run(filename, src) { + Ok(result) => { + let json = CString::new(result.json_result).unwrap().into_raw(); + let yaml = CString::new(result.yaml_result).unwrap().into_raw(); + let log = CString::new(result.log_message).unwrap().into_raw(); + let err = CString::new(result.err_message).unwrap().into_raw(); + + let exec_result = ExecProgramResult { + json_result: json, + yaml_result: yaml, + log_message: log, + err_message: err, + }; + + Box::into_raw(Box::new(exec_result)) as *const ExecProgramResult + } + Err(err) => { + let result = ExecProgramResult { + err_message: CString::new(err).unwrap().into_raw(), + json_result: std::ptr::null(), + yaml_result: std::ptr::null(), + log_message: std::ptr::null(), + }; + Box::into_raw(Box::new(result)) as *const ExecProgramResult + } + } +} + +/// Free memory allocated for the ExecProgramResult. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_free_exec_program_result(result: *const ExecProgramResult) { + if result.is_null() { + return; + } + + let result = unsafe { Box::from_raw(result as *mut ExecProgramResult) }; + + if !result.json_result.is_null() { + let _ = unsafe { CString::from_raw(result.json_result as *mut c_char) }; // Free the C string + } + if !result.yaml_result.is_null() { + let _ = unsafe { CString::from_raw(result.yaml_result as *mut c_char) }; // Free the C string + } + if !result.log_message.is_null() { + let _ = unsafe { CString::from_raw(result.log_message as *mut c_char) }; // Free the C string + } + if !result.err_message.is_null() { + let _ = unsafe { CString::from_raw(result.err_message as *mut c_char) }; // Free the C string + } + + // Result itself will be freed when going out of scope +} + +/// Get the YAML result from ExecProgramResult. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_result_get_yaml_result( + result: *const ExecProgramResult, +) -> *const c_char { + if result.is_null() { + return std::ptr::null(); + } + + let result = unsafe { &*result }; + if result.yaml_result.is_null() { + return std::ptr::null(); + } + + result.yaml_result +} + +/// Get the JSON result from ExecProgramResult. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_result_get_json_result( + result: *const ExecProgramResult, +) -> *const c_char { + if result.is_null() { + return std::ptr::null(); + } + + let result = unsafe { &*result }; + if result.json_result.is_null() { + return std::ptr::null(); + } + + result.json_result +} + +/// Get the error message from ExecProgramResult. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_result_get_err_message( + result: *const ExecProgramResult, +) -> *const c_char { + if result.is_null() { + return std::ptr::null(); + } + + let result = unsafe { &*result }; + if result.err_message.is_null() { + return std::ptr::null(); + } + + result.err_message +} + +/// Get the log message from ExecProgramResult. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_result_get_log_message( + result: *const ExecProgramResult, +) -> *const c_char { + if result.is_null() { + return std::ptr::null(); + } + + let result = unsafe { &*result }; + if result.log_message.is_null() { + return std::ptr::null(); + } + + result.log_message +} + +/// Exposes a normal kcl run function to the WASM host. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_run( + filename_ptr: *const c_char, + src_ptr: *const c_char, +) -> *const c_char { + if filename_ptr.is_null() || src_ptr.is_null() { + return std::ptr::null(); + } + let filename = unsafe { CStr::from_ptr(filename_ptr).to_str().unwrap() }; + let src = unsafe { CStr::from_ptr(src_ptr).to_str().unwrap() }; + + match intern_run(filename, src) { + Ok(result) => CString::new(result.yaml_result).unwrap().into_raw(), + Err(err) => CString::new(format!("ERROR:{err}")).unwrap().into_raw(), + } +} + +/// Exposes a normal kcl run function with the log message to the WASM host. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_run_with_log_message( + filename_ptr: *const c_char, + src_ptr: *const c_char, +) -> *const c_char { + if filename_ptr.is_null() || src_ptr.is_null() { + return std::ptr::null(); + } + let filename = unsafe { CStr::from_ptr(filename_ptr).to_str().unwrap() }; + let src = unsafe { CStr::from_ptr(src_ptr).to_str().unwrap() }; + + match intern_run(filename, src) { + Ok(result) => CString::new(result.log_message + &result.yaml_result) + .unwrap() + .into_raw(), + Err(err) => CString::new(format!("ERROR:{err}")).unwrap().into_raw(), + } +} + +/// Exposes a normal kcl fmt function to the WASM host. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_fmt(src_ptr: *const c_char) -> *const c_char { + if src_ptr.is_null() { + return std::ptr::null(); + } + let src = unsafe { CStr::from_ptr(src_ptr).to_str().unwrap() }; + + match intern_fmt(src) { + Ok(result) => CString::new(result).unwrap().into_raw(), + Err(err) => CString::new(format!("ERROR:{err}")).unwrap().into_raw(), + } +} + +/// Exposes a normal kcl version function to the WASM host. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_version() -> *const c_char { + CString::new(kcl_version::VERSION).unwrap().into_raw() +} + +/// Exposes a normal kcl runtime error function to the WASM host. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_runtime_err(buffer: *mut u8, length: usize) -> isize { + KCL_RUNTIME_PANIC_RECORD.with(|e| { + let message = &e.borrow().message; + if !message.is_empty() { + let bytes = message.as_bytes(); + let copy_len = std::cmp::min(bytes.len(), length); + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, copy_len); + } + copy_len as isize + } else { + 0 + } + }) +} diff --git a/crates/lib/src/lib.rs b/crates/lib/src/lib.rs new file mode 100644 index 000000000..535f96037 --- /dev/null +++ b/crates/lib/src/lib.rs @@ -0,0 +1,131 @@ +#![allow(clippy::missing_safety_doc)] + +use std::ffi::{CStr, c_char, c_int}; +use std::process::ExitCode; + +use kcl_api::FormatCodeArgs; +use kcl_api::{API, ExecProgramArgs}; + +mod capi; +pub use capi::*; +use kcl_parser::ParseSessionRef; +use kcl_runner::exec_program; +use kcl_runtime::PanicInfo; + +/// KCL CLI run function CAPI. +/// +/// args is a ExecProgramArgs JSON string. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn libkcl_run( + args: *const c_char, + plugin_agent: *const c_char, +) -> *const c_char { + let prev_hook = std::panic::take_hook(); + + // disable print panic info + std::panic::set_hook(Box::new(|_info| {})); + let libkcl_run_unsafe_result = + std::panic::catch_unwind(|| libkcl_run_unsafe(args, plugin_agent)); + std::panic::set_hook(prev_hook); + + match libkcl_run_unsafe_result { + Ok(result) => match result { + Ok(result) => { + let c_string = + std::ffi::CString::new(result.as_str()).expect("CString::new failed"); + let ptr = c_string.into_raw(); + ptr as *const c_char + } + Err(result) => { + let result = format!("ERROR:{result}"); + let c_string = + std::ffi::CString::new(result.as_str()).expect("CString::new failed"); + let ptr = c_string.into_raw(); + ptr as *const c_char + } + }, + Err(err) => { + let err_message = kcl_error::err_to_str(err); + let result = format!("ERROR:{err_message:}"); + let c_string = std::ffi::CString::new(result.as_str()).expect("CString::new failed"); + let ptr = c_string.into_raw(); + ptr as *const c_char + } + } +} + +/// KCL CLI run function CAPI. +fn libkcl_run_unsafe(args: *const c_char, plugin_agent: *const c_char) -> Result { + let mut args = kcl_runner::ExecProgramArgs::from_str( + unsafe { std::ffi::CStr::from_ptr(args) }.to_str().unwrap(), + ); + args.plugin_agent = plugin_agent as u64; + exec_program(ParseSessionRef::default(), &args) + .map_err(|e| PanicInfo::from(e.to_string()).to_json_string()) + .map(|r| r.json_result) +} + +/// KCL CLI main function CAPI. +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn libkcl_main( + argc: c_int, + argv: *const *const c_char, +) -> *mut ExitCode { + let prev_hook = std::panic::take_hook(); + + // disable print panic info + std::panic::set_hook(Box::new(|_info| {})); + let libkcl_main_result = std::panic::catch_unwind(|| { + let args: Vec<&str> = unsafe { + std::slice::from_raw_parts(argv, argc as usize) + .iter() + .map(|ptr| CStr::from_ptr(*ptr).to_str().unwrap()) + .collect() + }; + kcl_cmd::main(args.as_slice()) + }); + std::panic::set_hook(prev_hook); + + match libkcl_main_result { + Ok(result) => match result { + Ok(()) => Box::into_raw(Box::new(ExitCode::SUCCESS)), + Err(err) => { + let backtrace = format!("{}", err.backtrace()); + if backtrace.is_empty() || backtrace.contains("disabled backtrace") { + eprintln!("{err}"); + } else { + eprintln!("{err}\nStack backtrace:\n{backtrace}"); + } + Box::into_raw(Box::new(ExitCode::FAILURE)) + } + }, + Err(err) => { + let err_str = kcl_error::err_to_str(err); + if !err_str.is_empty() { + eprintln!("{err_str}"); + } + Box::into_raw(Box::new(ExitCode::FAILURE)) + } + } +} + +fn intern_run(filename: &str, src: &str) -> Result { + let api = API::default(); + let args = &ExecProgramArgs { + k_filename_list: vec![filename.to_string()], + k_code_list: vec![src.to_string()], + ..Default::default() + }; + api.exec_program(args).map_err(|err| err.to_string()) +} + +fn intern_fmt(src: &str) -> Result { + let api = API::default(); + let args = &FormatCodeArgs { + source: src.to_string(), + }; + match api.format_code(args) { + Ok(result) => String::from_utf8(result.formatted).map_err(|err| err.to_string()), + Err(err) => Err(err.to_string()), + } +} diff --git a/crates/loader/Cargo.toml b/crates/loader/Cargo.toml new file mode 100644 index 000000000..0dbaea620 --- /dev/null +++ b/crates/loader/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "kcl-loader" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +anyhow = "1.0" + +kcl-ast = { path = "../ast" } +kcl-ast-pretty = { path = "../ast_pretty" } +kcl-parser = { path = "../parser" } +kcl-sema = { path = "../sema" } +kcl-error = { path = "../error" } +kcl-query = { path = "../query" } +kcl-utils = { path = "../utils" } +kcl-primitives = { path = "../primitives" } +maplit = "1.0.2" + +[dev-dependencies] +insta = "1.8.0" diff --git a/crates/loader/src/lib.rs b/crates/loader/src/lib.rs new file mode 100644 index 000000000..31034e6f7 --- /dev/null +++ b/crates/loader/src/lib.rs @@ -0,0 +1,296 @@ +#[cfg(test)] +mod tests; + +pub mod option; +pub mod util; + +use anyhow::Result; +use kcl_ast::ast::Program; +use kcl_error::{Diagnostic, diagnostic::Range}; +use kcl_parser::{KCLModuleCache, LoadProgramOptions, ParseSessionRef, load_program}; +use kcl_primitives::{IndexMap, IndexSet}; +use kcl_sema::{ + advanced_resolver::AdvancedResolver, + core::{ + global_state::GlobalState, + scope::{LocalSymbolScopeKind, ScopeData, ScopeRef}, + symbol::{SymbolData, SymbolRef}, + }, + namer::Namer, + resolver::{ + resolve_program_with_opts, + scope::{KCLScopeCache, NodeKey}, + }, + ty::{Type, TypeRef}, +}; +use kcl_utils::path::PathPrefix; +use std::path::PathBuf; + +type Errors = IndexSet; + +#[derive(Debug, Clone)] +pub struct LoadPackageOptions { + pub paths: Vec, + pub load_opts: Option, + pub resolve_ast: bool, + pub load_builtin: bool, +} + +impl Default for LoadPackageOptions { + fn default() -> Self { + Self { + paths: Default::default(), + load_opts: Default::default(), + resolve_ast: true, + load_builtin: false, + } + } +} + +#[derive(Debug, Clone, Default)] +pub struct Packages { + /// AST Program + pub program: Program, + /// All compiled files in the package + pub paths: Vec, + /// All Parse errors + pub parse_errors: Errors, + /// Type errors + pub type_errors: Errors, + /// Symbol information + pub symbols: IndexMap, + /// Scope information + pub scopes: IndexMap, + /// AST Node-Symbol mapping + pub node_symbol_map: IndexMap, + /// - mapping + pub pkg_scope_map: IndexMap, + /// Symbol-AST Node mapping + pub symbol_node_map: IndexMap, + /// Fully qualified name mapping + pub fully_qualified_name_map: IndexMap, +} + +#[derive(Debug, Clone)] +pub struct SymbolInfo { + pub ty: TypeRef, + pub name: String, + pub range: Range, + pub owner: Option, + pub def: Option, + pub attrs: Vec, + pub is_global: bool, +} + +#[derive(Debug, Clone)] +pub struct ScopeInfo { + /// Scope kind + pub kind: ScopeKind, + /// Scope parent + pub parent: Option, + /// Scope owner + pub owner: Option, + /// Children scopes + pub children: Vec, + /// Definitions + pub defs: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ScopeKind { + Package, + Module, + List, + Dict, + Quant, + Lambda, + SchemaDef, + Config, + Check, + Callable, +} + +/// load_package provides users with the ability to parse kcl program and sematic model +/// information including symbols, types, definitions, etc. +pub fn load_packages(opts: &LoadPackageOptions) -> Result { + load_packages_with_cache( + opts, + KCLModuleCache::default(), + KCLScopeCache::default(), + &mut GlobalState::default(), + ) +} + +/// load_package_with_cache provides users with the ability to parse kcl program and sematic model +/// information including symbols, types, definitions, etc. +pub fn load_packages_with_cache( + opts: &LoadPackageOptions, + module_cache: KCLModuleCache, + scope_cache: KCLScopeCache, + gs: &mut GlobalState, +) -> Result { + let sess = ParseSessionRef::default(); + let paths: Vec<&str> = opts.paths.iter().map(|s| s.as_str()).collect(); + let parse_result = load_program( + sess.clone(), + &paths, + opts.load_opts.clone(), + Some(module_cache), + )?; + let parse_errors = parse_result.errors; + let (program, type_errors, gs) = if opts.resolve_ast { + let mut program = parse_result.program; + let prog_scope = resolve_program_with_opts( + &mut program, + kcl_sema::resolver::Options { + merge_program: false, + type_erasure: false, + ..Default::default() + }, + Some(scope_cache), + ); + let node_ty_map = prog_scope.node_ty_map; + Namer::find_symbols(&program, gs); + AdvancedResolver::resolve_program(&program, gs, node_ty_map.clone())?; + (program, prog_scope.handler.diagnostics.clone(), gs) + } else { + (parse_result.program, IndexSet::default(), gs) + }; + let mut packages = Packages { + program, + paths: parse_result.paths, + parse_errors, + type_errors, + ..Default::default() + }; + if !opts.resolve_ast { + return Ok(packages); + } + let symbols = gs.get_symbols(); + if opts.load_builtin { + for (_, symbol_ref) in symbols.get_builtin_symbols() { + if let Some(symbol) = symbols.get_symbol(*symbol_ref) { + let def_ty = match symbol.get_definition() { + Some(def) => symbols + .get_symbol(def) + .unwrap() + .get_sema_info() + .ty + .clone() + .unwrap_or(Type::any_ref()), + None => symbol.get_sema_info().ty.clone().unwrap_or(Type::any_ref()), + }; + let info = SymbolInfo { + ty: def_ty, + range: symbol.get_range(), + name: symbol.get_name(), + owner: symbol.get_owner(), + def: symbol.get_definition(), + attrs: symbol.get_all_attributes(symbols, None), + is_global: symbol.is_global(), + }; + packages.symbols.insert(*symbol_ref, info); + } + } + } + for path in &packages.paths { + let path_str = path + .to_str() + .ok_or(anyhow::anyhow!("path {} to str failed", path.display()))? + .adjust_canonicalization(); + if let Some(files) = gs.get_sema_db().get_file_sema(&path_str) { + for symbol_ref in files.get_symbols() { + if let Some(symbol) = symbols.get_symbol(*symbol_ref) { + let def_ty = match symbol.get_definition() { + Some(def) => symbols + .get_symbol(def) + .unwrap() + .get_sema_info() + .ty + .clone() + .unwrap_or(Type::any_ref()), + None => symbol.get_sema_info().ty.clone().unwrap_or(Type::any_ref()), + }; + let info = SymbolInfo { + ty: def_ty, + range: symbol.get_range(), + name: symbol.get_name(), + owner: symbol.get_owner(), + def: symbol.get_definition(), + attrs: symbol.get_all_attributes(symbols, None), + is_global: symbol.is_global(), + }; + packages.symbols.insert(*symbol_ref, info); + } + } + } + } + let scopes = gs.get_scopes(); + for (path, scope_ref) in scopes.get_root_scope_map() { + packages.pkg_scope_map.insert(path.clone(), *scope_ref); + // Root scopes + if let Some(scope_ref) = scopes.get_root_scope(path.clone()) { + collect_scope_info( + &mut packages.scopes, + &scope_ref, + scopes, + symbols, + ScopeKind::Package, + ); + } + } + // Update package semantic mappings + packages.node_symbol_map = symbols.get_node_symbol_map().clone(); + packages.symbol_node_map = symbols.get_symbol_node_map().clone(); + packages.fully_qualified_name_map = symbols.get_fully_qualified_name_map().clone(); + Ok(packages) +} + +impl From for ScopeKind { + fn from(value: LocalSymbolScopeKind) -> Self { + match value { + LocalSymbolScopeKind::List => ScopeKind::List, + LocalSymbolScopeKind::Dict => ScopeKind::Dict, + LocalSymbolScopeKind::Quant => ScopeKind::Quant, + LocalSymbolScopeKind::Lambda => ScopeKind::Lambda, + LocalSymbolScopeKind::SchemaDef => ScopeKind::SchemaDef, + LocalSymbolScopeKind::Config => ScopeKind::Config, + LocalSymbolScopeKind::Check => ScopeKind::Check, + LocalSymbolScopeKind::Callable => ScopeKind::Callable, + } + } +} + +fn collect_scope_info( + scopes: &mut IndexMap, + scope_ref: &ScopeRef, + scope_data: &ScopeData, + symbol_data: &SymbolData, + kind: ScopeKind, +) { + if let Some(scope) = scope_data.get_scope(scope_ref) { + let kind = if let Some(scope) = scope_data.try_get_local_scope(scope_ref) { + scope.get_kind().clone().into() + } else { + kind + }; + scopes.insert( + *scope_ref, + ScopeInfo { + kind, + parent: scope.get_parent(), + owner: scope.get_owner(), + children: scope.get_children(), + defs: scope + .get_all_defs(scope_data, symbol_data, None, false, true) + .values() + .copied() + .collect::>(), + }, + ); + + for s in scope.get_children() { + collect_scope_info(scopes, &s, scope_data, symbol_data, ScopeKind::Module); + } + } +} diff --git a/kclvm/loader/src/option.rs b/crates/loader/src/option.rs similarity index 90% rename from kclvm/loader/src/option.rs rename to crates/loader/src/option.rs index fca192ada..d817c9db5 100644 --- a/kclvm/loader/src/option.rs +++ b/crates/loader/src/option.rs @@ -1,10 +1,10 @@ use anyhow::Result; -use kclvm_ast::{ast, walker::MutSelfWalker}; -use kclvm_sema::builtin::BUILTIN_FUNCTIONS; -use kclvm_sema::{builtin::option::OptionHelp, resolver::scope::NodeKey}; +use kcl_ast::{ast, walker::MutSelfWalker}; +use kcl_sema::builtin::BUILTIN_FUNCTIONS; +use kcl_sema::{builtin::option::OptionHelp, resolver::scope::NodeKey}; use crate::util::{get_call_args_string, get_call_args_strip_string}; -use crate::{load_packages, util::get_call_args_bool, LoadPackageOptions, Packages}; +use crate::{LoadPackageOptions, Packages, load_packages, util::get_call_args_bool}; #[derive(Debug)] struct OptionHelpExtractor<'ctx> { diff --git a/crates/loader/src/snapshots/kcl_loader__tests__assign_stmt_0.snap b/crates/loader/src/snapshots/kcl_loader__tests__assign_stmt_0.snap new file mode 100644 index 000000000..425c55d06 --- /dev/null +++ b/crates/loader/src/snapshots/kcl_loader__tests__assign_stmt_0.snap @@ -0,0 +1,88 @@ +--- +source: crates/loader/src/tests.rs +expression: "format! (\"{:#?}\", p.symbols.values())" +--- +[ + SymbolInfo { + ty: Type { + kind: Int, + is_type_alias: false, + flags: INT, + }, + name: "a", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 0, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 1, + ), + }, + ), + owner: Some( + SymbolRef { + id: Index { + index: 16, + generation: 0, + }, + kind: Package, + }, + ), + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Value, + }, + ), + attrs: [], + is_global: true, + }, + SymbolInfo { + ty: Type { + kind: IntLit( + 1, + ), + is_type_alias: false, + flags: INT | LITERAL, + }, + name: "@NumberLitExpression", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 5, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 5, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [], + is_global: false, + }, +] diff --git a/crates/loader/src/snapshots/kcl_loader__tests__assign_stmt_1.snap b/crates/loader/src/snapshots/kcl_loader__tests__assign_stmt_1.snap new file mode 100644 index 000000000..a1a22a42a --- /dev/null +++ b/crates/loader/src/snapshots/kcl_loader__tests__assign_stmt_1.snap @@ -0,0 +1,126 @@ +--- +source: crates/loader/src/tests.rs +expression: "format! (\"{:#?}\", p.symbols.values())" +--- +[ + SymbolInfo { + ty: Type { + kind: Int, + is_type_alias: false, + flags: INT, + }, + name: "a", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 0, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 1, + ), + }, + ), + owner: Some( + SymbolRef { + id: Index { + index: 16, + generation: 0, + }, + kind: Package, + }, + ), + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Value, + }, + ), + attrs: [], + is_global: true, + }, + SymbolInfo { + ty: Type { + kind: IntLit( + 1, + ), + is_type_alias: false, + flags: INT | LITERAL, + }, + name: "@NumberLitExpression", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 5, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 5, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: IntLit( + 1, + ), + is_type_alias: false, + flags: INT | LITERAL, + }, + name: "@NumberLitExpression", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 9, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 9, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 1, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [], + is_global: false, + }, +] diff --git a/crates/loader/src/snapshots/kcl_loader__tests__assign_stmt_2.snap b/crates/loader/src/snapshots/kcl_loader__tests__assign_stmt_2.snap new file mode 100644 index 000000000..8b2314352 --- /dev/null +++ b/crates/loader/src/snapshots/kcl_loader__tests__assign_stmt_2.snap @@ -0,0 +1,162 @@ +--- +source: crates/loader/src/tests.rs +expression: "format! (\"{:#?}\", p.symbols.values())" +--- +[ + SymbolInfo { + ty: Type { + kind: Int, + is_type_alias: false, + flags: INT, + }, + name: "a", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 0, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 1, + ), + }, + ), + owner: Some( + SymbolRef { + id: Index { + index: 16, + generation: 0, + }, + kind: Package, + }, + ), + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Value, + }, + ), + attrs: [], + is_global: true, + }, + SymbolInfo { + ty: Type { + kind: IntLit( + 1, + ), + is_type_alias: false, + flags: INT | LITERAL, + }, + name: "@NumberLitExpression", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 6, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 6, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: IntLit( + 1, + ), + is_type_alias: false, + flags: INT | LITERAL, + }, + name: "@NumberLitExpression", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 10, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 10, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 1, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: Int, + is_type_alias: false, + flags: INT, + }, + name: "@ParenExpression", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 11, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 11, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 2, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [], + is_global: false, + }, +] diff --git a/crates/loader/src/snapshots/kcl_loader__tests__builtin_call_0.snap b/crates/loader/src/snapshots/kcl_loader__tests__builtin_call_0.snap new file mode 100644 index 000000000..9cddc39ce --- /dev/null +++ b/crates/loader/src/snapshots/kcl_loader__tests__builtin_call_0.snap @@ -0,0 +1,340 @@ +--- +source: crates/loader/src/tests.rs +expression: "format! (\"{:#?}\", p.symbols.values())" +--- +[ + SymbolInfo { + ty: Type { + kind: Function( + FunctionType { + doc: "Prints the values to a stream, or to the system stdout by default.\nOptional keyword arguments:\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.", + params: [], + self_ty: None, + return_ty: Type { + kind: None, + is_type_alias: false, + flags: NONE, + }, + is_variadic: true, + kw_only_index: None, + }, + ), + is_type_alias: false, + flags: FUNCTION, + }, + name: "print", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 0, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 5, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 1, + generation: 0, + }, + kind: Function, + }, + ), + attrs: [], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: StrLit( + "hello world", + ), + is_type_alias: false, + flags: STR | LITERAL, + }, + name: "@StringLitExpression", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 19, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 19, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [ + SymbolRef { + id: Index { + index: 149, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 150, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 151, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 152, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 153, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 154, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 155, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 156, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 157, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 158, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 159, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 160, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 161, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 162, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 163, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 164, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 165, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 166, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 167, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 168, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 169, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 170, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 171, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 172, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 173, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 174, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 175, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 176, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 177, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 178, + generation: 0, + }, + kind: Function, + }, + ], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: None, + is_type_alias: false, + flags: NONE, + }, + name: "@CallExpression", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 20, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 20, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 1, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [], + is_global: false, + }, +] diff --git a/crates/loader/src/snapshots/kcl_loader__tests__builtin_call_1.snap b/crates/loader/src/snapshots/kcl_loader__tests__builtin_call_1.snap new file mode 100644 index 000000000..cecc6d025 --- /dev/null +++ b/crates/loader/src/snapshots/kcl_loader__tests__builtin_call_1.snap @@ -0,0 +1,1071 @@ +--- +source: crates/loader/src/tests.rs +expression: "format! (\"{:#?}\", p.symbols.values())" +--- +[ + SymbolInfo { + ty: Type { + kind: Any, + is_type_alias: false, + flags: ANY, + }, + name: "a", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 0, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 1, + ), + }, + ), + owner: Some( + SymbolRef { + id: Index { + index: 16, + generation: 0, + }, + kind: Package, + }, + ), + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Value, + }, + ), + attrs: [], + is_global: true, + }, + SymbolInfo { + ty: Type { + kind: Function( + FunctionType { + doc: "Return the top level argument by the key", + params: [ + Parameter { + name: "key", + ty: Type { + kind: Str, + is_type_alias: false, + flags: STR, + }, + has_default: false, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "type", + ty: Type { + kind: Str, + is_type_alias: false, + flags: STR, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "required", + ty: Type { + kind: Bool, + is_type_alias: false, + flags: BOOL, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "default", + ty: Type { + kind: Any, + is_type_alias: false, + flags: ANY, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "help", + ty: Type { + kind: Str, + is_type_alias: false, + flags: STR, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + ], + self_ty: None, + return_ty: Type { + kind: Any, + is_type_alias: false, + flags: ANY, + }, + is_variadic: false, + kw_only_index: Some( + 1, + ), + }, + ), + is_type_alias: false, + flags: FUNCTION, + }, + name: "option", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 4, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 10, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Function, + }, + ), + attrs: [], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: StrLit( + "key", + ), + is_type_alias: false, + flags: STR | LITERAL, + }, + name: "@StringLitExpression", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 16, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 16, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [ + SymbolRef { + id: Index { + index: 149, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 150, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 151, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 152, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 153, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 154, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 155, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 156, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 157, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 158, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 159, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 160, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 161, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 162, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 163, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 164, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 165, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 166, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 167, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 168, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 169, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 170, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 171, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 172, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 173, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 174, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 175, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 176, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 177, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 178, + generation: 0, + }, + kind: Function, + }, + ], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: StrLit( + "str", + ), + is_type_alias: false, + flags: STR | LITERAL, + }, + name: "type", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 18, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 22, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 1, + generation: 0, + }, + kind: Value, + }, + ), + attrs: [ + SymbolRef { + id: Index { + index: 149, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 150, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 151, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 152, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 153, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 154, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 155, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 156, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 157, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 158, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 159, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 160, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 161, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 162, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 163, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 164, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 165, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 166, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 167, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 168, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 169, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 170, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 171, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 172, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 173, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 174, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 175, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 176, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 177, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 178, + generation: 0, + }, + kind: Function, + }, + ], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: StrLit( + "str", + ), + is_type_alias: false, + flags: STR | LITERAL, + }, + name: "@StringLitExpression", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 28, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 28, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 1, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [ + SymbolRef { + id: Index { + index: 149, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 150, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 151, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 152, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 153, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 154, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 155, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 156, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 157, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 158, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 159, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 160, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 161, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 162, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 163, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 164, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 165, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 166, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 167, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 168, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 169, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 170, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 171, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 172, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 173, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 174, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 175, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 176, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 177, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 178, + generation: 0, + }, + kind: Function, + }, + ], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: BoolLit( + true, + ), + is_type_alias: false, + flags: BOOL | LITERAL, + }, + name: "required", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 30, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 38, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 2, + generation: 0, + }, + kind: Value, + }, + ), + attrs: [], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: BoolLit( + true, + ), + is_type_alias: false, + flags: BOOL | LITERAL, + }, + name: "@NameConstantLitExpression", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 43, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 43, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 2, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: Any, + is_type_alias: false, + flags: ANY, + }, + name: "@CallExpression", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 44, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 44, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 3, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [], + is_global: false, + }, +] diff --git a/crates/loader/src/snapshots/kcl_loader__tests__builtin_call_2.snap b/crates/loader/src/snapshots/kcl_loader__tests__builtin_call_2.snap new file mode 100644 index 000000000..36fb8292c --- /dev/null +++ b/crates/loader/src/snapshots/kcl_loader__tests__builtin_call_2.snap @@ -0,0 +1,1403 @@ +--- +source: crates/loader/src/tests.rs +expression: "format! (\"{:#?}\", p.symbols.values())" +--- +[ + SymbolInfo { + ty: Type { + kind: Function( + FunctionType { + doc: "Return the top level argument by the key", + params: [ + Parameter { + name: "key", + ty: Type { + kind: Str, + is_type_alias: false, + flags: STR, + }, + has_default: false, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "type", + ty: Type { + kind: Str, + is_type_alias: false, + flags: STR, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "required", + ty: Type { + kind: Bool, + is_type_alias: false, + flags: BOOL, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "default", + ty: Type { + kind: Any, + is_type_alias: false, + flags: ANY, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "help", + ty: Type { + kind: Str, + is_type_alias: false, + flags: STR, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + ], + self_ty: None, + return_ty: Type { + kind: Any, + is_type_alias: false, + flags: ANY, + }, + is_variadic: false, + kw_only_index: Some( + 1, + ), + }, + ), + is_type_alias: false, + flags: FUNCTION, + }, + name: "opt", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 0, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 3, + ), + }, + ), + owner: Some( + SymbolRef { + id: Index { + index: 16, + generation: 0, + }, + kind: Package, + }, + ), + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Value, + }, + ), + attrs: [], + is_global: true, + }, + SymbolInfo { + ty: Type { + kind: Function( + FunctionType { + doc: "Return the top level argument by the key", + params: [ + Parameter { + name: "key", + ty: Type { + kind: Str, + is_type_alias: false, + flags: STR, + }, + has_default: false, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "type", + ty: Type { + kind: Str, + is_type_alias: false, + flags: STR, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "required", + ty: Type { + kind: Bool, + is_type_alias: false, + flags: BOOL, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "default", + ty: Type { + kind: Any, + is_type_alias: false, + flags: ANY, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "help", + ty: Type { + kind: Str, + is_type_alias: false, + flags: STR, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + ], + self_ty: None, + return_ty: Type { + kind: Any, + is_type_alias: false, + flags: ANY, + }, + is_variadic: false, + kw_only_index: Some( + 1, + ), + }, + ), + is_type_alias: false, + flags: FUNCTION, + }, + name: "option", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 6, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 12, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Function, + }, + ), + attrs: [], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: Any, + is_type_alias: false, + flags: ANY, + }, + name: "a", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 0, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 1, + ), + }, + ), + owner: Some( + SymbolRef { + id: Index { + index: 16, + generation: 0, + }, + kind: Package, + }, + ), + def: Some( + SymbolRef { + id: Index { + index: 1, + generation: 0, + }, + kind: Value, + }, + ), + attrs: [], + is_global: true, + }, + SymbolInfo { + ty: Type { + kind: Function( + FunctionType { + doc: "Return the top level argument by the key", + params: [ + Parameter { + name: "key", + ty: Type { + kind: Str, + is_type_alias: false, + flags: STR, + }, + has_default: false, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "type", + ty: Type { + kind: Str, + is_type_alias: false, + flags: STR, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "required", + ty: Type { + kind: Bool, + is_type_alias: false, + flags: BOOL, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "default", + ty: Type { + kind: Any, + is_type_alias: false, + flags: ANY, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "help", + ty: Type { + kind: Str, + is_type_alias: false, + flags: STR, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + ], + self_ty: None, + return_ty: Type { + kind: Any, + is_type_alias: false, + flags: ANY, + }, + is_variadic: false, + kw_only_index: Some( + 1, + ), + }, + ), + is_type_alias: false, + flags: FUNCTION, + }, + name: "opt", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 4, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 7, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Value, + }, + ), + attrs: [], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: StrLit( + "key", + ), + is_type_alias: false, + flags: STR | LITERAL, + }, + name: "@StringLitExpression", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 13, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 13, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [ + SymbolRef { + id: Index { + index: 149, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 150, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 151, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 152, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 153, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 154, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 155, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 156, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 157, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 158, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 159, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 160, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 161, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 162, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 163, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 164, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 165, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 166, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 167, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 168, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 169, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 170, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 171, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 172, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 173, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 174, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 175, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 176, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 177, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 178, + generation: 0, + }, + kind: Function, + }, + ], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: StrLit( + "str", + ), + is_type_alias: false, + flags: STR | LITERAL, + }, + name: "type", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 15, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 19, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 2, + generation: 0, + }, + kind: Value, + }, + ), + attrs: [ + SymbolRef { + id: Index { + index: 149, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 150, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 151, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 152, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 153, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 154, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 155, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 156, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 157, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 158, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 159, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 160, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 161, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 162, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 163, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 164, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 165, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 166, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 167, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 168, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 169, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 170, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 171, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 172, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 173, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 174, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 175, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 176, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 177, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 178, + generation: 0, + }, + kind: Function, + }, + ], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: StrLit( + "str", + ), + is_type_alias: false, + flags: STR | LITERAL, + }, + name: "@StringLitExpression", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 25, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 25, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 1, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [ + SymbolRef { + id: Index { + index: 149, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 150, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 151, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 152, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 153, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 154, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 155, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 156, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 157, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 158, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 159, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 160, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 161, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 162, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 163, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 164, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 165, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 166, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 167, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 168, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 169, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 170, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 171, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 172, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 173, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 174, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 175, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 176, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 177, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 178, + generation: 0, + }, + kind: Function, + }, + ], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: BoolLit( + true, + ), + is_type_alias: false, + flags: BOOL | LITERAL, + }, + name: "required", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 27, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 35, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 3, + generation: 0, + }, + kind: Value, + }, + ), + attrs: [], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: BoolLit( + true, + ), + is_type_alias: false, + flags: BOOL | LITERAL, + }, + name: "@NameConstantLitExpression", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 40, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 40, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 2, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: Any, + is_type_alias: false, + flags: ANY, + }, + name: "@CallExpression", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 41, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 41, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 3, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [], + is_global: false, + }, +] diff --git a/crates/loader/src/snapshots/kcl_loader__tests__import_stmt_0.snap b/crates/loader/src/snapshots/kcl_loader__tests__import_stmt_0.snap new file mode 100644 index 000000000..1db12b4bb --- /dev/null +++ b/crates/loader/src/snapshots/kcl_loader__tests__import_stmt_0.snap @@ -0,0 +1,545 @@ +--- +source: crates/loader/src/tests.rs +expression: "format! (\"{:#?}\", p.symbols.values())" +--- +[ + SymbolInfo { + ty: Type { + kind: Module( + ModuleType { + pkgpath: "math", + imported: [ + "test.k", + ], + kind: System, + }, + ), + is_type_alias: false, + flags: MODULE, + }, + name: "math", + range: ( + Position { + filename: "test.k", + line: 1, + column: Some( + 7, + ), + }, + Position { + filename: "test.k", + line: 1, + column: Some( + 11, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 3, + generation: 0, + }, + kind: Package, + }, + ), + attrs: [ + SymbolRef { + id: Index { + index: 52, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 53, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 54, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 55, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 56, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 57, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 58, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 59, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 60, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 61, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 62, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 63, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 64, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 65, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 66, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 67, + generation: 0, + }, + kind: Function, + }, + ], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: Float, + is_type_alias: false, + flags: FLOAT, + }, + name: "a", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 0, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 1, + ), + }, + ), + owner: Some( + SymbolRef { + id: Index { + index: 16, + generation: 0, + }, + kind: Package, + }, + ), + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Value, + }, + ), + attrs: [], + is_global: true, + }, + SymbolInfo { + ty: Type { + kind: Module( + ModuleType { + pkgpath: "math", + imported: [ + "test.k", + ], + kind: System, + }, + ), + is_type_alias: false, + flags: MODULE, + }, + name: "math", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 4, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 8, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 3, + generation: 0, + }, + kind: Package, + }, + ), + attrs: [ + SymbolRef { + id: Index { + index: 52, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 53, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 54, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 55, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 56, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 57, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 58, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 59, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 60, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 61, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 62, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 63, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 64, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 65, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 66, + generation: 0, + }, + kind: Function, + }, + SymbolRef { + id: Index { + index: 67, + generation: 0, + }, + kind: Function, + }, + ], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: Function( + FunctionType { + doc: "Return the logarithm of `x` to the base `e`.", + params: [ + Parameter { + name: "x", + ty: Type { + kind: Union( + [ + Type { + kind: Int, + is_type_alias: false, + flags: INT, + }, + Type { + kind: Float, + is_type_alias: false, + flags: FLOAT, + }, + ], + ), + is_type_alias: false, + flags: UNION, + }, + has_default: false, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + Parameter { + name: "e", + ty: Type { + kind: Float, + is_type_alias: false, + flags: FLOAT, + }, + has_default: true, + default_value: None, + range: ( + Position { + filename: "", + line: 1, + column: None, + }, + Position { + filename: "", + line: 1, + column: None, + }, + ), + }, + ], + self_ty: None, + return_ty: Type { + kind: Float, + is_type_alias: false, + flags: FLOAT, + }, + is_variadic: false, + kw_only_index: None, + }, + ), + is_type_alias: false, + flags: FUNCTION, + }, + name: "log", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 9, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 12, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 62, + generation: 0, + }, + kind: Function, + }, + ), + attrs: [], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: IntLit( + 10, + ), + is_type_alias: false, + flags: INT | LITERAL, + }, + name: "@NumberLitExpression", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 15, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 15, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [], + is_global: false, + }, + SymbolInfo { + ty: Type { + kind: Float, + is_type_alias: false, + flags: FLOAT, + }, + name: "@CallExpression", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 16, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 16, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 1, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [], + is_global: false, + }, +] diff --git a/crates/loader/src/snapshots/kcl_loader__tests__import_stmt_1.snap b/crates/loader/src/snapshots/kcl_loader__tests__import_stmt_1.snap new file mode 100644 index 000000000..e7a316d65 --- /dev/null +++ b/crates/loader/src/snapshots/kcl_loader__tests__import_stmt_1.snap @@ -0,0 +1,86 @@ +--- +source: crates/loader/src/tests.rs +expression: "format! (\"{:#?}\", p.symbols.values())" +--- +[ + SymbolInfo { + ty: Type { + kind: Any, + is_type_alias: false, + flags: ANY, + }, + name: "a", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 0, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 1, + ), + }, + ), + owner: Some( + SymbolRef { + id: Index { + index: 16, + generation: 0, + }, + kind: Package, + }, + ), + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Value, + }, + ), + attrs: [], + is_global: true, + }, + SymbolInfo { + ty: Type { + kind: Any, + is_type_alias: false, + flags: ANY, + }, + name: "@IdentifierExpression", + range: ( + Position { + filename: "test.k", + line: 3, + column: Some( + 9, + ), + }, + Position { + filename: "test.k", + line: 3, + column: Some( + 9, + ), + }, + ), + owner: None, + def: Some( + SymbolRef { + id: Index { + index: 0, + generation: 0, + }, + kind: Expression, + }, + ), + attrs: [], + is_global: false, + }, +] diff --git a/crates/loader/src/snapshots/kcl_loader__tests__list_options_0.snap b/crates/loader/src/snapshots/kcl_loader__tests__list_options_0.snap new file mode 100644 index 000000000..5a1e6aa21 --- /dev/null +++ b/crates/loader/src/snapshots/kcl_loader__tests__list_options_0.snap @@ -0,0 +1,13 @@ +--- +source: crates/loader/src/tests.rs +expression: "format! (\"{:#?}\", options)" +--- +[ + OptionHelp { + name: "key", + ty: "int", + required: false, + default_value: "", + help: "", + }, +] diff --git a/crates/loader/src/snapshots/kcl_loader__tests__list_options_1.snap b/crates/loader/src/snapshots/kcl_loader__tests__list_options_1.snap new file mode 100644 index 000000000..9a4f1c853 --- /dev/null +++ b/crates/loader/src/snapshots/kcl_loader__tests__list_options_1.snap @@ -0,0 +1,20 @@ +--- +source: crates/loader/src/tests.rs +expression: "format! (\"{:#?}\", options)" +--- +[ + OptionHelp { + name: "key1", + ty: "str", + required: true, + default_value: "", + help: "", + }, + OptionHelp { + name: "key2", + ty: "int", + required: false, + default_value: "", + help: "", + }, +] diff --git a/crates/loader/src/snapshots/kcl_loader__tests__list_options_2.snap b/crates/loader/src/snapshots/kcl_loader__tests__list_options_2.snap new file mode 100644 index 000000000..a3858ffec --- /dev/null +++ b/crates/loader/src/snapshots/kcl_loader__tests__list_options_2.snap @@ -0,0 +1,20 @@ +--- +source: crates/loader/src/tests.rs +expression: "format! (\"{:#?}\", options)" +--- +[ + OptionHelp { + name: "key1", + ty: "str", + required: true, + default_value: "\"value\"", + help: "help me", + }, + OptionHelp { + name: "key2", + ty: "", + required: false, + default_value: "", + help: "", + }, +] diff --git a/crates/loader/src/snapshots/kcl_loader__tests__list_options_3.snap b/crates/loader/src/snapshots/kcl_loader__tests__list_options_3.snap new file mode 100644 index 000000000..2734a958d --- /dev/null +++ b/crates/loader/src/snapshots/kcl_loader__tests__list_options_3.snap @@ -0,0 +1,13 @@ +--- +source: crates/loader/src/tests.rs +expression: "format! (\"{:#?}\", options)" +--- +[ + OptionHelp { + name: "key1", + ty: "int", + required: false, + default_value: "123", + help: "help me", + }, +] diff --git a/kclvm/loader/src/test_data/test_list_variables/supported.k b/crates/loader/src/test_data/test_list_variables/supported.k similarity index 100% rename from kclvm/loader/src/test_data/test_list_variables/supported.k rename to crates/loader/src/test_data/test_list_variables/supported.k diff --git a/kclvm/loader/src/test_data/test_list_variables/unsupported.k b/crates/loader/src/test_data/test_list_variables/unsupported.k similarity index 100% rename from kclvm/loader/src/test_data/test_list_variables/unsupported.k rename to crates/loader/src/test_data/test_list_variables/unsupported.k diff --git a/crates/loader/src/tests.rs b/crates/loader/src/tests.rs new file mode 100644 index 000000000..d6cb557bf --- /dev/null +++ b/crates/loader/src/tests.rs @@ -0,0 +1,76 @@ +use crate::option::list_options; +use crate::{LoadPackageOptions, load_packages}; +use kcl_parser::LoadProgramOptions; + +#[macro_export] +macro_rules! load_package_snapshot { + ($name:ident, $src:expr) => { + #[test] + fn $name() { + let p = load_packages(&LoadPackageOptions { + paths: vec!["test.k".to_string()], + load_opts: Some(LoadProgramOptions { + k_code_list: vec![$src.to_string()], + ..Default::default() + }), + load_builtin: false, + ..Default::default() + }) + .unwrap(); + insta::assert_snapshot!(format!("{:#?}", p.symbols.values())); + } + }; +} + +load_package_snapshot! {assign_stmt_0, "a = 1"} +load_package_snapshot! {assign_stmt_1, "a = 1 + 1"} +load_package_snapshot! {assign_stmt_2, "a = (1 + 1)"} + +load_package_snapshot! {import_stmt_0, r#"import math + +a = math.log(10) +"#} +load_package_snapshot! {import_stmt_1, r#"import pkg + +a = pkg.a +"#} +load_package_snapshot! {builtin_call_0, r#"print("hello world")"#} +load_package_snapshot! {builtin_call_1, r#"a = option("key", type="str", required=True)"#} +load_package_snapshot! {builtin_call_2, r#"opt = option + +a = opt("key", type="str", required=True) +"#} + +#[macro_export] +macro_rules! list_options_snapshot { + ($name:ident, $src:expr) => { + #[test] + fn $name() { + let options = list_options(&LoadPackageOptions { + paths: vec!["test.k".to_string()], + load_opts: Some(LoadProgramOptions { + k_code_list: vec![$src.to_string()], + ..Default::default() + }), + load_builtin: false, + ..Default::default() + }) + .unwrap(); + insta::assert_snapshot!(format!("{:#?}", options)); + } + }; +} +list_options_snapshot! {list_options_0, r#"a = option("key", type="int")"#} +list_options_snapshot! {list_options_1, r#"opt = option + +a = opt("key1", type="str", required=True) +b = option("key2", type="int") +"#} +list_options_snapshot! {list_options_2, r#" +a = option("key1", type="str", required=True, default="value", help="help me") +if True: + b = option("key2") +"#} +list_options_snapshot! {list_options_3, r#" +a = option("key1", type="int", required=False, default=123, help="help me") +"#} diff --git a/crates/loader/src/util.rs b/crates/loader/src/util.rs new file mode 100644 index 000000000..4b6e6f483 --- /dev/null +++ b/crates/loader/src/util.rs @@ -0,0 +1,68 @@ +use std::collections::HashMap; + +use kcl_ast::ast; +use kcl_ast_pretty::{ASTNode, print_ast_node}; +use kcl_sema::eval::str_literal_eval; + +pub(crate) fn get_call_args_bool( + call_expr: &ast::CallExpr, + index: usize, + key: Option<&str>, +) -> bool { + let val = get_call_args_string(call_expr, index, key); + val == "True" || val == "true" +} + +pub(crate) fn get_call_args_strip_string( + call_expr: &ast::CallExpr, + index: usize, + key: Option<&str>, +) -> String { + let value = get_call_args_string(call_expr, index, key); + match str_literal_eval(&value, false, false) { + Some(value) => value, + None => value, + } +} + +pub(crate) fn get_call_args_string( + call_expr: &ast::CallExpr, + index: usize, + key: Option<&str>, +) -> String { + let (args, kwargs) = arguments_to_string(&call_expr.args, &call_expr.keywords); + if let Some(key) = key { + if let Some(val) = kwargs.get(key) { + return val.to_string(); + } + } + if index < args.len() { + return args[index].to_string(); + } + "".to_string() +} + +/// Print call arguments to argument vector and keyword mapping. +pub fn arguments_to_string( + args: &[ast::NodeRef], + kwargs: &[ast::NodeRef], +) -> (Vec, HashMap) { + ( + args.iter() + .map(|a| print_ast_node(ASTNode::Expr(a))) + .collect(), + kwargs + .iter() + .map(|a| { + ( + a.node.arg.node.get_name(), + a.node + .value + .as_ref() + .map(|v| print_ast_node(ASTNode::Expr(v))) + .unwrap_or_default(), + ) + }) + .collect(), + ) +} diff --git a/crates/macros/Cargo.toml b/crates/macros/Cargo.toml new file mode 100644 index 000000000..818f20b01 --- /dev/null +++ b/crates/macros/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "kcl-macros" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[lib] +proc-macro = true + +[dependencies] +synstructure = "0.12.1" +syn = { version = "1", features = ["full"] } +proc-macro2 = "1" +quote = "1" diff --git a/kclvm/macros/src/lib.rs b/crates/macros/src/lib.rs similarity index 100% rename from kclvm/macros/src/lib.rs rename to crates/macros/src/lib.rs diff --git a/kclvm/macros/src/symbols.rs b/crates/macros/src/symbols.rs similarity index 99% rename from kclvm/macros/src/symbols.rs rename to crates/macros/src/symbols.rs index 144f33b80..1e7187203 100644 --- a/kclvm/macros/src/symbols.rs +++ b/crates/macros/src/symbols.rs @@ -11,7 +11,7 @@ use proc_macro2::{Span, TokenStream}; use quote::quote; use std::collections::HashMap; use syn::parse::{Parse, ParseStream, Result}; -use syn::{braced, punctuated::Punctuated, Ident, LitStr, Token}; +use syn::{Ident, LitStr, Token, braced, punctuated::Punctuated}; #[cfg(test)] mod tests; diff --git a/kclvm/macros/src/symbols/tests.rs b/crates/macros/src/symbols/tests.rs similarity index 100% rename from kclvm/macros/src/symbols/tests.rs rename to crates/macros/src/symbols/tests.rs diff --git a/crates/parser/Cargo.toml b/crates/parser/Cargo.toml new file mode 100644 index 000000000..704c36259 --- /dev/null +++ b/crates/parser/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "kcl-parser" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +compiler_base_span = "0.1.2" +compiler_base_session = "0.1.3" +compiler_base_error = "0.1.6" +compiler_base_macros = "0.1.1" +tracing = "0.1" +serde = { version = "1", features = ["derive"] } +serde_json = "1.0" +rustc_lexer = "0.1.0" +either = "1.1.0" +enquote = "1.1.0" +unicode_names2 = "0.4" +bstr = "0.2.16" +petgraph = "0.6.0" +num-bigint = "0.4" +regex = "1.7.0" +anyhow = "1.0" +parking_lot = "0.12.3" +glob = "0.3.1" + +kcl-lexer = { path = "../lexer" } +kcl-ast = { path = "../ast" } +kcl-span = { path = "../span" } +kcl-error = { path = "../error" } +kcl-config = { path = "../config" } +kcl-sema = { path = "../sema" } +kcl-utils = { path = "../utils" } +kcl-primitives = { path = "../primitives" } +walkdir = "2" + +[dev-dependencies] +expect-test = "1.0" +insta = "1.8.0" diff --git a/kclvm/parser/src/entry.rs b/crates/parser/src/entry.rs similarity index 94% rename from kclvm/parser/src/entry.rs rename to crates/parser/src/entry.rs index def1f2039..d24af290c 100644 --- a/kclvm/parser/src/entry.rs +++ b/crates/parser/src/entry.rs @@ -1,10 +1,10 @@ use anyhow::Result; use glob::glob; -use kclvm_config::modfile::get_pkg_root; -use kclvm_config::modfile::KCL_FILE_SUFFIX; -use kclvm_config::path::ModRelativePath; -use kclvm_utils::path::PathPrefix; -use kclvm_utils::path::{is_absolute, is_dir, path_exist}; +use kcl_config::modfile::KCL_FILE_SUFFIX; +use kcl_config::modfile::get_pkg_root; +use kcl_config::path::ModRelativePath; +use kcl_utils::path::PathPrefix; +use kcl_utils::path::{is_absolute, is_dir, path_exist}; use std::collections::VecDeque; use std::fs; use std::path::Path; @@ -216,8 +216,8 @@ pub fn get_normalized_k_files_from_paths( /// /// ```rust /// use std::path::PathBuf; -/// use kclvm_parser::entry::get_compile_entries_from_paths; -/// use kclvm_parser::LoadProgramOptions; +/// use kcl_parser::entry::get_compile_entries_from_paths; +/// use kcl_parser::LoadProgramOptions; /// let testpath = PathBuf::from("./src/testdata/multimods").canonicalize().unwrap(); /// /// // [`kcl1_path`] is a normal path of the package [`kcl1`] root directory. @@ -325,15 +325,15 @@ pub fn get_compile_entries_from_paths( // If the [`ModRelativePath`] with prefix '${KCL_MOD}' } else if path.is_relative_path()? && path.get_root_pkg_name()?.is_none() { // Push it into `result`, and deal it later. - let mut entry = Entry::new(kclvm_ast::MAIN_PKG.to_string(), path.get_path()); + let mut entry = Entry::new(kcl_ast::MAIN_PKG.to_string(), path.get_path()); entry.push_k_code(k_code_queue.pop_front()); result.push_entry(entry); continue; } else if let Some(root) = get_pkg_root(&file) { // If the path is a normal path. - let mut entry: Entry = Entry::new(kclvm_ast::MAIN_PKG.to_string(), root.clone()); + let mut entry: Entry = Entry::new(kcl_ast::MAIN_PKG.to_string(), root.clone()); entry.extend_k_files_and_codes( - get_main_files_from_pkg_path(&file, &root, kclvm_ast::MAIN_PKG, opts)?, + get_main_files_from_pkg_path(&file, &root, kcl_ast::MAIN_PKG, opts)?, &mut k_code_queue, ); result.push_entry(entry); @@ -342,13 +342,13 @@ pub fn get_compile_entries_from_paths( // The main 'kcl.mod' can not be found, the empty path "" will be took by default. if result - .get_unique_normal_paths_by_name(kclvm_ast::MAIN_PKG) + .get_unique_normal_paths_by_name(kcl_ast::MAIN_PKG) .is_empty() { - let mut entry = Entry::new(kclvm_ast::MAIN_PKG.to_string(), "".to_string()); + let mut entry = Entry::new(kcl_ast::MAIN_PKG.to_string(), "".to_string()); for file in &file_paths { entry.extend_k_files_and_codes( - get_main_files_from_pkg_path(&file, "", kclvm_ast::MAIN_PKG, opts)?, + get_main_files_from_pkg_path(&file, "", kcl_ast::MAIN_PKG, opts)?, &mut k_code_queue, ); } @@ -356,13 +356,13 @@ pub fn get_compile_entries_from_paths( } let main_pkg_paths_count = result - .get_unique_normal_paths_by_name(kclvm_ast::MAIN_PKG) + .get_unique_normal_paths_by_name(kcl_ast::MAIN_PKG) .len(); let pkg_root = if main_pkg_paths_count == 1 { // If the 'kcl.mod' can be found only once, the package root path will be the path of the 'kcl.mod'. result - .get_unique_normal_paths_by_name(kclvm_ast::MAIN_PKG) + .get_unique_normal_paths_by_name(kcl_ast::MAIN_PKG) .get(0) .unwrap() .to_string() @@ -380,12 +380,12 @@ pub fn get_compile_entries_from_paths( // Replace the '${KCL_MOD}' of all the paths with package name '__main__'. result.apply_to_all_entries(|entry| { let path = ModRelativePath::from(entry.path().to_string()); - if entry.name() == kclvm_ast::MAIN_PKG && path.is_relative_path()? { + if entry.name() == kcl_ast::MAIN_PKG && path.is_relative_path()? { entry.set_path(pkg_root.to_string()); entry.extend_k_files(get_main_files_from_pkg_path( &path.canonicalize_by_root_path(&pkg_root)?, &pkg_root, - kclvm_ast::MAIN_PKG, + kcl_ast::MAIN_PKG, opts, )?); } diff --git a/kclvm/parser/src/file_graph.rs b/crates/parser/src/file_graph.rs similarity index 98% rename from kclvm/parser/src/file_graph.rs rename to crates/parser/src/file_graph.rs index 63ae5ec90..32031c9fd 100644 --- a/kclvm/parser/src/file_graph.rs +++ b/crates/parser/src/file_graph.rs @@ -1,8 +1,8 @@ use std::{collections::HashMap, path::PathBuf}; -use kclvm_ast::ast::Module; -use kclvm_primitives::{DefaultHashBuilder, IndexMap}; -use kclvm_utils::path::PathPrefix; +use kcl_ast::ast::Module; +use kcl_primitives::{DefaultHashBuilder, IndexMap}; +use kcl_utils::path::PathPrefix; use petgraph::{prelude::StableDiGraph, visit::EdgeRef}; use std::hash::Hash; /// File with package info diff --git a/kclvm/parser/src/lexer/indent.rs b/crates/parser/src/lexer/indent.rs similarity index 95% rename from kclvm/parser/src/lexer/indent.rs rename to crates/parser/src/lexer/indent.rs index f53ee8ff3..8826ad041 100644 --- a/kclvm/parser/src/lexer/indent.rs +++ b/crates/parser/src/lexer/indent.rs @@ -4,8 +4,8 @@ use std::cmp::Ordering; use crate::lexer::IndentOrDedents; use crate::lexer::Lexer; -use kclvm_ast::token::VALID_SPACES_LENGTH; -use kclvm_ast::token::{self, Token}; +use kcl_ast::token::VALID_SPACES_LENGTH; +use kcl_ast::token::{self, Token}; #[derive(Clone, Copy, PartialEq, Debug, Default)] pub(crate) struct IndentLevel { @@ -38,7 +38,7 @@ impl IndentLevel { impl<'a> Lexer<'a> { pub(crate) fn lex_indent_context( &mut self, - token: kclvm_lexer::TokenKind, + token: kcl_lexer::TokenKind, ) -> Option { // process for indent context for a newline if !self.indent_cxt.new_line_beginning { @@ -46,18 +46,17 @@ impl<'a> Lexer<'a> { } match token { - kclvm_lexer::TokenKind::LineComment { doc_style: _ } - | kclvm_lexer::TokenKind::Newline => { + kcl_lexer::TokenKind::LineComment { doc_style: _ } | kcl_lexer::TokenKind::Newline => { // No in(de)ent in comment line and new line self.indent_cxt.tabs = 0; self.indent_cxt.spaces = 0; None } - kclvm_lexer::TokenKind::Tab => { + kcl_lexer::TokenKind::Tab => { self.indent_cxt.tabs += 1; None } - kclvm_lexer::TokenKind::Space => { + kcl_lexer::TokenKind::Space => { self.indent_cxt.spaces += 1; None } diff --git a/crates/parser/src/lexer/mod.rs b/crates/parser/src/lexer/mod.rs new file mode 100644 index 000000000..8ea38f5bf --- /dev/null +++ b/crates/parser/src/lexer/mod.rs @@ -0,0 +1,757 @@ +//! A KCL lexer. +//! +//! The lexer is built on the low level [`kcl_lexer`] +//! +//! It's main responsibilities: +//! 1. Mapping low level [`kcl_lexer::Token`] tokens into [`kcl_ast::Token`] tokens, +//! and provide TokenStream to downstream [`kcl_parser::parser`]. +//! 2. Validations on Literals(String, Int, Float). +//! 3. Validations on closure of delim tokens. +//! 4. Validations on indent and dedent. +//! +//! The main differences of tokens between ast and lexer is: +//! 1. AST Affinity, based on unary, binary and other operations. +//! 2. Has Indent and dedent. +//! 3. Don't have some tokens(such as ';', '..', '..=', '<-') + +mod indent; +mod string; + +#[cfg(test)] +mod tests; + +use compiler_base_macros::bug; +use compiler_base_span::{self, BytePos, Span, span::new_byte_pos}; +use kcl_ast::ast::NumberBinarySuffix; +use kcl_ast::token::VALID_SPACES_LENGTH; +use kcl_ast::token::{self, BinOpToken, CommentKind, Token, TokenKind}; +use kcl_ast::token_stream::TokenStream; +use kcl_error::ParseErrorMessage; +use kcl_lexer::Base; +use kcl_span::symbol::Symbol; +pub(crate) use string::str_content_eval; + +use self::indent::IndentLevel; +use crate::session::ParseSession; + +/// EntryPoint of the lexer. +/// Parse token streams from an input raw string and a fixed start point. +/// Return an iterable token stream. +pub fn parse_token_streams(sess: &ParseSession, src: &str, start_pos: BytePos) -> TokenStream { + Lexer { + sess, + start_pos, + pos: start_pos, + tok_start_pos: start_pos, + end_src_index: src.len(), + src, + token: TokenWithIndents::Token { + token: Token::dummy(), + }, + indent_cxt: IndentContext { + delims: Vec::new(), + tabs: 0, + spaces: 0, + new_line_beginning: false, + indents: vec![Default::default()], + }, + } + .into_tokens() +} + +/// A token or a token with indent. +enum TokenWithIndents { + Token { + token: Token, + }, + WithIndent { + token: Token, + indent: IndentOrDedents, + }, +} + +/// A indent or a fixed count of dedents. +enum IndentOrDedents { + Indent { token: Token }, + Dedents { tokens: Vec }, +} + +impl TokenWithIndents { + pub(crate) fn is_eof(&self) -> bool { + match self { + TokenWithIndents::Token { token } => *token == token::Eof, + TokenWithIndents::WithIndent { token, indent: _ } => *token == token::Eof, + } + } + + pub(crate) fn append_to(&self, buf: &mut TokenStreamBuilder) { + match self { + TokenWithIndents::Token { token } => { + buf.push(*token); + } + TokenWithIndents::WithIndent { token, indent } => { + match indent { + IndentOrDedents::Indent { token } => { + buf.push(*token); + } + IndentOrDedents::Dedents { tokens } => { + for dedent in tokens { + buf.push(*dedent); + } + } + } + + buf.push(*token); + } + } + } +} + +struct Lexer<'a> { + /// Initial position, read-only. + start_pos: BytePos, + + /// The absolute offset within the source_map of the current character. + pos: BytePos, + + /// The start position of the current token. + tok_start_pos: BytePos, + + /// Stop reading src at this index. + end_src_index: usize, + + /// Source text to tokenize. + src: &'a str, + + /// Token + token: TokenWithIndents, + + /// A on-going context to handle indent/dedents + indent_cxt: IndentContext, + + /// parse-time session + pub sess: &'a ParseSession, +} + +struct IndentContext { + /// A new line flag + new_line_beginning: bool, + + /// Delim stack + delims: Vec, + + /// tab counter + tabs: usize, + + /// space counter + spaces: usize, + + /// Indents stack + indents: Vec, +} + +impl<'a> Lexer<'a> { + fn into_tokens(mut self) -> TokenStream { + let mut buf = TokenStreamBuilder::default(); + // In the process of look-behind lexing, it is necessary to check the type of the previous token in 'buf', + // If the previous token and the current token can form a multi-character token, + // then the previous token will be popped from 'buf'. + // + // Therefore, the method 'self.token()' needs to take the mutable reference of 'buf' as an incoming argument. + self.token = self.token(&mut buf); + + while !self.token.is_eof() { + self.token.append_to(&mut buf); + self.token = self.token(&mut buf); + } + + self.eof(&mut buf); + buf.into_token_stream() + } + + fn token(&mut self, tok_stream_builder: &mut TokenStreamBuilder) -> TokenWithIndents { + loop { + let start_src_index = self.src_index(self.pos); + let text: &str = &self.src[start_src_index..self.end_src_index]; + + if text.is_empty() { + return TokenWithIndents::Token { + token: Token::new(token::Eof, self.span(self.pos, self.pos)), + }; + } + + // fetch next token + let token = kcl_lexer::first_token(text); + + // Detect and handle indent cases before lexing on-going token + let indent = self.lex_indent_context(token.kind); + + // Because of the 'look-behind', the 'start' of the current token becomes a two-way cursor, + // which can not only move forward, but also move backward when 'look-behind'. + // Therefore, the value of 'self.tok_start_pos' can be changed in 'self.lex_token()'. + self.tok_start_pos = self.pos; + // update pos after token and indent handling + self.pos = self.pos + new_byte_pos(token.len as u32); + + // In the process of look-behind lexing, it is necessary to check the type of the previous token in 'tok_stream_builder', + // If the previous token and the current token can form a multi-character token, + // then the previous token will be popped from 'tok_stream_builder'. + // Therefore, the method 'self.lex_token()' needs to take the mutable reference of 'tok_stream_builder' as an incoming argument. + if let Some(kind) = self.lex_token(token, self.tok_start_pos, tok_stream_builder) { + let span = self.span(self.tok_start_pos, self.pos); + + match indent { + Some(iord) => { + // return the token with the leading indent/dedents + return TokenWithIndents::WithIndent { + token: Token::new(kind, span), + indent: iord, + }; + } + None => { + // return the token itself + return TokenWithIndents::Token { + token: Token::new(kind, span), + }; + } + } + } + } + } + + /// Turns `kcl_lexer::TokenKind` into a rich `kcl_ast::TokenKind`. + fn lex_token( + &mut self, + token: kcl_lexer::Token, + start: BytePos, + tok_stream_builder: &mut TokenStreamBuilder, + ) -> Option { + Some(match token.kind { + kcl_lexer::TokenKind::LineComment { doc_style: _ } => { + let s = self.str_from(start); + token::DocComment(CommentKind::Line(Symbol::intern(s))) + } + // Whitespace + kcl_lexer::TokenKind::Newline => { + self.indent_cxt.new_line_beginning = true; + token::Newline + } + kcl_lexer::TokenKind::Tab + | kcl_lexer::TokenKind::Space + | kcl_lexer::TokenKind::CarriageReturn + | kcl_lexer::TokenKind::Whitespace => return None, + // Identifier + kcl_lexer::TokenKind::Ident => { + let s = self.str_from(start); + token::Ident(Symbol::intern(s)) + } + // Literal + kcl_lexer::TokenKind::Literal { kind, suffix_start } => { + let suffix_start = start + new_byte_pos(suffix_start as u32); + let (kind, symbol, suffix, raw) = self.lex_literal(start, suffix_start, kind); + token::Literal(token::Lit { + kind, + symbol, + suffix, + raw, + }) + } + // Unary op + kcl_lexer::TokenKind::Tilde => token::UnaryOp(token::UTilde), + kcl_lexer::TokenKind::Bang => { + self.sess.struct_message_error_with_suggestions( + ParseErrorMessage::InvalidTokenNot, + self.span(start, self.pos), + Some(vec!["not ".to_string()]), + ); + token::UnaryOp(token::UNot) + } + // Binary op + kcl_lexer::TokenKind::Plus => token::BinOp(token::Plus), + kcl_lexer::TokenKind::Minus => token::BinOp(token::Minus), + kcl_lexer::TokenKind::Star => token::BinOp(token::Star), + kcl_lexer::TokenKind::Slash => token::BinOp(token::Slash), + kcl_lexer::TokenKind::Percent => token::BinOp(token::Percent), + kcl_lexer::TokenKind::StarStar => token::BinOp(token::StarStar), + kcl_lexer::TokenKind::SlashSlash => token::BinOp(token::SlashSlash), + kcl_lexer::TokenKind::Caret => token::BinOp(token::Caret), + kcl_lexer::TokenKind::And => token::BinOp(token::And), + kcl_lexer::TokenKind::Or => token::BinOp(token::Or), + kcl_lexer::TokenKind::LtLt => token::BinOp(token::Shl), + kcl_lexer::TokenKind::GtGt => token::BinOp(token::Shr), + // Binary op eq + kcl_lexer::TokenKind::PlusEq => token::BinOpEq(token::Plus), + kcl_lexer::TokenKind::MinusEq => token::BinOpEq(token::Minus), + kcl_lexer::TokenKind::StarEq => token::BinOpEq(token::Star), + kcl_lexer::TokenKind::SlashEq => token::BinOpEq(token::Slash), + kcl_lexer::TokenKind::PercentEq => token::BinOpEq(token::Percent), + kcl_lexer::TokenKind::StarStarEq => token::BinOpEq(token::StarStar), + kcl_lexer::TokenKind::SlashSlashEq => token::BinOpEq(token::SlashSlash), + kcl_lexer::TokenKind::CaretEq => token::BinOpEq(token::Caret), + kcl_lexer::TokenKind::AndEq => token::BinOpEq(token::And), + kcl_lexer::TokenKind::OrEq => token::BinOpEq(token::Or), + kcl_lexer::TokenKind::LtLtEq => token::BinOpEq(token::Shl), + kcl_lexer::TokenKind::GtGtEq => token::BinOpEq(token::Shr), + // Binary cmp + kcl_lexer::TokenKind::EqEq => token::BinCmp(token::Eq), + kcl_lexer::TokenKind::BangEq => token::BinCmp(token::NotEq), + kcl_lexer::TokenKind::Lt => token::BinCmp(token::Lt), + kcl_lexer::TokenKind::LtEq => token::BinCmp(token::LtEq), + // If the current token is '>', + // then lexer need to check whether the previous token is '-', + // if yes, return token '->', if not return token '>'. + kcl_lexer::TokenKind::Gt => match self.look_behind(&token, tok_stream_builder) { + Some(tok_kind) => tok_kind, + None => token::BinCmp(token::Gt), + }, + kcl_lexer::TokenKind::GtEq => token::BinCmp(token::GtEq), + // Structural symbols + kcl_lexer::TokenKind::At => token::At, + kcl_lexer::TokenKind::Dot => token::Dot, + kcl_lexer::TokenKind::DotDotDot => token::DotDotDot, + kcl_lexer::TokenKind::Comma => token::Comma, + kcl_lexer::TokenKind::Colon => token::Colon, + kcl_lexer::TokenKind::Dollar => token::Dollar, + kcl_lexer::TokenKind::Question => token::Question, + kcl_lexer::TokenKind::Eq => token::Assign, + // Delim tokens + kcl_lexer::TokenKind::OpenParen => { + self.indent_cxt.delims.push(token::OpenDelim(token::Paren)); + token::OpenDelim(token::Paren) + } + kcl_lexer::TokenKind::CloseParen => match self.indent_cxt.delims.pop() { + // check delim stack + Some(delim) => match delim { + // expected case + token::OpenDelim(token::Paren) => token::CloseDelim(token::Paren), + // error recovery + token::OpenDelim(token::Brace) => { + self.sess.struct_span_error( + "error nesting on close paren", + self.span(start, self.pos), + ); + token::CloseDelim(token::Brace) + } + // error recovery + token::OpenDelim(token::Bracket) => { + self.sess.struct_span_error( + "error nesting on close paren", + self.span(start, self.pos), + ); + token::CloseDelim(token::Bracket) + } + // impossible case + _ => bug!("Impossible!"), + }, + // error recovery + None => { + self.sess.struct_span_error( + "error nesting on close paren", + self.span(start, self.pos), + ); + token::CloseDelim(token::Paren) + } + }, + kcl_lexer::TokenKind::OpenBrace => { + self.indent_cxt.delims.push(token::OpenDelim(token::Brace)); + token::OpenDelim(token::Brace) + } + kcl_lexer::TokenKind::CloseBrace => match self.indent_cxt.delims.pop() { + // check delim stack + Some(delim) => match delim { + // expected case + token::OpenDelim(token::Brace) => token::CloseDelim(token::Brace), + // error recovery + token::OpenDelim(token::Paren) => { + self.sess.struct_span_error( + "error nesting on close brace", + self.span(start, self.pos), + ); + token::CloseDelim(token::Paren) + } + // error recovery + token::OpenDelim(token::Bracket) => { + self.sess.struct_span_error( + "error nesting on close brace", + self.span(start, self.pos), + ); + token::CloseDelim(token::Bracket) + } + // impossible case + _ => bug!("Impossible!"), + }, + // error recovery + None => { + self.sess.struct_span_error( + "error nesting on close brace", + self.span(start, self.pos), + ); + token::CloseDelim(token::Brace) + } + }, + kcl_lexer::TokenKind::OpenBracket => { + self.indent_cxt + .delims + .push(token::OpenDelim(token::Bracket)); + token::OpenDelim(token::Bracket) + } + kcl_lexer::TokenKind::CloseBracket => match self.indent_cxt.delims.pop() { + // check delim stack + Some(delim) => match delim { + // expected case + token::OpenDelim(token::Bracket) => token::CloseDelim(token::Bracket), + // error recovery + token::OpenDelim(token::Brace) => { + self.sess.struct_span_error( + "mismatched closing delimiter", + self.span(start, self.pos), + ); + token::CloseDelim(token::Brace) + } + // error recovery + token::OpenDelim(token::Paren) => { + self.sess.struct_span_error( + "mismatched closing delimiter", + self.span(start, self.pos), + ); + token::CloseDelim(token::Paren) + } + // impossible case + _ => bug!("Impossible!"), + }, + // error recovery + None => { + self.sess.struct_span_error( + "mismatched closing delimiter", + self.span(start, self.pos), + ); + token::CloseDelim(token::Bracket) + } + }, + kcl_lexer::TokenKind::LineContinue => return None, + kcl_lexer::TokenKind::InvalidLineContinue => { + // If we encounter an illegal line continuation character, + // we will restore it to a normal line continuation character. + self.sess.struct_message_error_with_suggestions( + ParseErrorMessage::CharAfterLineContinuationToken, + self.span(start, self.pos), + None, + ); + return None; + } + kcl_lexer::TokenKind::Semi => { + // If we encounter an illegal semi token ';', raise a friendly error. + self.sess.struct_message_error_with_suggestions( + ParseErrorMessage::RedundantSemicolon, + self.span(start, self.pos), + Some(vec!["".to_string()]), + ); + return None; + } + _ => { + self.sess + .struct_span_error("unknown start of token", self.span(start, self.pos)); + return None; + } + }) + } + + /// From the lexed tokens stack, check whether the token at the top of the stack and the current character can combine a new token. + /// If yes, lexer will pop the token at the top of the stack and return a new token combined with the token poped and the current character. + /// If not, return None. + fn look_behind( + &mut self, + tok: &kcl_lexer::Token, + tok_stream_builder: &mut TokenStreamBuilder, + ) -> Option { + match tok.kind { + // Most multi-character tokens are lexed in ['kcl-lexer'], + // and the multi-character tokens that need to be lexed in ['kcl-parser/lexer'] are only token '->'. + // If a new multi-character token is added later, the corresponding operation can be added here. + kcl_lexer::TokenKind::Gt => { + if tok_stream_builder + .pop_if_tok_kind(&TokenKind::BinOp(BinOpToken::Minus)) + .is_some() + { + // After the previous token pops up, 'self.tok_start_pos' needs to be updated. + if self.tok_start_pos >= new_byte_pos(1) { + self.tok_start_pos = self.tok_start_pos - new_byte_pos(1); + return Some(TokenKind::RArrow); + } else { + bug!("Internal Bugs: Please connect us to fix it, invalid token start pos") + } + } + } + _ => return None, + } + None + } + + fn lex_literal( + &self, + start: BytePos, + suffix_start: BytePos, + kind: kcl_lexer::LiteralKind, + ) -> (token::LitKind, Symbol, Option, Option) { + match kind { + kcl_lexer::LiteralKind::Str { + terminated, + triple_quoted, + } => { + let start_char = self.char_from(start); + let (is_raw, quote_char_pos, quote_char) = match start_char { + 'r' | 'R' => { + let pos = start + new_byte_pos(1); + (true, pos, self.char_from(pos)) + } + _ => (false, start, start_char), + }; + if !terminated { + self.sess.struct_span_error( + "unterminated string", + self.span(quote_char_pos, self.pos), + ); + } + // Cut offset before validation. + let offset: u32 = if triple_quoted { + if is_raw { 4 } else { 3 } + } else if is_raw { + 2 + } else { + 1 + }; + + let content_start = start + new_byte_pos(offset); + let mut content_end = suffix_start - new_byte_pos(offset); + if is_raw { + content_end = content_end + new_byte_pos(1); + } + // For unclosed quote string, cut offset of the string content. + if !terminated { + content_end = content_end + new_byte_pos(if triple_quoted { 3 } else { 1 }) + } + // If start > end, it is a invalid string content. + let value = if content_start > content_end { + // If get an error string from the eval process, + // directly return an empty string. + self.sess.struct_span_error( + "invalid string syntax", + self.span(content_start, self.pos), + ); + "".to_string() + } else { + let string_content = self.str_from_to(content_start, content_end); + match str_content_eval(string_content, quote_char, triple_quoted, false, is_raw) + { + Some(v) => v, + None => { + // If get an error string from the eval process, + // directly return an empty string. + self.sess.struct_span_error( + "invalid string syntax", + self.span(content_start, self.pos), + ); + "".to_string() + } + } + }; + + ( + token::Str { + is_long_string: triple_quoted, + is_raw, + }, + Symbol::intern(&value), + None, + Some(self.symbol_from_to(start, suffix_start)), + ) + } + kcl_lexer::LiteralKind::Int { base, empty_int } => { + if empty_int { + self.sess.struct_span_error( + "no valid digits found for number", + self.span(start, self.pos), + ); + // If it is a empty int, returns number 0. + (token::Integer, Symbol::intern("0"), None, None) + } else { + let symbol = if self.validate_literal_int(base, start, suffix_start) { + self.symbol_from_to(start, suffix_start) + } else { + Symbol::intern("0") + }; + + let suffix = if suffix_start < self.pos { + let suffix_str = self.str_from(suffix_start); + // int binary suffix + if !NumberBinarySuffix::all_names().contains(&suffix_str) { + self.sess.struct_span_error( + "invalid int binary suffix", + self.span(start, self.pos), + ); + None + } else { + Some(Symbol::intern(suffix_str)) + } + } else { + None + }; + + (token::Integer, symbol, suffix, None) + } + } + + kcl_lexer::LiteralKind::Float { + base, + empty_exponent, + } => { + let symbol = if self.validate_literal_float(base, start, empty_exponent) { + self.symbol_from_to(start, suffix_start) + } else { + Symbol::intern("0") + }; + (token::Float, symbol, None, None) + } + kcl_lexer::LiteralKind::Bool { terminated: _ } => ( + token::Bool, + self.symbol_from_to(start, suffix_start), + None, + None, + ), + } + } + + fn validate_literal_int( + &self, + base: Base, + content_start: BytePos, + content_end: BytePos, + ) -> bool { + let base = match base { + Base::Binary => 2, + Base::Octal => 8, + Base::Hexadecimal => 16, + Base::Decimal => return true, + }; + let s = self.str_from_to(content_start + new_byte_pos(2), content_end); + for (idx, c) in s.char_indices() { + let idx = idx as u32; + if c != '_' && c.to_digit(base).is_none() { + let lo = content_start + new_byte_pos(2 + idx); + let hi = content_start + new_byte_pos(2 + idx + c.len_utf8() as u32); + + self.sess.struct_span_error( + &format!("invalid digit for a base {base} literal, start: {lo}, stop: {hi}"), + self.span(lo, self.pos), + ); + return false; + } + } + true + } + + fn validate_literal_float(&self, base: Base, start: BytePos, empty_exponent: bool) -> bool { + if empty_exponent { + self.sess.struct_span_error( + "expected at least one digit in exponent", + self.span(start, self.pos), + ); + false + } else { + match base { + kcl_lexer::Base::Hexadecimal | kcl_lexer::Base::Octal | kcl_lexer::Base::Binary => { + self.sess.struct_span_error( + &format!("{} float literal is not supported", base.describe()), + self.span(start, self.pos), + ); + false + } + _ => true, + } + } + } + + fn span(&self, lo: BytePos, hi: BytePos) -> Span { + Span::new(lo, hi) + } + + #[inline] + fn src_index(&self, pos: BytePos) -> usize { + (pos - self.start_pos).0 as usize + } + + /// Char at `pos` in the source + fn char_from(&self, pos: BytePos) -> char { + self.src.as_bytes()[self.src_index(pos)] as char + } + + /// Slice of the source text from `start` up to but excluding `self.pos`, + /// meaning the slice does not include the character `self.ch`. + fn str_from(&self, start: BytePos) -> &str { + self.str_from_to(start, self.pos) + } + + /// Slice of the source text spanning from `start` up to but excluding `end`. + fn str_from_to(&self, start: BytePos, end: BytePos) -> &str { + &self.src[self.src_index(start)..self.src_index(end)] + } + + fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol { + Symbol::intern(self.str_from_to(start, end)) + } + + fn eof(&mut self, buf: &mut TokenStreamBuilder) { + if !self.indent_cxt.new_line_beginning { + self.indent_cxt.new_line_beginning = true; + buf.push(Token::new(token::Newline, self.span(self.pos, self.pos))); + } + + while self.indent_cxt.indents.len() > 1 { + self.indent_cxt.indents.pop(); + buf.push(Token::new( + token::Dedent(VALID_SPACES_LENGTH), + self.span(self.pos, self.pos), + )); + } + + buf.push(Token::new(token::Eof, self.span(self.pos, self.pos))); + } +} + +#[derive(Default)] +struct TokenStreamBuilder { + buf: Vec, +} + +impl TokenStreamBuilder { + fn push(&mut self, token: Token) { + self.buf.push(token) + } + + fn into_token_stream(self) -> TokenStream { + TokenStream::new(self.buf) + } + + /// Pop the token at the top of the stack, and return None if the stack is empty. + fn pop(&mut self) -> Option { + self.buf.pop() + } + + /// If the token kind at the top of the stack is 'expected_tok_kind', + /// pop the token and return it, otherwise do nothing and return None. + fn pop_if_tok_kind(&mut self, expected_tok_kind: &TokenKind) -> Option { + if self.peek_tok_kind() == expected_tok_kind { + self.pop() + } else { + None + } + } + + /// Peek the kind of the token on the top of the stack. + fn peek_tok_kind(&self) -> &TokenKind { + match self.buf.last() { + Some(tok) => &tok.kind, + None => &TokenKind::Dummy, + } + } +} diff --git a/kclvm/parser/src/lexer/string.rs b/crates/parser/src/lexer/string.rs similarity index 100% rename from kclvm/parser/src/lexer/string.rs rename to crates/parser/src/lexer/string.rs diff --git a/crates/parser/src/lexer/tests.rs b/crates/parser/src/lexer/tests.rs new file mode 100644 index 000000000..958cb88e7 --- /dev/null +++ b/crates/parser/src/lexer/tests.rs @@ -0,0 +1,851 @@ +use super::*; +use crate::lexer::str_content_eval; +use crate::session::ParseSession; +use compiler_base_error::diagnostic_handler::DiagnosticHandler; +use compiler_base_session::Session; +use compiler_base_span::{FilePathMapping, SourceMap, span::new_byte_pos}; +use expect_test::{Expect, expect}; +use kcl_error::Handler; +use kcl_span::create_session_globals_then; +use parking_lot::RwLock; +use std::path::PathBuf; +use std::sync::Arc; + +impl ParseSession { + #[inline] + pub(crate) fn with_source_map(sm: Arc) -> Self { + Self( + Arc::new(Session::new(sm, Arc::new(DiagnosticHandler::default()))), + RwLock::new(Handler::default()), + ) + } +} + +/// lexing the 'src'. +fn lex(src: &str) -> (String, String) { + let sm = SourceMap::new(FilePathMapping::empty()); + sm.new_source_file(PathBuf::from("").into(), src.to_string()); + let sess = &ParseSession::with_source_map(Arc::new(sm)); + + // preprocess the input str by [`SourceFile`] + let sf = sess + .0 + .sm + .new_source_file(PathBuf::from("").into(), src.to_string()); + + let src_from_sf = match sf.src.as_ref() { + Some(src) => src, + None => { + panic!("Unreachable code") + } + }; + + let res = create_session_globals_then(|| { + parse_token_streams(sess, src_from_sf, new_byte_pos(0)) + .iter() + .map(|token| format!("{:?}\n", token)) + .collect() + }); + + let err_msgs = sess + .0 + .emit_all_diags_into_string() + .unwrap() + .iter() + .map(|err| err.as_ref().unwrap().to_string()) + .collect(); + + (res, err_msgs) +} + +/// check the invalid panic message. +fn check_lexing_with_err_msg(src: &str, expect: Expect, expect_err_msg: Expect) { + let (got, got_err) = lex(src); + expect.assert_eq(&got); + expect_err_msg.assert_eq(&got_err); +} + +fn check_lexing(src: &str, expect: Expect) { + expect.assert_eq(&lex(src).0); +} + +// Get the code snippets from 'src' by token.span, and compare with expect. +fn check_span(src: &str, expect: Expect) { + let sm = SourceMap::new(FilePathMapping::empty()); + sm.new_source_file(PathBuf::from("").into(), src.to_string()); + let sess = &ParseSession::with_source_map(Arc::new(SourceMap::new(FilePathMapping::empty()))); + + create_session_globals_then(move || { + let actual: String = parse_token_streams(sess, src, new_byte_pos(0)) + .iter() + .map(|token| format!("{:?}\n", sm.span_to_snippet(token.span).unwrap())) + .collect(); + expect.assert_eq(&actual) + }); +} + +#[test] +fn test_str_content_eval() { + let cases = [ + // true cases + (("1", '\'', false, false, false), Some("1".to_string())), + (("1", '"', false, false, false), Some("1".to_string())), + ( + ("1\\n2", '"', false, false, false), + Some("1\n2".to_string()), + ), + ( + ("1\\n2", '"', false, false, true), + Some("1\\n2".to_string()), + ), + (("1\\2", '"', false, false, true), Some("1\\2".to_string())), + (("1", '\'', true, false, false), Some("1".to_string())), + (("1", '"', true, false, false), Some("1".to_string())), + (("1\n2", '"', true, false, false), Some("1\n2".to_string())), + ]; + for ((input, quote_char, triple_quoted, is_bytes, is_raw), expected) in cases { + assert_eq!( + str_content_eval(input, quote_char, triple_quoted, is_bytes, is_raw), + expected, + "test failed, input: {input}" + ) + } +} + +#[test] +fn smoke_test() { + check_lexing( + "lambda { println(\"kcl\") }\n", + expect![[r#" + Token { kind: Ident(Symbol(SymbolIndex { idx: 18 })), span: Span { base_or_index: 0, len_or_tag: 6 } } + Token { kind: OpenDelim(Brace), span: Span { base_or_index: 7, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 9, len_or_tag: 7 } } + Token { kind: OpenDelim(Paren), span: Span { base_or_index: 16, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 43 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 44 })) }), span: Span { base_or_index: 17, len_or_tag: 5 } } + Token { kind: CloseDelim(Paren), span: Span { base_or_index: 22, len_or_tag: 1 } } + Token { kind: CloseDelim(Brace), span: Span { base_or_index: 24, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 25, len_or_tag: 1 } } + Token { kind: Eof, span: Span { base_or_index: 26, len_or_tag: 0 } } + "#]], + ) +} + +#[test] +fn comment_flavors() { + check_lexing( + r" +# line +", + expect![[r#" + Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: DocComment(Line(Symbol(SymbolIndex { idx: 42 }))), span: Span { base_or_index: 1, len_or_tag: 6 } } + Token { kind: Newline, span: Span { base_or_index: 7, len_or_tag: 1 } } + Token { kind: Eof, span: Span { base_or_index: 8, len_or_tag: 0 } } +"#]], + ) +} + +#[test] +fn simple_tokens() { + check_lexing( + r####" +, +. +( +) +{ +} +[ +] +@ +# +~ +? +: +$ += +! +< +> +== +!= +>= +<= +- +& +| ++ +* +/ +^ +% +** +// +<< +>> +... ++= +-= +*= +/= +%= +&= +|= +^= +**= +//= +<<= +>>= +-> +"####, + expect![[r#" + Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: Comma, span: Span { base_or_index: 1, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 2, len_or_tag: 1 } } + Token { kind: Dot, span: Span { base_or_index: 3, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 4, len_or_tag: 1 } } + Token { kind: OpenDelim(Paren), span: Span { base_or_index: 5, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 6, len_or_tag: 1 } } + Token { kind: CloseDelim(Paren), span: Span { base_or_index: 7, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 8, len_or_tag: 1 } } + Token { kind: OpenDelim(Brace), span: Span { base_or_index: 9, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 10, len_or_tag: 1 } } + Token { kind: CloseDelim(Brace), span: Span { base_or_index: 11, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 12, len_or_tag: 1 } } + Token { kind: OpenDelim(Bracket), span: Span { base_or_index: 13, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 14, len_or_tag: 1 } } + Token { kind: CloseDelim(Bracket), span: Span { base_or_index: 15, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 16, len_or_tag: 1 } } + Token { kind: At, span: Span { base_or_index: 17, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 18, len_or_tag: 1 } } + Token { kind: DocComment(Line(Symbol(SymbolIndex { idx: 42 }))), span: Span { base_or_index: 19, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 20, len_or_tag: 1 } } + Token { kind: UnaryOp(UTilde), span: Span { base_or_index: 21, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 22, len_or_tag: 1 } } + Token { kind: Question, span: Span { base_or_index: 23, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 24, len_or_tag: 1 } } + Token { kind: Colon, span: Span { base_or_index: 25, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 26, len_or_tag: 1 } } + Token { kind: Dollar, span: Span { base_or_index: 27, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 28, len_or_tag: 1 } } + Token { kind: Assign, span: Span { base_or_index: 29, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 30, len_or_tag: 1 } } + Token { kind: UnaryOp(UNot), span: Span { base_or_index: 31, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 32, len_or_tag: 1 } } + Token { kind: BinCmp(Lt), span: Span { base_or_index: 33, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 34, len_or_tag: 1 } } + Token { kind: BinCmp(Gt), span: Span { base_or_index: 35, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 36, len_or_tag: 1 } } + Token { kind: BinCmp(Eq), span: Span { base_or_index: 37, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 39, len_or_tag: 1 } } + Token { kind: BinCmp(NotEq), span: Span { base_or_index: 40, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 42, len_or_tag: 1 } } + Token { kind: BinCmp(GtEq), span: Span { base_or_index: 43, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 45, len_or_tag: 1 } } + Token { kind: BinCmp(LtEq), span: Span { base_or_index: 46, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 48, len_or_tag: 1 } } + Token { kind: BinOp(Minus), span: Span { base_or_index: 49, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 50, len_or_tag: 1 } } + Token { kind: BinOp(And), span: Span { base_or_index: 51, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 52, len_or_tag: 1 } } + Token { kind: BinOp(Or), span: Span { base_or_index: 53, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 54, len_or_tag: 1 } } + Token { kind: BinOp(Plus), span: Span { base_or_index: 55, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 56, len_or_tag: 1 } } + Token { kind: BinOp(Star), span: Span { base_or_index: 57, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 58, len_or_tag: 1 } } + Token { kind: BinOp(Slash), span: Span { base_or_index: 59, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 60, len_or_tag: 1 } } + Token { kind: BinOp(Caret), span: Span { base_or_index: 61, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 62, len_or_tag: 1 } } + Token { kind: BinOp(Percent), span: Span { base_or_index: 63, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 64, len_or_tag: 1 } } + Token { kind: BinOp(StarStar), span: Span { base_or_index: 65, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 67, len_or_tag: 1 } } + Token { kind: BinOp(SlashSlash), span: Span { base_or_index: 68, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 70, len_or_tag: 1 } } + Token { kind: BinOp(Shl), span: Span { base_or_index: 71, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 73, len_or_tag: 1 } } + Token { kind: BinOp(Shr), span: Span { base_or_index: 74, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 76, len_or_tag: 1 } } + Token { kind: DotDotDot, span: Span { base_or_index: 77, len_or_tag: 3 } } + Token { kind: Newline, span: Span { base_or_index: 80, len_or_tag: 1 } } + Token { kind: BinOpEq(Plus), span: Span { base_or_index: 81, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 83, len_or_tag: 1 } } + Token { kind: BinOpEq(Minus), span: Span { base_or_index: 84, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 86, len_or_tag: 1 } } + Token { kind: BinOpEq(Star), span: Span { base_or_index: 87, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 89, len_or_tag: 1 } } + Token { kind: BinOpEq(Slash), span: Span { base_or_index: 90, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 92, len_or_tag: 1 } } + Token { kind: BinOpEq(Percent), span: Span { base_or_index: 93, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 95, len_or_tag: 1 } } + Token { kind: BinOpEq(And), span: Span { base_or_index: 96, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 98, len_or_tag: 1 } } + Token { kind: BinOpEq(Or), span: Span { base_or_index: 99, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 101, len_or_tag: 1 } } + Token { kind: BinOpEq(Caret), span: Span { base_or_index: 102, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 104, len_or_tag: 1 } } + Token { kind: BinOpEq(StarStar), span: Span { base_or_index: 105, len_or_tag: 3 } } + Token { kind: Newline, span: Span { base_or_index: 108, len_or_tag: 1 } } + Token { kind: BinOpEq(SlashSlash), span: Span { base_or_index: 109, len_or_tag: 3 } } + Token { kind: Newline, span: Span { base_or_index: 112, len_or_tag: 1 } } + Token { kind: BinOpEq(Shl), span: Span { base_or_index: 113, len_or_tag: 3 } } + Token { kind: Newline, span: Span { base_or_index: 116, len_or_tag: 1 } } + Token { kind: BinOpEq(Shr), span: Span { base_or_index: 117, len_or_tag: 3 } } + Token { kind: Newline, span: Span { base_or_index: 120, len_or_tag: 1 } } + Token { kind: RArrow, span: Span { base_or_index: 121, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 123, len_or_tag: 1 } } + Token { kind: Eof, span: Span { base_or_index: 124, len_or_tag: 0 } } + "#]], + ) +} + +#[test] +fn nonstring_literal() { + check_lexing( + r####" +1234 +0b101 +0xABC +1.0 +1.0e10 +0777 +0077 +1Ki +"####, + expect![[r#" + Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: None }), span: Span { base_or_index: 1, len_or_tag: 4 } } + Token { kind: Newline, span: Span { base_or_index: 5, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 43 }), suffix: None, raw: None }), span: Span { base_or_index: 6, len_or_tag: 5 } } + Token { kind: Newline, span: Span { base_or_index: 11, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 44 }), suffix: None, raw: None }), span: Span { base_or_index: 12, len_or_tag: 5 } } + Token { kind: Newline, span: Span { base_or_index: 17, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Float, symbol: Symbol(SymbolIndex { idx: 45 }), suffix: None, raw: None }), span: Span { base_or_index: 18, len_or_tag: 3 } } + Token { kind: Newline, span: Span { base_or_index: 21, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Float, symbol: Symbol(SymbolIndex { idx: 46 }), suffix: None, raw: None }), span: Span { base_or_index: 22, len_or_tag: 6 } } + Token { kind: Newline, span: Span { base_or_index: 28, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 47 }), suffix: None, raw: None }), span: Span { base_or_index: 29, len_or_tag: 4 } } + Token { kind: Newline, span: Span { base_or_index: 33, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 48 }), suffix: None, raw: None }), span: Span { base_or_index: 34, len_or_tag: 4 } } + Token { kind: Newline, span: Span { base_or_index: 38, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 33 }), suffix: Some(Symbol(SymbolIndex { idx: 49 })), raw: None }), span: Span { base_or_index: 39, len_or_tag: 3 } } + Token { kind: Newline, span: Span { base_or_index: 42, len_or_tag: 1 } } + Token { kind: Eof, span: Span { base_or_index: 43, len_or_tag: 0 } } + "#]], + ) +} + +#[test] +fn string_literal() { + check_lexing( + r####" +'a' +"a" +'''a''' +"""a""" +r'a' +r"a" +r'''a''' +r"""a""" +R'a' +R"a" +R'''a''' +R"""a""" +"####, + expect![[r#" + Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 43 })) }), span: Span { base_or_index: 1, len_or_tag: 3 } } + Token { kind: Newline, span: Span { base_or_index: 4, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 44 })) }), span: Span { base_or_index: 5, len_or_tag: 3 } } + Token { kind: Newline, span: Span { base_or_index: 8, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: true, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 45 })) }), span: Span { base_or_index: 9, len_or_tag: 7 } } + Token { kind: Newline, span: Span { base_or_index: 16, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: true, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 46 })) }), span: Span { base_or_index: 17, len_or_tag: 7 } } + Token { kind: Newline, span: Span { base_or_index: 24, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 47 })) }), span: Span { base_or_index: 25, len_or_tag: 4 } } + Token { kind: Newline, span: Span { base_or_index: 29, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 48 })) }), span: Span { base_or_index: 30, len_or_tag: 4 } } + Token { kind: Newline, span: Span { base_or_index: 34, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: true, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 49 })) }), span: Span { base_or_index: 35, len_or_tag: 8 } } + Token { kind: Newline, span: Span { base_or_index: 43, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: true, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 50 })) }), span: Span { base_or_index: 44, len_or_tag: 8 } } + Token { kind: Newline, span: Span { base_or_index: 52, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 51 })) }), span: Span { base_or_index: 53, len_or_tag: 4 } } + Token { kind: Newline, span: Span { base_or_index: 57, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 52 })) }), span: Span { base_or_index: 58, len_or_tag: 4 } } + Token { kind: Newline, span: Span { base_or_index: 62, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: true, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 53 })) }), span: Span { base_or_index: 63, len_or_tag: 8 } } + Token { kind: Newline, span: Span { base_or_index: 71, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: true, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 54 })) }), span: Span { base_or_index: 72, len_or_tag: 8 } } + Token { kind: Newline, span: Span { base_or_index: 80, len_or_tag: 1 } } + Token { kind: Eof, span: Span { base_or_index: 81, len_or_tag: 0 } } + "#]], + ) +} + +#[test] +fn indents() { + check_lexing( + r####" +if test0: + if test1: + println("true true") + else: + println("true false") +println("end") +"####, + expect![[r#" + Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 10 })), span: Span { base_or_index: 1, len_or_tag: 2 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 4, len_or_tag: 5 } } + Token { kind: Colon, span: Span { base_or_index: 9, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 10, len_or_tag: 1 } } + Token { kind: Indent(0), span: Span { base_or_index: 15, len_or_tag: 0 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 10 })), span: Span { base_or_index: 15, len_or_tag: 2 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 18, len_or_tag: 5 } } + Token { kind: Colon, span: Span { base_or_index: 23, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 24, len_or_tag: 1 } } + Token { kind: Indent(0), span: Span { base_or_index: 33, len_or_tag: 0 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 44 })), span: Span { base_or_index: 33, len_or_tag: 7 } } + Token { kind: OpenDelim(Paren), span: Span { base_or_index: 40, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 45 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 46 })) }), span: Span { base_or_index: 41, len_or_tag: 11 } } + Token { kind: CloseDelim(Paren), span: Span { base_or_index: 52, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 53, len_or_tag: 1 } } + Token { kind: Dedent(0), span: Span { base_or_index: 58, len_or_tag: 0 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 12 })), span: Span { base_or_index: 58, len_or_tag: 4 } } + Token { kind: Colon, span: Span { base_or_index: 62, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 63, len_or_tag: 1 } } + Token { kind: Indent(0), span: Span { base_or_index: 72, len_or_tag: 0 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 44 })), span: Span { base_or_index: 72, len_or_tag: 7 } } + Token { kind: OpenDelim(Paren), span: Span { base_or_index: 79, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 47 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 48 })) }), span: Span { base_or_index: 80, len_or_tag: 12 } } + Token { kind: CloseDelim(Paren), span: Span { base_or_index: 92, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 93, len_or_tag: 1 } } + Token { kind: Dedent(0), span: Span { base_or_index: 94, len_or_tag: 0 } } + Token { kind: Dedent(0), span: Span { base_or_index: 94, len_or_tag: 0 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 44 })), span: Span { base_or_index: 94, len_or_tag: 7 } } + Token { kind: OpenDelim(Paren), span: Span { base_or_index: 101, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 49 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 50 })) }), span: Span { base_or_index: 102, len_or_tag: 5 } } + Token { kind: CloseDelim(Paren), span: Span { base_or_index: 107, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 108, len_or_tag: 1 } } + Token { kind: Eof, span: Span { base_or_index: 109, len_or_tag: 0 } } + "#]], + ) +} + +#[test] +fn binary_expr_0() { + check_lexing( + r####"1 + a or b"####, + expect![[r#" + Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 33 }), suffix: None, raw: None }), span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: BinOp(Plus), span: Span { base_or_index: 2, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 4, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 13 })), span: Span { base_or_index: 6, len_or_tag: 2 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 9, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 10, len_or_tag: 0 } } + Token { kind: Eof, span: Span { base_or_index: 10, len_or_tag: 0 } } + "#]], + ); +} + +#[test] +fn schema_expr_0() { + check_lexing( + r####" +Schema (1, 2) { + k=v +} +"####, + expect![[r#" + Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 1, len_or_tag: 6 } } + Token { kind: OpenDelim(Paren), span: Span { base_or_index: 8, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 33 }), suffix: None, raw: None }), span: Span { base_or_index: 9, len_or_tag: 1 } } + Token { kind: Comma, span: Span { base_or_index: 10, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 34 }), suffix: None, raw: None }), span: Span { base_or_index: 12, len_or_tag: 1 } } + Token { kind: CloseDelim(Paren), span: Span { base_or_index: 13, len_or_tag: 1 } } + Token { kind: OpenDelim(Brace), span: Span { base_or_index: 15, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 16, len_or_tag: 1 } } + Token { kind: Indent(0), span: Span { base_or_index: 21, len_or_tag: 0 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 21, len_or_tag: 1 } } + Token { kind: Assign, span: Span { base_or_index: 22, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 44 })), span: Span { base_or_index: 23, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 24, len_or_tag: 1 } } + Token { kind: Dedent(0), span: Span { base_or_index: 25, len_or_tag: 0 } } + Token { kind: CloseDelim(Brace), span: Span { base_or_index: 25, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 26, len_or_tag: 1 } } + Token { kind: Eof, span: Span { base_or_index: 27, len_or_tag: 0 } } + "#]], + ); +} + +#[test] +fn schema_expr_1() { + check_lexing( + r####"Schema (1, 2) { + k=v +}"####, + expect![[r#" + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 0, len_or_tag: 6 } } + Token { kind: OpenDelim(Paren), span: Span { base_or_index: 7, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 33 }), suffix: None, raw: None }), span: Span { base_or_index: 8, len_or_tag: 1 } } + Token { kind: Comma, span: Span { base_or_index: 9, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 34 }), suffix: None, raw: None }), span: Span { base_or_index: 11, len_or_tag: 1 } } + Token { kind: CloseDelim(Paren), span: Span { base_or_index: 12, len_or_tag: 1 } } + Token { kind: OpenDelim(Brace), span: Span { base_or_index: 14, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 15, len_or_tag: 1 } } + Token { kind: Indent(0), span: Span { base_or_index: 20, len_or_tag: 0 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 20, len_or_tag: 1 } } + Token { kind: Assign, span: Span { base_or_index: 21, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 44 })), span: Span { base_or_index: 22, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 23, len_or_tag: 1 } } + Token { kind: Dedent(0), span: Span { base_or_index: 24, len_or_tag: 0 } } + Token { kind: CloseDelim(Brace), span: Span { base_or_index: 24, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 25, len_or_tag: 0 } } + Token { kind: Eof, span: Span { base_or_index: 25, len_or_tag: 0 } } + "#]], + ); +} + +#[test] +fn test_peek() { + let src = "\na=1"; + let sm = SourceMap::new(FilePathMapping::empty()); + sm.new_source_file(PathBuf::from("").into(), src.to_string()); + let sess = ParseSession::with_source_map(Arc::new(sm)); + + create_session_globals_then(|| { + let stream = parse_token_streams(&sess, src, new_byte_pos(0)); + let mut cursor = stream.cursor(); + + let tok0 = cursor.next(); + assert_eq!( + format!("{tok0:?}"), + "Some(Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } })" + ); + + let peek = cursor.peek(); + assert_eq!( + format!("{peek:?}"), + "Some(Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 1, len_or_tag: 1 } })" + ); + }); +} + +#[test] +fn test_assign_stmt() { + check_lexing( + r####" +a=1 +"####, + expect![[r#" + Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 1, len_or_tag: 1 } } + Token { kind: Assign, span: Span { base_or_index: 2, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 33 }), suffix: None, raw: None }), span: Span { base_or_index: 3, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 4, len_or_tag: 1 } } + Token { kind: Eof, span: Span { base_or_index: 5, len_or_tag: 0 } } + "#]], + ) +} + +#[test] +fn test_token_span() { + let src = r#" +schema Person: + name: str = "kcl" + +x0 = Person {} + "#; + check_span( + src, + expect![ + r#""\n" +"schema" +"Person" +":" +"\n" +"" +"name" +":" +"str" +"=" +"\"kcl\"" +"\n" +"\n" +"" +"x0" +"=" +"Person" +"{" +"}" +"\n" +"" +"# + ], + ) +} + +#[test] +fn test_source_file() { + let src = "\r\n\r\n\r\r\n\n\n\r".to_string(); + let sm = kcl_span::SourceMap::new(FilePathMapping::empty()); + let sf = sm.new_source_file(PathBuf::from("").into(), src); + match sf.src.as_ref() { + Some(src_from_sf) => { + assert_eq!(src_from_sf.as_str(), "\n\n\r\n\n\n\r"); + } + None => { + unreachable!(); + } + }; +} + +#[test] +fn test_parse_token_stream() { + check_lexing( + "\n\r\n\r\n\r\r\n", + expect![[r#" + Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 1, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 2, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 4, len_or_tag: 1 } } + Token { kind: Eof, span: Span { base_or_index: 5, len_or_tag: 0 } } + "#]], + ); +} + +#[cfg(target_os = "windows")] +#[test] +fn test_parse_token_stream_on_win() { + use std::{fs, path::Path}; + let src = fs::read_to_string( + Path::new(".") + .join("testdata") + .join("hello_win.k") + .display() + .to_string(), + ) + .unwrap(); + assert_eq!( + src, + "\r\nschema Person:\r\n name: str = \"kcl\"\r\n\r\nx0 = Person {}\r\n" + ); + + check_lexing( + &src, + expect![[r#" + Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 4 })), span: Span { base_or_index: 1, len_or_tag: 6 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 8, len_or_tag: 6 } } + Token { kind: Colon, span: Span { base_or_index: 14, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 15, len_or_tag: 1 } } + Token { kind: Indent(0), span: Span { base_or_index: 20, len_or_tag: 0 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 20, len_or_tag: 4 } } + Token { kind: Colon, span: Span { base_or_index: 24, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 31 })), span: Span { base_or_index: 26, len_or_tag: 3 } } + Token { kind: Assign, span: Span { base_or_index: 30, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 44 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 45 })) }), span: Span { base_or_index: 32, len_or_tag: 5 } } + Token { kind: Newline, span: Span { base_or_index: 37, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 38, len_or_tag: 1 } } + Token { kind: Dedent(0), span: Span { base_or_index: 39, len_or_tag: 0 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 46 })), span: Span { base_or_index: 39, len_or_tag: 2 } } + Token { kind: Assign, span: Span { base_or_index: 42, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 44, len_or_tag: 6 } } + Token { kind: OpenDelim(Brace), span: Span { base_or_index: 51, len_or_tag: 1 } } + Token { kind: CloseDelim(Brace), span: Span { base_or_index: 52, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 53, len_or_tag: 1 } } + Token { kind: Eof, span: Span { base_or_index: 54, len_or_tag: 0 } } + "#]], + ); +} + +#[test] +fn test_rarrow() { + check_lexing( + "lambda x: int, y: int -> int { x + y }\n", + expect![[r#" + Token { kind: Ident(Symbol(SymbolIndex { idx: 18 })), span: Span { base_or_index: 0, len_or_tag: 6 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 7, len_or_tag: 1 } } + Token { kind: Colon, span: Span { base_or_index: 8, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 10, len_or_tag: 3 } } + Token { kind: Comma, span: Span { base_or_index: 13, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 15, len_or_tag: 1 } } + Token { kind: Colon, span: Span { base_or_index: 16, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 18, len_or_tag: 3 } } + Token { kind: RArrow, span: Span { base_or_index: 22, len_or_tag: 2 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 25, len_or_tag: 3 } } + Token { kind: OpenDelim(Brace), span: Span { base_or_index: 29, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 31, len_or_tag: 1 } } + Token { kind: BinOp(Plus), span: Span { base_or_index: 33, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 35, len_or_tag: 1 } } + Token { kind: CloseDelim(Brace), span: Span { base_or_index: 37, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 38, len_or_tag: 1 } } + Token { kind: Eof, span: Span { base_or_index: 39, len_or_tag: 0 } } + "#]], + ); +} + +#[test] +fn test_minus_unicode_gt_invalid() { + check_lexing_with_err_msg( + "lambda x: int, y: int -\u{feff}> int { x + y }\n", + expect![[r#" + Token { kind: Ident(Symbol(SymbolIndex { idx: 18 })), span: Span { base_or_index: 0, len_or_tag: 6 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 7, len_or_tag: 1 } } + Token { kind: Colon, span: Span { base_or_index: 8, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 10, len_or_tag: 3 } } + Token { kind: Comma, span: Span { base_or_index: 13, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 15, len_or_tag: 1 } } + Token { kind: Colon, span: Span { base_or_index: 16, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 18, len_or_tag: 3 } } + Token { kind: RArrow, span: Span { base_or_index: 25, len_or_tag: 2 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 28, len_or_tag: 3 } } + Token { kind: OpenDelim(Brace), span: Span { base_or_index: 32, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 34, len_or_tag: 1 } } + Token { kind: BinOp(Plus), span: Span { base_or_index: 36, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 38, len_or_tag: 1 } } + Token { kind: CloseDelim(Brace), span: Span { base_or_index: 40, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 41, len_or_tag: 1 } } + Token { kind: Eof, span: Span { base_or_index: 42, len_or_tag: 0 } } + "#]], + expect![["error[E1001]: InvalidSyntax\nunknown start of token\n\n"]], + ); +} + +#[test] +fn test_unicode_minus_gt_invalid() { + check_lexing_with_err_msg( + "lambda x: int, y: int \u{feff}-> int { x + y }\n", + expect![[r#" + Token { kind: Ident(Symbol(SymbolIndex { idx: 18 })), span: Span { base_or_index: 0, len_or_tag: 6 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 7, len_or_tag: 1 } } + Token { kind: Colon, span: Span { base_or_index: 8, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 10, len_or_tag: 3 } } + Token { kind: Comma, span: Span { base_or_index: 13, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 15, len_or_tag: 1 } } + Token { kind: Colon, span: Span { base_or_index: 16, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 18, len_or_tag: 3 } } + Token { kind: RArrow, span: Span { base_or_index: 25, len_or_tag: 2 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 28, len_or_tag: 3 } } + Token { kind: OpenDelim(Brace), span: Span { base_or_index: 32, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 34, len_or_tag: 1 } } + Token { kind: BinOp(Plus), span: Span { base_or_index: 36, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 38, len_or_tag: 1 } } + Token { kind: CloseDelim(Brace), span: Span { base_or_index: 40, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 41, len_or_tag: 1 } } + Token { kind: Eof, span: Span { base_or_index: 42, len_or_tag: 0 } } + "#]], + expect![["error[E1001]: InvalidSyntax\nunknown start of token\n\n"]], + ); +} + +#[test] +fn test_minus_gt_unicode_invalid() { + check_lexing_with_err_msg( + "lambda x: int, y: int ->\u{feff} int { x + y }\n", + expect![[r#" + Token { kind: Ident(Symbol(SymbolIndex { idx: 18 })), span: Span { base_or_index: 0, len_or_tag: 6 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 7, len_or_tag: 1 } } + Token { kind: Colon, span: Span { base_or_index: 8, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 10, len_or_tag: 3 } } + Token { kind: Comma, span: Span { base_or_index: 13, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 15, len_or_tag: 1 } } + Token { kind: Colon, span: Span { base_or_index: 16, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 18, len_or_tag: 3 } } + Token { kind: RArrow, span: Span { base_or_index: 22, len_or_tag: 2 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 28, len_or_tag: 3 } } + Token { kind: OpenDelim(Brace), span: Span { base_or_index: 32, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 34, len_or_tag: 1 } } + Token { kind: BinOp(Plus), span: Span { base_or_index: 36, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 38, len_or_tag: 1 } } + Token { kind: CloseDelim(Brace), span: Span { base_or_index: 40, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 41, len_or_tag: 1 } } + Token { kind: Eof, span: Span { base_or_index: 42, len_or_tag: 0 } } + "#]], + expect![["error[E1001]: InvalidSyntax\nunknown start of token\n\n"]], + ); +} + +#[test] +fn test_only_minus() { + check_lexing( + "-", + expect![[r#" + Token { kind: BinOp(Minus), span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 1, len_or_tag: 0 } } + Token { kind: Eof, span: Span { base_or_index: 1, len_or_tag: 0 } } + "#]], + ); +} + +#[test] +fn test_begin_with_minus() { + check_lexing( + "-123", + expect![[r#" + Token { kind: BinOp(Minus), span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: None }), span: Span { base_or_index: 1, len_or_tag: 3 } } + Token { kind: Newline, span: Span { base_or_index: 4, len_or_tag: 0 } } + Token { kind: Eof, span: Span { base_or_index: 4, len_or_tag: 0 } } + "#]], + ); +} + +#[test] +fn test_only_gt() { + check_lexing( + ">", + expect![[r#" + Token { kind: BinCmp(Gt), span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: Newline, span: Span { base_or_index: 1, len_or_tag: 0 } } + Token { kind: Eof, span: Span { base_or_index: 1, len_or_tag: 0 } } + "#]], + ); +} + +#[test] +fn test_begin_with_gt() { + check_lexing( + ">sdjkd + ==", + expect![[r#" + Token { kind: BinCmp(Gt), span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 1, len_or_tag: 5 } } + Token { kind: BinOp(Plus), span: Span { base_or_index: 7, len_or_tag: 1 } } + Token { kind: BinCmp(Eq), span: Span { base_or_index: 9, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 11, len_or_tag: 0 } } + Token { kind: Eof, span: Span { base_or_index: 11, len_or_tag: 0 } } + "#]], + ); +} + +#[test] +fn test_double_rarrow() { + check_lexing( + "->->", + expect![[r#" + Token { kind: RArrow, span: Span { base_or_index: 0, len_or_tag: 2 } } + Token { kind: RArrow, span: Span { base_or_index: 2, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 4, len_or_tag: 0 } } + Token { kind: Eof, span: Span { base_or_index: 4, len_or_tag: 0 } } + "#]], + ); +} + +#[test] +fn test_mess_rarrow() { + check_lexing( + "-->>->", + expect![[r#" + Token { kind: BinOp(Minus), span: Span { base_or_index: 0, len_or_tag: 1 } } + Token { kind: BinOp(Minus), span: Span { base_or_index: 1, len_or_tag: 1 } } + Token { kind: BinOp(Shr), span: Span { base_or_index: 2, len_or_tag: 2 } } + Token { kind: RArrow, span: Span { base_or_index: 4, len_or_tag: 2 } } + Token { kind: Newline, span: Span { base_or_index: 6, len_or_tag: 0 } } + Token { kind: Eof, span: Span { base_or_index: 6, len_or_tag: 0 } } + "#]], + ); +} diff --git a/crates/parser/src/lib.rs b/crates/parser/src/lib.rs new file mode 100644 index 000000000..63e2aa094 --- /dev/null +++ b/crates/parser/src/lib.rs @@ -0,0 +1,1312 @@ +//! Copyright The KCL Authors. All rights reserved. + +pub mod entry; +pub mod file_graph; +mod lexer; +mod parser; +mod session; + +#[cfg(test)] +mod tests; + +extern crate kcl_error; + +use crate::entry::get_compile_entries_from_paths; +pub use crate::session::{ParseSession, ParseSessionRef}; +use compiler_base_macros::bug; +use compiler_base_session::Session; +use compiler_base_span::span::new_byte_pos; +use file_graph::{Pkg, PkgFile, PkgFileGraph, PkgMap, toposort}; +use kcl_ast::ast::Module; +use kcl_ast::{MAIN_PKG, ast}; +use kcl_config::modfile::{KCL_FILE_EXTENSION, KCL_FILE_SUFFIX, KCL_MOD_FILE, get_vendor_home}; +use kcl_error::diagnostic::{Errors, Range}; +use kcl_error::{ErrorKind, Message, Position, Style}; +use kcl_primitives::IndexMap; +use kcl_sema::plugin::PLUGIN_MODULE_PREFIX; +use kcl_utils::path::PathPrefix; +use kcl_utils::pkgpath::parse_external_pkg_name; +use kcl_utils::pkgpath::rm_external_pkg_name; + +use anyhow::Result; +use lexer::parse_token_streams; +use parser::Parser; +use std::collections::{HashMap, HashSet, VecDeque}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, RwLock}; + +use kcl_span::create_session_globals_then; + +#[derive(Default, Debug)] +/// [`PkgInfo`] is some basic information about a kcl package. +pub(crate) struct PkgInfo { + /// the name of the kcl package. + pkg_name: String, + /// path to save the package locally. e.g. /usr/xxx + pkg_root: String, + /// package path. e.g. konfig.base.xxx + pkg_path: String, + /// The kcl files that need to be compiled in this package. + k_files: Vec, +} + +impl PkgInfo { + /// New a [`PkgInfo`]. + pub(crate) fn new( + pkg_name: String, + pkg_root: String, + pkg_path: String, + k_files: Vec, + ) -> Self { + PkgInfo { + pkg_name, + pkg_root, + pkg_path, + k_files, + } + } +} + +/// parser mode +#[derive(Debug, Clone)] +pub enum ParseMode { + Null, + ParseComments, +} + +/// LoadProgramResult denotes the result of the whole program and a topological +/// ordering of all known files, +#[derive(Debug, Clone)] +pub struct LoadProgramResult { + /// Program AST + pub program: ast::Program, + /// Parse errors + pub errors: Errors, + /// The topological ordering of all known files. + pub paths: Vec, +} + +/// ParseFileResult denotes the result of a single file including AST, +/// errors and import dependencies. +#[derive(Debug, Clone)] +pub struct ParseFileResult { + /// Module AST + pub module: ast::Module, + /// Parse errors + pub errors: Errors, + /// Dependency paths. + pub deps: Vec, +} + +/// Parse a KCL file to the AST module with parse errors. +pub fn parse_single_file(filename: &str, code: Option) -> Result { + let filename = filename.adjust_canonicalization(); + let sess = Arc::new(ParseSession::default()); + let mut loader = Loader::new( + sess, + &[&filename], + Some(LoadProgramOptions { + load_packages: false, + k_code_list: if let Some(code) = code { + vec![code] + } else { + vec![] + }, + ..Default::default() + }), + None, + ); + let result = loader.load_main()?; + let module = match result.program.get_main_package_first_module() { + Some(module) => module.clone(), + None => ast::Module::default(), + }; + let file_graph = match loader.file_graph.read() { + Ok(file_graph) => file_graph, + Err(e) => { + return Err(anyhow::anyhow!( + "Failed to read KCL file graph. Because '{e}'" + )); + } + }; + let file = PkgFile::new(PathBuf::from(filename), MAIN_PKG.to_string()); + let deps = if file_graph.contains_file(&file) { + file_graph.dependencies_of(&file).into_iter().collect() + } else { + vec![] + }; + Ok(ParseFileResult { + module, + errors: result.errors.clone(), + deps, + }) +} + +/// Parse a KCL file to the AST module and return errors when meets parse errors as result. +pub fn parse_file_force_errors(filename: &str, code: Option) -> Result { + let sess = Arc::new(ParseSession::default()); + let result = parse_file_with_global_session(sess.clone(), filename, code); + if sess.0.diag_handler.has_errors()? { + let err = sess + .0 + .emit_nth_diag_into_string(0)? + .unwrap_or(Ok(ErrorKind::InvalidSyntax.name()))?; + Err(anyhow::anyhow!(err)) + } else { + result + } +} + +/// Parse a KCL file to the AST module with the parse session . +pub fn parse_file_with_session( + sess: ParseSessionRef, + filename: &str, + code: Option, +) -> Result { + // Code source. + let src = if let Some(s) = code { + s + } else { + match std::fs::read_to_string(filename) { + Ok(src) => src, + Err(err) => { + return Err(anyhow::anyhow!( + "Failed to load KCL file '{filename}'. Because '{err}'" + )); + } + } + }; + + // Build a source map to store file sources. + let sf = sess + .0 + .sm + .new_source_file(PathBuf::from(filename).into(), src); + + let src_from_sf = match sf.src.as_ref() { + Some(src) => src, + None => { + return Err(anyhow::anyhow!( + "Internal Bug: Failed to load KCL file '{filename}'." + )); + } + }; + + // Lexer + let stream = lexer::parse_token_streams(&sess, src_from_sf.as_str(), sf.start_pos); + // Parser + let mut p = parser::Parser::new(&sess, stream); + let mut m = p.parse_module(); + m.filename = filename.to_string().adjust_canonicalization(); + + Ok(m) +} + +/// Parse a KCL file to the AST module with the parse session and the global session +#[inline] +pub fn parse_file_with_global_session( + sess: ParseSessionRef, + filename: &str, + code: Option, +) -> Result { + create_session_globals_then(move || parse_file_with_session(sess, filename, code)) +} + +/// Parse a source string to a expression. When input empty string, it will return [None]. +/// +/// # Examples +/// ``` +/// use kcl_ast::ast; +/// use kcl_parser::parse_expr; +/// +/// let expr = parse_expr("'alice'").unwrap(); +/// assert!(matches!(expr.node, ast::Expr::StringLit(_))); +/// let expr = parse_expr(""); +/// assert!(matches!(expr, None)); +/// ``` +pub fn parse_expr(src: &str) -> Option> { + if src.is_empty() { + None + } else { + let sess = Arc::new(Session::default()); + let sf = sess + .sm + .new_source_file(PathBuf::from("").into(), src.to_string()); + let src_from_sf = match sf.src.as_ref() { + Some(src) => src, + None => { + bug!("Internal Bug: Failed to load KCL file."); + } + }; + + let sess = &&ParseSession::with_session(sess); + + let expr: Option> = Some(create_session_globals_then(|| { + let stream = parse_token_streams(sess, src_from_sf.as_str(), new_byte_pos(0)); + let mut parser = Parser::new(sess, stream); + parser.parse_expr() + })); + expr + } +} + +#[derive(Debug, Clone)] +pub struct LoadProgramOptions { + pub work_dir: String, + pub k_code_list: Vec, + pub vendor_dirs: Vec, + pub package_maps: HashMap, + /// The parser mode. + pub mode: ParseMode, + /// Whether to load packages. + pub load_packages: bool, + /// Whether to load plugins + pub load_plugins: bool, +} + +impl Default for LoadProgramOptions { + fn default() -> Self { + Self { + work_dir: Default::default(), + k_code_list: Default::default(), + vendor_dirs: vec![get_vendor_home()], + package_maps: Default::default(), + mode: ParseMode::ParseComments, + load_packages: true, + load_plugins: false, + } + } +} + +/// Load the KCL program by paths and options, +/// "module_cache" is used to cache parsed asts to support incremental parse, +/// if it is None, module caching will be disabled +/// +/// # Examples +/// +/// ``` +/// use kcl_parser::{load_program, ParseSession}; +/// use kcl_parser::KCLModuleCache; +/// use kcl_ast::ast::Program; +/// use std::sync::Arc; +/// +/// // Create sessions +/// let sess = Arc::new(ParseSession::default()); +/// // Create module cache +/// let module_cache = KCLModuleCache::default(); +/// +/// // Parse kcl file +/// let kcl_path = "./testdata/import-01.k"; +/// let prog = load_program(sess.clone(), &[kcl_path], None, Some(module_cache.clone())).unwrap(); +/// +/// ``` +pub fn load_program( + sess: ParseSessionRef, + paths: &[&str], + opts: Option, + module_cache: Option, +) -> Result { + Loader::new(sess, paths, opts, module_cache).load_main() +} + +pub type KCLModuleCache = Arc>; + +#[derive(Default, Debug)] +pub struct ModuleCache { + /// File ast cache + pub ast_cache: IndexMap>>, + /// Which pkgs the file belongs to. Sometimes a file is not only contained in the pkg in the file system directory, but may also be in the main package. + pub file_pkg: IndexMap>, + /// File dependency cache + pub dep_cache: IndexMap, + /// File source code + pub source_code: IndexMap, + + pub last_compile_input: (Vec, Option), +} + +impl ModuleCache { + pub fn clear(&mut self, path: &PathBuf) { + self.ast_cache.swap_remove(path); + self.source_code.swap_remove(path); + if let Some(pkgs) = self.file_pkg.swap_remove(path) { + for pkg in &pkgs { + self.dep_cache.swap_remove(pkg); + } + } + } +} +struct Loader { + sess: ParseSessionRef, + paths: Vec, + opts: LoadProgramOptions, + module_cache: KCLModuleCache, + file_graph: FileGraphCache, + pkgmap: PkgMap, + parsed_file: HashSet, +} + +impl Loader { + fn new( + sess: ParseSessionRef, + paths: &[&str], + opts: Option, + module_cache: Option, + ) -> Self { + Self { + sess, + paths: paths + .iter() + .map(|s| kcl_utils::path::convert_windows_drive_letter(s)) + .collect(), + opts: opts.unwrap_or_default(), + module_cache: module_cache.unwrap_or_default(), + file_graph: FileGraphCache::default(), + pkgmap: Default::default(), + parsed_file: HashSet::new(), + } + } + + #[inline] + fn load_main(&mut self) -> Result { + create_session_globals_then(move || self._load_main()) + } + + fn _load_main(&mut self) -> Result { + parse_program( + self.sess.clone(), + self.paths.clone(), + self.module_cache.clone(), + self.file_graph.clone(), + &mut self.pkgmap, + &mut self.parsed_file, + &self.opts, + ) + } +} + +fn fix_rel_import_path_with_file( + pkgroot: &str, + m: &mut ast::Module, + file: &PkgFile, + pkgmap: &PkgMap, + opts: &LoadProgramOptions, + sess: ParseSessionRef, +) { + for stmt in &mut m.body { + let pos = stmt.pos().clone(); + if let ast::Stmt::Import(import_spec) = &mut stmt.node { + let fix_path = kcl_config::vfs::fix_import_path( + pkgroot, + &m.filename, + import_spec.path.node.as_str(), + ); + import_spec.path.node = fix_path.clone(); + + let pkg = pkgmap.get(file).expect("file not in pkgmap"); + import_spec.pkg_name = pkg.pkg_name.clone(); + // Load the import package source code and compile. + let pkg_info = find_packages( + pos.into(), + &pkg.pkg_name, + &pkg.pkg_root, + &fix_path, + opts, + sess.clone(), + ) + .unwrap_or(None); + if let Some(pkg_info) = &pkg_info { + // Add the external package name as prefix of the [`kcl_ast::ImportStmt`]'s member [`path`]. + import_spec.path.node = pkg_info.pkg_path.to_string(); + import_spec.pkg_name = pkg_info.pkg_name.clone(); + } + } + } +} + +fn is_plugin_pkg(pkgpath: &str) -> bool { + pkgpath.starts_with(PLUGIN_MODULE_PREFIX) +} + +fn is_builtin_pkg(pkgpath: &str) -> bool { + let system_modules = kcl_sema::builtin::system_module::STANDARD_SYSTEM_MODULES; + system_modules.contains(&pkgpath) +} + +fn find_packages( + pos: ast::Pos, + pkg_name: &str, + pkg_root: &str, + pkg_path: &str, + opts: &LoadProgramOptions, + sess: ParseSessionRef, +) -> Result> { + if pkg_path.is_empty() { + return Ok(None); + } + + // plugin pkgs + if is_plugin_pkg(pkg_path) { + if !opts.load_plugins { + sess.1.write().add_error( + ErrorKind::CannotFindModule, + &[Message { + range: Into::::into(pos), + style: Style::Line, + message: format!("the plugin package `{}` is not found, please confirm if plugin mode is enabled", pkg_path), + note: None, + suggested_replacement: None, + }], + ); + } + return Ok(None); + } + + // builtin pkgs + if is_builtin_pkg(pkg_path) { + return Ok(None); + } + + // 1. Look for in the current package's directory. + let is_internal = is_internal_pkg(pkg_name, pkg_root, pkg_path)?; + // 2. Look for in the vendor path. + let is_external = is_external_pkg(pkg_path, opts)?; + + // 3. Internal and external packages cannot be duplicated + if is_external.is_some() && is_internal.is_some() { + sess.1.write().add_error( + ErrorKind::CannotFindModule, + &[Message { + range: Into::::into(pos), + style: Style::Line, + message: format!( + "the `{}` is found multiple times in the current package and vendor package", + pkg_path + ), + note: None, + suggested_replacement: None, + }], + ); + return Ok(None); + } + + // 4. Get package information based on whether the package is internal or external. + + match is_internal.or(is_external) { + Some(pkg_info) => Ok(Some(pkg_info)), + None => { + sess.1.write().add_error( + ErrorKind::CannotFindModule, + &[Message { + range: Into::::into(pos), + style: Style::Line, + message: format!("pkgpath {} not found in the program", pkg_path), + note: None, + suggested_replacement: None, + }], + ); + let mut suggestions = vec![format!("browse more packages at 'https://artifacthub.io'")]; + + if let Ok(pkg_name) = parse_external_pkg_name(pkg_path) { + suggestions.insert( + 0, + format!( + "try 'kcl mod add {}' to download the missing package", + pkg_name + ), + ); + } + sess.1.write().add_suggestions(suggestions); + Ok(None) + } + } +} + +/// Search [`pkgpath`] among all the paths in [`pkgroots`]. +/// +/// # Notes +/// +/// All paths in [`pkgpath`] must contain the kcl.mod file. +/// It returns the parent directory of kcl.mod if present, or none if not. +fn pkg_exists(pkgroots: &[String], pkgpath: &str) -> Option { + pkgroots + .into_iter() + .find(|root| pkg_exists_in_path(root, pkgpath)) + .cloned() +} + +/// Search for [`pkgpath`] under [`path`]. +/// It only returns [`true`] if [`path`]/[`pkgpath`] or [`path`]/[`pkgpath.k`] exists. +fn pkg_exists_in_path(path: &str, pkgpath: &str) -> bool { + let mut pathbuf = PathBuf::from(path); + pkgpath.split('.').for_each(|s| pathbuf.push(s)); + pathbuf.exists() || pathbuf.with_extension(KCL_FILE_EXTENSION).exists() +} + +/// Look for [`pkgpath`] in the current package's [`pkgroot`]. +/// If found, return to the [`PkgInfo`], else return [`None`] +/// +/// # Error +/// +/// [`is_internal_pkg`] will return an error if the package's source files cannot be found. +fn is_internal_pkg(pkg_name: &str, pkg_root: &str, pkg_path: &str) -> Result> { + match pkg_exists(&[pkg_root.to_string()], pkg_path) { + Some(internal_pkg_root) => { + let fullpath = if pkg_name == kcl_ast::MAIN_PKG { + pkg_path.to_string() + } else { + format!("{}.{}", pkg_name, pkg_path) + }; + let k_files = get_pkg_kfile_list(pkg_root, pkg_path)?; + Ok(Some(PkgInfo::new( + pkg_name.to_string(), + internal_pkg_root, + fullpath, + k_files, + ))) + } + None => Ok(None), + } +} + +fn get_pkg_kfile_list(pkgroot: &str, pkgpath: &str) -> Result> { + // plugin pkgs + if is_plugin_pkg(pkgpath) { + return Ok(Vec::new()); + } + + // builtin pkgs + if is_builtin_pkg(pkgpath) { + return Ok(Vec::new()); + } + + if pkgroot.is_empty() { + return Err(anyhow::anyhow!(format!("pkgroot not found: {:?}", pkgpath))); + } + + let mut pathbuf = std::path::PathBuf::new(); + pathbuf.push(pkgroot); + + for s in pkgpath.split('.') { + pathbuf.push(s); + } + + let abspath = match pathbuf.canonicalize() { + Ok(p) => p.to_str().unwrap().to_string(), + Err(_) => pathbuf.as_path().to_str().unwrap().to_string(), + }; + if std::path::Path::new(abspath.as_str()).exists() { + return get_dir_files(abspath.as_str()); + } + + let as_k_path = abspath + KCL_FILE_SUFFIX; + if std::path::Path::new((as_k_path).as_str()).exists() { + return Ok(vec![as_k_path]); + } + + Ok(Vec::new()) +} + +/// Get file list in the directory. +fn get_dir_files(dir: &str) -> Result> { + if !std::path::Path::new(dir).exists() { + return Ok(Vec::new()); + } + + let mut list = Vec::new(); + for path in std::fs::read_dir(dir)? { + let path = path?; + if !path + .file_name() + .to_str() + .unwrap() + .ends_with(KCL_FILE_SUFFIX) + { + continue; + } + if path.file_name().to_str().unwrap().ends_with("_test.k") { + continue; + } + if path.file_name().to_str().unwrap().starts_with('_') { + continue; + } + + let s = format!("{}", path.path().display()); + list.push(s); + } + + list.sort(); + Ok(list) +} + +/// Look for [`pkgpath`] in the external package's home. +/// If found, return to the [`PkgInfo`], else return [`None`] +/// +/// # Error +/// +/// - [`is_external_pkg`] will return an error if the package's source files cannot be found. +/// - The name of the external package could not be resolved from [`pkg_path`]. +fn is_external_pkg(pkg_path: &str, opts: &LoadProgramOptions) -> Result> { + let pkg_name = parse_external_pkg_name(pkg_path)?; + let external_pkg_root = if let Some(root) = opts.package_maps.get(&pkg_name) { + PathBuf::from(root).join(KCL_MOD_FILE) + } else { + match pkg_exists(&opts.vendor_dirs, pkg_path) { + Some(path) => PathBuf::from(path).join(&pkg_name).join(KCL_MOD_FILE), + None => return Ok(None), + } + }; + + if external_pkg_root.exists() { + return Ok(Some(match external_pkg_root.parent() { + Some(root) => { + let abs_root: String = match root.canonicalize() { + Ok(p) => p.to_str().unwrap().to_string(), + Err(_) => root.display().to_string(), + }; + let k_files = get_pkg_kfile_list(&abs_root, &rm_external_pkg_name(pkg_path)?)?; + PkgInfo::new( + pkg_name.to_string(), + abs_root, + pkg_path.to_string(), + k_files, + ) + } + None => return Ok(None), + })); + } else { + Ok(None) + } +} + +pub type ASTCache = Arc>>>; +pub type FileGraphCache = Arc>; + +pub fn parse_file( + sess: ParseSessionRef, + file: PkgFile, + src: Option, + module_cache: KCLModuleCache, + pkgs: &mut HashMap>, + pkgmap: &mut PkgMap, + file_graph: FileGraphCache, + opts: &LoadProgramOptions, +) -> Result> { + let src = match src { + Some(src) => Some(src), + None => match &module_cache.read() { + Ok(cache) => cache.source_code.get(file.get_path()), + Err(_) => None, + } + .cloned(), + }; + let m = parse_file_with_session(sess.clone(), file.get_path().to_str().unwrap(), src)?; + let deps = get_deps(&file, &m, pkgs, pkgmap, opts, sess)?; + let dep_files = deps.keys().map(|f| f.clone()).collect(); + pkgmap.extend(deps.clone()); + match &mut module_cache.write() { + Ok(module_cache) => { + module_cache + .ast_cache + .insert(file.get_path().clone(), Arc::new(RwLock::new(m))); + match module_cache.file_pkg.get_mut(&file.get_path().clone()) { + Some(s) => { + s.insert(file.clone()); + } + None => { + let mut s = HashSet::new(); + s.insert(file.clone()); + module_cache.file_pkg.insert(file.get_path().clone(), s); + } + } + module_cache.dep_cache.insert(file.clone(), deps); + } + Err(e) => return Err(anyhow::anyhow!("Parse file failed: {e}")), + } + + match &mut file_graph.write() { + Ok(file_graph) => { + file_graph.update_file(&file, &dep_files); + } + Err(e) => return Err(anyhow::anyhow!("Parse file failed: {e}")), + } + + Ok(dep_files) +} + +pub fn get_deps( + file: &PkgFile, + m: &Module, + pkgs: &mut HashMap>, + pkgmap: &PkgMap, + opts: &LoadProgramOptions, + sess: ParseSessionRef, +) -> Result { + let mut deps = PkgMap::default(); + for stmt in &m.body { + let pos = stmt.pos().clone(); + let pkg = pkgmap.get(file).expect("file not in pkgmap").clone(); + if let ast::Stmt::Import(import_spec) = &stmt.node { + let fix_path = kcl_config::vfs::fix_import_path( + &pkg.pkg_root, + &m.filename, + import_spec.path.node.as_str(), + ); + let pkg_info = find_packages( + pos.into(), + &pkg.pkg_name, + &pkg.pkg_root, + &fix_path, + opts, + sess.clone(), + )?; + if let Some(pkg_info) = &pkg_info { + // If k_files is empty, the pkg information will not be found in the file graph. + // Record the empty pkg to prevent loss. After the parse file is completed, fill in the modules + if pkg_info.k_files.is_empty() { + pkgs.insert(pkg_info.pkg_path.clone(), vec![]); + } + + pkg_info.k_files.iter().for_each(|p| { + let file = PkgFile::new(p.into(), pkg_info.pkg_path.clone()); + deps.insert( + file.clone(), + file_graph::Pkg { + pkg_name: pkg_info.pkg_name.clone(), + pkg_root: pkg_info.pkg_root.clone().into(), + }, + ); + }); + } + } + } + Ok(deps) +} + +pub fn parse_pkg( + sess: ParseSessionRef, + files: Vec<(PkgFile, Option)>, + module_cache: KCLModuleCache, + pkgs: &mut HashMap>, + pkgmap: &mut PkgMap, + file_graph: FileGraphCache, + opts: &LoadProgramOptions, +) -> Result> { + let mut dependent = vec![]; + for (file, src) in files { + let deps = parse_file( + sess.clone(), + file.clone(), + src, + module_cache.clone(), + pkgs, + pkgmap, + file_graph.clone(), + opts, + )?; + dependent.extend(deps); + } + Ok(dependent) +} + +pub fn parse_entry( + sess: ParseSessionRef, + entry: &entry::Entry, + module_cache: KCLModuleCache, + pkgs: &mut HashMap>, + pkgmap: &mut PkgMap, + file_graph: FileGraphCache, + opts: &LoadProgramOptions, + parsed_file: &mut HashSet, +) -> Result> { + let k_files = entry.get_k_files(); + let maybe_k_codes = entry.get_k_codes(); + let mut files = vec![]; + let mut new_files = HashSet::new(); + for (i, f) in k_files.iter().enumerate() { + let file = PkgFile::new(f.adjust_canonicalization().into(), MAIN_PKG.to_string()); + files.push((file.clone(), maybe_k_codes.get(i).unwrap_or(&None).clone())); + new_files.insert(file.clone()); + pkgmap.insert( + file, + Pkg { + pkg_name: entry.name().clone(), + pkg_root: entry.path().into(), + }, + ); + } + let dependent_paths = parse_pkg( + sess.clone(), + files, + module_cache.clone(), + pkgs, + pkgmap, + file_graph.clone(), + opts, + )?; + let mut unparsed_file: VecDeque = dependent_paths.into(); + + // Bfs unparsed and import files + while let Some(file) = unparsed_file.pop_front() { + match &mut module_cache.write() { + Ok(m_cache) => match m_cache.file_pkg.get_mut(file.get_path()) { + Some(s) => { + // The module ast has been parsed, but does not belong to the same package + if s.insert(file.clone()) { + new_files.insert(file.clone()); + } + } + None => { + let mut s = HashSet::new(); + s.insert(file.clone()); + m_cache.file_pkg.insert(file.get_path().clone(), s); + new_files.insert(file.clone()); + } + }, + Err(e) => return Err(anyhow::anyhow!("Parse file failed: {e}")), + } + + let module_cache_read = module_cache.read(); + match &module_cache_read { + Ok(m_cache) => match m_cache.ast_cache.get(file.get_path()) { + Some(m) => { + let deps = m_cache.dep_cache.get(&file).cloned().unwrap_or_else(|| { + get_deps(&file, &m.read().unwrap(), pkgs, pkgmap, opts, sess.clone()) + .unwrap() + }); + let dep_files: Vec = deps.keys().map(|f| f.clone()).collect(); + pkgmap.extend(deps.clone()); + + match &mut file_graph.write() { + Ok(file_graph) => { + file_graph.update_file(&file, &dep_files); + + for dep in dep_files { + if parsed_file.insert(dep.clone()) { + unparsed_file.push_back(dep.clone()); + } + } + + continue; + } + Err(e) => return Err(anyhow::anyhow!("Parse entry failed: {e}")), + } + } + None => { + new_files.insert(file.clone()); + drop(module_cache_read); + let deps = parse_file( + sess.clone(), + file, + None, + module_cache.clone(), + pkgs, + pkgmap, + file_graph.clone(), + &opts, + )?; + for dep in deps { + if parsed_file.insert(dep.clone()) { + unparsed_file.push_back(dep.clone()); + } + } + } + }, + Err(e) => return Err(anyhow::anyhow!("Parse entry failed: {e}")), + }; + } + Ok(new_files) +} + +pub fn parse_program( + sess: ParseSessionRef, + paths: Vec, + module_cache: KCLModuleCache, + file_graph: FileGraphCache, + pkgmap: &mut PkgMap, + parsed_file: &mut HashSet, + opts: &LoadProgramOptions, +) -> Result { + let compile_entries = get_compile_entries_from_paths(&paths, &opts)?; + let workdir = compile_entries + .get_root_path() + .to_string() + .adjust_canonicalization(); + let mut pkgs: HashMap> = HashMap::new(); + let mut new_files = HashSet::new(); + for entry in compile_entries.iter() { + new_files.extend(parse_entry( + sess.clone(), + entry, + module_cache.clone(), + &mut pkgs, + pkgmap, + file_graph.clone(), + &opts, + parsed_file, + )?); + } + + let files = match file_graph.read() { + Ok(file_graph) => { + let files = match file_graph.toposort() { + Ok(files) => files, + Err(_) => file_graph.paths(), + }; + + let file_path_graph = file_graph.file_path_graph().0; + if let Err(cycle) = toposort(&file_path_graph) { + let formatted_cycle = cycle + .iter() + .map(|file| format!("- {}\n", file.to_string_lossy())) + .collect::(); + + sess.1.write().add_error( + ErrorKind::RecursiveLoad, + &[Message { + range: (Position::dummy_pos(), Position::dummy_pos()), + style: Style::Line, + message: format!( + "Could not compiles due to cyclic import statements\n{}", + formatted_cycle.trim_end() + ), + note: None, + suggested_replacement: None, + }], + ); + } + files + } + Err(e) => return Err(anyhow::anyhow!("Parse program failed: {e}")), + }; + + let mut modules: HashMap>> = HashMap::new(); + for file in files.iter() { + let filename = file.get_path().to_str().unwrap().to_string(); + let m_ref = match module_cache.read() { + Ok(module_cache) => module_cache + .ast_cache + .get(file.get_path()) + .expect(&format!( + "Module not found in module: {:?}", + file.get_path() + )) + .clone(), + Err(e) => return Err(anyhow::anyhow!("Parse program failed: {e}")), + }; + if new_files.contains(file) { + let pkg = pkgmap.get(file).expect("file not in pkgmap"); + let mut m = m_ref.write().unwrap(); + fix_rel_import_path_with_file(&pkg.pkg_root, &mut m, file, &pkgmap, opts, sess.clone()); + } + modules.insert(filename.clone(), m_ref); + match pkgs.get_mut(&file.pkg_path) { + Some(pkg_modules) => { + pkg_modules.push(filename.clone()); + } + None => { + pkgs.insert(file.pkg_path.clone(), vec![filename]); + } + } + } + let program = ast::Program { + root: workdir, + pkgs, + pkgs_not_imported: HashMap::new(), + modules, + modules_not_imported: HashMap::new(), + }; + + Ok(LoadProgramResult { + program, + errors: sess.1.read().diagnostics.clone(), + paths: files.iter().map(|file| file.get_path().clone()).collect(), + }) +} + +/// If there are too many files in the directory, it will affect the performance of lsp. Set a maximum number of files +const MAX_SCAN_FILES: usize = 1000; + +/// Parse all kcl files under path and dependencies from opts. +/// Different from `load_program`, this function will compile files that are not imported. +pub fn load_all_files_under_paths( + sess: ParseSessionRef, + paths: &[&str], + opts: Option, + module_cache: Option, +) -> Result { + let mut loader = Loader::new(sess.clone(), paths, opts.clone(), module_cache.clone()); + create_session_globals_then(move || { + match parse_program( + loader.sess.clone(), + loader.paths.clone(), + loader.module_cache.clone(), + loader.file_graph.clone(), + &mut loader.pkgmap, + &mut loader.parsed_file, + &loader.opts, + ) { + Ok(res) => { + let diag = sess.1.read().diagnostics.clone(); + let mut res = res.clone(); + let k_files_from_import = res.paths.clone(); + let mut paths = paths.to_vec(); + paths.push(&res.program.root); + let module_cache = loader.module_cache.clone(); + let mut module_cache_write = module_cache.write(); + match &mut module_cache_write { + Ok(m_cache) => { + let paths: Vec = paths.iter().map(|p| p.to_string()).collect(); + let paths_is_cached = paths == m_cache.last_compile_input.0; + let opt_is_cached = match (&m_cache.last_compile_input.1, &opts) { + (None, None) => true, + (Some(old), Some(new)) => old.package_maps == new.package_maps, + _ => false, + }; + if paths_is_cached && opt_is_cached { + return Ok(res); + } else { + m_cache.last_compile_input = (paths, opts.clone()) + } + } + Err(e) => return Err(anyhow::anyhow!("Parse entry failed: {e}")), + } + drop(module_cache_write); + + let (k_files_under_path, pkgmap) = + get_files_from_path(&res.program.root, &paths, opts)?; + + if k_files_under_path.len() > MAX_SCAN_FILES { + return Ok(res); + } + + loader.pkgmap.extend(pkgmap); + + // Filter unparsed file + let mut unparsed_file: VecDeque = VecDeque::new(); + for (pkg, paths) in &k_files_under_path { + for p in paths { + if !k_files_from_import.contains(p) { + let pkgfile = PkgFile::new(p.clone(), pkg.clone()); + let module_cache_read = module_cache.read(); + match &module_cache_read { + Ok(m_cache) => match m_cache.ast_cache.get(pkgfile.get_path()) { + Some(_) => continue, + None => { + unparsed_file.push_back(pkgfile); + } + }, + _ => {} + } + } + } + } + + let pkgs_not_imported = &mut res.program.pkgs_not_imported; + + let mut new_files = HashSet::new(); + // Bfs unparsed and import files + loader.parsed_file.extend(unparsed_file.clone()); + while let Some(file) = unparsed_file.pop_front() { + new_files.insert(file.clone()); + let module_cache_read = module_cache.read(); + match &module_cache_read { + Ok(m_cache) => match m_cache.ast_cache.get(file.get_path()) { + Some(_) => continue, + None => { + drop(module_cache_read); + let deps = parse_file( + sess.clone(), + file.clone(), + None, + module_cache.clone(), + pkgs_not_imported, + &mut loader.pkgmap, + loader.file_graph.clone(), + &loader.opts, + )?; + + let m_ref = match module_cache.read() { + Ok(module_cache) => module_cache + .ast_cache + .get(file.get_path()) + .expect(&format!( + "Module not found in module: {:?}", + file.get_path() + )) + .clone(), + Err(e) => { + return Err(anyhow::anyhow!("Parse program failed: {e}")); + } + }; + + let pkg = loader.pkgmap.get(&file).expect("file not in pkgmap"); + let mut m = m_ref.write().unwrap(); + fix_rel_import_path_with_file( + &pkg.pkg_root, + &mut m, + &file, + &loader.pkgmap, + &loader.opts, + sess.clone(), + ); + + for dep in deps { + if loader.parsed_file.insert(dep.clone()) { + unparsed_file.push_back(dep.clone()); + } + } + } + }, + Err(e) => return Err(anyhow::anyhow!("Parse entry failed: {e}")), + } + } + + // Merge unparsed module into res + let modules_not_imported = &mut res.program.modules_not_imported; + for file in &new_files { + let filename = file.get_path().to_str().unwrap().to_string(); + let m_ref = match module_cache.read() { + Ok(module_cache) => module_cache + .ast_cache + .get(file.get_path()) + .expect(&format!( + "Module not found in module: {:?}", + file.get_path() + )) + .clone(), + Err(e) => return Err(anyhow::anyhow!("Parse program failed: {e}")), + }; + modules_not_imported.insert(filename.clone(), m_ref); + match pkgs_not_imported.get_mut(&file.pkg_path) { + Some(pkg_modules) => { + pkg_modules.push(filename.clone()); + } + None => { + pkgs_not_imported.insert(file.pkg_path.clone(), vec![filename]); + } + } + } + sess.1.write().diagnostics = diag; + return Ok(res); + } + e => return e, + } + }) +} + +/// Get all kcl files under path and dependencies from opts, regardless of whether they are imported or not +pub fn get_files_from_path( + root: &str, + paths: &[&str], + opts: Option, +) -> Result<(HashMap>, HashMap)> { + let mut k_files_under_path = HashMap::new(); + let mut pkgmap = HashMap::new(); + + // get files from config + if let Some(opt) = &opts { + for (name, path) in &opt.package_maps { + let path_buf = PathBuf::from(path.clone()); + if path_buf.is_dir() { + let all_k_files_under_path = get_kcl_files(path.clone(), true)?; + for f in &all_k_files_under_path { + let p = PathBuf::from(f); + let fix_path = { + match p.parent().unwrap().strip_prefix(Path::new(&path)) { + Ok(p) => Path::new(&name).join(p), + Err(_) => match p.parent().unwrap().strip_prefix(Path::new(&path)) { + Ok(p) => Path::new(&name).join(p), + Err(_) => Path::new(&name).to_path_buf(), + }, + } + } + .to_str() + .unwrap() + .to_string(); + let mut fix_path = fix_path + .replace(['/', '\\'], ".") + .trim_end_matches('.') + .to_string(); + + if fix_path.is_empty() { + fix_path = MAIN_PKG.to_string(); + } + + let pkgfile = PkgFile::new(p.clone(), fix_path.clone()); + pkgmap.insert( + pkgfile, + Pkg { + pkg_name: name.clone(), + pkg_root: path.clone(), + }, + ); + k_files_under_path + .entry(fix_path) + .or_insert(Vec::new()) + .push(p); + } + } + } + } + + // get files from input paths + for path in paths { + let path_buf = PathBuf::from(path); + if path_buf.is_dir() { + let all_k_files_under_path = get_kcl_files(path, true)?; + for f in &all_k_files_under_path { + let p = PathBuf::from(f.adjust_canonicalization()); + let fix_path = p + .parent() + .unwrap() + .strip_prefix(root) + .unwrap() + .to_str() + .unwrap() + .to_string(); + + let fix_path = fix_path + .replace(['/', '\\'], ".") + .trim_end_matches('.') + .to_string(); + + let pkgfile = PkgFile::new(p.clone(), fix_path.clone()); + pkgmap.insert( + pkgfile, + Pkg { + pkg_name: MAIN_PKG.to_owned(), + pkg_root: path.to_string(), + }, + ); + k_files_under_path + .entry(fix_path) + .or_insert(Vec::new()) + .push(p); + } + } + } + + Ok((k_files_under_path, pkgmap)) +} + +/// Get kcl files from path. +pub fn get_kcl_files>(path: P, recursively: bool) -> Result> { + let mut files = vec![]; + let walkdir = if recursively { + walkdir::WalkDir::new(path) + } else { + walkdir::WalkDir::new(path).max_depth(1) + }; + for entry in walkdir.into_iter().filter_map(|e| e.ok()) { + let path = entry.path(); + if path.is_file() { + let file = path.to_str().unwrap(); + if file.ends_with(KCL_FILE_SUFFIX) { + files.push(file.to_string()) + } + } + } + files.sort(); + Ok(files) +} diff --git a/kclvm/parser/src/parser/expr.rs b/crates/parser/src/parser/expr.rs similarity index 98% rename from kclvm/parser/src/parser/expr.rs rename to crates/parser/src/parser/expr.rs index f3a501e79..3fc20ec86 100644 --- a/kclvm/parser/src/parser/expr.rs +++ b/crates/parser/src/parser/expr.rs @@ -4,8 +4,8 @@ extern crate enquote; use std::vec; -use super::int::bytes_to_int; use super::Parser; +use super::int::bytes_to_int; use anyhow::bail; use either::{self, Either}; @@ -13,11 +13,11 @@ use either::{self, Either}; use crate::parser::precedence::Precedence; use anyhow::Result; use compiler_base_error::unit_type::{TypeWithUnit, UnitUsize}; -use kclvm_ast::ast::*; -use kclvm_ast::node_ref; -use kclvm_ast::token; -use kclvm_ast::token::{BinOpToken, DelimToken, TokenKind, VALID_SPACES_LENGTH}; -use kclvm_span::symbol::kw; +use kcl_ast::ast::*; +use kcl_ast::node_ref; +use kcl_ast::token; +use kcl_ast::token::{BinOpToken, DelimToken, TokenKind, VALID_SPACES_LENGTH}; +use kcl_span::symbol::kw; /// Parser implementation of expressions, which consists of sub-expressions, /// operand and tokens. Like the general LL1 parser, parser constantly looking for @@ -169,7 +169,7 @@ impl<'a> Parser<'a> { // If no peek is found, a dummy token is returned for error recovery. let peek = match self.cursor.peek() { Some(peek) => peek, - None => kclvm_ast::token::Token::dummy(), + None => kcl_ast::token::Token::dummy(), }; if self.token.is_keyword(kw::Not) && peek.is_keyword(kw::In) { BinOrCmpOp::Cmp(CmpOp::NotIn) @@ -253,7 +253,7 @@ impl<'a> Parser<'a> { fn parse_if_expr( &mut self, body: NodeRef, - token: kclvm_ast::token::Token, + token: kcl_ast::token::Token, ) -> NodeRef { if self.token.is_keyword(kw::If) { self.bump(); @@ -1056,7 +1056,7 @@ impl<'a> Parser<'a> { /// Syntax: /// list_items: expr ((COMMA [NEWLINE] | NEWLINE) expr)* [COMMA] [NEWLINE] pub(crate) fn parse_list_items(&mut self, has_newline: bool) -> Vec> { - let is_terminator = |token: &kclvm_ast::token::Token| match &token.kind { + let is_terminator = |token: &kcl_ast::token::Token| match &token.kind { TokenKind::CloseDelim(DelimToken::Bracket) | TokenKind::Eof => true, TokenKind::Newline if !has_newline => true, _ => token.is_keyword(kw::For), @@ -1382,7 +1382,7 @@ impl<'a> Parser<'a> { /// Syntax: /// config_entries: config_entry ((COMMA [NEWLINE] | NEWLINE) config_entry)* [COMMA] [NEWLINE] fn parse_config_entries(&mut self, has_newline: bool) -> Vec> { - let is_terminator = |token: &kclvm_ast::token::Token| match &token.kind { + let is_terminator = |token: &kcl_ast::token::Token| match &token.kind { TokenKind::CloseDelim(DelimToken::Brace) | TokenKind::Eof => true, TokenKind::Newline if !has_newline => true, _ => token.is_keyword(kw::For), @@ -2049,7 +2049,7 @@ impl<'a> Parser<'a> { let mut args: Vec> = Vec::new(); let mut keywords: Vec> = Vec::new(); let mut has_keyword = false; - let is_terminator = |token: &kclvm_ast::token::Token| match &token.kind { + let is_terminator = |token: &kcl_ast::token::Token| match &token.kind { TokenKind::CloseDelim(DelimToken::Paren) | TokenKind::Eof => true, TokenKind::Newline if !has_newline => true, _ => token.is_keyword(kw::For), @@ -2428,7 +2428,7 @@ impl<'a> Parser<'a> { pub(crate) fn expr_as_identifier( &mut self, expr: NodeRef, - token: kclvm_ast::token::Token, + token: kcl_ast::token::Token, ) -> Identifier { if let Expr::Identifier(x) = expr.node { x @@ -2472,7 +2472,10 @@ impl<'a> Parser<'a> { Expr::Identifier(identifier) => Ok(self.identifier_as_assign_target_paths(identifier)), Expr::Selector(selector) => { if selector.has_question { - bail!("'{}' is an illegal expression for assignment, because the left-hand side of an assignment expression may not be an optional attribute access.", expr.node.get_expr_name()); + bail!( + "'{}' is an illegal expression for assignment, because the left-hand side of an assignment expression may not be an optional attribute access.", + expr.node.get_expr_name() + ); } else { let mut value_paths = self.expr_as_assign_target_paths(&selector.value)?; let mut attr_values = @@ -2483,14 +2486,20 @@ impl<'a> Parser<'a> { } Expr::Subscript(subscript) => { if subscript.has_question { - bail!("'{}' is an illegal expression for assignment, because the left-hand side of an assignment expression may not be an optional subscript access.", expr.node.get_expr_name()); + bail!( + "'{}' is an illegal expression for assignment, because the left-hand side of an assignment expression may not be an optional subscript access.", + expr.node.get_expr_name() + ); } else { let mut value_paths = self.expr_as_assign_target_paths(&subscript.value)?; if let Some(index) = &subscript.index { value_paths.push(MemberOrIndex::Index(index.clone())); Ok(value_paths) } else { - bail!("'{}' is an illegal expression for assignment, because the left-hand side of an assignment expression may not be a slice access.", expr.node.get_expr_name()); + bail!( + "'{}' is an illegal expression for assignment, because the left-hand side of an assignment expression may not be a slice access.", + expr.node.get_expr_name() + ); } } } diff --git a/kclvm/parser/src/parser/int.rs b/crates/parser/src/parser/int.rs similarity index 97% rename from kclvm/parser/src/parser/int.rs rename to crates/parser/src/parser/int.rs index 78e2201c2..068ec8276 100644 --- a/kclvm/parser/src/parser/int.rs +++ b/crates/parser/src/parser/int.rs @@ -24,7 +24,7 @@ pub fn bytes_to_int(lit: &[u8], mut base: u32) -> Option { base = base_deteced; (true, radix_len) } else { - if let [_first, ref others @ .., last] = lit { + if let [_first, others @ .., last] = lit { let is_zero = others.iter().all(|&c| c == b'0' || c == b'_') && *last == b'0'; if !is_zero { diff --git a/crates/parser/src/parser/mod.rs b/crates/parser/src/parser/mod.rs new file mode 100644 index 000000000..630fb933a --- /dev/null +++ b/crates/parser/src/parser/mod.rs @@ -0,0 +1,231 @@ +//! A KCL Parser. +//! +//! The parser is built on top of the [`kcl_parser::lexer`], and ordering KCL tokens +//! [`kcl_ast::token`] to KCL ast nodes [`kcl_ast::ast`]. +//! +//! The parser follows a LL1 parsing method, which constantly looking for +//! left-side derivation until a terminal token found. Since we hand-written the parser, +//! there is more flexibility in dealing with deduction priorities. +//! +//! KCL syntax elements can be simply divided into statements, expressions and tokens, +//! in which statement consists of expressions and tokens. In expression, operand is the most +//! complex part to enable all kinds of ident, constant, list, dict, config exprs. +//! +//! The parser error recovery strategy design is [here](https://github.com/kcl-lang/kcl/issues/420). + +#![macro_use] + +mod expr; +mod int; +mod module; +mod precedence; +mod stmt; +#[cfg(test)] +mod tests; +mod ty; + +use crate::session::ParseSession; + +use compiler_base_span::span::{BytePos, new_byte_pos}; +use kcl_ast::ast::{Comment, NodeRef, PosTuple}; +use kcl_ast::token::{CommentKind, Token, TokenKind}; +use kcl_ast::token_stream::{Cursor, TokenStream}; +use kcl_error::ParseErrorMessage; +use kcl_span::symbol::Symbol; +use kcl_utils::path::PathPrefix; + +/// The parser is built on top of the [`kcl_parser::lexer`], and ordering KCL tokens +/// [`kcl_ast::token`] to KCL ast nodes [`kcl_ast::ast`]. +pub struct Parser<'a> { + /// The current token. + pub token: Token, + /// The previous token. + pub prev_token: Token, + /// Stream cursor + cursor: Cursor, + /// all comments. + comments: Vec>, + /// parse-time session + pub sess: &'a ParseSession, +} + +/// The DropMarker is used to mark whether to discard the token Mark whether to discard the token. +/// The principle is to store the index of the token in the token stream. When there is no index +/// change during the parse process, it is discarded and an error is output +#[derive(Debug, Default, Clone, Copy)] +pub(crate) struct DropMarker(usize); + +impl<'a> Parser<'a> { + pub fn new(sess: &'a ParseSession, stream: TokenStream) -> Self { + let (non_comment_tokens, comments) = Parser::split_token_stream(sess, stream); + + let mut parser = Parser { + token: Token::dummy(), + prev_token: Token::dummy(), + cursor: TokenStream::new(non_comment_tokens).cursor(), + comments, + sess, + }; + + // bump to the first token + parser.bump(); + + parser + } + + /// Get an AST position from the token pair (lo_tok, hi_tok). + #[inline] + pub(crate) fn token_span_pos(&mut self, lo_tok: Token, hi_tok: Token) -> PosTuple { + self.byte_pos_to_pos(lo_tok.span.lo(), hi_tok.span.hi()) + } + + /// Get an AST position from the byte pos pair (lo, hi). + pub(crate) fn byte_pos_to_pos(&mut self, lo: BytePos, hi: BytePos) -> PosTuple { + let lo = self.sess.lookup_char_pos(lo); + let hi = self.sess.lookup_char_pos(hi); + + let filename = kcl_utils::path::convert_windows_drive_letter(&format!( + "{}", + lo.file.name.prefer_remapped() + )) + .adjust_canonicalization(); + + ( + filename, + lo.line as u64, + lo.col.0 as u64, + hi.line as u64, + hi.col.0 as u64, + ) + } + + pub(crate) fn bump(&mut self) { + self.prev_token = self.token; + let next = self.cursor.next(); + + if let Some(token) = next { + self.token = token + } + } + + /// Whether the parser has the next token in the token stream. + #[inline] + pub(crate) fn has_next(&mut self) -> bool { + self.cursor.next().is_some() + } + + #[inline] + /// Whether the parser has the next token in the token stream. + pub(crate) fn peek_has_next(&mut self) -> bool { + self.cursor.peek().is_some() + } + + pub(crate) fn bump_keyword(&mut self, kw: Symbol) { + if !self.token.is_keyword(kw) { + self.sess.struct_token_error(&[kw.into()], self.token); + } + self.bump(); + } + + pub(crate) fn bump_token(&mut self, kind: TokenKind) { + if self.token.kind != kind { + self.sess.struct_token_error(&[kind.into()], self.token); + } + self.bump(); + } + + pub(crate) fn skip_newlines(&mut self) { + while let TokenKind::Newline = self.token.kind { + self.bump(); + } + } + + /// Mark the token index. + pub(crate) fn mark(&mut self) -> DropMarker { + DropMarker(self.cursor.index()) + } + + /// Decide to discard token according to the current index. + pub(crate) fn drop(&mut self, marker: DropMarker) -> bool { + if marker.0 == self.cursor.index() { + let token_str: String = self.token.into(); + self.sess + .struct_message_error(ParseErrorMessage::ExpectExpr(token_str), self.token.span); + self.bump(); + true + } else { + false + } + } +} + +impl<'a> Parser<'a> { + fn split_token_stream( + sess: &'a ParseSession, + stream: TokenStream, + ) -> (Vec, Vec>) { + let mut comments = Vec::new(); + let mut non_comment_tokens = Vec::new(); + + for (i, tok) in stream.iter().enumerate() { + let prev_token = if i == 0 { + Token { + kind: TokenKind::Dummy, + span: kcl_span::Span::new(new_byte_pos(0), new_byte_pos(0)), + } + } else { + stream[i - 1] + }; + + // eof: add newline + if tok.kind == TokenKind::Eof { + // append Newline + if prev_token.kind != TokenKind::Newline { + non_comment_tokens.push(Token { + kind: TokenKind::Newline, + span: tok.span, + }); + } + non_comment_tokens.push(*tok); + break; + } + + // split comments + if matches!(tok.kind, TokenKind::DocComment(_)) { + if let TokenKind::DocComment(comment_kind) = tok.kind { + match comment_kind { + CommentKind::Line(x) => { + let lo = sess.lookup_char_pos(tok.span.lo()); + let hi = sess.lookup_char_pos(tok.span.hi()); + let filename = kcl_utils::path::convert_windows_drive_letter(&format!( + "{}", + lo.file.name.prefer_remapped() + )) + .adjust_canonicalization(); + + let node = kcl_ast::ast::Node { + id: kcl_ast::ast::AstIndex::default(), + node: Comment { + text: x.as_str().to_string(), + }, + filename, + line: lo.line as u64, + column: lo.col.0 as u64, + end_line: hi.line as u64, + end_column: hi.col.0 as u64, + }; + + comments.push(NodeRef::new(node)); + } + } + } + continue; + } + + // normal tokens + non_comment_tokens.push(*tok); + } + + (non_comment_tokens, comments) + } +} diff --git a/crates/parser/src/parser/module.rs b/crates/parser/src/parser/module.rs new file mode 100644 index 000000000..21ed71699 --- /dev/null +++ b/crates/parser/src/parser/module.rs @@ -0,0 +1,68 @@ +use kcl_ast::ast::*; +use kcl_ast::node_ref; +use kcl_ast::{token::LitKind, token::TokenKind}; + +use super::Parser; + +impl<'a> Parser<'a> { + /// Syntax: + /// start: (NEWLINE | statement)* + pub fn parse_module(&mut self) -> Module { + let doc = self.parse_doc(); + let body = self.parse_body(); + Module { + filename: "".to_string(), + doc, + comments: self.comments.clone(), + body, + } + } + + pub(crate) fn parse_doc(&mut self) -> Option> { + // doc string + match self.token.kind { + TokenKind::Literal(lit) => { + if let LitKind::Str { is_long_string, .. } = lit.kind { + if is_long_string { + let doc_expr = self.parse_str_expr(lit); + self.skip_newlines(); + match &doc_expr.node { + Expr::StringLit(str) => { + Some(node_ref!(str.raw_value.clone(), doc_expr.pos())) + } + Expr::JoinedString(str) => { + Some(node_ref!(str.raw_value.clone(), doc_expr.pos())) + } + _ => None, + } + } else { + None + } + } else { + None + } + } + _ => None, + } + } + + fn parse_body(&mut self) -> Vec> { + let mut stmts = Vec::new(); + loop { + if matches!(self.token.kind, TokenKind::Eof) { + self.bump(); + break; + } + + if let Some(stmt) = self.parse_stmt() { + stmts.push(stmt); + } else { + // Error recovery from panic mode: Once an error is detected (the statement is None), + // the symbols in the input are continuously discarded (one symbol at a time), until the + // "synchronous lexical unit" is found (the statement start token e.g., import, schema, etc). + self.bump(); + } + } + stmts + } +} diff --git a/crates/parser/src/parser/precedence.rs b/crates/parser/src/parser/precedence.rs new file mode 100644 index 000000000..812b7edb8 --- /dev/null +++ b/crates/parser/src/parser/precedence.rs @@ -0,0 +1,89 @@ +use kcl_ast::token::{Token, TokenKind}; + +use kcl_span::symbol::kw; + +#[repr(i32)] +#[derive(PartialEq, PartialOrd, Debug, Clone)] +pub enum Precedence { + /// lowest place holder + Lowest, + /// as + As, + /// logic or || + LogicOr, + /// logic and && + LogicAnd, + /// ==, != + Equals, + /// in, not it + InOrNotIn, + /// is, is not + IsOrIsNot, + /// >, <, >=, <= + LessGreater, + /// | + BitOr, + /// ^ + BitXor, + /// & + BitAnd, + /// >>, << + Shift, + /// +, - + Sum, + /// *, /, % // + Product, + /// ** + Power, + /// +X, -X, !X + Prefix, +} + +impl From for Precedence { + fn from(tok: Token) -> Self { + if tok.is_keyword(kw::As) { + return Precedence::As; + } + match tok.kind { + TokenKind::UnaryOp(_) => Precedence::Prefix, + TokenKind::BinOp(ot) => match ot { + kcl_ast::token::BinOpToken::Plus | kcl_ast::token::BinOpToken::Minus => { + Precedence::Sum + } + kcl_ast::token::BinOpToken::Star + | kcl_ast::token::BinOpToken::Slash + | kcl_ast::token::BinOpToken::Percent + | kcl_ast::token::BinOpToken::SlashSlash => Precedence::Product, + kcl_ast::token::BinOpToken::StarStar => Precedence::Power, + kcl_ast::token::BinOpToken::Caret => Precedence::BitXor, + kcl_ast::token::BinOpToken::And => Precedence::BitAnd, + kcl_ast::token::BinOpToken::Or => Precedence::BitOr, + kcl_ast::token::BinOpToken::Shl | kcl_ast::token::BinOpToken::Shr => { + Precedence::Shift + } + }, + TokenKind::BinCmp(ct) => match ct { + kcl_ast::token::BinCmpToken::Eq | kcl_ast::token::BinCmpToken::NotEq => { + Precedence::Equals + } + kcl_ast::token::BinCmpToken::Lt + | kcl_ast::token::BinCmpToken::LtEq + | kcl_ast::token::BinCmpToken::Gt + | kcl_ast::token::BinCmpToken::GtEq => Precedence::LessGreater, + }, + _ => { + if tok.is_keyword(kw::Or) { + Precedence::LogicOr + } else if tok.is_keyword(kw::And) { + Precedence::LogicAnd + } else if tok.is_keyword(kw::In) { + Precedence::InOrNotIn + } else if tok.is_keyword(kw::Is) { + Precedence::IsOrIsNot + } else { + Precedence::Lowest + } + } + } + } +} diff --git a/kclvm/parser/src/parser/stmt.rs b/crates/parser/src/parser/stmt.rs similarity index 98% rename from kclvm/parser/src/parser/stmt.rs rename to crates/parser/src/parser/stmt.rs index ab097099e..9e4f9dfb0 100644 --- a/kclvm/parser/src/parser/stmt.rs +++ b/crates/parser/src/parser/stmt.rs @@ -1,17 +1,17 @@ #![allow(dead_code)] #![allow(unused_macros)] -use compiler_base_span::{span::new_byte_pos, BytePos, Span}; -use kclvm_ast::token::VALID_SPACES_LENGTH; -use kclvm_ast::token::{CommentKind, DelimToken, LitKind, Token, TokenKind}; -use kclvm_ast::{ast::*, expr_as, node_ref}; -use kclvm_error::ParseErrorMessage; -use kclvm_span::symbol::kw; +use compiler_base_span::{BytePos, Span, span::new_byte_pos}; +use kcl_ast::token::VALID_SPACES_LENGTH; +use kcl_ast::token::{CommentKind, DelimToken, LitKind, Token, TokenKind}; +use kcl_ast::{ast::*, expr_as, node_ref}; +use kcl_error::ParseErrorMessage; +use kcl_span::symbol::kw; use super::Parser; /// Parser implementation of statements, which consists of expressions and tokens. -/// Parser uses `parse_exprlist` and `parse_expr` in [`kclvm_parser::parser::expr`] +/// Parser uses `parse_exprlist` and `parse_expr` in [`kcl_parser::parser::expr`] /// to get a expression node, and then concretize it into the specified expression node, /// and then assemble it into the corresponding statement node. impl<'a> Parser<'a> { @@ -209,7 +209,7 @@ impl<'a> Parser<'a> { self.token.kind, TokenKind::OpenDelim(DelimToken::Brace) | TokenKind::OpenDelim(DelimToken::Paren) ) { - if let Type::Named(ref identifier) = typ.node { + if let Type::Named(identifier) = &typ.node { let identifier = node_ref!(Expr::Identifier(identifier.clone()), typ.pos()); let schema_expr = if matches!(self.token.kind, TokenKind::OpenDelim(DelimToken::Paren)) { @@ -717,12 +717,12 @@ impl<'a> Parser<'a> { if name .node - .ends_with(kclvm_sema::resolver::global::MIXIN_SUFFIX) + .ends_with(kcl_sema::resolver::global::MIXIN_SUFFIX) { is_mixin = true; } else if name .node - .ends_with(kclvm_sema::resolver::global::PROTOCOL_SUFFIX) + .ends_with(kcl_sema::resolver::global::PROTOCOL_SUFFIX) { is_protocol = true; } @@ -901,7 +901,7 @@ impl<'a> Parser<'a> { if matches!(self.token.kind, TokenKind::Newline | TokenKind::Eof) { let expect_tokens: Vec = close_tokens .iter() - .map(|t| >::into(*t)) + .map(|t| >::into(*t)) .collect(); self.sess.struct_token_error(&expect_tokens, self.token); break; diff --git a/kclvm/parser/src/parser/tests.rs b/crates/parser/src/parser/tests.rs similarity index 100% rename from kclvm/parser/src/parser/tests.rs rename to crates/parser/src/parser/tests.rs diff --git a/crates/parser/src/parser/ty.rs b/crates/parser/src/parser/ty.rs new file mode 100644 index 000000000..4d5607d74 --- /dev/null +++ b/crates/parser/src/parser/ty.rs @@ -0,0 +1,291 @@ +#![allow(dead_code)] + +use super::Parser; + +use kcl_ast::ast::{Expr, Node, NodeRef, Type}; +use kcl_ast::token; +use kcl_ast::token::{BinOpToken, DelimToken, TokenKind}; +use kcl_ast::{ast, expr_as}; +use kcl_span::symbol::{kw, sym}; + +impl<'a> Parser<'a> { + /// Syntax: + /// + /// type: type_element (OR type_element)* + /// type_element: schema_type | function_type | basic_type | compound_type | literal_type + /// function_type: LEFT_PARENTHESES [type_element (COMMA type_element)*] RIGHT_PARENTHESES [RIGHT_ARROW type_element] + /// schema_type: identifier + /// basic_type: STRING_TYPE | INT_TYPE | FLOAT_TYPE | BOOL_TYPE | ANY_TYPE + /// compound_type: list_type | dict_type + /// list_type: LEFT_BRACKETS (type)? RIGHT_BRACKETS + /// dict_type: LEFT_BRACE (type)? COLON (type)? RIGHT_BRACE + /// literal_type: string | number | TRUE | FALSE + pub(crate) fn parse_type_annotation(&mut self) -> NodeRef { + let token = self.token; + let mut type_node_list = vec![self.parse_type_element()]; + + while let TokenKind::BinOp(BinOpToken::Or) = self.token.kind { + self.bump(); + let t = self.parse_type_element(); + type_node_list.push(t); + } + + if type_node_list.len() > 1 { + let mut union_type = ast::UnionType { + type_elements: Vec::new(), + }; + for v in type_node_list.iter_mut() { + union_type.type_elements.push(v.clone()); + } + + Box::new(Node::node( + Type::Union(union_type.clone()), + self.sess.struct_token_loc(token, self.prev_token), + )) + } else { + type_node_list[0].clone() + } + } + + fn parse_type_element(&mut self) -> NodeRef { + let token = self.token; + + // any + if self.token.is_keyword(kw::Any) { + let t = Type::Any; + self.bump_keyword(kw::Any); + return Box::new(Node::node( + t, + self.sess.struct_token_loc(token, self.prev_token), + )); + } + // lit: true/false + else if self.token.is_keyword(kw::True) { + self.bump_keyword(kw::True); + return Box::new(Node::node( + Type::Literal(ast::LiteralType::Bool(true)), + self.sess.struct_token_loc(token, self.prev_token), + )); + } else if self.token.is_keyword(kw::False) { + self.bump_keyword(kw::False); + return Box::new(Node::node( + Type::Literal(ast::LiteralType::Bool(false)), + self.sess.struct_token_loc(token, self.prev_token), + )); + } + // basic type + else if self.token.is_keyword(sym::bool) { + let t = Type::Basic(ast::BasicType::Bool); + self.bump_keyword(sym::bool); + return Box::new(Node::node( + t, + self.sess.struct_token_loc(token, self.prev_token), + )); + } else if self.token.is_keyword(sym::int) { + let t = Type::Basic(ast::BasicType::Int); + self.bump_keyword(sym::int); + return Box::new(Node::node( + t, + self.sess.struct_token_loc(token, self.prev_token), + )); + } else if self.token.is_keyword(sym::float) { + let t = Type::Basic(ast::BasicType::Float); + self.bump_keyword(sym::float); + return Box::new(Node::node( + t, + self.sess.struct_token_loc(token, self.prev_token), + )); + } else if self.token.is_keyword(sym::str) { + let t = Type::Basic(ast::BasicType::Str); + self.bump_keyword(sym::str); + return Box::new(Node::node( + t, + self.sess.struct_token_loc(token, self.prev_token), + )); + } + + // named type + if let TokenKind::Ident(_) = self.token.kind { + let ident = self.parse_identifier_expr(); + let ident = expr_as!(ident, Expr::Identifier).unwrap(); + let t = Type::Named(ident); + return Box::new(Node::node( + t, + self.sess.struct_token_loc(token, self.prev_token), + )); + } + // lit type + else if let TokenKind::Literal(lit) = self.token.kind { + let t = match lit.kind { + token::LitKind::Bool => { + if lit.symbol == kw::True { + ast::LiteralType::Bool(true) + } else if lit.symbol == kw::False { + ast::LiteralType::Bool(false) + } else { + self.sess + .struct_token_error(&[kw::True.into(), kw::False.into()], self.token); + ast::LiteralType::Bool(false) + } + } + token::LitKind::Integer => { + let v = lit.symbol.as_str().parse::().unwrap(); + if let Some(suffix) = lit.suffix { + let x = ast::NumberBinarySuffix::try_from(suffix.as_str().as_str()); + ast::LiteralType::Int(ast::IntLiteralType { + value: v, + suffix: Some(x.unwrap()), + }) + } else { + ast::LiteralType::Int(ast::IntLiteralType { + value: v, + suffix: None, + }) + } + } + token::LitKind::Float => { + let v = lit.symbol.as_str().parse::().unwrap(); + ast::LiteralType::Float(v) + } + token::LitKind::Str { .. } => ast::LiteralType::Str(lit.symbol.as_str()), + _ => { + if self.token.is_keyword(kw::True) { + ast::LiteralType::Bool(true) + } else if self.token.is_keyword(kw::False) { + ast::LiteralType::Bool(false) + } else { + self.sess + .struct_token_error(&[kw::True.into(), kw::False.into()], self.token); + ast::LiteralType::Bool(false) + } + } + }; + + let t = Type::Literal(t); + + self.bump(); + + return Box::new(Node::node( + t, + self.sess.struct_token_loc(token, self.prev_token), + )); + } + // [type] + else if let TokenKind::OpenDelim(DelimToken::Bracket) = self.token.kind { + self.bump_token(TokenKind::OpenDelim(DelimToken::Bracket)); + + if let TokenKind::CloseDelim(DelimToken::Bracket) = self.token.kind { + self.bump(); + let t = Type::List(ast::ListType { inner_type: None }); + + return Box::new(Node::node( + t, + self.sess.struct_token_loc(token, self.prev_token), + )); + } else { + let elem_type = self.parse_type_annotation(); + let t = Type::List(ast::ListType { + inner_type: Some(elem_type), + }); + + self.bump_token(TokenKind::CloseDelim(DelimToken::Bracket)); + + return Box::new(Node::node( + t, + self.sess.struct_token_loc(token, self.prev_token), + )); + } + } + // {key:value} + else if let TokenKind::OpenDelim(DelimToken::Brace) = self.token.kind { + self.bump_token(TokenKind::OpenDelim(DelimToken::Brace)); + + let key_type = if let TokenKind::Colon = self.token.kind { + None + } else { + Some(self.parse_type_annotation()) + }; + + self.bump_token(TokenKind::Colon); + + let value_type = if let TokenKind::CloseDelim(DelimToken::Brace) = self.token.kind { + None + } else { + Some(self.parse_type_annotation()) + }; + + let t = Type::Dict(ast::DictType { + key_type, + value_type, + }); + + self.bump_token(TokenKind::CloseDelim(DelimToken::Brace)); + + return Box::new(Node::node( + t, + self.sess.struct_token_loc(token, self.prev_token), + )); + } + // (type) -> type + else if let TokenKind::OpenDelim(DelimToken::Paren) = self.token.kind { + self.bump_token(TokenKind::OpenDelim(DelimToken::Paren)); + let mut params_type = vec![]; + // Parse all the params type until the params list end ')' + while self.token.kind != TokenKind::CloseDelim(DelimToken::Paren) + && self.peek_has_next() + { + params_type.push(self.parse_type_annotation()); + // All the params type should be separated by ',' + if let TokenKind::Comma = self.token.kind { + self.bump_token(TokenKind::Comma); + } + } + // If there is no params type, set it to None + let params_ty = if params_type.is_empty() { + None + } else { + Some(params_type) + }; + + self.bump_token(TokenKind::CloseDelim(DelimToken::Paren)); + // If there is a return type, parse it + // Return type start with '->' + let ret_ty = if let TokenKind::RArrow = self.token.kind { + self.bump_token(TokenKind::RArrow); + Some(self.parse_type_annotation()) + } else { + None + }; + + let t = Type::Function(ast::FunctionType { params_ty, ret_ty }); + + return Box::new(Node::node( + t, + self.sess.struct_token_loc(token, self.prev_token), + )); + } + // Expect type tokens + self.sess.struct_token_error( + &[ + kw::Any.into(), + sym::bool.into(), + sym::int.into(), + sym::float.into(), + sym::str.into(), + kw::True.into(), + kw::False.into(), + TokenKind::ident_value(), + TokenKind::literal_value(), + TokenKind::OpenDelim(DelimToken::Bracket).into(), + TokenKind::OpenDelim(DelimToken::Brace).into(), + TokenKind::CloseDelim(DelimToken::Paren).into(), + ], + self.token, + ); + self.bump(); + Box::new(Node::node( + Type::Any, + self.sess.struct_token_loc(token, self.prev_token), + )) + } +} diff --git a/crates/parser/src/session/mod.rs b/crates/parser/src/session/mod.rs new file mode 100644 index 000000000..5eeac6257 --- /dev/null +++ b/crates/parser/src/session/mod.rs @@ -0,0 +1,123 @@ +use anyhow::Result; +use compiler_base_macros::bug; +use compiler_base_session::Session; +use kcl_ast::token::Token; +use kcl_error::{Diagnostic, Handler, ParseError, ParseErrorMessage}; +use kcl_primitives::IndexSet; +use kcl_span::{BytePos, Loc, Span}; +use parking_lot::RwLock; +use std::sync::Arc; + +pub type ParseSessionRef = Arc; + +/// ParseSession represents the data associated with a parse session such as the +/// source map and the error handler. +#[derive(Default)] +pub struct ParseSession(pub Arc, pub RwLock); + +impl ParseSession { + /// New a parse session with the global session. + #[inline] + pub fn with_session(sess: Arc) -> Self { + Self(sess, RwLock::new(Handler::default())) + } + + /// Lookup char pos from span. + #[inline] + pub(crate) fn lookup_char_pos(&self, pos: BytePos) -> Loc { + self.0.sm.lookup_char_pos(pos) + } + + /// Returns the source snippet as [String] corresponding to the given [Span]. + #[inline] + pub fn span_to_snippet(&self, span: Span) -> String { + self.0.sm.span_to_snippet(span).unwrap() + } + + /// Struct an loc of first and last valid tokens in an expr, returns a loc tuple + pub fn struct_token_loc(&self, lot: Token, hit: Token) -> (Loc, Loc) { + ( + self.lookup_char_pos(lot.span.lo()), + self.lookup_char_pos(hit.span.hi()), + ) + } + + /// Construct an loc of ont token. + pub fn token_loc(&self, tok: Token) -> (Loc, Loc) { + ( + self.lookup_char_pos(tok.span.lo()), + self.lookup_char_pos(tok.span.hi()), + ) + } + + /// Struct and report an error based on a token and not abort the compiler process. + #[inline] + pub fn struct_token_error(&self, expected: &[String], got: Token) { + self.add_parse_err(ParseError::UnexpectedToken { + expected: expected.iter().map(|tok| tok.into()).collect(), + got: got.into(), + span: got.span, + }); + } + + /// Struct and report an error based on a span and not abort the compiler process. + #[inline] + pub fn struct_span_error(&self, msg: &str, span: Span) { + self.add_parse_err(ParseError::String { + message: msg.to_string(), + span, + }); + } + + #[inline] + pub fn struct_message_error(&self, msg: ParseErrorMessage, span: Span) { + self.add_parse_err(ParseError::Message { + message: msg, + span, + suggestions: None, + }); + } + + #[inline] + pub fn struct_message_error_with_suggestions( + &self, + msg: ParseErrorMessage, + span: Span, + suggestions: Option>, + ) { + self.add_parse_err(ParseError::Message { + message: msg, + span, + suggestions, + }); + } + + /// Add a error into the session. + #[inline] + fn add_parse_err(&self, err: ParseError) { + let add_error = || -> Result<()> { + self.0.add_err(err.clone().into_diag(&self.0)?)?; + self.1.write().add_diagnostic(err.into_diag(&self.0)?); + Ok(()) + }; + if let Err(err) = add_error() { + bug!( + "compiler session internal error occurs: {}", + err.to_string() + ) + } + } + + /// Append diagnostics into the parse session. + pub fn append_diagnostic(&self, diagnostics: IndexSet) -> &Self { + for diagnostic in diagnostics { + self.1.write().add_diagnostic(diagnostic); + } + self + } + + /// Classify diagnostics into errors and warnings. + pub fn classification(&self) -> (IndexSet, IndexSet) { + self.1.read().classification() + } +} diff --git a/kclvm/parser/src/testdata/multimods/kcl1/kcl.mod b/crates/parser/src/testdata/multimods/kcl1/kcl.mod similarity index 100% rename from kclvm/parser/src/testdata/multimods/kcl1/kcl.mod rename to crates/parser/src/testdata/multimods/kcl1/kcl.mod diff --git a/kclvm/parser/src/testdata/multimods/kcl1/main.k b/crates/parser/src/testdata/multimods/kcl1/main.k similarity index 100% rename from kclvm/parser/src/testdata/multimods/kcl1/main.k rename to crates/parser/src/testdata/multimods/kcl1/main.k diff --git a/kclvm/parser/src/testdata/multimods/kcl2/kcl.mod b/crates/parser/src/testdata/multimods/kcl2/kcl.mod similarity index 100% rename from kclvm/parser/src/testdata/multimods/kcl2/kcl.mod rename to crates/parser/src/testdata/multimods/kcl2/kcl.mod diff --git a/kclvm/parser/src/testdata/multimods/kcl2/main.k b/crates/parser/src/testdata/multimods/kcl2/main.k similarity index 100% rename from kclvm/parser/src/testdata/multimods/kcl2/main.k rename to crates/parser/src/testdata/multimods/kcl2/main.k diff --git a/kclvm/parser/src/testdata/pkg_not_found/suggestions.k b/crates/parser/src/testdata/pkg_not_found/suggestions.k similarity index 100% rename from kclvm/parser/src/testdata/pkg_not_found/suggestions.k rename to crates/parser/src/testdata/pkg_not_found/suggestions.k diff --git a/kclvm/parser/src/testdata/test_k_code_list/main.k b/crates/parser/src/testdata/test_k_code_list/main.k similarity index 100% rename from kclvm/parser/src/testdata/test_k_code_list/main.k rename to crates/parser/src/testdata/test_k_code_list/main.k diff --git a/kclvm/parser/src/testdata/test_k_code_list/main1.k b/crates/parser/src/testdata/test_k_code_list/main1.k similarity index 100% rename from kclvm/parser/src/testdata/test_k_code_list/main1.k rename to crates/parser/src/testdata/test_k_code_list/main1.k diff --git a/crates/parser/src/tests.rs b/crates/parser/src/tests.rs new file mode 100644 index 000000000..2706141fb --- /dev/null +++ b/crates/parser/src/tests.rs @@ -0,0 +1,870 @@ +use std::{ + env, + panic::{catch_unwind, set_hook}, + path::Path, +}; + +use compiler_base_span::{FilePathMapping, SourceMap}; +use entry::expand_input_files; +use kcl_config::modfile::{KCL_PKG_PATH, get_vendor_home}; + +use crate::*; + +use core::any::Any; + +mod ast; +mod error_recovery; +mod expr; +mod file; +mod types; + +#[macro_export] +macro_rules! parse_expr_snapshot { + ($name:ident, $src:expr) => { + #[test] + fn $name() { + insta::assert_snapshot!($crate::tests::parsing_expr_string($src)); + } + }; +} + +#[macro_export] +macro_rules! parse_module_snapshot { + ($name:ident, $src:expr) => { + #[test] + fn $name() { + insta::assert_snapshot!($crate::tests::parsing_module_string($src)); + } + }; +} + +#[macro_export] +macro_rules! parse_type_snapshot { + ($name:ident, $src:expr) => { + #[test] + fn $name() { + insta::assert_snapshot!($crate::tests::parsing_type_string($src)); + } + }; +} + +#[macro_export] +macro_rules! parse_type_node_snapshot { + ($name:ident, $src:expr) => { + #[test] + fn $name() { + insta::assert_snapshot!($crate::tests::parsing_type_node_string($src)); + } + }; +} + +#[macro_export] +macro_rules! parse_file_ast_json_snapshot { + ($name:ident, $filename:expr, $src:expr) => { + #[test] + fn $name() { + insta::assert_snapshot!($crate::tests::parsing_file_ast_json($filename, $src)); + } + }; +} + +#[macro_export] +macro_rules! parse_file_snapshot { + ($name:ident, $filename:expr) => { + #[test] + fn $name() { + insta::assert_snapshot!($crate::tests::parsing_file_string($filename)); + } + }; +} + +pub(crate) fn parsing_expr_string(src: &str) -> String { + let sm = SourceMap::new(FilePathMapping::empty()); + let sf = sm.new_source_file(PathBuf::from("").into(), src.to_string()); + let sess = &ParseSession::with_source_map(Arc::new(sm)); + + match sf.src.as_ref() { + Some(src_from_sf) => create_session_globals_then(|| { + let stream = parse_token_streams(sess, src_from_sf.as_str(), new_byte_pos(0)); + let mut parser = Parser::new(sess, stream); + let expr = parser.parse_expr(); + format!("{expr:#?}\n") + }), + None => "".to_string(), + } +} + +pub(crate) fn parsing_module_string(src: &str) -> String { + let sm = SourceMap::new(FilePathMapping::empty()); + let sf = sm.new_source_file(PathBuf::from("").into(), src.to_string()); + let sess = &ParseSession::with_source_map(Arc::new(sm)); + + match sf.src.as_ref() { + Some(src_from_sf) => create_session_globals_then(|| { + let stream = parse_token_streams(sess, src_from_sf.as_str(), new_byte_pos(0)); + let mut parser = Parser::new(sess, stream); + let module = parser.parse_module(); + format!("{module:#?}\n") + }), + None => "".to_string(), + } +} + +pub(crate) fn parsing_type_string(src: &str) -> String { + let sm = SourceMap::new(FilePathMapping::empty()); + sm.new_source_file(PathBuf::from("").into(), src.to_string()); + let sess = &ParseSession::with_source_map(Arc::new(sm)); + + create_session_globals_then(|| { + let stream = parse_token_streams(sess, src, new_byte_pos(0)); + let mut parser = Parser::new(sess, stream); + let typ = parser.parse_type_annotation(); + format!("{typ:#?}\n") + }) +} + +pub(crate) fn parsing_type_node_string(src: &str) -> String { + let sm = SourceMap::new(FilePathMapping::empty()); + sm.new_source_file(PathBuf::from("").into(), src.to_string()); + let sess = &ParseSession::with_source_map(Arc::new(sm)); + + create_session_globals_then(|| { + let stream = parse_token_streams(sess, src, new_byte_pos(0)); + let mut parser = Parser::new(sess, stream); + let typ = parser.parse_type_annotation(); + typ.node.to_string() + }) +} + +pub(crate) fn parsing_file_ast_json(filename: &str, src: &str) -> String { + let m = crate::parse_file_with_global_session( + Arc::new(ParseSession::default()), + filename, + Some(src.into()), + ) + .unwrap(); + serde_json::ser::to_string_pretty(&m).unwrap() +} + +pub(crate) fn parsing_file_string(filename: &str) -> String { + let code = std::fs::read_to_string(filename).unwrap(); + let m = crate::parse_single_file(filename.trim_start_matches("testdata/"), Some(code)) + .expect(filename) + .module; + serde_json::ser::to_string_pretty(&m).unwrap() +} + +pub fn check_result_panic_info(result: Result<(), Box>) { + if let Err(e) = result { + assert!(e.downcast::().is_ok()); + }; +} + +const PARSE_EXPR_INVALID_TEST_CASES: &[&str] = + &["fs1_i1re1~s", "fh==-h==-", "8_________i", "1MM", "0x00x"]; + +#[test] +pub fn test_parse_expr_invalid() { + for case in PARSE_EXPR_INVALID_TEST_CASES { + set_hook(Box::new(|_| {})); + let result = catch_unwind(|| { + parse_expr(case); + }); + check_result_panic_info(result); + } +} + +const PARSE_FILE_INVALID_TEST_CASES: &[&str] = &[ + "a: int", // No initial value error + "a -", // Invalid binary expression error + "a?: int", // Invalid optional annotation error + "if a not is not b: a = 1", // Logic operator error + "if True:\n a=1\n b=2", // Indent error with recovery + "a[1::::]", // List slice error + "a[1 a]", // List index error + "{a ++ 1}", // Config attribute operator error + "func(a=1,b)", // Call argument error + "'${}'", // Empty string interpolation error + "'${a: jso}'", // Invalid string interpolation format spec error +]; + +#[test] +pub fn test_parse_file_invalid() { + for case in PARSE_FILE_INVALID_TEST_CASES { + let result = parse_file_force_errors("test.k", Some((&case).to_string())); + assert!(result.is_err(), "case: {case}, result {result:?}"); + } +} + +pub fn test_vendor_home() { + let vendor = &PathBuf::from(".") + .join("testdata") + .join("test_vendor") + .canonicalize() + .unwrap() + .display() + .to_string() + .adjust_canonicalization(); + unsafe { env::set_var(KCL_PKG_PATH, vendor) }; + assert_eq!(get_vendor_home(), vendor.to_string()); +} + +fn set_vendor_home() -> String { + // set env vendor + let vendor = &PathBuf::from(".") + .join("testdata") + .join("test_vendor") + .canonicalize() + .unwrap() + .display() + .to_string() + .adjust_canonicalization(); + unsafe { env::set_var(KCL_PKG_PATH, vendor) }; + debug_assert_eq!(get_vendor_home(), vendor.to_string()); + vendor.to_string() +} + +#[test] +/// The testing will set environment variables, +/// so can not to execute test cases concurrently. +fn test_in_order() { + test_import_vendor_by_external_arguments(); + println!("{:?} PASS", "test_import_vendor_by_external_arguments"); + test_import_vendor_without_vendor_home(); + println!("{:?} PASS", "test_import_vendor_without_vendor_home"); + test_import_vendor_without_kclmod(); + println!("{:?} PASS", "test_import_vendor_without_kclmod"); + test_import_vendor(); + println!("{:?} PASS", "test_import_vendor"); + test_import_vendor_with_same_internal_pkg(); + println!("{:?} PASS", "test_import_vendor_with_same_internal_pkg"); + test_import_vendor_without_kclmod_and_same_name(); + println!( + "{:?} PASS", + "test_import_vendor_without_kclmod_and_same_name" + ); + test_vendor_home(); + println!("{:?} PASS", "test_vendor_home"); + test_pkg_not_found_suggestion(); + println!("{:?} PASS", "test_pkg_not_found_suggestion"); +} + +pub fn test_import_vendor() { + let module_cache = KCLModuleCache::default(); + let vendor = set_vendor_home(); + let sm = SourceMap::new(FilePathMapping::empty()); + let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); + + let test_cases = vec![ + ("assign.k", vec!["__main__", "assign", "assign.assign"]), + ( + "config_expr.k", + vec!["__main__", "config_expr", "config_expr.config_expr_02"], + ), + ( + "nested_vendor.k", + vec![ + "__main__", + "nested_vendor", + "nested_vendor.nested_vendor", + "vendor_subpkg", + "vendor_subpkg.sub.sub1", + "vendor_subpkg.sub.sub2", + "vendor_subpkg.sub.sub", + "vendor_subpkg.sub", + ], + ), + ( + "subpkg.k", + vec![ + "__main__", + "vendor_subpkg", + "vendor_subpkg.sub.sub1", + "vendor_subpkg.sub.sub", + "vendor_subpkg.sub.sub2", + "vendor_subpkg.sub", + ], + ), + ]; + + let dir = &PathBuf::from(".") + .join("testdata") + .join("import_vendor") + .canonicalize() + .unwrap(); + + let test_fn = + |test_case_name: &&str, pkgs: &Vec<&str>, module_cache: Option| { + let test_case_path = dir + .join(test_case_name) + .display() + .to_string() + .adjust_canonicalization(); + let m = load_program(sess.clone(), &[&test_case_path], None, module_cache) + .unwrap() + .program; + assert_eq!(m.pkgs.len(), pkgs.len()); + m.pkgs.clone().into_iter().for_each(|(name, modules)| { + println!("{:?} - {:?}", test_case_name, name); + assert!(pkgs.contains(&name.as_str())); + for pkg in pkgs.clone() { + if name == pkg { + if name == "__main__" { + assert_eq!(modules.len(), 1); + let module = m.get_module(modules.get(0).unwrap()).unwrap().unwrap(); + assert_eq!(module.filename, test_case_path); + } else { + modules.into_iter().for_each(|module| { + let module = m.get_module(&module).unwrap().unwrap(); + assert!(module.filename.contains(&vendor)); + }); + } + break; + } + } + }); + }; + + test_cases + .iter() + .for_each(|(test_case_name, pkgs)| test_fn(test_case_name, pkgs, None)); + + test_cases.iter().for_each(|(test_case_name, pkgs)| { + test_fn(test_case_name, pkgs, Some(module_cache.clone())) + }); +} + +pub fn test_import_vendor_without_kclmod() { + let vendor = set_vendor_home(); + let sm = SourceMap::new(FilePathMapping::empty()); + let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); + + let test_cases = vec![("import_vendor.k", vec!["__main__", "assign.assign"])]; + + let dir = &PathBuf::from(".") + .join("testdata_without_kclmod") + .canonicalize() + .unwrap(); + + test_cases.into_iter().for_each(|(test_case_name, pkgs)| { + let test_case_path = dir + .join(test_case_name) + .display() + .to_string() + .adjust_canonicalization(); + let m = load_program(sess.clone(), &[&test_case_path], None, None) + .unwrap() + .program; + assert_eq!(m.pkgs.len(), pkgs.len()); + m.pkgs.clone().into_iter().for_each(|(name, modules)| { + assert!(pkgs.contains(&name.as_str())); + for pkg in pkgs.clone() { + if name == pkg { + if name == "__main__" { + assert_eq!(modules.len(), 1); + let module = m.get_module(modules.get(0).unwrap()).unwrap().unwrap(); + assert_eq!(module.filename, test_case_path); + } else { + modules.into_iter().for_each(|module| { + let module = m.get_module(&module).unwrap().unwrap(); + assert!(module.filename.contains(&vendor)); + }); + } + break; + } + } + }); + }); +} + +pub fn test_import_vendor_without_vendor_home() { + unsafe { env::set_var(KCL_PKG_PATH, "") }; + let sm = SourceMap::new(FilePathMapping::empty()); + let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); + let dir = &PathBuf::from(".") + .join("testdata") + .join("import_vendor") + .canonicalize() + .unwrap(); + let test_case_path = dir.join("assign.k").display().to_string(); + match load_program(sess.clone(), &[&test_case_path], None, None) { + Ok(_) => { + let errors = sess.classification().0; + let msgs = [ + "pkgpath assign not found in the program", + "try 'kcl mod add assign' to download the missing package", + "browse more packages at 'https://artifacthub.io'", + "pkgpath assign.assign not found in the program", + ]; + assert_eq!(errors.len(), msgs.len()); + for (diag, m) in errors.iter().zip(msgs.iter()) { + assert_eq!(diag.messages[0].message, m.to_string()); + } + } + Err(_) => { + panic!("Unreachable code.") + } + } + + match load_program( + sess.clone(), + &[&test_case_path], + None, + Some(KCLModuleCache::default()), + ) { + Ok(_) => { + let errors = sess.classification().0; + let msgs = [ + "pkgpath assign not found in the program", + "try 'kcl mod add assign' to download the missing package", + "browse more packages at 'https://artifacthub.io'", + "pkgpath assign.assign not found in the program", + ]; + assert_eq!(errors.len(), msgs.len()); + for (diag, m) in errors.iter().zip(msgs.iter()) { + assert_eq!(diag.messages[0].message, m.to_string()); + } + } + Err(_) => { + panic!("Unreachable code.") + } + } +} + +fn test_import_vendor_with_same_internal_pkg() { + set_vendor_home(); + let sm = SourceMap::new(FilePathMapping::empty()); + let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); + let dir = &PathBuf::from(".") + .join("testdata") + .join("import_vendor") + .canonicalize() + .unwrap(); + let test_case_path = dir.join("same_name.k").display().to_string(); + match load_program(sess.clone(), &[&test_case_path], None, None) { + Ok(_) => { + let errors = sess.classification().0; + let msgs = [ + "the `same_vendor` is found multiple times in the current package and vendor package", + ]; + assert_eq!(errors.len(), msgs.len()); + for (diag, m) in errors.iter().zip(msgs.iter()) { + assert_eq!(diag.messages[0].message, m.to_string()); + } + } + Err(_) => { + panic!("Unreachable code.") + } + } + match load_program( + sess.clone(), + &[&test_case_path], + None, + Some(KCLModuleCache::default()), + ) { + Ok(_) => { + let errors = sess.classification().0; + let msgs = [ + "the `same_vendor` is found multiple times in the current package and vendor package", + ]; + assert_eq!(errors.len(), msgs.len()); + for (diag, m) in errors.iter().zip(msgs.iter()) { + assert_eq!(diag.messages[0].message, m.to_string()); + } + } + Err(_) => { + panic!("Unreachable code.") + } + } +} + +fn test_import_vendor_without_kclmod_and_same_name() { + set_vendor_home(); + let sm = SourceMap::new(FilePathMapping::empty()); + let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); + let dir = &PathBuf::from(".") + .join("testdata_without_kclmod") + .join("same_name") + .canonicalize() + .unwrap(); + let test_case_path = dir.join("assign.k").display().to_string(); + match load_program(sess.clone(), &[&test_case_path], None, None) { + Ok(_) => { + let errors = sess.classification().0; + let msgs = + ["the `assign` is found multiple times in the current package and vendor package"]; + assert_eq!(errors.len(), msgs.len()); + for (diag, m) in errors.iter().zip(msgs.iter()) { + assert_eq!(diag.messages[0].message, m.to_string()); + } + } + Err(_) => { + panic!("Unreachable code.") + } + } + + match load_program( + sess.clone(), + &[&test_case_path], + None, + Some(KCLModuleCache::default()), + ) { + Ok(_) => { + let errors = sess.classification().0; + let msgs = + ["the `assign` is found multiple times in the current package and vendor package"]; + assert_eq!(errors.len(), msgs.len()); + for (diag, m) in errors.iter().zip(msgs.iter()) { + assert_eq!(diag.messages[0].message, m.to_string()); + } + } + Err(_) => { + panic!("Unreachable code.") + } + } +} + +fn test_import_vendor_by_external_arguments() { + let vendor = set_vendor_home(); + let sm = SourceMap::new(FilePathMapping::empty()); + let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); + let module_cache = KCLModuleCache::default(); + let external_dir = &PathBuf::from(".") + .join("testdata") + .join("test_vendor") + .canonicalize() + .unwrap(); + + let test_cases = vec![ + ( + "import_by_external_assign.k", + "assign", + vec!["__main__", "assign"], + ), + ( + "import_by_external_config_expr.k", + "config_expr", + vec!["__main__", "config_expr"], + ), + ( + "import_by_external_nested_vendor.k", + "nested_vendor", + vec![ + "__main__", + "nested_vendor", + "vendor_subpkg", + "vendor_subpkg.sub.sub2", + "vendor_subpkg.sub.sub1", + "vendor_subpkg.sub.sub", + "vendor_subpkg.sub", + ], + ), + ( + "import_by_external_vendor_subpkg.k", + "vendor_subpkg", + vec![ + "__main__", + "vendor_subpkg", + "vendor_subpkg.sub.sub1", + "vendor_subpkg.sub.sub2", + "vendor_subpkg.sub.sub", + "vendor_subpkg.sub", + ], + ), + ]; + + let dir = &PathBuf::from(".") + .join("testdata_without_kclmod") + .canonicalize() + .unwrap(); + + let test_fn = |test_case_name: &&str, + dep_name: &&str, + pkgs: &Vec<&str>, + module_cache: Option| { + let mut opts = LoadProgramOptions::default(); + opts.package_maps.insert( + dep_name.to_string(), + external_dir.join(dep_name).display().to_string(), + ); + let test_case_path = dir + .join(test_case_name) + .display() + .to_string() + .adjust_canonicalization(); + let m = load_program(sess.clone(), &[&test_case_path], None, module_cache) + .unwrap() + .program; + assert_eq!(m.pkgs.len(), pkgs.len()); + m.pkgs.clone().into_iter().for_each(|(name, modules)| { + assert!(pkgs.contains(&name.as_str())); + for pkg in pkgs.clone() { + if name == pkg { + if name == "__main__" { + assert_eq!(modules.len(), 1); + let module = m.get_module(modules.get(0).unwrap()).unwrap().unwrap(); + assert_eq!(module.filename, test_case_path); + } else { + modules.into_iter().for_each(|module| { + let module = m.get_module(&module).unwrap().unwrap(); + assert!(module.filename.contains(&vendor)); + }); + } + break; + } + } + }); + }; + + test_cases + .iter() + .for_each(|(test_case_name, dep_name, pkgs)| test_fn(test_case_name, dep_name, pkgs, None)); + + test_cases + .iter() + .for_each(|(test_case_name, dep_name, pkgs)| { + test_fn(test_case_name, dep_name, pkgs, Some(module_cache.clone())) + }); +} + +#[test] +fn test_get_compile_entries_from_paths() { + let testpath = PathBuf::from("./src/testdata/multimods") + .canonicalize() + .unwrap(); + + // [`kcl1_path`] is a normal path of the package [`kcl1`] root directory. + // It looks like `/xxx/xxx/xxx`. + let kcl1_path = testpath.join("kcl1"); + + // [`kcl2_path`] is a mod relative path of the packege [`kcl2`] root directory. + // It looks like `${kcl2:KCL_MOD}/xxx/xxx` + let kcl2_path = PathBuf::from("${kcl2:KCL_MOD}/main.k"); + + // [`kcl3_path`] is a mod relative path of the [`__main__`] packege. + let kcl3_path = PathBuf::from("${KCL_MOD}/main.k"); + + // [`package_maps`] is a map to show the real path of the mod relative path [`kcl2`]. + let mut opts = LoadProgramOptions::default(); + opts.package_maps.insert( + "kcl2".to_string(), + testpath.join("kcl2").to_str().unwrap().to_string(), + ); + + // [`get_compile_entries_from_paths`] will return the map of package name to package root real path. + let entries = get_compile_entries_from_paths( + &[ + kcl1_path.to_str().unwrap().to_string(), + kcl2_path.display().to_string(), + kcl3_path.display().to_string(), + ], + &opts, + ) + .unwrap(); + + assert_eq!(entries.len(), 3); + + assert_eq!(entries.get_nth_entry(0).unwrap().name(), "__main__"); + assert_eq!( + PathBuf::from(entries.get_nth_entry(0).unwrap().path()) + .canonicalize() + .unwrap() + .display() + .to_string(), + kcl1_path.canonicalize().unwrap().to_str().unwrap() + ); + + assert_eq!(entries.get_nth_entry(1).unwrap().name(), "kcl2"); + assert_eq!( + PathBuf::from(entries.get_nth_entry(1).unwrap().path()) + .canonicalize() + .unwrap() + .display() + .to_string(), + testpath + .join("kcl2") + .canonicalize() + .unwrap() + .to_str() + .unwrap() + ); + + assert_eq!(entries.get_nth_entry(2).unwrap().name(), "__main__"); + assert_eq!( + PathBuf::from(entries.get_nth_entry(2).unwrap().path()) + .canonicalize() + .unwrap() + .to_str() + .unwrap(), + kcl1_path.canonicalize().unwrap().to_str().unwrap() + ); +} + +#[test] +fn test_dir_with_k_code_list() { + let sm = SourceMap::new(FilePathMapping::empty()); + let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); + let testpath = PathBuf::from("./src/testdata/test_k_code_list") + .canonicalize() + .unwrap(); + + let mut opts = LoadProgramOptions::default(); + opts.k_code_list = vec!["test_code = 1".to_string()]; + + match load_program( + sess.clone(), + &[&testpath.display().to_string()], + Some(opts.clone()), + None, + ) { + Ok(_) => panic!("unreachable code"), + Err(err) => assert!(err.to_string().contains("Invalid code list")), + } + + match load_program( + sess.clone(), + &[&testpath.display().to_string()], + Some(opts), + Some(KCLModuleCache::default()), + ) { + Ok(_) => panic!("unreachable code"), + Err(err) => assert!(err.to_string().contains("Invalid code list")), + } +} + +pub fn test_pkg_not_found_suggestion() { + let sm = SourceMap::new(FilePathMapping::empty()); + let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); + let dir = &PathBuf::from("./src/testdata/pkg_not_found") + .canonicalize() + .unwrap(); + let test_case_path = dir.join("suggestions.k").display().to_string(); + match load_program(sess.clone(), &[&test_case_path], None, None) { + Ok(_) => { + let errors = sess.classification().0; + let msgs = [ + "pkgpath k9s not found in the program", + "try 'kcl mod add k9s' to download the missing package", + "browse more packages at 'https://artifacthub.io'", + ]; + assert_eq!(errors.len(), msgs.len()); + for (diag, m) in errors.iter().zip(msgs.iter()) { + assert_eq!(diag.messages[0].message, m.to_string()); + } + } + Err(_) => { + panic!("Unreachable code.") + } + } +} + +#[test] +fn test_expand_input_files_with_kcl_mod() { + let path = PathBuf::from("testdata/expand_file_pattern"); + let input_files = vec![ + path.join("**").join("main.k").to_string_lossy().to_string(), + "${KCL_MOD}/testdata/expand_file_pattern/KCL_MOD".to_string(), + ]; + let expected_files = vec![ + path.join("kcl1/kcl2/main.k").to_string_lossy().to_string(), + path.join("kcl1/kcl4/main.k").to_string_lossy().to_string(), + path.join("kcl1/main.k").to_string_lossy().to_string(), + path.join("kcl3/main.k").to_string_lossy().to_string(), + path.join("main.k").to_string_lossy().to_string(), + "${KCL_MOD}/testdata/expand_file_pattern/KCL_MOD".to_string(), + ]; + let got_paths: Vec = expand_input_files(&input_files) + .iter() + .map(|s| s.replace(['/', '\\'], "")) + .collect(); + let expect_paths: Vec = expected_files + .iter() + .map(|s| s.replace(['/', '\\'], "")) + .collect(); + assert_eq!(got_paths, expect_paths); +} + +#[test] +#[cfg(not(windows))] +fn test_expand_input_files() { + let input_files = vec!["./testdata/expand_file_pattern/**/main.k".to_string()]; + let mut expected_files = vec![ + Path::new("testdata/expand_file_pattern/kcl1/kcl2/main.k") + .to_string_lossy() + .to_string(), + Path::new("testdata/expand_file_pattern/kcl3/main.k") + .to_string_lossy() + .to_string(), + Path::new("testdata/expand_file_pattern/main.k") + .to_string_lossy() + .to_string(), + Path::new("testdata/expand_file_pattern/kcl1/main.k") + .to_string_lossy() + .to_string(), + Path::new("testdata/expand_file_pattern/kcl1/kcl4/main.k") + .to_string_lossy() + .to_string(), + ]; + expected_files.sort(); + let mut input = expand_input_files(&input_files); + input.sort(); + assert_eq!(input, expected_files); + + let input_files = vec![ + "./testdata/expand_file_pattern/kcl1/main.k".to_string(), + "./testdata/expand_file_pattern/**/main.k".to_string(), + ]; + let mut expected_files = vec![ + Path::new("testdata/expand_file_pattern/kcl1/main.k") + .to_string_lossy() + .to_string(), + Path::new("testdata/expand_file_pattern/kcl1/main.k") + .to_string_lossy() + .to_string(), + Path::new("testdata/expand_file_pattern/kcl1/kcl2/main.k") + .to_string_lossy() + .to_string(), + Path::new("testdata/expand_file_pattern/kcl1/kcl4/main.k") + .to_string_lossy() + .to_string(), + Path::new("testdata/expand_file_pattern/kcl3/main.k") + .to_string_lossy() + .to_string(), + Path::new("testdata/expand_file_pattern/main.k") + .to_string_lossy() + .to_string(), + ]; + expected_files.sort(); + let mut input = expand_input_files(&input_files); + input.sort(); + assert_eq!(input, expected_files); +} + +#[test] +fn parse_all_file_under_path() { + let testpath = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("testdata") + .join("parse_all_modules"); + + let main = testpath.join("a"); + let main = main.to_str().unwrap(); + let helloworld = testpath.join("helloworld_0.0.1"); + let b = testpath.join("b"); + + let sess = ParseSessionRef::default(); + let mut opt = LoadProgramOptions::default(); + opt.vendor_dirs = vec![get_vendor_home()]; + opt.package_maps + .insert("b".to_string(), b.to_str().unwrap().to_string()); + opt.package_maps.insert( + "helloworld".to_string(), + helloworld.to_str().unwrap().to_string(), + ); + + let res = load_all_files_under_paths(sess.clone(), &[main], Some(opt), None).unwrap(); + + assert_eq!(res.program.pkgs.keys().len(), 1); + assert_eq!(res.program.pkgs_not_imported.keys().len(), 3); + + assert_eq!(res.paths.len(), 1); +} diff --git a/kclvm/parser/src/tests/ast.rs b/crates/parser/src/tests/ast.rs similarity index 100% rename from kclvm/parser/src/tests/ast.rs rename to crates/parser/src/tests/ast.rs diff --git a/kclvm/parser/src/tests/error_recovery.rs b/crates/parser/src/tests/error_recovery.rs similarity index 100% rename from kclvm/parser/src/tests/error_recovery.rs rename to crates/parser/src/tests/error_recovery.rs diff --git a/kclvm/parser/src/tests/expr.rs b/crates/parser/src/tests/expr.rs similarity index 100% rename from kclvm/parser/src/tests/expr.rs rename to crates/parser/src/tests/expr.rs diff --git a/kclvm/parser/src/tests/file.rs b/crates/parser/src/tests/file.rs similarity index 100% rename from kclvm/parser/src/tests/file.rs rename to crates/parser/src/tests/file.rs diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__assign_stmt.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__assign_stmt.snap new file mode 100644 index 000000000..7c393b772 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__assign_stmt.snap @@ -0,0 +1,58 @@ +--- +source: crates/parser/src/tests/ast.rs +expression: "$crate :: tests :: parsing_file_ast_json(\"hello.k\", r####\"a=123\"####)" +--- +{ + "filename": "hello.k", + "doc": null, + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "a", + "filename": "hello.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 1 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "hello.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 1 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 123 + } + }, + "filename": "hello.k", + "line": 1, + "column": 2, + "end_line": 1, + "end_column": 5 + }, + "ty": null + }, + "filename": "hello.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 5 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__basic_stmt.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__basic_stmt.snap new file mode 100644 index 000000000..7f15ac75f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__basic_stmt.snap @@ -0,0 +1,193 @@ +--- +source: crates/parser/src/tests/ast.rs +expression: "$crate :: tests ::\nparsing_file_ast_json(\"hello.k\",\nr####\"\n# comment1\na = 1\n# comment22\nb = 2\n# comment333\nc = 3 # comment4444\n \"####)" +--- +{ + "filename": "hello.k", + "doc": null, + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "a", + "filename": "hello.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 1 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "hello.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 1 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "hello.k", + "line": 3, + "column": 4, + "end_line": 3, + "end_column": 5 + }, + "ty": null + }, + "filename": "hello.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 5 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "b", + "filename": "hello.k", + "line": 5, + "column": 0, + "end_line": 5, + "end_column": 1 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "hello.k", + "line": 5, + "column": 0, + "end_line": 5, + "end_column": 1 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 2 + } + }, + "filename": "hello.k", + "line": 5, + "column": 4, + "end_line": 5, + "end_column": 5 + }, + "ty": null + }, + "filename": "hello.k", + "line": 5, + "column": 0, + "end_line": 5, + "end_column": 5 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "c", + "filename": "hello.k", + "line": 7, + "column": 0, + "end_line": 7, + "end_column": 1 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "hello.k", + "line": 7, + "column": 0, + "end_line": 7, + "end_column": 1 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 3 + } + }, + "filename": "hello.k", + "line": 7, + "column": 4, + "end_line": 7, + "end_column": 5 + }, + "ty": null + }, + "filename": "hello.k", + "line": 7, + "column": 0, + "end_line": 7, + "end_column": 5 + } + ], + "comments": [ + { + "node": { + "text": "# comment1" + }, + "filename": "hello.k", + "line": 2, + "column": 0, + "end_line": 2, + "end_column": 10 + }, + { + "node": { + "text": "# comment22" + }, + "filename": "hello.k", + "line": 4, + "column": 0, + "end_line": 4, + "end_column": 11 + }, + { + "node": { + "text": "# comment333" + }, + "filename": "hello.k", + "line": 6, + "column": 0, + "end_line": 6, + "end_column": 12 + }, + { + "node": { + "text": "# comment4444" + }, + "filename": "hello.k", + "line": 7, + "column": 6, + "end_line": 7, + "end_column": 19 + } + ] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__if_stmt_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__if_stmt_0.snap new file mode 100644 index 000000000..9f13863a8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__if_stmt_0.snap @@ -0,0 +1,557 @@ +--- +source: crates/parser/src/tests/ast.rs +expression: "$crate :: tests ::\nparsing_file_ast_json(\"hello.k\",\nr####\"\na = 10\nb = 12\n_condition = 0\nif a == 11 or b == 13: _condition = 1\nelif a == 10 and b == 12: _condition = 2\ncondition = _condition\n \"####)" +--- +{ + "filename": "hello.k", + "doc": null, + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "a", + "filename": "hello.k", + "line": 2, + "column": 0, + "end_line": 2, + "end_column": 1 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "hello.k", + "line": 2, + "column": 0, + "end_line": 2, + "end_column": 1 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 10 + } + }, + "filename": "hello.k", + "line": 2, + "column": 4, + "end_line": 2, + "end_column": 6 + }, + "ty": null + }, + "filename": "hello.k", + "line": 2, + "column": 0, + "end_line": 2, + "end_column": 6 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "b", + "filename": "hello.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 1 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "hello.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 1 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 12 + } + }, + "filename": "hello.k", + "line": 3, + "column": 4, + "end_line": 3, + "end_column": 6 + }, + "ty": null + }, + "filename": "hello.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 6 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "_condition", + "filename": "hello.k", + "line": 4, + "column": 0, + "end_line": 4, + "end_column": 10 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "hello.k", + "line": 4, + "column": 0, + "end_line": 4, + "end_column": 10 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 0 + } + }, + "filename": "hello.k", + "line": 4, + "column": 13, + "end_line": 4, + "end_column": 14 + }, + "ty": null + }, + "filename": "hello.k", + "line": 4, + "column": 0, + "end_line": 4, + "end_column": 14 + }, + { + "node": { + "type": "If", + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "_condition", + "filename": "hello.k", + "line": 5, + "column": 23, + "end_line": 5, + "end_column": 33 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "hello.k", + "line": 5, + "column": 23, + "end_line": 5, + "end_column": 33 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "hello.k", + "line": 5, + "column": 36, + "end_line": 5, + "end_column": 37 + }, + "ty": null + }, + "filename": "hello.k", + "line": 5, + "column": 23, + "end_line": 5, + "end_column": 37 + } + ], + "cond": { + "node": { + "type": "Binary", + "left": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "a", + "filename": "hello.k", + "line": 5, + "column": 3, + "end_line": 5, + "end_column": 4 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 5, + "column": 3, + "end_line": 5, + "end_column": 4 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 11 + } + }, + "filename": "hello.k", + "line": 5, + "column": 8, + "end_line": 5, + "end_column": 10 + } + ] + }, + "filename": "hello.k", + "line": 5, + "column": 3, + "end_line": 5, + "end_column": 21 + }, + "op": "Or", + "right": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "b", + "filename": "hello.k", + "line": 5, + "column": 14, + "end_line": 5, + "end_column": 15 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 5, + "column": 14, + "end_line": 5, + "end_column": 15 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 13 + } + }, + "filename": "hello.k", + "line": 5, + "column": 19, + "end_line": 5, + "end_column": 21 + } + ] + }, + "filename": "hello.k", + "line": 5, + "column": 14, + "end_line": 5, + "end_column": 21 + } + }, + "filename": "hello.k", + "line": 5, + "column": 3, + "end_line": 5, + "end_column": 21 + }, + "orelse": [ + { + "node": { + "type": "If", + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "_condition", + "filename": "hello.k", + "line": 6, + "column": 26, + "end_line": 6, + "end_column": 36 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "hello.k", + "line": 6, + "column": 26, + "end_line": 6, + "end_column": 36 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 2 + } + }, + "filename": "hello.k", + "line": 6, + "column": 39, + "end_line": 6, + "end_column": 40 + }, + "ty": null + }, + "filename": "hello.k", + "line": 6, + "column": 26, + "end_line": 6, + "end_column": 40 + } + ], + "cond": { + "node": { + "type": "Binary", + "left": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "a", + "filename": "hello.k", + "line": 6, + "column": 5, + "end_line": 6, + "end_column": 6 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 6, + "column": 5, + "end_line": 6, + "end_column": 6 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 10 + } + }, + "filename": "hello.k", + "line": 6, + "column": 10, + "end_line": 6, + "end_column": 12 + } + ] + }, + "filename": "hello.k", + "line": 6, + "column": 5, + "end_line": 6, + "end_column": 24 + }, + "op": "And", + "right": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "b", + "filename": "hello.k", + "line": 6, + "column": 17, + "end_line": 6, + "end_column": 18 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 6, + "column": 17, + "end_line": 6, + "end_column": 18 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 12 + } + }, + "filename": "hello.k", + "line": 6, + "column": 22, + "end_line": 6, + "end_column": 24 + } + ] + }, + "filename": "hello.k", + "line": 6, + "column": 17, + "end_line": 6, + "end_column": 24 + } + }, + "filename": "hello.k", + "line": 6, + "column": 5, + "end_line": 6, + "end_column": 24 + }, + "orelse": [] + }, + "filename": "hello.k", + "line": 6, + "column": 0, + "end_line": 7, + "end_column": 0 + } + ] + }, + "filename": "hello.k", + "line": 5, + "column": 0, + "end_line": 7, + "end_column": 0 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "condition", + "filename": "hello.k", + "line": 7, + "column": 0, + "end_line": 7, + "end_column": 9 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "hello.k", + "line": 7, + "column": 0, + "end_line": 7, + "end_column": 9 + } + ], + "value": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "_condition", + "filename": "hello.k", + "line": 7, + "column": 12, + "end_line": 7, + "end_column": 22 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 7, + "column": 12, + "end_line": 7, + "end_column": 22 + }, + "ty": null + }, + "filename": "hello.k", + "line": 7, + "column": 0, + "end_line": 7, + "end_column": 22 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__if_stmt_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__if_stmt_1.snap new file mode 100644 index 000000000..1ca0dde97 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__if_stmt_1.snap @@ -0,0 +1,320 @@ +--- +source: crates/parser/src/tests/ast.rs +expression: "$crate :: tests ::\nparsing_file_ast_json(\"hello.k\",\nr####\"\ndata2 = {\n **{key = \"value1\"}\n if a == 123: if b == 456: key = \"value2\"\n}\n \"####)" +--- +{ + "filename": "hello.k", + "doc": null, + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "data2", + "filename": "hello.k", + "line": 2, + "column": 0, + "end_line": 2, + "end_column": 5 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "hello.k", + "line": 2, + "column": 0, + "end_line": 2, + "end_column": 5 + } + ], + "value": { + "node": { + "type": "Config", + "items": [ + { + "node": { + "key": null, + "value": { + "node": { + "type": "Config", + "items": [ + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "key", + "filename": "hello.k", + "line": 3, + "column": 7, + "end_line": 3, + "end_column": 10 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 3, + "column": 7, + "end_line": 3, + "end_column": 10 + }, + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"value1\"", + "value": "value1" + }, + "filename": "hello.k", + "line": 3, + "column": 13, + "end_line": 3, + "end_column": 21 + }, + "operation": "Override" + }, + "filename": "hello.k", + "line": 3, + "column": 7, + "end_line": 3, + "end_column": 21 + } + ] + }, + "filename": "hello.k", + "line": 3, + "column": 6, + "end_line": 3, + "end_column": 22 + }, + "operation": "Union" + }, + "filename": "hello.k", + "line": 3, + "column": 4, + "end_line": 3, + "end_column": 22 + }, + { + "node": { + "key": null, + "value": { + "node": { + "type": "ConfigIfEntry", + "if_cond": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "a", + "filename": "hello.k", + "line": 4, + "column": 7, + "end_line": 4, + "end_column": 8 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 4, + "column": 7, + "end_line": 4, + "end_column": 8 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 123 + } + }, + "filename": "hello.k", + "line": 4, + "column": 12, + "end_line": 4, + "end_column": 15 + } + ] + }, + "filename": "hello.k", + "line": 4, + "column": 7, + "end_line": 4, + "end_column": 15 + }, + "items": [ + { + "node": { + "key": null, + "value": { + "node": { + "type": "ConfigIfEntry", + "if_cond": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "b", + "filename": "hello.k", + "line": 4, + "column": 20, + "end_line": 4, + "end_column": 21 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 4, + "column": 20, + "end_line": 4, + "end_column": 21 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 456 + } + }, + "filename": "hello.k", + "line": 4, + "column": 25, + "end_line": 4, + "end_column": 28 + } + ] + }, + "filename": "hello.k", + "line": 4, + "column": 20, + "end_line": 4, + "end_column": 28 + }, + "items": [ + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "key", + "filename": "hello.k", + "line": 4, + "column": 30, + "end_line": 4, + "end_column": 33 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 4, + "column": 30, + "end_line": 4, + "end_column": 33 + }, + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"value2\"", + "value": "value2" + }, + "filename": "hello.k", + "line": 4, + "column": 36, + "end_line": 4, + "end_column": 44 + }, + "operation": "Override" + }, + "filename": "hello.k", + "line": 4, + "column": 30, + "end_line": 4, + "end_column": 44 + } + ], + "orelse": null + }, + "filename": "hello.k", + "line": 4, + "column": 17, + "end_line": 5, + "end_column": 0 + }, + "operation": "Override" + }, + "filename": "hello.k", + "line": 4, + "column": 17, + "end_line": 5, + "end_column": 0 + } + ], + "orelse": null + }, + "filename": "hello.k", + "line": 4, + "column": 4, + "end_line": 5, + "end_column": 0 + }, + "operation": "Union" + }, + "filename": "hello.k", + "line": 4, + "column": 4, + "end_line": 5, + "end_column": 0 + } + ] + }, + "filename": "hello.k", + "line": 2, + "column": 8, + "end_line": 5, + "end_column": 1 + }, + "ty": null + }, + "filename": "hello.k", + "line": 2, + "column": 0, + "end_line": 5, + "end_column": 1 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__schema_stmt.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__schema_stmt.snap new file mode 100644 index 000000000..034553ded --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__ast__schema_stmt.snap @@ -0,0 +1,913 @@ +--- +source: crates/parser/src/tests/ast.rs +expression: "$crate :: tests ::\nparsing_file_ast_json(\"hello.k\",\nr####\"\nschema TestBool:\n []\n [str ]: int\n [a: str]: int\n [a: ...str]: int\n [...str]: int\n a: int\n b?: str\n c: int = 0\n d?: str = \"\"\n\n [a]\n [a, b, c]\n [\n 1\n ]\n [\n a\n ]\n [a for a in [1, 2, 3]]\n [\n a for a in [1, 2, 3]\n ]\n\n check:\n a > 1, \"msg\"\n name not None, \"we fail here\"\n \"####)" +--- +{ + "filename": "hello.k", + "doc": null, + "body": [ + { + "node": { + "type": "Schema", + "doc": null, + "name": { + "node": "TestBool", + "filename": "hello.k", + "line": 2, + "column": 7, + "end_line": 2, + "end_column": 15 + }, + "parent_name": null, + "for_host_name": null, + "is_mixin": false, + "is_protocol": false, + "args": null, + "mixins": [], + "body": [ + { + "node": { + "type": "Expr", + "exprs": [ + { + "node": { + "type": "List", + "elts": [], + "ctx": "Load" + }, + "filename": "hello.k", + "line": 3, + "column": 4, + "end_line": 3, + "end_column": 6 + } + ] + }, + "filename": "hello.k", + "line": 3, + "column": 4, + "end_line": 3, + "end_column": 6 + }, + { + "node": { + "type": "SchemaAttr", + "doc": "", + "name": { + "node": "a", + "filename": "hello.k", + "line": 8, + "column": 4, + "end_line": 8, + "end_column": 5 + }, + "op": null, + "value": null, + "is_optional": false, + "decorators": [], + "ty": { + "node": { + "type": "Basic", + "value": "Int" + }, + "filename": "hello.k", + "line": 8, + "column": 7, + "end_line": 8, + "end_column": 10 + } + }, + "filename": "hello.k", + "line": 8, + "column": 4, + "end_line": 8, + "end_column": 10 + }, + { + "node": { + "type": "SchemaAttr", + "doc": "", + "name": { + "node": "b", + "filename": "hello.k", + "line": 9, + "column": 4, + "end_line": 9, + "end_column": 5 + }, + "op": null, + "value": null, + "is_optional": true, + "decorators": [], + "ty": { + "node": { + "type": "Basic", + "value": "Str" + }, + "filename": "hello.k", + "line": 9, + "column": 8, + "end_line": 9, + "end_column": 11 + } + }, + "filename": "hello.k", + "line": 9, + "column": 4, + "end_line": 10, + "end_column": 0 + }, + { + "node": { + "type": "SchemaAttr", + "doc": "", + "name": { + "node": "c", + "filename": "hello.k", + "line": 10, + "column": 4, + "end_line": 10, + "end_column": 5 + }, + "op": "Assign", + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 0 + } + }, + "filename": "hello.k", + "line": 10, + "column": 13, + "end_line": 10, + "end_column": 14 + }, + "is_optional": false, + "decorators": [], + "ty": { + "node": { + "type": "Basic", + "value": "Int" + }, + "filename": "hello.k", + "line": 10, + "column": 7, + "end_line": 10, + "end_column": 10 + } + }, + "filename": "hello.k", + "line": 10, + "column": 4, + "end_line": 10, + "end_column": 14 + }, + { + "node": { + "type": "SchemaAttr", + "doc": "", + "name": { + "node": "d", + "filename": "hello.k", + "line": 11, + "column": 4, + "end_line": 11, + "end_column": 5 + }, + "op": "Assign", + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"\"", + "value": "" + }, + "filename": "hello.k", + "line": 11, + "column": 14, + "end_line": 11, + "end_column": 16 + }, + "is_optional": true, + "decorators": [], + "ty": { + "node": { + "type": "Basic", + "value": "Str" + }, + "filename": "hello.k", + "line": 11, + "column": 8, + "end_line": 11, + "end_column": 11 + } + }, + "filename": "hello.k", + "line": 11, + "column": 4, + "end_line": 13, + "end_column": 0 + }, + { + "node": { + "type": "Expr", + "exprs": [ + { + "node": { + "type": "List", + "elts": [ + { + "node": { + "type": "Identifier", + "names": [ + { + "node": "a", + "filename": "hello.k", + "line": 13, + "column": 5, + "end_line": 13, + "end_column": 6 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 13, + "column": 5, + "end_line": 13, + "end_column": 6 + } + ], + "ctx": "Load" + }, + "filename": "hello.k", + "line": 13, + "column": 4, + "end_line": 13, + "end_column": 7 + } + ] + }, + "filename": "hello.k", + "line": 13, + "column": 4, + "end_line": 13, + "end_column": 7 + }, + { + "node": { + "type": "Expr", + "exprs": [ + { + "node": { + "type": "List", + "elts": [ + { + "node": { + "type": "Identifier", + "names": [ + { + "node": "a", + "filename": "hello.k", + "line": 14, + "column": 5, + "end_line": 14, + "end_column": 6 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 14, + "column": 5, + "end_line": 14, + "end_column": 6 + }, + { + "node": { + "type": "Identifier", + "names": [ + { + "node": "b", + "filename": "hello.k", + "line": 14, + "column": 8, + "end_line": 14, + "end_column": 9 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 14, + "column": 8, + "end_line": 14, + "end_column": 9 + }, + { + "node": { + "type": "Identifier", + "names": [ + { + "node": "c", + "filename": "hello.k", + "line": 14, + "column": 11, + "end_line": 14, + "end_column": 12 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 14, + "column": 11, + "end_line": 14, + "end_column": 12 + } + ], + "ctx": "Load" + }, + "filename": "hello.k", + "line": 14, + "column": 4, + "end_line": 14, + "end_column": 13 + } + ] + }, + "filename": "hello.k", + "line": 14, + "column": 4, + "end_line": 14, + "end_column": 13 + }, + { + "node": { + "type": "Expr", + "exprs": [ + { + "node": { + "type": "List", + "elts": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "hello.k", + "line": 16, + "column": 8, + "end_line": 16, + "end_column": 9 + } + ], + "ctx": "Load" + }, + "filename": "hello.k", + "line": 15, + "column": 4, + "end_line": 17, + "end_column": 5 + } + ] + }, + "filename": "hello.k", + "line": 15, + "column": 4, + "end_line": 17, + "end_column": 5 + }, + { + "node": { + "type": "Expr", + "exprs": [ + { + "node": { + "type": "List", + "elts": [ + { + "node": { + "type": "Identifier", + "names": [ + { + "node": "a", + "filename": "hello.k", + "line": 19, + "column": 8, + "end_line": 19, + "end_column": 9 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 19, + "column": 8, + "end_line": 19, + "end_column": 9 + } + ], + "ctx": "Load" + }, + "filename": "hello.k", + "line": 18, + "column": 4, + "end_line": 20, + "end_column": 5 + } + ] + }, + "filename": "hello.k", + "line": 18, + "column": 4, + "end_line": 20, + "end_column": 5 + }, + { + "node": { + "type": "Expr", + "exprs": [ + { + "node": { + "type": "ListComp", + "elt": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "a", + "filename": "hello.k", + "line": 21, + "column": 5, + "end_line": 21, + "end_column": 6 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 21, + "column": 5, + "end_line": 21, + "end_column": 6 + }, + "generators": [ + { + "node": { + "targets": [ + { + "node": { + "names": [ + { + "node": "a", + "filename": "hello.k", + "line": 21, + "column": 11, + "end_line": 21, + "end_column": 12 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 21, + "column": 11, + "end_line": 21, + "end_column": 12 + } + ], + "iter": { + "node": { + "type": "List", + "elts": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "hello.k", + "line": 21, + "column": 17, + "end_line": 21, + "end_column": 18 + }, + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 2 + } + }, + "filename": "hello.k", + "line": 21, + "column": 20, + "end_line": 21, + "end_column": 21 + }, + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 3 + } + }, + "filename": "hello.k", + "line": 21, + "column": 23, + "end_line": 21, + "end_column": 24 + } + ], + "ctx": "Load" + }, + "filename": "hello.k", + "line": 21, + "column": 16, + "end_line": 21, + "end_column": 25 + }, + "ifs": [] + }, + "filename": "hello.k", + "line": 21, + "column": 7, + "end_line": 21, + "end_column": 25 + } + ] + }, + "filename": "hello.k", + "line": 21, + "column": 4, + "end_line": 21, + "end_column": 26 + } + ] + }, + "filename": "hello.k", + "line": 21, + "column": 4, + "end_line": 21, + "end_column": 26 + }, + { + "node": { + "type": "Expr", + "exprs": [ + { + "node": { + "type": "ListComp", + "elt": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "a", + "filename": "hello.k", + "line": 23, + "column": 8, + "end_line": 23, + "end_column": 9 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 23, + "column": 8, + "end_line": 23, + "end_column": 9 + }, + "generators": [ + { + "node": { + "targets": [ + { + "node": { + "names": [ + { + "node": "a", + "filename": "hello.k", + "line": 23, + "column": 14, + "end_line": 23, + "end_column": 15 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 23, + "column": 14, + "end_line": 23, + "end_column": 15 + } + ], + "iter": { + "node": { + "type": "List", + "elts": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "hello.k", + "line": 23, + "column": 20, + "end_line": 23, + "end_column": 21 + }, + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 2 + } + }, + "filename": "hello.k", + "line": 23, + "column": 23, + "end_line": 23, + "end_column": 24 + }, + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 3 + } + }, + "filename": "hello.k", + "line": 23, + "column": 26, + "end_line": 23, + "end_column": 27 + } + ], + "ctx": "Load" + }, + "filename": "hello.k", + "line": 23, + "column": 19, + "end_line": 23, + "end_column": 28 + }, + "ifs": [] + }, + "filename": "hello.k", + "line": 23, + "column": 10, + "end_line": 24, + "end_column": 0 + } + ] + }, + "filename": "hello.k", + "line": 22, + "column": 4, + "end_line": 24, + "end_column": 5 + } + ] + }, + "filename": "hello.k", + "line": 22, + "column": 4, + "end_line": 24, + "end_column": 5 + } + ], + "decorators": [], + "checks": [ + { + "node": { + "test": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "a", + "filename": "hello.k", + "line": 27, + "column": 8, + "end_line": 27, + "end_column": 9 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 27, + "column": 8, + "end_line": 27, + "end_column": 9 + }, + "ops": [ + "Gt" + ], + "comparators": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "hello.k", + "line": 27, + "column": 12, + "end_line": 27, + "end_column": 13 + } + ] + }, + "filename": "hello.k", + "line": 27, + "column": 8, + "end_line": 27, + "end_column": 13 + }, + "if_cond": null, + "msg": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"msg\"", + "value": "msg" + }, + "filename": "hello.k", + "line": 27, + "column": 15, + "end_line": 27, + "end_column": 20 + } + }, + "filename": "hello.k", + "line": 27, + "column": 8, + "end_line": 27, + "end_column": 20 + }, + { + "node": { + "test": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "name", + "filename": "hello.k", + "line": 28, + "column": 8, + "end_line": 28, + "end_column": 12 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello.k", + "line": 28, + "column": 8, + "end_line": 28, + "end_column": 12 + }, + "if_cond": null, + "msg": null + }, + "filename": "hello.k", + "line": 28, + "column": 8, + "end_line": 28, + "end_column": 12 + }, + { + "node": { + "test": { + "node": { + "type": "Unary", + "op": "Not", + "operand": { + "node": { + "type": "NameConstantLit", + "value": "None" + }, + "filename": "hello.k", + "line": 28, + "column": 17, + "end_line": 28, + "end_column": 21 + } + }, + "filename": "hello.k", + "line": 28, + "column": 13, + "end_line": 28, + "end_column": 21 + }, + "if_cond": null, + "msg": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"we fail here\"", + "value": "we fail here" + }, + "filename": "hello.k", + "line": 28, + "column": 23, + "end_line": 28, + "end_column": 37 + } + }, + "filename": "hello.k", + "line": 28, + "column": 13, + "end_line": 28, + "end_column": 37 + } + ], + "index_signature": { + "node": { + "key_name": null, + "value": null, + "any_other": true, + "key_ty": { + "node": { + "type": "Basic", + "value": "Str" + }, + "filename": "hello.k", + "line": 7, + "column": 8, + "end_line": 7, + "end_column": 11 + }, + "value_ty": { + "node": { + "type": "Basic", + "value": "Int" + }, + "filename": "hello.k", + "line": 7, + "column": 14, + "end_line": 7, + "end_column": 17 + } + }, + "filename": "hello.k", + "line": 7, + "column": 4, + "end_line": 8, + "end_column": 0 + } + }, + "filename": "hello.k", + "line": 2, + "column": 0, + "end_line": 29, + "end_column": 8 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assert_stmt_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assert_stmt_recovery_0.snap new file mode 100644 index 000000000..54917d515 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assert_stmt_recovery_0.snap @@ -0,0 +1,34 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"assert\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assert( + AssertStmt { + test: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + if_cond: None, + msg: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assert_stmt_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assert_stmt_recovery_1.snap new file mode 100644 index 000000000..a5b95ff9c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assert_stmt_recovery_1.snap @@ -0,0 +1,55 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"assert a.\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assert( + AssertStmt { + test: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + Node { + node: "", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 9, + }, + if_cond: None, + msg: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assert_stmt_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assert_stmt_recovery_2.snap new file mode 100644 index 000000000..794898ed8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assert_stmt_recovery_2.snap @@ -0,0 +1,74 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"assert True,,, 'msg'\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assert( + AssertStmt { + test: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 11, + }, + if_cond: None, + msg: Some( + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 13, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'msg'", + value: "msg", + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 20, + }, + ], + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 20, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assert_stmt_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assert_stmt_recovery_3.snap new file mode 100644 index 000000000..b45d46a13 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assert_stmt_recovery_3.snap @@ -0,0 +1,123 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"assert True if data else 'msg'\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assert( + AssertStmt { + test: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 11, + }, + if_cond: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "data", + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 19, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 19, + }, + ), + msg: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 19, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "else", + filename: "", + line: 1, + column: 20, + end_line: 1, + end_column: 24, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 20, + end_line: 1, + end_column: 24, + }, + ], + }, + ), + filename: "", + line: 1, + column: 20, + end_line: 1, + end_column: 24, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'msg'", + value: "msg", + }, + ), + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 30, + }, + ], + }, + ), + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 30, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_0.snap new file mode 100644 index 000000000..94133ea52 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_0.snap @@ -0,0 +1,54 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a = \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_1.snap new file mode 100644 index 000000000..63c3c86e7 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_1.snap @@ -0,0 +1,39 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\" = 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_10.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_10.snap new file mode 100644 index 000000000..6832fa5cb --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_10.snap @@ -0,0 +1,75 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a[0] -= 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: AugAssign( + AugAssignStmt { + target: Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [ + Index( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + ], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, + }, + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + op: Sub, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_11.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_11.snap new file mode 100644 index 000000000..5c5ea737b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_11.snap @@ -0,0 +1,85 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a[0].b -= 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: AugAssign( + AugAssignStmt { + target: Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [ + Index( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + Member( + Node { + node: "b", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ), + ], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + op: Sub, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_12.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_12.snap new file mode 100644 index 000000000..9114fde29 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_12.snap @@ -0,0 +1,87 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a.b[0] = 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [ + Member( + Node { + node: "b", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + Index( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + ], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 10, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_13.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_13.snap new file mode 100644 index 000000000..6b68dbfd6 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_13.snap @@ -0,0 +1,39 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a().b = 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_14.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_14.snap new file mode 100644 index 000000000..07c192e29 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_14.snap @@ -0,0 +1,39 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a.b[1:2] = 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 12, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_15.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_15.snap new file mode 100644 index 000000000..76af81668 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_15.snap @@ -0,0 +1,39 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a.b[1::2].c = 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 15, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 15, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_16.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_16.snap new file mode 100644 index 000000000..a2f2eac99 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_16.snap @@ -0,0 +1,113 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a.b[c.d].e = 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [ + Member( + Node { + node: "b", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + Index( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "c", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + Node { + node: "d", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ), + Member( + Node { + node: "e", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + ), + ], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 10, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 14, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_17.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_17.snap new file mode 100644 index 000000000..f6fe37c53 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_17.snap @@ -0,0 +1,124 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a.b[1 + 1].e = 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [ + Member( + Node { + node: "b", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + Index( + Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 9, + }, + ), + Member( + Node { + node: "e", + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 12, + }, + ), + ], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 16, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 16, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_18.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_18.snap new file mode 100644 index 000000000..2c9605679 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_18.snap @@ -0,0 +1,118 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a.b[f()].e = 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [ + Member( + Node { + node: "b", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + Index( + Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "f", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + args: [], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ), + Member( + Node { + node: "e", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + ), + ], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 10, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 14, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_2.snap new file mode 100644 index 000000000..50f26d607 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_2.snap @@ -0,0 +1,65 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a: int =\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 8, + }, + ty: Some( + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_3.snap new file mode 100644 index 000000000..1343c56a5 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_3.snap @@ -0,0 +1,83 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a: a = 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ty: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_4.snap new file mode 100644 index 000000000..8a19ea61d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_4.snap @@ -0,0 +1,63 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 2, + }, + ty: Some( + Node { + node: Any, + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 2, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_5.snap new file mode 100644 index 000000000..62a036c28 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_5.snap @@ -0,0 +1,73 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a = b = \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + Node { + node: Target { + name: Node { + node: "b", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 8, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_6.snap new file mode 100644 index 000000000..9cb626a9c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_6.snap @@ -0,0 +1,78 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a() = b. = c\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "b", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + paths: [ + Member( + Node { + node: "", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 9, + }, + ), + ], + pkgpath: "", + }, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 8, + }, + ], + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "c", + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 12, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 12, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_7.snap new file mode 100644 index 000000000..aebd3c792 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_7.snap @@ -0,0 +1,73 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a: () = 0\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: None, + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 5, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_8.snap new file mode 100644 index 000000000..aebd3c792 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_8.snap @@ -0,0 +1,73 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a: () = 0\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: None, + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 5, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_9.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_9.snap new file mode 100644 index 000000000..d1bf19a96 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__assign_stmt_recovery_9.snap @@ -0,0 +1,10 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a ++= 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_0.snap new file mode 100644 index 000000000..9b33d9c8e --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_0.snap @@ -0,0 +1,27 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a not is b\"#)" +--- +Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_1.snap new file mode 100644 index 000000000..e6861c72d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_1.snap @@ -0,0 +1,66 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a is is not b\"#)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ops: [ + Is, + ], + comparators: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "is", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_2.snap new file mode 100644 index 000000000..2998a7b6b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_2.snap @@ -0,0 +1,27 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a not b\"#)" +--- +Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_3.snap new file mode 100644 index 000000000..be104ad4d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_3.snap @@ -0,0 +1,27 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a not is in b\"#)" +--- +Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_4.snap new file mode 100644 index 000000000..4ce2fca8f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_4.snap @@ -0,0 +1,66 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a in in b\"#)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ops: [ + In, + ], + comparators: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "in", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_5.snap new file mode 100644 index 000000000..3307a5e3c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_5.snap @@ -0,0 +1,74 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a ++ b\"#)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + op: Add, + right: Node { + node: Unary( + UnaryExpr { + op: UAdd, + operand: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_6.snap new file mode 100644 index 000000000..3aca9002d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_6.snap @@ -0,0 +1,96 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a -not- b\"#)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + op: Sub, + right: Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + op: Sub, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_7.snap new file mode 100644 index 000000000..576008254 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_7.snap @@ -0,0 +1,62 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a +is b\"#)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + op: Add, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "is", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 5, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_8.snap new file mode 100644 index 000000000..f28901b0a --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__binary_recovery_8.snap @@ -0,0 +1,27 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a +=+ b\"#)" +--- +Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_0.snap new file mode 100644 index 000000000..67e4c5844 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_0.snap @@ -0,0 +1,40 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a(\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_1.snap new file mode 100644 index 000000000..778dc59b7 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_1.snap @@ -0,0 +1,40 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a(]\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_10.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_10.snap new file mode 100644 index 000000000..3cb66dd12 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_10.snap @@ -0,0 +1,71 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a(\n 1,\n 2\n)\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + ], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_11.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_11.snap new file mode 100644 index 000000000..8ec027756 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_11.snap @@ -0,0 +1,71 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a(\n 1,\n2,\n)\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 3, + column: 0, + end_line: 3, + end_column: 1, + }, + ], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_12.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_12.snap new file mode 100644 index 000000000..8ec027756 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_12.snap @@ -0,0 +1,71 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a(\n 1,\n2,\n)\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 3, + column: 0, + end_line: 3, + end_column: 1, + }, + ], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_13.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_13.snap new file mode 100644 index 000000000..55feea4d9 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_13.snap @@ -0,0 +1,71 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a(\n 1,,\n2,\n)\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 3, + column: 0, + end_line: 3, + end_column: 1, + }, + ], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_14.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_14.snap new file mode 100644 index 000000000..5c59f8747 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_14.snap @@ -0,0 +1,71 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a(\n 1,\n 2,\n]\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + ], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_2.snap new file mode 100644 index 000000000..84e00c801 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_2.snap @@ -0,0 +1,64 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a(a,,)\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_3.snap new file mode 100644 index 000000000..56c2802db --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_3.snap @@ -0,0 +1,112 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a.b(a=1,2)\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + Node { + node: "b", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ], + keywords: [ + Node { + node: Keyword { + arg: Node { + node: Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + value: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ), + }, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 10, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_4.snap new file mode 100644 index 000000000..c25da03b4 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_4.snap @@ -0,0 +1,112 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a(a.ba=1,2)\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + ], + keywords: [ + Node { + node: Keyword { + arg: Node { + node: Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + Node { + node: "ba", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 6, + }, + value: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ), + }, + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 8, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_5.snap new file mode 100644 index 000000000..591c6a125 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_5.snap @@ -0,0 +1,95 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a(a.b+a=1,2)\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + ], + keywords: [ + Node { + node: Keyword { + arg: Node { + node: Identifier { + names: [], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 7, + }, + value: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ), + }, + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 9, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_6.snap new file mode 100644 index 000000000..29cbd75a3 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_6.snap @@ -0,0 +1,79 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a(a-1.b=1)\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [], + keywords: [ + Node { + node: Keyword { + arg: Node { + node: Identifier { + names: [], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 7, + }, + value: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ), + }, + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 9, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 10, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_7.snap new file mode 100644 index 000000000..c16699212 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_7.snap @@ -0,0 +1,102 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a(type=\"list\", \"key\")\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"key\"", + value: "key", + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 20, + }, + ], + keywords: [ + Node { + node: Keyword { + arg: Node { + node: Identifier { + names: [ + Node { + node: "type", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 6, + }, + value: Some( + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"list\"", + value: "list", + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 13, + }, + ), + }, + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 13, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 21, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_8.snap new file mode 100644 index 000000000..087b81398 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_8.snap @@ -0,0 +1,71 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a(\n 1,2\n)\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 2, + column: 6, + end_line: 2, + end_column: 7, + }, + ], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 3, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_9.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_9.snap new file mode 100644 index 000000000..0aadfa5e6 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__call_recovery_9.snap @@ -0,0 +1,71 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a(1,2\n)\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_0.snap new file mode 100644 index 000000000..57f0690b7 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_0.snap @@ -0,0 +1,132 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[i for i in [1,2,3]]\")" +--- +Node { + node: ListComp( + ListComp { + elt: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + generators: [ + Node { + node: CompClause { + targets: [ + Node { + node: Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + iter: Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 16, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 17, + end_line: 1, + end_column: 18, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 19, + }, + ifs: [], + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 19, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 20, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_1.snap new file mode 100644 index 000000000..a82ab6901 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_1.snap @@ -0,0 +1,132 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[i, j for i in [1,2,3]]\")" +--- +Node { + node: ListComp( + ListComp { + elt: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + generators: [ + Node { + node: CompClause { + targets: [ + Node { + node: Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + ], + iter: Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 17, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 18, + end_line: 1, + end_column: 19, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 20, + end_line: 1, + end_column: 21, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 22, + }, + ifs: [], + }, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 22, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 23, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_2.snap new file mode 100644 index 000000000..5f4fffc21 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_2.snap @@ -0,0 +1,17 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[for i in [1,2,3]]\")" +--- +Node { + node: List( + ListExpr { + elts: [], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 18, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_3.snap new file mode 100644 index 000000000..19b1151e3 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_3.snap @@ -0,0 +1,150 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{i for i in [1,2,3]}\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ), + value: Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ops: [ + In, + ], + comparators: [ + Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 16, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 17, + end_line: 1, + end_column: 18, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 19, + }, + ], + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 19, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 19, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 20, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_4.snap new file mode 100644 index 000000000..de8f6591f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_4.snap @@ -0,0 +1,195 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{i: for i in [1,2,3]}\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ), + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "for", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + operation: Union, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 7, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ops: [ + In, + ], + comparators: [ + Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 15, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 17, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 18, + end_line: 1, + end_column: 19, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 20, + }, + ], + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 20, + }, + ), + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 21, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 21, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 21, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_5.snap new file mode 100644 index 000000000..e1dc83327 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_5.snap @@ -0,0 +1,200 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{i: 1, j for i in [1,2,3]}\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + operation: Union, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 5, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "j", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ), + value: Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + ops: [ + In, + ], + comparators: [ + Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 19, + end_line: 1, + end_column: 20, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 22, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 23, + end_line: 1, + end_column: 24, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 18, + end_line: 1, + end_column: 25, + }, + ], + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 25, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 25, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 26, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_6.snap new file mode 100644 index 000000000..247c85d27 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__comp_clause_recovery_6.snap @@ -0,0 +1,16 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{for i in [1,2,3]}\")" +--- +Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 18, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_0.snap new file mode 100644 index 000000000..fd6f2abd7 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_0.snap @@ -0,0 +1,77 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a <> b\"#)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ops: [ + Lt, + Gt, + ], + comparators: [ + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_1.snap new file mode 100644 index 000000000..9889482c3 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_1.snap @@ -0,0 +1,106 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a < !b >!1\"#)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ops: [ + Lt, + Gt, + ], + comparators: [ + Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 6, + }, + Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 10, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 10, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_2.snap new file mode 100644 index 000000000..9889482c3 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_2.snap @@ -0,0 +1,106 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a < !b >!1\"#)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ops: [ + Lt, + Gt, + ], + comparators: [ + Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 6, + }, + Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 10, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 10, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_3.snap new file mode 100644 index 000000000..6792344b0 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_3.snap @@ -0,0 +1,88 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a <<< b\"#)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + op: LShift, + right: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, + }, + ops: [ + Lt, + ], + comparators: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_4.snap new file mode 100644 index 000000000..030e1dc45 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_4.snap @@ -0,0 +1,89 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a <+< b\"#)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ops: [ + Lt, + Lt, + ], + comparators: [ + Node { + node: Unary( + UnaryExpr { + op: UAdd, + operand: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_5.snap new file mode 100644 index 000000000..e8f1723a5 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_5.snap @@ -0,0 +1,78 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a >+ b\"#)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ops: [ + Gt, + ], + comparators: [ + Node { + node: Unary( + UnaryExpr { + op: UAdd, + operand: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_6.snap new file mode 100644 index 000000000..a2eaf5d56 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__compare_recovery_6.snap @@ -0,0 +1,89 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"+ b\"#)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ops: [ + Lt, + Gt, + ], + comparators: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + Node { + node: Unary( + UnaryExpr { + op: UAdd, + operand: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_0.snap new file mode 100644 index 000000000..e2f8904d8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_0.snap @@ -0,0 +1,16 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{\")" +--- +Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_1.snap new file mode 100644 index 000000000..d996b3db2 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_1.snap @@ -0,0 +1,67 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{a = 1\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 6, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_10.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_10.snap new file mode 100644 index 000000000..49eed93e5 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_10.snap @@ -0,0 +1,118 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{**a, *b}\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: None, + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + operation: Union, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 4, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Binary( + BinaryExpr { + left: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + op: Mul, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 8, + }, + ), + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 9, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 9, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_11.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_11.snap new file mode 100644 index 000000000..5ff3d90dd --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_11.snap @@ -0,0 +1,149 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{if True: a = , b = 2}\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: None, + value: Node { + node: ConfigIfEntry( + ConfigIfEntryExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 8, + }, + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + ), + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 15, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 15, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 15, + }, + operation: Union, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 15, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 17, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 17, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 20, + end_line: 1, + end_column: 21, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 21, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 22, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_12.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_12.snap new file mode 100644 index 000000000..aad9b6578 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_12.snap @@ -0,0 +1,171 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{if True: *a, b = 2}\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: None, + value: Node { + node: ConfigIfEntry( + ConfigIfEntryExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 8, + }, + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Binary( + BinaryExpr { + left: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + op: Mul, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 12, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 12, + }, + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 12, + }, + ), + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 13, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 13, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 13, + }, + operation: Union, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 13, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 15, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 15, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 18, + end_line: 1, + end_column: 19, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 19, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 20, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_13.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_13.snap new file mode 100644 index 000000000..89f8e6ba5 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_13.snap @@ -0,0 +1,101 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{if True: key: {}}\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: None, + value: Node { + node: ConfigIfEntry( + ConfigIfEntryExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 8, + }, + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "key", + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 13, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 13, + }, + ), + value: Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 17, + }, + operation: Union, + }, + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 17, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 18, + }, + operation: Union, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 17, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 18, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_14.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_14.snap new file mode 100644 index 000000000..f523dd7bc --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_14.snap @@ -0,0 +1,102 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{if True: key: []}\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: None, + value: Node { + node: ConfigIfEntry( + ConfigIfEntryExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 8, + }, + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "key", + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 13, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 13, + }, + ), + value: Node { + node: List( + ListExpr { + elts: [], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 17, + }, + operation: Union, + }, + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 17, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 18, + }, + operation: Union, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 17, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 18, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_15.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_15.snap new file mode 100644 index 000000000..28180f436 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_15.snap @@ -0,0 +1,62 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{你好\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "你好", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 3, + }, + ), + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 3, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_2.snap new file mode 100644 index 000000000..2cedb13a7 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_2.snap @@ -0,0 +1,117 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{a = 1, b = 2\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 6, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 13, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 13, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 13, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_3.snap new file mode 100644 index 000000000..63ed741fd --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_3.snap @@ -0,0 +1,115 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{a = {a = 1}\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ), + value: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 11, + }, + ], + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 12, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 12, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_4.snap new file mode 100644 index 000000000..3ab045ee5 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_4.snap @@ -0,0 +1,115 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{a = {a = 1\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ), + value: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 11, + }, + ], + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 11, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 11, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_5.snap new file mode 100644 index 000000000..7a5e747d9 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_5.snap @@ -0,0 +1,149 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"{\n a = 1\n b = 2\n \"#)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 2, + column: 8, + end_line: 2, + end_column: 9, + }, + operation: Override, + }, + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 9, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + operation: Override, + }, + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 9, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 4, + column: 4, + end_line: 4, + end_column: 4, + }, + ), + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 4, + column: 4, + end_line: 4, + end_column: 4, + }, + operation: Override, + }, + filename: "", + line: 4, + column: 4, + end_line: 4, + end_column: 4, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_6.snap new file mode 100644 index 000000000..450aa1a65 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_6.snap @@ -0,0 +1,117 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{a = 1 b = 2}\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 6, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 12, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 12, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 13, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_7.snap new file mode 100644 index 000000000..2138ba3da --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_7.snap @@ -0,0 +1,149 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{a = 1,, b = 2}\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 6, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ), + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 10, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 12, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 14, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 15, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_8.snap new file mode 100644 index 000000000..3b3bb2a9a --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_8.snap @@ -0,0 +1,129 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{a = 1 ~ b = 2}\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 6, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Unary( + UnaryExpr { + op: Invert, + operand: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 10, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 14, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 15, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_9.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_9.snap new file mode 100644 index 000000000..53f2012a0 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__config_recovery_9.snap @@ -0,0 +1,119 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"{*a, **b}\")" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Binary( + BinaryExpr { + left: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + op: Mul, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 3, + }, + ), + value: Node { + node: Binary( + BinaryExpr { + left: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 7, + }, + op: Pow, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 8, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 8, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_0.snap new file mode 100644 index 000000000..86986d3a7 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_0.snap @@ -0,0 +1,79 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:(\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Any, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_1.snap new file mode 100644 index 000000000..95095da13 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_1.snap @@ -0,0 +1,102 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:(i\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Named( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + Node { + node: Any, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 4, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_10.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_10.snap new file mode 100644 index 000000000..8d3268a66 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_10.snap @@ -0,0 +1,102 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:({\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Dict( + DictType { + key_type: Some( + Node { + node: Any, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + ), + value_type: Some( + Node { + node: Any, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 4, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_11.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_11.snap new file mode 100644 index 000000000..0a47565fd --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_11.snap @@ -0,0 +1,117 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:({i\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 5, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Dict( + DictType { + key_type: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + value_type: Some( + Node { + node: Any, + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 5, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 5, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 5, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_12.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_12.snap new file mode 100644 index 000000000..13b2b6163 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_12.snap @@ -0,0 +1,117 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:({i:\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Dict( + DictType { + key_type: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + value_type: Some( + Node { + node: Any, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 6, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_13.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_13.snap new file mode 100644 index 000000000..6445b4ddd --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_13.snap @@ -0,0 +1,132 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:({i:i\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 7, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Dict( + DictType { + key_type: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + value_type: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 7, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 7, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_14.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_14.snap new file mode 100644 index 000000000..e5d94ae57 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_14.snap @@ -0,0 +1,119 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:({i:int\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 9, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Dict( + DictType { + key_type: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + value_type: Some( + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 9, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 9, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_15.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_15.snap new file mode 100644 index 000000000..43cea3f46 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_15.snap @@ -0,0 +1,127 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:({i:int]\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 10, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Dict( + DictType { + key_type: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + value_type: Some( + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 9, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 10, + }, + Node { + node: Any, + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 10, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 10, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_16.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_16.snap new file mode 100644 index 000000000..39e12f31c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_16.snap @@ -0,0 +1,114 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:({str:int]\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 12, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Dict( + DictType { + key_type: Some( + Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ), + value_type: Some( + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 11, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 12, + }, + Node { + node: Any, + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 12, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 12, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_17.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_17.snap new file mode 100644 index 000000000..baad0cb82 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_17.snap @@ -0,0 +1,114 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:({str:int}\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 12, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Dict( + DictType { + key_type: Some( + Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ), + value_type: Some( + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 11, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 12, + }, + Node { + node: Any, + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 12, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 12, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_18.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_18.snap new file mode 100644 index 000000000..47dd50698 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_18.snap @@ -0,0 +1,122 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:({str:int} ->\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 15, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Dict( + DictType { + key_type: Some( + Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ), + value_type: Some( + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 11, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 12, + }, + Node { + node: Any, + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 15, + }, + Node { + node: Any, + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 15, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 15, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_19.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_19.snap new file mode 100644 index 000000000..58922149c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_19.snap @@ -0,0 +1,130 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:({str:int}) -> i\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 18, + end_line: 1, + end_column: 18, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Dict( + DictType { + key_type: Some( + Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ), + value_type: Some( + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 11, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 12, + }, + ], + ), + ret_ty: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 17, + end_line: 1, + end_column: 18, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 17, + end_line: 1, + end_column: 18, + }, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 18, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_2.snap new file mode 100644 index 000000000..b2c32ea4e --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_2.snap @@ -0,0 +1,89 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:(int\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + Node { + node: Any, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 6, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_20.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_20.snap new file mode 100644 index 000000000..1179007a6 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_20.snap @@ -0,0 +1,128 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:(str|int) -> i\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 16, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Union( + UnionType { + type_elements: [ + Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 10, + }, + ], + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 10, + }, + ], + ), + ret_ty: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 16, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 16, + }, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 16, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_21.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_21.snap new file mode 100644 index 000000000..5a99447ac --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_21.snap @@ -0,0 +1,138 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:(str|int, int) -> i\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 21, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Union( + UnionType { + type_elements: [ + Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 10, + }, + ], + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 10, + }, + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 15, + }, + ], + ), + ret_ty: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 20, + end_line: 1, + end_column: 21, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 20, + end_line: 1, + end_column: 21, + }, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 21, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_22.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_22.snap new file mode 100644 index 000000000..c68b21d58 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_22.snap @@ -0,0 +1,135 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:(str|int, int|\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 16, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Union( + UnionType { + type_elements: [ + Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 10, + }, + ], + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 10, + }, + Node { + node: Union( + UnionType { + type_elements: [ + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 15, + }, + Node { + node: Any, + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 16, + }, + ], + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 16, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 16, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_23.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_23.snap new file mode 100644 index 000000000..d85a99c21 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_23.snap @@ -0,0 +1,151 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:(str|int, int|) ->\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 20, + end_line: 1, + end_column: 20, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Union( + UnionType { + type_elements: [ + Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 10, + }, + ], + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 10, + }, + Node { + node: Union( + UnionType { + type_elements: [ + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 15, + }, + Node { + node: Any, + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 17, + }, + ], + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 17, + }, + Node { + node: Any, + filename: "", + line: 1, + column: 18, + end_line: 1, + end_column: 20, + }, + Node { + node: Any, + filename: "", + line: 1, + column: 20, + end_line: 1, + end_column: 20, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 20, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_3.snap new file mode 100644 index 000000000..c1900b96c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_3.snap @@ -0,0 +1,78 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:i)\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ty: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_4.snap new file mode 100644 index 000000000..88153fed2 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_4.snap @@ -0,0 +1,107 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:([i\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 5, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: List( + ListType { + inner_type: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 5, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 5, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_5.snap new file mode 100644 index 000000000..1af3d80bd --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_5.snap @@ -0,0 +1,115 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:([i:\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: List( + ListType { + inner_type: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + Node { + node: Any, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 6, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_6.snap new file mode 100644 index 000000000..ea8b28570 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_6.snap @@ -0,0 +1,115 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:([i]\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: List( + ListType { + inner_type: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + Node { + node: Any, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 6, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_7.snap new file mode 100644 index 000000000..08f96cf64 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_7.snap @@ -0,0 +1,102 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:([int]\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 8, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: List( + ListType { + inner_type: Some( + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 8, + }, + Node { + node: Any, + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 8, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 8, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_8.snap new file mode 100644 index 000000000..09d4fad1c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_8.snap @@ -0,0 +1,94 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:([int\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 7, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: List( + ListType { + inner_type: Some( + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 7, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 7, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_9.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_9.snap new file mode 100644 index 000000000..6b5ba1e0d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__fn_ty_annotation_recovery_9.snap @@ -0,0 +1,102 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"a:({}\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 5, + }, + ty: Some( + Node { + node: Function( + FunctionType { + params_ty: Some( + [ + Node { + node: Dict( + DictType { + key_type: Some( + Node { + node: Any, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + value_type: Some( + Node { + node: Any, + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 5, + }, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 5, + }, + ], + ), + ret_ty: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 5, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_0.snap new file mode 100644 index 000000000..324ef8581 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_0.snap @@ -0,0 +1,50 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"1 if\"#)" +--- +Node { + node: If( + IfExpr { + body: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + cond: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + orelse: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_1.snap new file mode 100644 index 000000000..324ef8581 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_1.snap @@ -0,0 +1,50 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"1 if\"#)" +--- +Node { + node: If( + IfExpr { + body: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + cond: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + orelse: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_2.snap new file mode 100644 index 000000000..1c6421b25 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_2.snap @@ -0,0 +1,52 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"1 if True\"#)" +--- +Node { + node: If( + IfExpr { + body: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 9, + }, + orelse: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 9, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_3.snap new file mode 100644 index 000000000..303618e6d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_3.snap @@ -0,0 +1,52 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"1 if True else\"#)" +--- +Node { + node: If( + IfExpr { + body: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 9, + }, + orelse: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 14, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 14, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_4.snap new file mode 100644 index 000000000..d7364d960 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_recovery_4.snap @@ -0,0 +1,27 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"if True else\"#)" +--- +Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "if", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_0.snap new file mode 100644 index 000000000..6adeb4621 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_0.snap @@ -0,0 +1,65 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"if True a = 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: If( + IfStmt { + body: [ + Node { + node: Assign( + AssignStmt { + targets: [], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 13, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 13, + }, + ], + cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 7, + }, + orelse: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 13, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_1.snap new file mode 100644 index 000000000..50e1bb8d4 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_1.snap @@ -0,0 +1,114 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"if True: a = 1 else if b = 2\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: If( + IfStmt { + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 14, + }, + ], + cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 7, + }, + orelse: [ + Node { + node: Assign( + AssignStmt { + targets: [], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 27, + end_line: 1, + end_column: 28, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 28, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 28, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_2.snap new file mode 100644 index 000000000..5a5c76e41 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_2.snap @@ -0,0 +1,83 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"if : a = 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: If( + IfStmt { + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 10, + }, + ], + cond: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + orelse: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 10, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_3.snap new file mode 100644 index 000000000..4a28be6be --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_3.snap @@ -0,0 +1,114 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"if True: a = 1 else b = 2\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: If( + IfStmt { + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 14, + }, + ], + cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 7, + }, + orelse: [ + Node { + node: Assign( + AssignStmt { + targets: [], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 24, + end_line: 1, + end_column: 25, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 22, + end_line: 1, + end_column: 25, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 25, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_4.snap new file mode 100644 index 000000000..ef2da13f8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_4.snap @@ -0,0 +1,109 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"if True: else: b = 2\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: If( + IfStmt { + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "else", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 13, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 13, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 19, + end_line: 1, + end_column: 20, + }, + ty: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 16, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 16, + }, + ), + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 20, + }, + ], + cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 7, + }, + orelse: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 20, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_5.snap new file mode 100644 index 000000000..5b2129c32 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_5.snap @@ -0,0 +1,58 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"if\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: If( + IfStmt { + body: [ + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 2, + }, + ], + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 2, + }, + ], + cond: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 2, + }, + orelse: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_6.snap new file mode 100644 index 000000000..6a1a8f138 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_6.snap @@ -0,0 +1,71 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"if else\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: If( + IfStmt { + body: [ + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 7, + }, + ], + cond: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "else", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 7, + }, + orelse: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_7.snap new file mode 100644 index 000000000..1cff60fd1 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_7.snap @@ -0,0 +1,36 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"if True:\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: If( + IfStmt { + body: [], + cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 7, + }, + orelse: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_8.snap new file mode 100644 index 000000000..9ddb28ab7 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_8.snap @@ -0,0 +1,138 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests ::\nparsing_module_string(r#\"if True: a = 1\nelse if False: b = 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: If( + IfStmt { + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 14, + }, + ], + cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 7, + }, + orelse: [ + Node { + node: Assign( + AssignStmt { + targets: [], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 2, + column: 19, + end_line: 2, + end_column: 20, + }, + ty: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 2, + column: 15, + end_line: 2, + end_column: 16, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 15, + end_line: 2, + end_column: 16, + }, + ), + }, + ), + filename: "", + line: 2, + column: 13, + end_line: 2, + end_column: 20, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 20, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_9.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_9.snap new file mode 100644 index 000000000..45be7ef79 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__if_stmt_recovery_9.snap @@ -0,0 +1,138 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests ::\nparsing_module_string(r#\"if True: a = 1\nelse False: b = 1\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: If( + IfStmt { + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + ty: None, + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 14, + }, + ], + cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 7, + }, + orelse: [ + Node { + node: Assign( + AssignStmt { + targets: [], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 2, + column: 16, + end_line: 2, + end_column: 17, + }, + ty: Some( + Node { + node: Named( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 2, + column: 12, + end_line: 2, + end_column: 13, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 12, + end_line: 2, + end_column: 13, + }, + ), + }, + ), + filename: "", + line: 2, + column: 10, + end_line: 2, + end_column: 17, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 17, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_recovery_0.snap new file mode 100644 index 000000000..26575110d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_recovery_0.snap @@ -0,0 +1,34 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"import json as j.a\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Import( + ImportStmt { + path: Node { + node: "json", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 11, + }, + rawpath: "json", + name: "json", + asname: None, + pkg_name: "", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 18, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_0.snap new file mode 100644 index 000000000..9c21591c8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_0.snap @@ -0,0 +1,34 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"import\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Import( + ImportStmt { + path: Node { + node: "", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + rawpath: "", + name: "", + asname: None, + pkg_name: "", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_1.snap new file mode 100644 index 000000000..39047795b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_1.snap @@ -0,0 +1,61 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"import 'pkg_path'\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Import( + ImportStmt { + path: Node { + node: "", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 6, + }, + rawpath: "", + name: "", + asname: None, + pkg_name: "", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'pkg_path'", + value: "pkg_path", + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 17, + }, + ], + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 17, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_2.snap new file mode 100644 index 000000000..6d52c60d8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_2.snap @@ -0,0 +1,34 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"import pkg_path.\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Import( + ImportStmt { + path: Node { + node: "pkg_path.", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 16, + }, + rawpath: "pkg_path.", + name: "", + asname: None, + pkg_name: "", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 16, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_3.snap new file mode 100644 index 000000000..2b8e6dd4b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_3.snap @@ -0,0 +1,76 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"import pkg_path[0]\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Import( + ImportStmt { + path: Node { + node: "pkg_path", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 15, + }, + rawpath: "pkg_path", + name: "pkg_path", + asname: None, + pkg_name: "", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 15, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 17, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 18, + }, + ], + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 18, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_4.snap new file mode 100644 index 000000000..f49e7ca66 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_4.snap @@ -0,0 +1,34 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"import .pkg_path.\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Import( + ImportStmt { + path: Node { + node: ".pkg_path.", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 17, + }, + rawpath: ".pkg_path.", + name: "", + asname: None, + pkg_name: "", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 17, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_5.snap new file mode 100644 index 000000000..33fee5adb --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_5.snap @@ -0,0 +1,43 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"import pkg_path as \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Import( + ImportStmt { + path: Node { + node: "pkg_path", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 15, + }, + rawpath: "pkg_path", + name: "", + asname: Some( + Node { + node: "", + filename: "", + line: 1, + column: 19, + end_line: 1, + end_column: 19, + }, + ), + pkg_name: "", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 18, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_6.snap new file mode 100644 index 000000000..5b39a448c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__import_stmt_recovery_6.snap @@ -0,0 +1,70 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"import pkg_path as 'data'\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Import( + ImportStmt { + path: Node { + node: "pkg_path", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 15, + }, + rawpath: "pkg_path", + name: "", + asname: Some( + Node { + node: "", + filename: "", + line: 1, + column: 19, + end_line: 1, + end_column: 19, + }, + ), + pkg_name: "", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 18, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'data'", + value: "data", + }, + ), + filename: "", + line: 1, + column: 19, + end_line: 1, + end_column: 25, + }, + ], + }, + ), + filename: "", + line: 1, + column: 19, + end_line: 1, + end_column: 25, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_0.snap new file mode 100644 index 000000000..aca057c65 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_0.snap @@ -0,0 +1,42 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"'${}'\"#)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: false, + values: [ + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + format_spec: None, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + ], + raw_value: "'${}'", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_1.snap new file mode 100644 index 000000000..b8f9cfd2b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_1.snap @@ -0,0 +1,77 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"'${a +}'\"#)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: false, + values: [ + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + op: Add, + right: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + format_spec: None, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + ], + raw_value: "'${a +}'", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_10.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_10.snap new file mode 100644 index 000000000..43f342982 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_10.snap @@ -0,0 +1,83 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"\"\"\"\n ${CC}\n\"\"\"\"#)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: true, + values: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\n ", + value: "\n ", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "CC", + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 6, + }, + format_spec: None, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 6, + }, + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\n", + value: "\n", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + ], + raw_value: "\"\"\"\n ${CC}\n\"\"\"", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 3, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_11.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_11.snap new file mode 100644 index 000000000..915d22e8b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_11.snap @@ -0,0 +1,143 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests ::\nparsing_expr_string(r#\"'\\\"false\\\" ${item.kind}: ${item.metadata.name}'\"#)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: false, + values: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\\\"false\\\" ", + value: "\"false\" ", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "item", + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 17, + }, + Node { + node: "kind", + filename: "", + line: 1, + column: 18, + end_line: 1, + end_column: 22, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 22, + }, + format_spec: None, + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 22, + }, + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: ": ", + value: ": ", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "item", + filename: "", + line: 1, + column: 27, + end_line: 1, + end_column: 31, + }, + Node { + node: "metadata", + filename: "", + line: 1, + column: 32, + end_line: 1, + end_column: 40, + }, + Node { + node: "name", + filename: "", + line: 1, + column: 41, + end_line: 1, + end_column: 45, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 27, + end_line: 1, + end_column: 45, + }, + format_spec: None, + }, + ), + filename: "", + line: 1, + column: 27, + end_line: 1, + end_column: 45, + }, + ], + raw_value: "'\\\"false\\\" ${item.kind}: ${item.metadata.name}'", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 47, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_12.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_12.snap new file mode 100644 index 000000000..73cf89796 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_12.snap @@ -0,0 +1,207 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests ::\nparsing_expr_string(r#\"'\\\"false\\\" ${item.kind}: ${item.metadata.name} \\\"true\\\" ${item} '\"#)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: false, + values: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\\\"false\\\" ", + value: "\"false\" ", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "item", + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 17, + }, + Node { + node: "kind", + filename: "", + line: 1, + column: 18, + end_line: 1, + end_column: 22, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 22, + }, + format_spec: None, + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 22, + }, + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: ": ", + value: ": ", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "item", + filename: "", + line: 1, + column: 27, + end_line: 1, + end_column: 31, + }, + Node { + node: "metadata", + filename: "", + line: 1, + column: 32, + end_line: 1, + end_column: 40, + }, + Node { + node: "name", + filename: "", + line: 1, + column: 41, + end_line: 1, + end_column: 45, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 27, + end_line: 1, + end_column: 45, + }, + format_spec: None, + }, + ), + filename: "", + line: 1, + column: 27, + end_line: 1, + end_column: 45, + }, + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: " \\\"true\\\" ", + value: " \"true\" ", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "item", + filename: "", + line: 1, + column: 58, + end_line: 1, + end_column: 62, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 58, + end_line: 1, + end_column: 62, + }, + format_spec: None, + }, + ), + filename: "", + line: 1, + column: 58, + end_line: 1, + end_column: 62, + }, + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: " ", + value: " ", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + ], + raw_value: "'\\\"false\\\" ${item.kind}: ${item.metadata.name} \\\"true\\\" ${item} '", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 65, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_13.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_13.snap new file mode 100644 index 000000000..6608e8aa9 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_13.snap @@ -0,0 +1,127 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests ::\nparsing_expr_string(r#\"'\\\"false\\\" \\${item.kind}: a${item.metadata.name} \\\"true\\\" \\${item} '\"#)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: false, + values: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\\\"false\\\" \\${item.kind}", + value: "\"false\" ${item.kind}", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: ": a", + value: ": a", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "item", + filename: "", + line: 1, + column: 29, + end_line: 1, + end_column: 33, + }, + Node { + node: "metadata", + filename: "", + line: 1, + column: 34, + end_line: 1, + end_column: 42, + }, + Node { + node: "name", + filename: "", + line: 1, + column: 43, + end_line: 1, + end_column: 47, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 29, + end_line: 1, + end_column: 47, + }, + format_spec: None, + }, + ), + filename: "", + line: 1, + column: 29, + end_line: 1, + end_column: 47, + }, + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: " \\\"true\\\" \\${item}", + value: " \"true\" ${item}", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: " ", + value: " ", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + ], + raw_value: "'\\\"false\\\" \\${item.kind}: a${item.metadata.name} \\\"true\\\" \\${item} '", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 68, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_2.snap new file mode 100644 index 000000000..28cbd2f09 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_2.snap @@ -0,0 +1,88 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"'${(a +}'\"#)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: false, + values: [ + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Paren( + ParenExpr { + expr: Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + op: Add, + right: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 7, + }, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 7, + }, + format_spec: None, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 7, + }, + ], + raw_value: "'${(a +}'", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_3.snap new file mode 100644 index 000000000..64b56f439 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_3.snap @@ -0,0 +1,33 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"'${a'\"#)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: false, + values: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "${a", + value: "${a", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + ], + raw_value: "'${a'", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_5.snap new file mode 100644 index 000000000..c834b4ea9 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_5.snap @@ -0,0 +1,82 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"'${a + 1 = }'\"#)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: false, + values: [ + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 8, + }, + format_spec: None, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 11, + }, + ], + raw_value: "'${a + 1 = }'", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 13, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_6.snap new file mode 100644 index 000000000..733e2b982 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_6.snap @@ -0,0 +1,55 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"'${a: json}'\"#)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: false, + values: [ + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + format_spec: None, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 10, + }, + ], + raw_value: "'${a: json}'", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_7.snap new file mode 100644 index 000000000..f1c288697 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_7.snap @@ -0,0 +1,71 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"'\\n${a: #json}'\"#)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: false, + values: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\\n", + value: "\n", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + format_spec: Some( + "#json", + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 13, + }, + ], + raw_value: "'\\n${a: #json}'", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 15, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_8.snap new file mode 100644 index 000000000..b6c44670b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_8.snap @@ -0,0 +1,85 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"'a\\nb${a: #json}\\n'\"#)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: false, + values: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "a\\nb", + value: "a\nb", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + format_spec: Some( + "#json", + ), + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 15, + }, + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\\n", + value: "\n", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + ], + raw_value: "'a\\nb${a: #json}\\n'", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 19, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_9.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_9.snap new file mode 100644 index 000000000..3839ccfb5 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__joined_string_recovery_9.snap @@ -0,0 +1,83 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"'''\\\n ${CC}\n'''\"#)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: true, + values: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\\\n ", + value: " ", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "CC", + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 6, + }, + format_spec: None, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 6, + }, + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\n", + value: "\n", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + ], + raw_value: "'''\\\n ${CC}\n'''", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 3, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_0.snap new file mode 100644 index 000000000..4f03f2425 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_0.snap @@ -0,0 +1,31 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"lambda\"#)" +--- +Node { + node: Lambda( + LambdaExpr { + args: Some( + Node { + node: Arguments { + args: [], + defaults: [], + ty_list: [], + }, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + ), + body: [], + return_ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_1.snap new file mode 100644 index 000000000..a3bb8be04 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_1.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"lambda {\"#)" +--- +Node { + node: Lambda( + LambdaExpr { + args: None, + body: [], + return_ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_2.snap new file mode 100644 index 000000000..d42a8a52e --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_2.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"lambda {}\"#)" +--- +Node { + node: Lambda( + LambdaExpr { + args: None, + body: [], + return_ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_3.snap new file mode 100644 index 000000000..cd2683609 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_3.snap @@ -0,0 +1,92 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"{lambda}\"#)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Lambda( + LambdaExpr { + args: Some( + Node { + node: Arguments { + args: [ + Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 7, + }, + ], + defaults: [ + None, + ], + ty_list: [ + None, + ], + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ), + body: [], + return_ty: None, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 8, + }, + ), + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 8, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 8, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_4.snap new file mode 100644 index 000000000..bb16c36cd --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_4.snap @@ -0,0 +1,53 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"{lambda{}\"#)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Lambda( + LambdaExpr { + args: None, + body: [], + return_ty: None, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 9, + }, + ), + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 9, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 9, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_5.snap new file mode 100644 index 000000000..c14d477c7 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__lambda_recovery_5.snap @@ -0,0 +1,92 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"{lambda a{}\"#)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Lambda( + LambdaExpr { + args: Some( + Node { + node: Arguments { + args: [ + Node { + node: Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ], + defaults: [ + None, + ], + ty_list: [ + None, + ], + }, + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ), + body: [], + return_ty: None, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 11, + }, + ), + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 11, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 11, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__line_continue_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__line_continue_recovery_0.snap new file mode 100644 index 000000000..dd83c6963 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__line_continue_recovery_0.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"0x\\\\2\\n12\")" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__line_continue_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__line_continue_recovery_1.snap new file mode 100644 index 000000000..d06eadcd1 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__line_continue_recovery_1.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"'abc\\\\ \\ndef\")" +--- +Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'abc\\ ", + value: "abc\\ ", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__line_continue_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__line_continue_recovery_2.snap new file mode 100644 index 000000000..30cce5357 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__line_continue_recovery_2.snap @@ -0,0 +1,44 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"'a' + \\\n'b'\n\"#)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'a'", + value: "a", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + op: Add, + right: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'b'", + value: "b", + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 3, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__line_continue_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__line_continue_recovery_3.snap new file mode 100644 index 000000000..94cd12f93 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__line_continue_recovery_3.snap @@ -0,0 +1,45 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"'a' + \\1\n'b'\n\"#)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'a'", + value: "a", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_0.snap new file mode 100644 index 000000000..0eae70c98 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_0.snap @@ -0,0 +1,17 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[\")" +--- +Node { + node: List( + ListExpr { + elts: [], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_1.snap new file mode 100644 index 000000000..19d59dd34 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_1.snap @@ -0,0 +1,33 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[0\")" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_10.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_10.snap new file mode 100644 index 000000000..1669d9699 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_10.snap @@ -0,0 +1,98 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[**a, *b\")" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: Binary( + BinaryExpr { + left: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 3, + }, + op: Pow, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 4, + }, + Node { + node: Starred( + StarredExpr { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 8, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_11.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_11.snap new file mode 100644 index 000000000..b94b1a77a --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_11.snap @@ -0,0 +1,90 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[if True: a, b]\")" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: ListIfItem( + ListIfItemExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 8, + }, + exprs: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 11, + }, + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 15, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_12.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_12.snap new file mode 100644 index 000000000..3c6ea3e69 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_12.snap @@ -0,0 +1,112 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[if True: **a, b]\")" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: ListIfItem( + ListIfItemExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 8, + }, + exprs: [ + Node { + node: Binary( + BinaryExpr { + left: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 12, + }, + op: Pow, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 13, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 13, + }, + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 13, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 13, + }, + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 16, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 16, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 17, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_13.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_13.snap new file mode 100644 index 000000000..3dd2fd074 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_13.snap @@ -0,0 +1,90 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"[\n if True:\n b = []\n]\n\"#)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: ListIfItem( + ListIfItemExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 11, + }, + exprs: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 10, + end_line: 3, + end_column: 11, + }, + Node { + node: List( + ListExpr { + elts: [], + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 12, + end_line: 3, + end_column: 14, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 0, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_14.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_14.snap new file mode 100644 index 000000000..f2a7f3dcd --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_14.snap @@ -0,0 +1,87 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"[\n if True:\n b = \n]\n\"#)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: ListIfItem( + ListIfItemExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 11, + }, + exprs: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 10, + end_line: 3, + end_column: 11, + }, + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 12, + end_line: 4, + end_column: 0, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 0, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_15.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_15.snap new file mode 100644 index 000000000..30199d679 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_15.snap @@ -0,0 +1,89 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"[\n if True:\n b -\n]\n\"#)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: ListIfItem( + ListIfItemExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 11, + }, + exprs: [ + Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + op: Sub, + right: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 11, + end_line: 4, + end_column: 0, + }, + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 11, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 0, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_16.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_16.snap new file mode 100644 index 000000000..0dfeb0155 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_16.snap @@ -0,0 +1,137 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests ::\nparsing_expr_string(r#\"{\n if True:\n b = [] = []\n}\n\"#)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: None, + value: Node { + node: ConfigIfEntry( + ConfigIfEntryExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 11, + }, + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ), + value: Node { + node: List( + ListExpr { + elts: [], + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 12, + end_line: 3, + end_column: 14, + }, + operation: Override, + }, + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 14, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 15, + end_line: 3, + end_column: 16, + }, + ), + value: Node { + node: List( + ListExpr { + elts: [], + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 17, + end_line: 3, + end_column: 19, + }, + operation: Override, + }, + filename: "", + line: 3, + column: 15, + end_line: 3, + end_column: 19, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 0, + }, + operation: Union, + }, + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 0, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_17.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_17.snap new file mode 100644 index 000000000..3983c6842 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_17.snap @@ -0,0 +1,134 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests ::\nparsing_expr_string(r#\"{\n if True:\n b = [] = \n}\n\"#)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: None, + value: Node { + node: ConfigIfEntry( + ConfigIfEntryExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 11, + }, + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ), + value: Node { + node: List( + ListExpr { + elts: [], + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 12, + end_line: 3, + end_column: 14, + }, + operation: Override, + }, + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 14, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 15, + end_line: 3, + end_column: 16, + }, + ), + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 17, + end_line: 4, + end_column: 0, + }, + operation: Override, + }, + filename: "", + line: 3, + column: 15, + end_line: 4, + end_column: 0, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 0, + }, + operation: Union, + }, + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 0, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_18.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_18.snap new file mode 100644 index 000000000..ffad08c5c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_18.snap @@ -0,0 +1,124 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests ::\nparsing_expr_string(r#\"{\n if True:\n b = [] -\n}\n\"#)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: None, + value: Node { + node: ConfigIfEntry( + ConfigIfEntryExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 11, + }, + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ), + value: Node { + node: Binary( + BinaryExpr { + left: Node { + node: List( + ListExpr { + elts: [], + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 12, + end_line: 3, + end_column: 14, + }, + op: Sub, + right: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 16, + end_line: 4, + end_column: 0, + }, + }, + ), + filename: "", + line: 3, + column: 12, + end_line: 3, + end_column: 16, + }, + operation: Override, + }, + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 16, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 0, + }, + operation: Union, + }, + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 0, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_2.snap new file mode 100644 index 000000000..8e4c4910b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_2.snap @@ -0,0 +1,48 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[0,1\")" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_3.snap new file mode 100644 index 000000000..d28bafd7c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_3.snap @@ -0,0 +1,62 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[[0,1]\")" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 6, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_4.snap new file mode 100644 index 000000000..651f7c041 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_4.snap @@ -0,0 +1,62 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[[0,1\")" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 5, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_5.snap new file mode 100644 index 000000000..adc84ac14 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_5.snap @@ -0,0 +1,48 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"[\n 0,\n 1\n \"#)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_6.snap new file mode 100644 index 000000000..57e98ebee --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_6.snap @@ -0,0 +1,48 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[0 1]\")" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_7.snap new file mode 100644 index 000000000..2c20f49d4 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_7.snap @@ -0,0 +1,48 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[0,, 1\")" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_8.snap new file mode 100644 index 000000000..0a7de423d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_8.snap @@ -0,0 +1,60 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[0 ~ 1\")" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + Node { + node: Unary( + UnaryExpr { + op: Invert, + operand: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_9.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_9.snap new file mode 100644 index 000000000..c1db023b8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__list_recovery_9.snap @@ -0,0 +1,98 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"[*a, **b]\")" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: Starred( + StarredExpr { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 3, + }, + Node { + node: Binary( + BinaryExpr { + left: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 7, + }, + op: Pow, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 8, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_0.snap new file mode 100644 index 000000000..2c8407e62 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_0.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"00\")" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_1.snap new file mode 100644 index 000000000..6ea099971 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_1.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"00a\")" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_10.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_10.snap new file mode 100644 index 000000000..ca09b085f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_10.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"100mm\")" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 100, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_2.snap new file mode 100644 index 000000000..9887d1f32 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_2.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"0x112.3\")" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Float( + 0.0, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_3.snap new file mode 100644 index 000000000..0482e4fe4 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_3.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"0o\")" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_4.snap new file mode 100644 index 000000000..8346c4d81 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_4.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"0oA\")" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_5.snap new file mode 100644 index 000000000..a3df2f61f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_5.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"0x\")" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_6.snap new file mode 100644 index 000000000..53992add6 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_6.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"0xH\")" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_7.snap new file mode 100644 index 000000000..73d0a24c0 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_7.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"0e0\")" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Float( + 0.0, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_8.snap new file mode 100644 index 000000000..c7bcf8bc7 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_8.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"0b333\")" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_9.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_9.snap new file mode 100644 index 000000000..b145bb662 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__number_literal_recovery_9.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"10KI\")" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 10, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_0.snap new file mode 100644 index 000000000..8f5f0612e --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_0.snap @@ -0,0 +1,38 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"(a\")" +--- +Node { + node: Paren( + ParenExpr { + expr: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_1.snap new file mode 100644 index 000000000..61ed2b508 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_1.snap @@ -0,0 +1,65 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"(a + 1\")" +--- +Node { + node: Paren( + ParenExpr { + expr: Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_2.snap new file mode 100644 index 000000000..ba2af7cc1 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_2.snap @@ -0,0 +1,25 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"(\"#)" +--- +Node { + node: Paren( + ParenExpr { + expr: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_3.snap new file mode 100644 index 000000000..7ffb3a526 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_3.snap @@ -0,0 +1,25 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"(]\"#)" +--- +Node { + node: Paren( + ParenExpr { + expr: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_4.snap new file mode 100644 index 000000000..ed65a41fb --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_4.snap @@ -0,0 +1,38 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"(a\"#)" +--- +Node { + node: Paren( + ParenExpr { + expr: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_5.snap new file mode 100644 index 000000000..1d6c924b5 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__paren_recovery_5.snap @@ -0,0 +1,60 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"(a +\"#)" +--- +Node { + node: Paren( + ParenExpr { + expr: Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + op: Add, + right: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 4, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__parse_body_item.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__parse_body_item.snap new file mode 100644 index 000000000..b30163712 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__parse_body_item.snap @@ -0,0 +1,93 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nx = {\n if True\n}\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "x", + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + ], + value: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: None, + value: Node { + node: ConfigIfEntry( + ConfigIfEntryExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 3, + column: 7, + end_line: 3, + end_column: 11, + }, + items: [], + orelse: None, + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 4, + end_column: 0, + }, + operation: Union, + }, + filename: "", + line: 3, + column: 4, + end_line: 4, + end_column: 0, + }, + ], + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 1, + }, + ty: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 4, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_0.snap new file mode 100644 index 000000000..d6ebccdd4 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_0.snap @@ -0,0 +1,36 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"rule\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Rule( + RuleStmt { + doc: None, + name: Node { + node: "", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + parent_rules: [], + decorators: [], + checks: [], + args: None, + for_host_name: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_1.snap new file mode 100644 index 000000000..d6c84e913 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_1.snap @@ -0,0 +1,36 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"rule A\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Rule( + RuleStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + parent_rules: [], + decorators: [], + checks: [], + args: None, + for_host_name: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_2.snap new file mode 100644 index 000000000..beeaa8b1a --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_2.snap @@ -0,0 +1,49 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"rule A[\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Rule( + RuleStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + parent_rules: [], + decorators: [], + checks: [], + args: Some( + Node { + node: Arguments { + args: [], + defaults: [], + ty_list: [], + }, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ), + for_host_name: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_3.snap new file mode 100644 index 000000000..f58399935 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_3.snap @@ -0,0 +1,58 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"rule A::\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Rule( + RuleStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + parent_rules: [], + decorators: [], + checks: [ + Node { + node: CheckExpr { + test: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 8, + }, + if_cond: None, + msg: None, + }, + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 8, + }, + ], + args: None, + for_host_name: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_4.snap new file mode 100644 index 000000000..d67c0e416 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_4.snap @@ -0,0 +1,58 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"rule A:B\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Rule( + RuleStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + parent_rules: [], + decorators: [], + checks: [ + Node { + node: CheckExpr { + test: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 8, + }, + if_cond: None, + msg: None, + }, + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 8, + }, + ], + args: None, + for_host_name: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_5.snap new file mode 100644 index 000000000..eb5fd4ed6 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_5.snap @@ -0,0 +1,49 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"rule A(:\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Rule( + RuleStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + parent_rules: [ + Node { + node: Identifier { + names: [], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + decorators: [], + checks: [], + args: None, + for_host_name: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_6.snap new file mode 100644 index 000000000..f2f8b198a --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_6.snap @@ -0,0 +1,60 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nrule A:\n True \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Rule( + RuleStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 5, + end_line: 2, + end_column: 6, + }, + parent_rules: [], + decorators: [], + checks: [ + Node { + node: CheckExpr { + test: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 8, + }, + if_cond: None, + msg: None, + }, + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 8, + }, + ], + args: None, + for_host_name: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 3, + end_column: 9, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_7.snap new file mode 100644 index 000000000..7d1ba5928 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__rule_stmt_recovery_7.snap @@ -0,0 +1,79 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nrule A:\n @\n\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Rule( + RuleStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 5, + end_line: 2, + end_column: 6, + }, + parent_rules: [], + decorators: [], + checks: [ + Node { + node: CheckExpr { + test: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + if_cond: None, + msg: None, + }, + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 4, + }, + Node { + node: CheckExpr { + test: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 5, + end_line: 3, + end_column: 6, + }, + if_cond: None, + msg: None, + }, + filename: "", + line: 3, + column: 5, + end_line: 3, + end_column: 5, + }, + ], + args: None, + for_host_name: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 3, + end_column: 6, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_0.snap new file mode 100644 index 000000000..14371fe3a --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_0.snap @@ -0,0 +1,50 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"s {\"#)" +--- +Node { + node: Schema( + SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "s", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_1.snap new file mode 100644 index 000000000..64e0a41db --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_1.snap @@ -0,0 +1,101 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"s {a=1\"#)" +--- +Node { + node: Schema( + SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "s", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + ], + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_2.snap new file mode 100644 index 000000000..c45f80f95 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_2.snap @@ -0,0 +1,35 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"s.0 {a=1}\"#)" +--- +Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "s", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + Node { + node: "", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_3.snap new file mode 100644 index 000000000..a464cbe9a --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_3.snap @@ -0,0 +1,61 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"s?.a {a=1}\"#)" +--- +Node { + node: Selector( + SelectorExpr { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "s", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ctx: Load, + has_question: true, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_4.snap new file mode 100644 index 000000000..8ddaddec8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_4.snap @@ -0,0 +1,109 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"s. {a=1}\"#)" +--- +Node { + node: Schema( + SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "s", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + Node { + node: "", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + args: [], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 8, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_5.snap new file mode 100644 index 000000000..6ea5e1bdf --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_5.snap @@ -0,0 +1,104 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"s( {a=1}\"#)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "s", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [ + Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 8, + }, + ], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_6.snap new file mode 100644 index 000000000..743c9c6e3 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_recovery_6.snap @@ -0,0 +1,101 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"s(] {a=1}\"#)" +--- +Node { + node: Schema( + SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "s", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + args: [], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 8, + }, + ], + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 9, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_0.snap new file mode 100644 index 000000000..c739713cc --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_0.snap @@ -0,0 +1,41 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_1.snap new file mode 100644 index 000000000..af34d72b2 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_1.snap @@ -0,0 +1,41 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_10.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_10.snap new file mode 100644 index 000000000..6bb0fbb9a --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_10.snap @@ -0,0 +1,77 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A:\n[str:]: []\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 0, + }, + Node { + node: Assign( + AssignStmt { + targets: [], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 2, + column: 10, + end_line: 2, + end_column: 10, + }, + ty: Some( + Node { + node: List( + ListType { + inner_type: None, + }, + ), + filename: "", + line: 2, + column: 8, + end_line: 2, + end_column: 10, + }, + ), + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 6, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_11.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_11.snap new file mode 100644 index 000000000..5d479d61f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_11.snap @@ -0,0 +1,75 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A:\n[str]: str = \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 0, + }, + Node { + node: Assign( + AssignStmt { + targets: [], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 2, + column: 13, + end_line: 2, + end_column: 13, + }, + ty: Some( + Node { + node: Basic( + Str, + ), + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 10, + }, + ), + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 12, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_12.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_12.snap new file mode 100644 index 000000000..343bd589e --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_12.snap @@ -0,0 +1,73 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A:\n[str]: = \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 0, + }, + Node { + node: Assign( + AssignStmt { + targets: [], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 2, + column: 9, + end_line: 2, + end_column: 9, + }, + ty: Some( + Node { + node: Any, + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + ), + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 5, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_13.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_13.snap new file mode 100644 index 000000000..cfb118d88 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_13.snap @@ -0,0 +1,77 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A:\n[str]: ''= \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 0, + }, + Node { + node: Assign( + AssignStmt { + targets: [], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 2, + column: 11, + end_line: 2, + end_column: 11, + }, + ty: Some( + Node { + node: Literal( + Str( + "", + ), + ), + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 9, + }, + ), + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 10, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_14.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_14.snap new file mode 100644 index 000000000..1f9b7ac9f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_14.snap @@ -0,0 +1,113 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A:\na??: int \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 0, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + ], + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "int", + filename: "", + line: 2, + column: 5, + end_line: 2, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 5, + end_line: 2, + end_column: 8, + }, + ], + }, + ), + filename: "", + line: 2, + column: 5, + end_line: 2, + end_column: 8, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_15.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_15.snap new file mode 100644 index 000000000..f9f64ccdc --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_15.snap @@ -0,0 +1,148 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A:\na!: int \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 0, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + ], + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 2, + column: 2, + end_line: 2, + end_column: 3, + }, + }, + ), + filename: "", + line: 2, + column: 1, + end_line: 2, + end_column: 2, + }, + ], + }, + ), + filename: "", + line: 2, + column: 1, + end_line: 2, + end_column: 2, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "int", + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 7, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_16.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_16.snap new file mode 100644 index 000000000..7b04ca7cf --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_16.snap @@ -0,0 +1,183 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A:\na!!: int \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 0, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + ], + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 2, + column: 2, + end_line: 2, + end_column: 3, + }, + }, + ), + filename: "", + line: 2, + column: 1, + end_line: 2, + end_column: 2, + }, + ], + }, + ), + filename: "", + line: 2, + column: 1, + end_line: 2, + end_column: 2, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 2, + column: 3, + end_line: 2, + end_column: 4, + }, + }, + ), + filename: "", + line: 2, + column: 2, + end_line: 2, + end_column: 3, + }, + ], + }, + ), + filename: "", + line: 2, + column: 2, + end_line: 2, + end_column: 3, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "int", + filename: "", + line: 2, + column: 5, + end_line: 2, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 5, + end_line: 2, + end_column: 8, + }, + ], + }, + ), + filename: "", + line: 2, + column: 5, + end_line: 2, + end_column: 8, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_17.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_17.snap new file mode 100644 index 000000000..22abaf488 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_17.snap @@ -0,0 +1,93 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A:\na: \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 0, + }, + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 2, + column: 3, + end_line: 2, + end_column: 3, + }, + ty: Some( + Node { + node: Any, + filename: "", + line: 2, + column: 3, + end_line: 2, + end_column: 3, + }, + ), + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_19.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_19.snap new file mode 100644 index 000000000..0e6e59b4d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_19.snap @@ -0,0 +1,109 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"@deprecated\nschema A:\n a: \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [ + Node { + node: SchemaAttr( + SchemaAttr { + doc: "", + name: Node { + node: "a", + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + op: None, + value: None, + is_optional: false, + decorators: [], + ty: Node { + node: Any, + filename: "", + line: 3, + column: 7, + end_line: 3, + end_column: 7, + }, + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 7, + }, + ], + decorators: [ + Node { + node: CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "deprecated", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 11, + }, + args: [], + keywords: [], + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 11, + }, + ], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 3, + end_column: 7, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_2.snap new file mode 100644 index 000000000..200e407a3 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_2.snap @@ -0,0 +1,54 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A[\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: Some( + Node { + node: Arguments { + args: [], + defaults: [], + ty_list: [], + }, + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ), + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_20.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_20.snap new file mode 100644 index 000000000..2edc07993 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_20.snap @@ -0,0 +1,10 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"@deprecated(\nschema A:\n a: \"#)" +--- +Module { + filename: "", + doc: None, + body: [], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_21.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_21.snap new file mode 100644 index 000000000..2edc07993 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_21.snap @@ -0,0 +1,10 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"@deprecated(\nschema A:\n a: \"#)" +--- +Module { + filename: "", + doc: None, + body: [], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_22.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_22.snap new file mode 100644 index 000000000..eae9745e3 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_22.snap @@ -0,0 +1,133 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"@deprecated(a\nschema A:\n a: \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [ + Node { + node: SchemaAttr( + SchemaAttr { + doc: "", + name: Node { + node: "a", + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + op: None, + value: None, + is_optional: false, + decorators: [], + ty: Node { + node: Any, + filename: "", + line: 3, + column: 7, + end_line: 3, + end_column: 7, + }, + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 7, + }, + ], + decorators: [ + Node { + node: CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "deprecated", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 11, + }, + args: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 13, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 13, + }, + ], + keywords: [], + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 13, + }, + ], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 3, + end_column: 7, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_23.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_23.snap new file mode 100644 index 000000000..211647de6 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_23.snap @@ -0,0 +1,133 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests ::\nparsing_module_string(r#\"@deprecated(a,\nschema A:\n a: \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [ + Node { + node: SchemaAttr( + SchemaAttr { + doc: "", + name: Node { + node: "a", + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + op: None, + value: None, + is_optional: false, + decorators: [], + ty: Node { + node: Any, + filename: "", + line: 3, + column: 7, + end_line: 3, + end_column: 7, + }, + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 7, + }, + ], + decorators: [ + Node { + node: CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "deprecated", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 11, + }, + args: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 13, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 13, + }, + ], + keywords: [], + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 14, + }, + ], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 3, + end_column: 7, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_24.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_24.snap new file mode 100644 index 000000000..b2e214695 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_24.snap @@ -0,0 +1,131 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests ::\nparsing_module_string(r#\"@deprecated((),\nschema A:\n a: \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [ + Node { + node: SchemaAttr( + SchemaAttr { + doc: "", + name: Node { + node: "a", + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + op: None, + value: None, + is_optional: false, + decorators: [], + ty: Node { + node: Any, + filename: "", + line: 3, + column: 7, + end_line: 3, + end_column: 7, + }, + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 7, + }, + ], + decorators: [ + Node { + node: CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "deprecated", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 11, + }, + args: [ + Node { + node: Paren( + ParenExpr { + expr: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 14, + }, + ], + keywords: [], + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 15, + }, + ], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 3, + end_column: 7, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_25.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_25.snap new file mode 100644 index 000000000..61bbc7cde --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_25.snap @@ -0,0 +1,63 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nschema A:\n check: \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [ + Node { + node: CheckExpr { + test: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 11, + end_line: 3, + end_column: 11, + }, + if_cond: None, + msg: None, + }, + filename: "", + line: 3, + column: 11, + end_line: 3, + end_column: 11, + }, + ], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 4, + end_column: 0, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_26.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_26.snap new file mode 100644 index 000000000..b4dc01d83 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_26.snap @@ -0,0 +1,84 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests ::\nparsing_module_string(r#\"\nschema A:\n check: \n @\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [ + Node { + node: CheckExpr { + test: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 4, + column: 8, + end_line: 4, + end_column: 9, + }, + if_cond: None, + msg: None, + }, + filename: "", + line: 4, + column: 8, + end_line: 4, + end_column: 8, + }, + Node { + node: CheckExpr { + test: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 4, + column: 9, + end_line: 4, + end_column: 9, + }, + if_cond: None, + msg: None, + }, + filename: "", + line: 4, + column: 9, + end_line: 4, + end_column: 9, + }, + ], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 4, + end_column: 9, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_27.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_27.snap new file mode 100644 index 000000000..6d8a0767f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_27.snap @@ -0,0 +1,145 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nschema A:\n [.str]: str \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [ + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Selector( + SelectorExpr { + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 5, + end_line: 3, + end_column: 6, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "str", + filename: "", + line: 3, + column: 6, + end_line: 3, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 3, + column: 6, + end_line: 3, + end_column: 9, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 3, + column: 5, + end_line: 3, + end_column: 9, + }, + ], + }, + ), + filename: "", + line: 3, + column: 5, + end_line: 3, + end_column: 9, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 9, + end_line: 3, + end_column: 10, + }, + ], + }, + ), + filename: "", + line: 3, + column: 9, + end_line: 3, + end_column: 10, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 16, + end_line: 3, + end_column: 16, + }, + ], + }, + ), + filename: "", + line: 3, + column: 16, + end_line: 3, + end_column: 16, + }, + ], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 4, + end_column: 0, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_28.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_28.snap new file mode 100644 index 000000000..3c954aae5 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_28.snap @@ -0,0 +1,168 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nschema A:\n [....str]: str \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [ + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 5, + end_line: 3, + end_column: 8, + }, + ], + }, + ), + filename: "", + line: 3, + column: 5, + end_line: 3, + end_column: 8, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Selector( + SelectorExpr { + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "str", + filename: "", + line: 3, + column: 9, + end_line: 3, + end_column: 12, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 3, + column: 9, + end_line: 3, + end_column: 12, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 12, + }, + ], + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 12, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 12, + end_line: 3, + end_column: 13, + }, + ], + }, + ), + filename: "", + line: 3, + column: 12, + end_line: 3, + end_column: 13, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 19, + end_line: 3, + end_column: 19, + }, + ], + }, + ), + filename: "", + line: 3, + column: 19, + end_line: 3, + end_column: 19, + }, + ], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 4, + end_column: 0, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_29.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_29.snap new file mode 100644 index 000000000..0614633ca --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_29.snap @@ -0,0 +1,74 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nschema A:\n @\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [ + Node { + node: SchemaAttr( + SchemaAttr { + doc: "", + name: Node { + node: "", + filename: "", + line: 3, + column: 5, + end_line: 3, + end_column: 5, + }, + op: None, + value: None, + is_optional: false, + decorators: [], + ty: Node { + node: Any, + filename: "", + line: 3, + column: 5, + end_line: 3, + end_column: 5, + }, + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + ], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 4, + end_column: 0, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_3.snap new file mode 100644 index 000000000..0881f9d6b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_3.snap @@ -0,0 +1,41 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A::\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_30.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_30.snap new file mode 100644 index 000000000..e6bb270f9 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_30.snap @@ -0,0 +1,99 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nschema A:\n .\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [ + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Selector( + SelectorExpr { + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 3, + column: 5, + end_line: 3, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 3, + column: 5, + end_line: 3, + end_column: 5, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + ], + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + ], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 3, + end_column: 5, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_31.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_31.snap new file mode 100644 index 000000000..bae20aeca --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_31.snap @@ -0,0 +1,87 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests ::\nparsing_module_string(r#\"\nschema A:\n [str]: str\n [str]: int\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: Some( + Node { + node: SchemaIndexSignature { + key_name: None, + value: None, + any_other: false, + key_ty: Node { + node: Named( + Identifier { + names: [ + Node { + node: "str", + filename: "", + line: 4, + column: 5, + end_line: 4, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 4, + column: 5, + end_line: 4, + end_column: 8, + }, + value_ty: Node { + node: Basic( + Int, + ), + filename: "", + line: 4, + column: 11, + end_line: 4, + end_column: 14, + }, + }, + filename: "", + line: 4, + column: 4, + end_line: 4, + end_column: 14, + }, + ), + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 4, + end_column: 14, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_32.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_32.snap new file mode 100644 index 000000000..ce5d38a78 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_32.snap @@ -0,0 +1,76 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nschema A:\n \"attr\": str\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [ + Node { + node: SchemaAttr( + SchemaAttr { + doc: "", + name: Node { + node: "attr", + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 10, + }, + op: None, + value: None, + is_optional: false, + decorators: [], + ty: Node { + node: Basic( + Str, + ), + filename: "", + line: 3, + column: 12, + end_line: 3, + end_column: 15, + }, + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 15, + }, + ], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 3, + end_column: 15, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_33.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_33.snap new file mode 100644 index 000000000..5f2a682b6 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_33.snap @@ -0,0 +1,85 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests ::\nparsing_module_string(r#\"\nschema A:\n \"\"\"Schema Doc\"\"\"\n \"attr\": str\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: Some( + Node { + node: "\"\"\"Schema Doc\"\"\"", + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 20, + }, + ), + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [ + Node { + node: SchemaAttr( + SchemaAttr { + doc: "", + name: Node { + node: "attr", + filename: "", + line: 4, + column: 4, + end_line: 4, + end_column: 10, + }, + op: None, + value: None, + is_optional: false, + decorators: [], + ty: Node { + node: Basic( + Str, + ), + filename: "", + line: 4, + column: 12, + end_line: 4, + end_column: 15, + }, + }, + ), + filename: "", + line: 4, + column: 4, + end_line: 4, + end_column: 15, + }, + ], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 4, + end_column: 15, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_34.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_34.snap new file mode 100644 index 000000000..99f774c7d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_34.snap @@ -0,0 +1,69 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nschema A:\n \"attr: str\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [ + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"attr: str", + value: "attr: str", + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 14, + }, + ], + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 14, + }, + ], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 3, + end_column: 14, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_35.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_35.snap new file mode 100644 index 000000000..121372606 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_35.snap @@ -0,0 +1,74 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nschema A:\n \"attr\":\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [ + Node { + node: SchemaAttr( + SchemaAttr { + doc: "", + name: Node { + node: "attr", + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 10, + }, + op: None, + value: None, + is_optional: false, + decorators: [], + ty: Node { + node: Any, + filename: "", + line: 3, + column: 11, + end_line: 3, + end_column: 11, + }, + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 11, + }, + ], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 3, + end_column: 11, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_36.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_36.snap new file mode 100644 index 000000000..e5e6cd119 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_36.snap @@ -0,0 +1,41 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nschema A:\n mixin: \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 4, + end_column: 0, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_37.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_37.snap new file mode 100644 index 000000000..a1aad9e92 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_37.snap @@ -0,0 +1,84 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nschema A:\n mixin: [\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [ + Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 3, + column: 11, + end_line: 3, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 3, + column: 11, + end_line: 3, + end_column: 11, + }, + Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 3, + column: 12, + end_line: 3, + end_column: 12, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 3, + column: 12, + end_line: 3, + end_column: 12, + }, + ], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 4, + end_column: 0, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_38.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_38.snap new file mode 100644 index 000000000..d8b587c54 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_38.snap @@ -0,0 +1,63 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nschema A:\n mixin: []\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [ + Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 3, + column: 11, + end_line: 3, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 3, + column: 11, + end_line: 3, + end_column: 11, + }, + ], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 3, + end_column: 13, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_39.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_39.snap new file mode 100644 index 000000000..de15d16de --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_39.snap @@ -0,0 +1,41 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nschema A:\n mixin []\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 3, + end_column: 12, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_4.snap new file mode 100644 index 000000000..83a8604aa --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_4.snap @@ -0,0 +1,77 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A:B\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "B", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + ], + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 10, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_40.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_40.snap new file mode 100644 index 000000000..5d98ac253 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_40.snap @@ -0,0 +1,41 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"\nschema A:\n mixin [\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 4, + end_column: 0, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_5.snap new file mode 100644 index 000000000..aeabc94c8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_5.snap @@ -0,0 +1,63 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A(:\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: Some( + Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 9, + }, + ), + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 10, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_6.snap new file mode 100644 index 000000000..029afdabc --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_6.snap @@ -0,0 +1,63 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A():\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: Some( + Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 9, + }, + ), + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_7.snap new file mode 100644 index 000000000..fed41acd6 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_7.snap @@ -0,0 +1,129 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A:\na:: int\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 0, + }, + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 7, + }, + ty: Some( + Node { + node: Any, + filename: "", + line: 2, + column: 2, + end_line: 2, + end_column: 3, + }, + ), + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "int", + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 7, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_8.snap new file mode 100644 index 000000000..9ecd07a5d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_8.snap @@ -0,0 +1,95 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A:\na: int =\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 0, + }, + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "a", + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + ], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 2, + column: 8, + end_line: 2, + end_column: 8, + }, + ty: Some( + Node { + node: Basic( + Int, + ), + filename: "", + line: 2, + column: 3, + end_line: 2, + end_column: 6, + }, + ), + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 8, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_9.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_9.snap new file mode 100644 index 000000000..119e6200f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__schema_stmt_recovery_9.snap @@ -0,0 +1,77 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"schema A:\n[]: []\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Schema( + SchemaStmt { + doc: None, + name: Node { + node: "A", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + parent_name: None, + for_host_name: None, + is_mixin: false, + is_protocol: false, + args: None, + mixins: [], + body: [], + decorators: [], + checks: [], + index_signature: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 0, + }, + Node { + node: Assign( + AssignStmt { + targets: [], + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 2, + column: 6, + end_line: 2, + end_column: 6, + }, + ty: Some( + Node { + node: List( + ListType { + inner_type: None, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 6, + }, + ), + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 2, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_0.snap new file mode 100644 index 000000000..781fc3c22 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_0.snap @@ -0,0 +1,35 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a.\"#)" +--- +Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + Node { + node: "", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_1.snap new file mode 100644 index 000000000..93b7140c6 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_1.snap @@ -0,0 +1,43 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a.b.\"#)" +--- +Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + Node { + node: "b", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + Node { + node: "", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_10.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_10.snap new file mode 100644 index 000000000..8df622b2e --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_10.snap @@ -0,0 +1,61 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a?.b?\"#)" +--- +Node { + node: Selector( + SelectorExpr { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ctx: Load, + has_question: true, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_11.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_11.snap new file mode 100644 index 000000000..b3c414ce4 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_11.snap @@ -0,0 +1,95 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a?.b?.c?\"#)" +--- +Node { + node: Selector( + SelectorExpr { + value: Node { + node: Selector( + SelectorExpr { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ctx: Load, + has_question: true, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "c", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ctx: Load, + has_question: true, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_12.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_12.snap new file mode 100644 index 000000000..13c66f632 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_12.snap @@ -0,0 +1,35 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a.0\"#)" +--- +Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + Node { + node: "", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_13.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_13.snap new file mode 100644 index 000000000..5870bba2c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_13.snap @@ -0,0 +1,43 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a..0\"#)" +--- +Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + Node { + node: "", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 2, + }, + Node { + node: "", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_14.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_14.snap new file mode 100644 index 000000000..9266a0231 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_14.snap @@ -0,0 +1,27 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a...\"#)" +--- +Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_2.snap new file mode 100644 index 000000000..11b40ca34 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_2.snap @@ -0,0 +1,51 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a.b.c.\"#)" +--- +Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + Node { + node: "b", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + Node { + node: "c", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + Node { + node: "", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_3.snap new file mode 100644 index 000000000..5cf63ae51 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_3.snap @@ -0,0 +1,52 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"''.\"#)" +--- +Node { + node: Selector( + SelectorExpr { + value: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "''", + value: "", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_4.snap new file mode 100644 index 000000000..8e6d33d77 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_4.snap @@ -0,0 +1,52 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"''.lower\"#)" +--- +Node { + node: Selector( + SelectorExpr { + value: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "''", + value: "", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "lower", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 8, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_5.snap new file mode 100644 index 000000000..ec69c1d6b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_5.snap @@ -0,0 +1,99 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"''.lower().\"#)" +--- +Node { + node: Selector( + SelectorExpr { + value: Node { + node: Call( + CallExpr { + func: Node { + node: Selector( + SelectorExpr { + value: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "''", + value: "", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "lower", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 8, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, + }, + args: [], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 10, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 11, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_6.snap new file mode 100644 index 000000000..6ed0a76a2 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_6.snap @@ -0,0 +1,61 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a?.\"#)" +--- +Node { + node: Selector( + SelectorExpr { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + ctx: Load, + has_question: true, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_7.snap new file mode 100644 index 000000000..87a06af86 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_7.snap @@ -0,0 +1,95 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a?.b?.\"#)" +--- +Node { + node: Selector( + SelectorExpr { + value: Node { + node: Selector( + SelectorExpr { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ctx: Load, + has_question: true, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + ctx: Load, + has_question: true, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_8.snap new file mode 100644 index 000000000..f7f7d5571 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_8.snap @@ -0,0 +1,129 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a?.b?.c?.\"#)" +--- +Node { + node: Selector( + SelectorExpr { + value: Node { + node: Selector( + SelectorExpr { + value: Node { + node: Selector( + SelectorExpr { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ctx: Load, + has_question: true, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "c", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ctx: Load, + has_question: true, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 9, + }, + ctx: Load, + has_question: true, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_9.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_9.snap new file mode 100644 index 000000000..3ef1914e4 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__select_recovery_9.snap @@ -0,0 +1,27 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a?\"#)" +--- +Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_0.snap new file mode 100644 index 000000000..12ce1cc87 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_0.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"'abc\")" +--- +Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'abc", + value: "abc", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_1.snap new file mode 100644 index 000000000..de6f07216 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_1.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"r'abc\")" +--- +Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "r'abc", + value: "abc", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_2.snap new file mode 100644 index 000000000..a9979788c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_2.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"'''abc\")" +--- +Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'''abc", + value: "''abc", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_3.snap new file mode 100644 index 000000000..d1327385a --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_3.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"r'''abc\")" +--- +Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "r'''abc", + value: "''abc", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_4.snap new file mode 100644 index 000000000..2b42bbc66 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_4.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"r''abc'\")" +--- +Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "r''", + value: "", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_5.snap new file mode 100644 index 000000000..9a4a30ea4 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_5.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"'\")" +--- +Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'", + value: "", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_6.snap new file mode 100644 index 000000000..eb611eaa3 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_6.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"'''\")" +--- +Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'''", + value: "''", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_7.snap new file mode 100644 index 000000000..09300af71 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_7.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"'\\n\")" +--- +Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'\n", + value: "", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_8.snap new file mode 100644 index 000000000..b64bd780e --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__string_literal_recovery_8.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(\"r'abc\\n\")" +--- +Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "r'abc", + value: "abc", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_0.snap new file mode 100644 index 000000000..84bb3f4d3 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_0.snap @@ -0,0 +1,60 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a[b 1]\"#)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_1.snap new file mode 100644 index 000000000..a43751b97 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_1.snap @@ -0,0 +1,55 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a[1,b]\"#)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: Some( + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ), + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_10.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_10.snap new file mode 100644 index 000000000..545319680 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_10.snap @@ -0,0 +1,100 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"[0]?.[0]\"#)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Selector( + SelectorExpr { + value: Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 5, + }, + ctx: Load, + has_question: true, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, + }, + index: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ), + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_11.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_11.snap new file mode 100644 index 000000000..4c1615362 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_11.snap @@ -0,0 +1,33 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"[0]??[0]\"#)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_12.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_12.snap new file mode 100644 index 000000000..49159db4d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_12.snap @@ -0,0 +1,100 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"[0].?[0]\"#)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Selector( + SelectorExpr { + value: Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, + }, + index: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ), + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: true, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_2.snap new file mode 100644 index 000000000..779a93b52 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_2.snap @@ -0,0 +1,68 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a[b;;b]\"#)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ), + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_3.snap new file mode 100644 index 000000000..c4379f075 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_3.snap @@ -0,0 +1,55 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a[b[b]\"#)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: Some( + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 6, + }, + ), + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_4.snap new file mode 100644 index 000000000..0f1e2881e --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_4.snap @@ -0,0 +1,44 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a[:::]\"#)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: None, + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_5.snap new file mode 100644 index 000000000..ab215d5e1 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_5.snap @@ -0,0 +1,76 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"a[:1:2:]\"#)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: None, + lower: None, + upper: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ), + step: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ), + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_6.snap new file mode 100644 index 000000000..7f16720a6 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_6.snap @@ -0,0 +1,106 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"[][a:b:c:d]\"#)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: List( + ListExpr { + elts: [], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + index: None, + lower: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ), + upper: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ), + step: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "c", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ), + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_7.snap new file mode 100644 index 000000000..abafd34ea --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_7.snap @@ -0,0 +1,34 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"[][]\"#)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: List( + ListExpr { + elts: [], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + index: None, + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_8.snap new file mode 100644 index 000000000..5dbcec009 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_8.snap @@ -0,0 +1,51 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"[][][]\"#)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Subscript( + Subscript { + value: Node { + node: List( + ListExpr { + elts: [], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + index: None, + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, + }, + index: None, + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_9.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_9.snap new file mode 100644 index 000000000..366cc869b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__subscript_recovery_9.snap @@ -0,0 +1,34 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"[]?[]\"#)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: List( + ListExpr { + elts: [], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + index: None, + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: true, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_0.snap new file mode 100644 index 000000000..77fbe271b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_0.snap @@ -0,0 +1,50 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"type\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: TypeAlias( + TypeAliasStmt { + type_name: Node { + node: Identifier { + names: [], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + type_value: Node { + node: "any", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + ty: Node { + node: Any, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 4, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_1.snap new file mode 100644 index 000000000..6d5964c42 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_1.snap @@ -0,0 +1,50 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"type 'pkg_path'\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: TypeAlias( + TypeAliasStmt { + type_name: Node { + node: Identifier { + names: [], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 15, + }, + type_value: Node { + node: "any", + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 15, + }, + ty: Node { + node: Any, + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 15, + }, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 15, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_2.snap new file mode 100644 index 000000000..8d1cf07f1 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_2.snap @@ -0,0 +1,67 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"type pkg_path.\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: TypeAlias( + TypeAliasStmt { + type_name: Node { + node: Identifier { + names: [ + Node { + node: "pkg_path", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 13, + }, + Node { + node: "", + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 14, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 14, + }, + type_value: Node { + node: "any", + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 14, + }, + ty: Node { + node: Any, + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 14, + }, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 14, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_3.snap new file mode 100644 index 000000000..013918756 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_3.snap @@ -0,0 +1,50 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"type pkg_path[0]\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: TypeAlias( + TypeAliasStmt { + type_name: Node { + node: Identifier { + names: [], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 16, + }, + type_value: Node { + node: "any", + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 16, + }, + ty: Node { + node: Any, + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 16, + }, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 16, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_4.snap new file mode 100644 index 000000000..94e1e18e6 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_4.snap @@ -0,0 +1,50 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"type .pkg_path.\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: TypeAlias( + TypeAliasStmt { + type_name: Node { + node: Identifier { + names: [], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 15, + }, + type_value: Node { + node: "any", + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 15, + }, + ty: Node { + node: Any, + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 15, + }, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 15, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_5.snap new file mode 100644 index 000000000..19ae62e5d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_5.snap @@ -0,0 +1,59 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"type pkg_path = \"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: TypeAlias( + TypeAliasStmt { + type_name: Node { + node: Identifier { + names: [ + Node { + node: "pkg_path", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 13, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 13, + }, + type_value: Node { + node: "any", + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 16, + }, + ty: Node { + node: Any, + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 16, + }, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 16, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_6.snap new file mode 100644 index 000000000..66721386f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__type_alias_recovery_6.snap @@ -0,0 +1,63 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"type pkg_path = 'data'\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: TypeAlias( + TypeAliasStmt { + type_name: Node { + node: Identifier { + names: [ + Node { + node: "pkg_path", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 13, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 13, + }, + type_value: Node { + node: "\"data\"", + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 22, + }, + ty: Node { + node: Literal( + Str( + "data", + ), + ), + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 22, + }, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 22, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_0.snap new file mode 100644 index 000000000..1515dc847 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_0.snap @@ -0,0 +1,39 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"!a\"#)" +--- +Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_1.snap new file mode 100644 index 000000000..8c1dc5a44 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_1.snap @@ -0,0 +1,26 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"!!a\"#)" +--- +Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_2.snap new file mode 100644 index 000000000..4eaf93055 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_2.snap @@ -0,0 +1,62 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"not (!a)\"#)" +--- +Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: Paren( + ParenExpr { + expr: Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 7, + }, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 8, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_3.snap new file mode 100644 index 000000000..d4e059168 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_3.snap @@ -0,0 +1,62 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"! (not a)\"#)" +--- +Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: Paren( + ParenExpr { + expr: Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 8, + }, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 9, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_5.snap new file mode 100644 index 000000000..c1450c462 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_5.snap @@ -0,0 +1,61 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"++i\"#)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Unary( + UnaryExpr { + op: UAdd, + operand: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + op: Add, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_6.snap new file mode 100644 index 000000000..26652284d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_6.snap @@ -0,0 +1,61 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"--i\"#)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Unary( + UnaryExpr { + op: USub, + operand: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + op: Sub, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_7.snap new file mode 100644 index 000000000..21a1b99fb --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_7.snap @@ -0,0 +1,61 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"-+i\"#)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Unary( + UnaryExpr { + op: USub, + operand: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + op: Add, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_8.snap new file mode 100644 index 000000000..afe892473 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unary_recovery_8.snap @@ -0,0 +1,26 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_expr_string(r#\"~~i\"#)" +--- +Node { + node: Unary( + UnaryExpr { + op: Invert, + operand: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_0.snap new file mode 100644 index 000000000..1eb63728c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_0.snap @@ -0,0 +1,87 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"s: Server {\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Unification( + UnificationStmt { + target: Node { + node: Identifier { + names: [ + Node { + node: "s", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Store, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + value: Node { + node: SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "Server", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + args: [], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_1.snap new file mode 100644 index 000000000..dd3022d11 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_1.snap @@ -0,0 +1,87 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"s: Server {}\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Unification( + UnificationStmt { + target: Node { + node: Identifier { + names: [ + Node { + node: "s", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Store, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + value: Node { + node: SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "Server", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + args: [], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 12, + }, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_2.snap new file mode 100644 index 000000000..72c2ab94c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_2.snap @@ -0,0 +1,87 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"s: Server (\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Unification( + UnificationStmt { + target: Node { + node: Identifier { + names: [ + Node { + node: "s", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Store, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + value: Node { + node: SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "Server", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + args: [], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 11, + }, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_3.snap new file mode 100644 index 000000000..95935cccf --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_3.snap @@ -0,0 +1,87 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"s: Server ()\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Unification( + UnificationStmt { + target: Node { + node: Identifier { + names: [ + Node { + node: "s", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Store, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + value: Node { + node: SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "Server", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + args: [], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 12, + }, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_4.snap new file mode 100644 index 000000000..a841bac29 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_4.snap @@ -0,0 +1,87 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"s: Server () {\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Unification( + UnificationStmt { + target: Node { + node: Identifier { + names: [ + Node { + node: "s", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Store, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + value: Node { + node: SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "Server", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + args: [], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 14, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 14, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_5.snap new file mode 100644 index 000000000..86276e120 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_5.snap @@ -0,0 +1,100 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"s: Server ( {\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Unification( + UnificationStmt { + target: Node { + node: Identifier { + names: [ + Node { + node: "s", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Store, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + value: Node { + node: SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "Server", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + args: [ + Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 13, + }, + ], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 13, + }, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 13, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 13, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_6.snap new file mode 100644 index 000000000..120f793c8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__error_recovery__unification_stmt_recovery_6.snap @@ -0,0 +1,87 @@ +--- +source: crates/parser/src/tests/error_recovery.rs +expression: "$crate :: tests :: parsing_module_string(r#\"s: Server ( }\"#)" +--- +Module { + filename: "", + doc: None, + body: [ + Node { + node: Unification( + UnificationStmt { + target: Node { + node: Identifier { + names: [ + Node { + node: "s", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Store, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + value: Node { + node: SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "Server", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 9, + }, + args: [], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 13, + }, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 13, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 13, + }, + ], + comments: [], +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_0.snap new file mode 100644 index 000000000..51cc1fd50 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_0.snap @@ -0,0 +1,73 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"1+2+3\"####)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_1.snap new file mode 100644 index 000000000..2ade3b231 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_1.snap @@ -0,0 +1,100 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"1+2*3-4\"####)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + op: Add, + right: Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + op: Mul, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 5, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, + }, + op: Sub, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 4, + ), + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_10.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_10.snap new file mode 100644 index 000000000..2e3a9c210 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_10.snap @@ -0,0 +1,89 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"1 + a and b\"####)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + op: Add, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, + }, + op: And, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_2.snap new file mode 100644 index 000000000..77d81efba --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_2.snap @@ -0,0 +1,100 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"1+2*3/4\"####)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + op: Add, + right: Node { + node: Binary( + BinaryExpr { + left: Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + op: Mul, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 5, + }, + op: Div, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 4, + ), + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 7, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_3.snap new file mode 100644 index 000000000..709d8a5f3 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_3.snap @@ -0,0 +1,62 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a or b\"####)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + op: Or, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_4.snap new file mode 100644 index 000000000..a6a80a84c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_4.snap @@ -0,0 +1,101 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"x == a or b\"####)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ops: [ + Eq, + ], + comparators: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, + }, + op: Or, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_5.snap new file mode 100644 index 000000000..a02d19c1f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_5.snap @@ -0,0 +1,108 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"22 > 11 and 111 < 222\"####)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Compare( + Compare { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 22, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + ops: [ + Gt, + ], + comparators: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 11, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 21, + }, + op: And, + right: Node { + node: Compare( + Compare { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 111, + ), + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 15, + }, + ops: [ + Lt, + ], + comparators: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 222, + ), + }, + ), + filename: "", + line: 1, + column: 18, + end_line: 1, + end_column: 21, + }, + ], + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 21, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 21, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_6.snap new file mode 100644 index 000000000..120475f39 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_6.snap @@ -0,0 +1,169 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"int(e.value) > 1 and i == 0\"####)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Compare( + Compare { + left: Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "int", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + args: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "e", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + Node { + node: "value", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 11, + }, + ], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, + }, + ops: [ + Gt, + ], + comparators: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 16, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 27, + }, + op: And, + right: Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 22, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 22, + }, + ops: [ + Eq, + ], + comparators: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 26, + end_line: 1, + end_column: 27, + }, + ], + }, + ), + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 27, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 27, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_7.snap new file mode 100644 index 000000000..44b92f89e --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_7.snap @@ -0,0 +1,71 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"key in ['key']\"####)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "key", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + ops: [ + In, + ], + comparators: [ + Node { + node: List( + ListExpr { + elts: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'key'", + value: "key", + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 13, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 14, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 14, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_8.snap new file mode 100644 index 000000000..b04e73bc5 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_8.snap @@ -0,0 +1,71 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"key not in ['key']\"####)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "key", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + ops: [ + NotIn, + ], + comparators: [ + Node { + node: List( + ListExpr { + elts: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'key'", + value: "key", + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 17, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 18, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 18, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_9.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_9.snap new file mode 100644 index 000000000..76f00cb64 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_9.snap @@ -0,0 +1,108 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"1 is 1 and 11 is not 22\"####)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Compare( + Compare { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ops: [ + Is, + ], + comparators: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 23, + }, + op: And, + right: Node { + node: Compare( + Compare { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 11, + ), + }, + ), + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 13, + }, + ops: [ + IsNot, + ], + comparators: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 22, + ), + }, + ), + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 23, + }, + ], + }, + ), + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 23, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 23, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_with_paren.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_with_paren.snap new file mode 100644 index 000000000..1e1bf5161 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__binary_expr_with_paren.snap @@ -0,0 +1,111 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"1*(2+3)-4\"####)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + op: Mul, + right: Node { + node: Paren( + ParenExpr { + expr: Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 7, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, + }, + op: Sub, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 4, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__call_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__call_expr_0.snap new file mode 100644 index 000000000..bfdeef294 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__call_expr_0.snap @@ -0,0 +1,40 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"func0()\"####)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "func0", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, + }, + args: [], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__call_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__call_expr_1.snap new file mode 100644 index 000000000..430c626f7 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__call_expr_1.snap @@ -0,0 +1,56 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"func1(1)\"####)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "func1", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__call_expr_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__call_expr_2.snap new file mode 100644 index 000000000..756b3ec08 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__call_expr_2.snap @@ -0,0 +1,88 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"func2(x=2)\"####)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "func2", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, + }, + args: [], + keywords: [ + Node { + node: Keyword { + arg: Node { + node: Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + value: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ), + }, + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 9, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 10, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__call_expr_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__call_expr_3.snap new file mode 100644 index 000000000..61d13cb95 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__call_expr_3.snap @@ -0,0 +1,104 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"func3(1,x=2)\"####)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "func3", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + keywords: [ + Node { + node: Keyword { + arg: Node { + node: Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + value: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + ), + }, + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 11, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_expr_0.snap new file mode 100644 index 000000000..03428468c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_expr_0.snap @@ -0,0 +1,136 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"{\n \"name\" = {\n \"name\": \"alice\"\n },\n \"gender\" = \"female\"\n}\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"name\"", + value: "name", + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 10, + }, + ), + value: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"name\"", + value: "name", + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 14, + }, + ), + value: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"alice\"", + value: "alice", + }, + ), + filename: "", + line: 3, + column: 16, + end_line: 3, + end_column: 23, + }, + operation: Union, + }, + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 23, + }, + ], + }, + ), + filename: "", + line: 2, + column: 13, + end_line: 4, + end_column: 5, + }, + operation: Override, + }, + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 5, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"gender\"", + value: "gender", + }, + ), + filename: "", + line: 5, + column: 4, + end_line: 5, + end_column: 12, + }, + ), + value: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"female\"", + value: "female", + }, + ), + filename: "", + line: 5, + column: 15, + end_line: 5, + end_column: 23, + }, + operation: Override, + }, + filename: "", + line: 5, + column: 4, + end_line: 5, + end_column: 23, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 6, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_expr_1.snap new file mode 100644 index 000000000..14cdb579b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_expr_1.snap @@ -0,0 +1,136 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"{\n \"name\" = {\n \"name\": \"alice\"\n }\n \"gender\" = \"female\",\n}\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"name\"", + value: "name", + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 10, + }, + ), + value: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"name\"", + value: "name", + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 14, + }, + ), + value: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"alice\"", + value: "alice", + }, + ), + filename: "", + line: 3, + column: 16, + end_line: 3, + end_column: 23, + }, + operation: Union, + }, + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 23, + }, + ], + }, + ), + filename: "", + line: 2, + column: 13, + end_line: 4, + end_column: 5, + }, + operation: Override, + }, + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 5, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"gender\"", + value: "gender", + }, + ), + filename: "", + line: 5, + column: 4, + end_line: 5, + end_column: 12, + }, + ), + value: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"female\"", + value: "female", + }, + ), + filename: "", + line: 5, + column: 15, + end_line: 5, + end_column: 23, + }, + operation: Override, + }, + filename: "", + line: 5, + column: 4, + end_line: 5, + end_column: 23, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 6, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_expr_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_expr_2.snap new file mode 100644 index 000000000..7f99e78a6 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_expr_2.snap @@ -0,0 +1,136 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"{\n \"name\" = {\n \"name\": \"alice\",\n }\n \"gender\" = \"female\"\n}\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"name\"", + value: "name", + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 10, + }, + ), + value: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"name\"", + value: "name", + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 14, + }, + ), + value: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"alice\"", + value: "alice", + }, + ), + filename: "", + line: 3, + column: 16, + end_line: 3, + end_column: 23, + }, + operation: Union, + }, + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 23, + }, + ], + }, + ), + filename: "", + line: 2, + column: 13, + end_line: 4, + end_column: 5, + }, + operation: Override, + }, + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 5, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"gender\"", + value: "gender", + }, + ), + filename: "", + line: 5, + column: 4, + end_line: 5, + end_column: 12, + }, + ), + value: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"female\"", + value: "female", + }, + ), + filename: "", + line: 5, + column: 15, + end_line: 5, + end_column: 23, + }, + operation: Override, + }, + filename: "", + line: 5, + column: 4, + end_line: 5, + end_column: 23, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 6, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_if_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_if_expr_0.snap new file mode 100644 index 000000000..544a74c38 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_if_expr_0.snap @@ -0,0 +1,104 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"{\n if True:\n a = 1\n}\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: None, + value: Node { + node: ConfigIfEntry( + ConfigIfEntryExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 11, + }, + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 3, + column: 12, + end_line: 3, + end_column: 13, + }, + operation: Override, + }, + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 13, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 0, + }, + operation: Union, + }, + filename: "", + line: 2, + column: 4, + end_line: 4, + end_column: 0, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_if_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_if_expr_1.snap new file mode 100644 index 000000000..5571a0b3a --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_if_expr_1.snap @@ -0,0 +1,168 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"{\n if True:\n a = 1\n else:\n a = 2\n}\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: None, + value: Node { + node: ConfigIfEntry( + ConfigIfEntryExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 11, + }, + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 3, + column: 12, + end_line: 3, + end_column: 13, + }, + operation: Override, + }, + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 13, + }, + ], + orelse: Some( + Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 5, + column: 8, + end_line: 5, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 5, + column: 8, + end_line: 5, + end_column: 9, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 5, + column: 12, + end_line: 5, + end_column: 13, + }, + operation: Override, + }, + filename: "", + line: 5, + column: 8, + end_line: 5, + end_column: 13, + }, + ], + }, + ), + filename: "", + line: 4, + column: 4, + end_line: 6, + end_column: 0, + }, + ), + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 6, + end_column: 0, + }, + operation: Union, + }, + filename: "", + line: 2, + column: 4, + end_line: 6, + end_column: 0, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 6, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_if_expr_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_if_expr_2.snap new file mode 100644 index 000000000..907ed11e1 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_if_expr_2.snap @@ -0,0 +1,287 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"{\n if True:\n a = 1\n elif x > 1:\n a = 2\n else:\n a = 3\n}\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: None, + value: Node { + node: ConfigIfEntry( + ConfigIfEntryExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 11, + }, + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 9, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 3, + column: 12, + end_line: 3, + end_column: 13, + }, + operation: Override, + }, + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 13, + }, + ], + orelse: Some( + Node { + node: ConfigIfEntry( + ConfigIfEntryExpr { + if_cond: Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 4, + column: 9, + end_line: 4, + end_column: 10, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 4, + column: 9, + end_line: 4, + end_column: 10, + }, + ops: [ + Gt, + ], + comparators: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 4, + column: 13, + end_line: 4, + end_column: 14, + }, + ], + }, + ), + filename: "", + line: 4, + column: 9, + end_line: 4, + end_column: 14, + }, + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 5, + column: 8, + end_line: 5, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 5, + column: 8, + end_line: 5, + end_column: 9, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 5, + column: 12, + end_line: 5, + end_column: 13, + }, + operation: Override, + }, + filename: "", + line: 5, + column: 8, + end_line: 5, + end_column: 13, + }, + ], + orelse: Some( + Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 7, + column: 8, + end_line: 7, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 7, + column: 8, + end_line: 7, + end_column: 9, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 7, + column: 12, + end_line: 7, + end_column: 13, + }, + operation: Override, + }, + filename: "", + line: 7, + column: 8, + end_line: 7, + end_column: 13, + }, + ], + }, + ), + filename: "", + line: 6, + column: 4, + end_line: 8, + end_column: 0, + }, + ), + }, + ), + filename: "", + line: 4, + column: 4, + end_line: 6, + end_column: 4, + }, + ), + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 8, + end_column: 0, + }, + operation: Union, + }, + filename: "", + line: 2, + column: 4, + end_line: 8, + end_column: 0, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 8, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_if_expr_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_if_expr_3.snap new file mode 100644 index 000000000..c962ef050 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__config_if_expr_3.snap @@ -0,0 +1,141 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"{\n if True:\n if False:\n a = 1\n}\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: None, + value: Node { + node: ConfigIfEntry( + ConfigIfEntryExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 11, + }, + items: [ + Node { + node: ConfigEntry { + key: None, + value: Node { + node: ConfigIfEntry( + ConfigIfEntryExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: False, + }, + ), + filename: "", + line: 3, + column: 11, + end_line: 3, + end_column: 16, + }, + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 4, + column: 12, + end_line: 4, + end_column: 13, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 4, + column: 12, + end_line: 4, + end_column: 13, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 4, + column: 16, + end_line: 4, + end_column: 17, + }, + operation: Override, + }, + filename: "", + line: 4, + column: 12, + end_line: 4, + end_column: 17, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 5, + end_column: 0, + }, + operation: Override, + }, + filename: "", + line: 3, + column: 8, + end_line: 5, + end_column: 0, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 5, + end_column: 0, + }, + operation: Union, + }, + filename: "", + line: 2, + column: 4, + end_line: 5, + end_column: 0, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 5, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__dict_comp_expr.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__dict_comp_expr.snap new file mode 100644 index 000000000..6e084d243 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__dict_comp_expr.snap @@ -0,0 +1,262 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"{k: v + 1 for k, v in {k1 = 1, k2 = 2}}\"####)" +--- +Node { + node: DictComp( + DictComp { + entry: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "k", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ), + value: Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "v", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 9, + }, + operation: Union, + }, + generators: [ + Node { + node: CompClause { + targets: [ + Node { + node: Identifier { + names: [ + Node { + node: "k", + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 15, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 15, + }, + Node { + node: Identifier { + names: [ + Node { + node: "v", + filename: "", + line: 1, + column: 17, + end_line: 1, + end_column: 18, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 17, + end_line: 1, + end_column: 18, + }, + ], + iter: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "k1", + filename: "", + line: 1, + column: 23, + end_line: 1, + end_column: 25, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 23, + end_line: 1, + end_column: 25, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 28, + end_line: 1, + end_column: 29, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 23, + end_line: 1, + end_column: 29, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "k2", + filename: "", + line: 1, + column: 31, + end_line: 1, + end_column: 33, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 31, + end_line: 1, + end_column: 33, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 36, + end_line: 1, + end_column: 37, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 31, + end_line: 1, + end_column: 37, + }, + ], + }, + ), + filename: "", + line: 1, + column: 22, + end_line: 1, + end_column: 38, + }, + ifs: [], + }, + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 38, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 39, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__dict_expr.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__dict_expr.snap new file mode 100644 index 000000000..9b87379a8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__dict_expr.snap @@ -0,0 +1,133 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"{k0=v0, k1=v1}\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "k0", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 3, + }, + ), + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "v0", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 6, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 6, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "k1", + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 10, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 10, + }, + ), + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "v1", + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 13, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 13, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 13, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 14, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_brace_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_brace_0.snap new file mode 100644 index 000000000..9e964143e --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_brace_0.snap @@ -0,0 +1,67 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"{a=2}\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 4, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_brace_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_brace_1.snap new file mode 100644 index 000000000..6a1000889 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_brace_1.snap @@ -0,0 +1,67 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"{a=2}}\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 4, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_0.snap new file mode 100644 index 000000000..949479f39 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_0.snap @@ -0,0 +1,48 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"[2,3]\"####)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_1.snap new file mode 100644 index 000000000..caddda9c2 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_1.snap @@ -0,0 +1,62 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"[[2,3]\"####)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 6, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_2.snap new file mode 100644 index 000000000..46e61e101 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_2.snap @@ -0,0 +1,48 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"[2,3]]\"####)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_3.snap new file mode 100644 index 000000000..89c0437cd --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_3.snap @@ -0,0 +1,48 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"[2,3\"####)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_4.snap new file mode 100644 index 000000000..4c784fdd3 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_4.snap @@ -0,0 +1,17 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"[\"####)" +--- +Node { + node: List( + ListExpr { + elts: [], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_5.snap new file mode 100644 index 000000000..2d0a84291 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_5.snap @@ -0,0 +1,48 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"[\n 1\n 2,\n]\n \"####)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 3, + column: 4, + end_line: 3, + end_column: 5, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_6.snap new file mode 100644 index 000000000..831881606 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_6.snap @@ -0,0 +1,48 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"[\n 1,2,\n]\n \"####)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 2, + column: 6, + end_line: 2, + end_column: 7, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 3, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_7.snap new file mode 100644 index 000000000..eccdc13f8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_bracket_7.snap @@ -0,0 +1,48 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"[\n 1,2,\n\n \"####)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 2, + column: 6, + end_line: 2, + end_column: 7, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 4, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_0.snap new file mode 100644 index 000000000..7e3de7480 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_0.snap @@ -0,0 +1,78 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"({a=2}\"####)" +--- +Node { + node: Paren( + ParenExpr { + expr: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 5, + }, + ], + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_1.snap new file mode 100644 index 000000000..250a068cb --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_1.snap @@ -0,0 +1,89 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"({a=(2}\"####)" +--- +Node { + node: Paren( + ParenExpr { + expr: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + value: Node { + node: Paren( + ParenExpr { + expr: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 7, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_2.snap new file mode 100644 index 000000000..89090ca87 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_2.snap @@ -0,0 +1,81 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"{a=[2]\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ), + value: Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 6, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_3.snap new file mode 100644 index 000000000..bcab31ee9 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_3.snap @@ -0,0 +1,81 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"[{a=2}\"####)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 5, + }, + ], + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 6, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_4.snap new file mode 100644 index 000000000..4a0d0323d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_4.snap @@ -0,0 +1,92 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"({a=[2}\"####)" +--- +Node { + node: Paren( + ParenExpr { + expr: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + value: Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 7, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_5.snap new file mode 100644 index 000000000..76857c556 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_5.snap @@ -0,0 +1,16 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"{\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_6.snap new file mode 100644 index 000000000..8c60289da --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_6.snap @@ -0,0 +1,67 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"{\n a = 1\n}\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 2, + column: 8, + end_line: 2, + end_column: 9, + }, + operation: Override, + }, + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 9, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 3, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_7.snap new file mode 100644 index 000000000..b2f3085d0 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_delim_7.snap @@ -0,0 +1,99 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"{\n a = 1\n\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + ), + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 2, + column: 8, + end_line: 2, + end_column: 9, + }, + operation: Override, + }, + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 9, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 2, + column: 10, + end_line: 2, + end_column: 10, + }, + ), + value: Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 2, + column: 10, + end_line: 2, + end_column: 10, + }, + operation: Override, + }, + filename: "", + line: 2, + column: 10, + end_line: 2, + end_column: 10, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 10, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_paren_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_paren_0.snap new file mode 100644 index 000000000..095a95bc3 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_paren_0.snap @@ -0,0 +1,57 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"(2+3)\"####)" +--- +Node { + node: Paren( + ParenExpr { + expr: Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 4, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_paren_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_paren_1.snap new file mode 100644 index 000000000..772add5b5 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_paren_1.snap @@ -0,0 +1,68 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"((2+3)\"####)" +--- +Node { + node: Paren( + ParenExpr { + expr: Node { + node: Paren( + ParenExpr { + expr: Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 5, + }, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_paren_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_paren_2.snap new file mode 100644 index 000000000..a8a52a2ea --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__expr_with_paren_2.snap @@ -0,0 +1,57 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"(2+3))\"####)" +--- +Node { + node: Paren( + ParenExpr { + expr: Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 4, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__if_expr.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__if_expr.snap new file mode 100644 index 000000000..17ea6d8ef --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__if_expr.snap @@ -0,0 +1,68 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"1 if true else 2\"####)" +--- +Node { + node: If( + IfExpr { + body: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + cond: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "true", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 9, + }, + orelse: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 16, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 16, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__lambda_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__lambda_expr_0.snap new file mode 100644 index 000000000..d67549c09 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__lambda_expr_0.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"lambda {}\"####)" +--- +Node { + node: Lambda( + LambdaExpr { + args: None, + body: [], + return_ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__lambda_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__lambda_expr_1.snap new file mode 100644 index 000000000..fd1d0a89d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__lambda_expr_1.snap @@ -0,0 +1,57 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"lambda x {}\"####)" +--- +Node { + node: Lambda( + LambdaExpr { + args: Some( + Node { + node: Arguments { + args: [ + Node { + node: Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + defaults: [ + None, + ], + ty_list: [ + None, + ], + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ), + body: [], + return_ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__lambda_expr_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__lambda_expr_2.snap new file mode 100644 index 000000000..1ed390789 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__lambda_expr_2.snap @@ -0,0 +1,116 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"lambda x: int -> int {x}\"####)" +--- +Node { + node: Lambda( + LambdaExpr { + args: Some( + Node { + node: Arguments { + args: [ + Node { + node: Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + defaults: [ + None, + ], + ty_list: [ + Some( + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 13, + }, + ), + ], + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 13, + }, + ), + body: [ + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 22, + end_line: 1, + end_column: 23, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 22, + end_line: 1, + end_column: 23, + }, + ], + }, + ), + filename: "", + line: 1, + column: 22, + end_line: 1, + end_column: 23, + }, + ], + return_ty: Some( + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 17, + end_line: 1, + end_column: 20, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 24, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__lambda_expr_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__lambda_expr_3.snap new file mode 100644 index 000000000..422509476 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__lambda_expr_3.snap @@ -0,0 +1,178 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"lambda {\n if True:\n _a = 1\n else:\n _a = 2\n _a\n}\"####)" +--- +Node { + node: Lambda( + LambdaExpr { + args: None, + body: [ + Node { + node: If( + IfStmt { + body: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "_a", + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 10, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 10, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 3, + column: 13, + end_line: 3, + end_column: 14, + }, + ty: None, + }, + ), + filename: "", + line: 3, + column: 8, + end_line: 3, + end_column: 14, + }, + ], + cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 2, + column: 7, + end_line: 2, + end_column: 11, + }, + orelse: [ + Node { + node: Assign( + AssignStmt { + targets: [ + Node { + node: Target { + name: Node { + node: "_a", + filename: "", + line: 5, + column: 8, + end_line: 5, + end_column: 10, + }, + paths: [], + pkgpath: "", + }, + filename: "", + line: 5, + column: 8, + end_line: 5, + end_column: 10, + }, + ], + value: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 5, + column: 13, + end_line: 5, + end_column: 14, + }, + ty: None, + }, + ), + filename: "", + line: 5, + column: 8, + end_line: 5, + end_column: 14, + }, + ], + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 6, + end_column: 4, + }, + Node { + node: Expr( + ExprStmt { + exprs: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "_a", + filename: "", + line: 6, + column: 4, + end_line: 6, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 6, + column: 4, + end_line: 6, + end_column: 6, + }, + ], + }, + ), + filename: "", + line: 6, + column: 4, + end_line: 6, + end_column: 6, + }, + ], + return_ty: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 7, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__line_continue.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__line_continue.snap new file mode 100644 index 000000000..9caab1494 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__line_continue.snap @@ -0,0 +1,46 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"1 + \\\n2\n\"####)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 2, + column: 0, + end_line: 2, + end_column: 1, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 2, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__list_comp_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__list_comp_expr_0.snap new file mode 100644 index 000000000..db8286d39 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__list_comp_expr_0.snap @@ -0,0 +1,159 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"[x ** 2 for x in [1, 2, 3]]\"####)" +--- +Node { + node: ListComp( + ListComp { + elt: Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + op: Pow, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 7, + }, + generators: [ + Node { + node: CompClause { + targets: [ + Node { + node: Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 13, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 13, + }, + ], + iter: Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 18, + end_line: 1, + end_column: 19, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 22, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 24, + end_line: 1, + end_column: 25, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 17, + end_line: 1, + end_column: 26, + }, + ifs: [], + }, + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 26, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 27, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__list_comp_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__list_comp_expr_1.snap new file mode 100644 index 000000000..a0ae1d153 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__list_comp_expr_1.snap @@ -0,0 +1,187 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"[i for i in [1, 2, 3] if i > 2]\"####)" +--- +Node { + node: ListComp( + ListComp { + elt: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + generators: [ + Node { + node: CompClause { + targets: [ + Node { + node: Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + iter: Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 17, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 19, + end_line: 1, + end_column: 20, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 21, + }, + ifs: [ + Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 26, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 26, + }, + ops: [ + Gt, + ], + comparators: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 29, + end_line: 1, + end_column: 30, + }, + ], + }, + ), + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 30, + }, + ], + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 30, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 31, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__list_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__list_expr_0.snap new file mode 100644 index 000000000..d0eee799d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__list_expr_0.snap @@ -0,0 +1,63 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"[1, 2, 3]\"####)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__list_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__list_expr_1.snap new file mode 100644 index 000000000..787147d02 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__list_expr_1.snap @@ -0,0 +1,89 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"[1, if True: 2, 3]\"####)" +--- +Node { + node: List( + ListExpr { + elts: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + Node { + node: ListIfItem( + ListIfItemExpr { + if_cond: Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 11, + }, + exprs: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + ], + orelse: None, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 14, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 16, + end_line: 1, + end_column: 17, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 18, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_0.snap new file mode 100644 index 000000000..de781cc17 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_0.snap @@ -0,0 +1,74 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"0 < a < 100\"####)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ops: [ + Lt, + Lt, + ], + comparators: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 100, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 11, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_1.snap new file mode 100644 index 000000000..fece4d1d2 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_1.snap @@ -0,0 +1,109 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"0 < a < 100 + a\"####)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ops: [ + Lt, + Lt, + ], + comparators: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 100, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 11, + }, + op: Add, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 15, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 15, + }, + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 15, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 15, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_2.snap new file mode 100644 index 000000000..832f9f036 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_2.snap @@ -0,0 +1,74 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"100 > a > 0\"####)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 100, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + ops: [ + Gt, + Gt, + ], + comparators: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_3.snap new file mode 100644 index 000000000..4ca4785f0 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_3.snap @@ -0,0 +1,109 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"100 + a > a > 0\"####)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 100, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + op: Add, + right: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, + }, + ops: [ + Gt, + Gt, + ], + comparators: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 15, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 15, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_4.snap new file mode 100644 index 000000000..b829a992d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_4.snap @@ -0,0 +1,66 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a is b\"####)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ops: [ + Is, + ], + comparators: [ + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_5.snap new file mode 100644 index 000000000..a7bbb6a21 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_5.snap @@ -0,0 +1,55 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a is not True\"####)" +--- +Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ops: [ + IsNot, + ], + comparators: [ + Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 13, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 13, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_6.snap new file mode 100644 index 000000000..8000e0a03 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__logic_expr_6.snap @@ -0,0 +1,157 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"not False or a > 0 and b is True\"####)" +--- +Node { + node: Binary( + BinaryExpr { + left: Node { + node: Unary( + UnaryExpr { + op: Not, + operand: Node { + node: NameConstantLit( + NameConstantLit { + value: False, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 9, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, + }, + op: Or, + right: Node { + node: Binary( + BinaryExpr { + left: Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + ops: [ + Gt, + ], + comparators: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 17, + end_line: 1, + end_column: 18, + }, + ], + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 32, + }, + op: And, + right: Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 23, + end_line: 1, + end_column: 24, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 23, + end_line: 1, + end_column: 24, + }, + ops: [ + Is, + ], + comparators: [ + Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 28, + end_line: 1, + end_column: 32, + }, + ], + }, + ), + filename: "", + line: 1, + column: 23, + end_line: 1, + end_column: 32, + }, + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 32, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 32, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__named_literal_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__named_literal_expr_0.snap new file mode 100644 index 000000000..2db224a16 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__named_literal_expr_0.snap @@ -0,0 +1,16 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(\"Undefined\")" +--- +Node { + node: NameConstantLit( + NameConstantLit { + value: Undefined, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__named_literal_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__named_literal_expr_1.snap new file mode 100644 index 000000000..dcab180e9 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__named_literal_expr_1.snap @@ -0,0 +1,16 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(\"None\")" +--- +Node { + node: NameConstantLit( + NameConstantLit { + value: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__named_literal_expr_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__named_literal_expr_2.snap new file mode 100644 index 000000000..798160c1b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__named_literal_expr_2.snap @@ -0,0 +1,16 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(\"True\")" +--- +Node { + node: NameConstantLit( + NameConstantLit { + value: True, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__named_literal_expr_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__named_literal_expr_3.snap new file mode 100644 index 000000000..3ae58fe51 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__named_literal_expr_3.snap @@ -0,0 +1,16 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(\"False\")" +--- +Node { + node: NameConstantLit( + NameConstantLit { + value: False, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__nonstring_literal_expr.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__nonstring_literal_expr.snap new file mode 100644 index 000000000..eb6e72348 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__nonstring_literal_expr.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"1234\"####)" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1234, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__number_bin_suffix_expr.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__number_bin_suffix_expr.snap new file mode 100644 index 000000000..0b93f3557 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__number_bin_suffix_expr.snap @@ -0,0 +1,21 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"1234Ki\"####)" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: Some( + Ki, + ), + value: Int( + 1234, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__parse_joined_string_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__parse_joined_string_0.snap new file mode 100644 index 000000000..fdae023f2 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__parse_joined_string_0.snap @@ -0,0 +1,74 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"'${123+200}'\"####)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: false, + values: [ + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Binary( + BinaryExpr { + left: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 123, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 6, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 200, + ), + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 10, + }, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 10, + }, + format_spec: None, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 10, + }, + ], + raw_value: "'${123+200}'", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__parse_joined_string_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__parse_joined_string_1.snap new file mode 100644 index 000000000..24a890162 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__parse_joined_string_1.snap @@ -0,0 +1,110 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"'abc${a+1}cde'\"####)" +--- +Node { + node: JoinedString( + JoinedString { + is_long_string: false, + values: [ + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "abc", + value: "abc", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + Node { + node: FormattedValue( + FormattedValue { + is_long_string: false, + value: Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 9, + }, + format_spec: None, + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 9, + }, + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "cde", + value: "cde", + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 1, + }, + ], + raw_value: "'abc${a+1}cde'", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 14, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_0.snap new file mode 100644 index 000000000..2863ce7ea --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_0.snap @@ -0,0 +1,43 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a.b.c\"####)" +--- +Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + Node { + node: "b", + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + Node { + node: "c", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_1.snap new file mode 100644 index 000000000..b5261da00 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_1.snap @@ -0,0 +1,81 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"'{}'.format(1)\"####)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Selector( + SelectorExpr { + value: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'{}'", + value: "{}", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "format", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 11, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 11, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 13, + }, + ], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 14, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_2.snap new file mode 100644 index 000000000..23b737374 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_2.snap @@ -0,0 +1,103 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"str(1).isdigit()\"####)" +--- +Node { + node: Call( + CallExpr { + func: Node { + node: Selector( + SelectorExpr { + value: Node { + node: Call( + CallExpr { + func: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "str", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "isdigit", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 14, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 14, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 14, + }, + args: [], + keywords: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 16, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_3.snap new file mode 100644 index 000000000..55727bb88 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_3.snap @@ -0,0 +1,50 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"{}.a\"####)" +--- +Node { + node: Selector( + SelectorExpr { + value: Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_4.snap new file mode 100644 index 000000000..791a4db9d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_4.snap @@ -0,0 +1,84 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"{}..a\"####)" +--- +Node { + node: Selector( + SelectorExpr { + value: Node { + node: Selector( + SelectorExpr { + value: Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_5.snap new file mode 100644 index 000000000..22a34314d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_5.snap @@ -0,0 +1,16 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"{}...a\"####)" +--- +Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_6.snap new file mode 100644 index 000000000..f134ab03b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_6.snap @@ -0,0 +1,85 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"[]..a\"####)" +--- +Node { + node: Selector( + SelectorExpr { + value: Node { + node: Selector( + SelectorExpr { + value: Node { + node: List( + ListExpr { + elts: [], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "", + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 3, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + attr: Node { + node: Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_7.snap new file mode 100644 index 000000000..7f31b4db7 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__primary_expr_7.snap @@ -0,0 +1,44 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"{}[[]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, + }, + index: Some( + Node { + node: Missing( + MissingExpr, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 5, + }, + ), + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_0.snap new file mode 100644 index 000000000..e651ddd72 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_0.snap @@ -0,0 +1,118 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"all x in collection {x > 0}\"####)" +--- +Node { + node: Quant( + QuantExpr { + target: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "collection", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 19, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 19, + }, + variables: [ + Node { + node: Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + op: All, + test: Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 22, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 22, + }, + ops: [ + Gt, + ], + comparators: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 26, + }, + ], + }, + ), + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 26, + }, + if_cond: None, + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 27, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_1.snap new file mode 100644 index 000000000..7931f2766 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_1.snap @@ -0,0 +1,118 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"any y in collection {y < 0}\"####)" +--- +Node { + node: Quant( + QuantExpr { + target: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "collection", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 19, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 19, + }, + variables: [ + Node { + node: Identifier { + names: [ + Node { + node: "y", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + op: Any, + test: Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "y", + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 22, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 22, + }, + ops: [ + Lt, + ], + comparators: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 26, + }, + ], + }, + ), + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 26, + }, + if_cond: None, + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 27, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_2.snap new file mode 100644 index 000000000..afc1eeea1 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_2.snap @@ -0,0 +1,114 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"map x in collection {x + 1}\"####)" +--- +Node { + node: Quant( + QuantExpr { + target: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "collection", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 19, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 19, + }, + variables: [ + Node { + node: Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + op: Map, + test: Node { + node: Binary( + BinaryExpr { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 22, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 22, + }, + op: Add, + right: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 26, + }, + }, + ), + filename: "", + line: 1, + column: 21, + end_line: 1, + end_column: 26, + }, + if_cond: None, + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 27, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_3.snap new file mode 100644 index 000000000..0aba737f6 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_3.snap @@ -0,0 +1,118 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"filter x in collection {x > 1}\"####)" +--- +Node { + node: Quant( + QuantExpr { + target: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "collection", + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 22, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 22, + }, + variables: [ + Node { + node: Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + op: Filter, + test: Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 24, + end_line: 1, + end_column: 25, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 24, + end_line: 1, + end_column: 25, + }, + ops: [ + Gt, + ], + comparators: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 28, + end_line: 1, + end_column: 29, + }, + ], + }, + ), + filename: "", + line: 1, + column: 24, + end_line: 1, + end_column: 29, + }, + if_cond: None, + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 30, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_4.snap new file mode 100644 index 000000000..0aba737f6 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_4.snap @@ -0,0 +1,118 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"filter x in collection {x > 1}\"####)" +--- +Node { + node: Quant( + QuantExpr { + target: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "collection", + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 22, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 22, + }, + variables: [ + Node { + node: Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + op: Filter, + test: Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "x", + filename: "", + line: 1, + column: 24, + end_line: 1, + end_column: 25, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 24, + end_line: 1, + end_column: 25, + }, + ops: [ + Gt, + ], + comparators: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 28, + end_line: 1, + end_column: 29, + }, + ], + }, + ), + filename: "", + line: 1, + column: 24, + end_line: 1, + end_column: 29, + }, + if_cond: None, + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 30, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_5.snap new file mode 100644 index 000000000..3e5a702f8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_5.snap @@ -0,0 +1,210 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"map i, e in [{k1 = \"v1\", k2 = \"v2\"}] { e }\"####)" +--- +Node { + node: Quant( + QuantExpr { + target: Node { + node: List( + ListExpr { + elts: [ + Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "k1", + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 16, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 16, + }, + ), + value: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"v1\"", + value: "v1", + }, + ), + filename: "", + line: 1, + column: 19, + end_line: 1, + end_column: 23, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 23, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "k2", + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 27, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 27, + }, + ), + value: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"v2\"", + value: "v2", + }, + ), + filename: "", + line: 1, + column: 30, + end_line: 1, + end_column: 34, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 34, + }, + ], + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 35, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 36, + }, + variables: [ + Node { + node: Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + Node { + node: Identifier { + names: [ + Node { + node: "e", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + op: Map, + test: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "e", + filename: "", + line: 1, + column: 39, + end_line: 1, + end_column: 40, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 39, + end_line: 1, + end_column: 40, + }, + if_cond: None, + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 42, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_6.snap new file mode 100644 index 000000000..2478b062c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__quant_expr_6.snap @@ -0,0 +1,265 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests ::\nparsing_expr_string(r####\"map i, e in [{k1 = \"v1\", k2 = \"v2\"}] { e if i > 0 }\"####)" +--- +Node { + node: Quant( + QuantExpr { + target: Node { + node: List( + ListExpr { + elts: [ + Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "k1", + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 16, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 16, + }, + ), + value: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"v1\"", + value: "v1", + }, + ), + filename: "", + line: 1, + column: 19, + end_line: 1, + end_column: 23, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 23, + }, + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "k2", + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 27, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 27, + }, + ), + value: Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"v2\"", + value: "v2", + }, + ), + filename: "", + line: 1, + column: 30, + end_line: 1, + end_column: 34, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 25, + end_line: 1, + end_column: 34, + }, + ], + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 35, + }, + ], + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 36, + }, + variables: [ + Node { + node: Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + Node { + node: Identifier { + names: [ + Node { + node: "e", + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 8, + }, + ], + op: Map, + test: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "e", + filename: "", + line: 1, + column: 39, + end_line: 1, + end_column: 40, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 39, + end_line: 1, + end_column: 40, + }, + if_cond: Some( + Node { + node: Compare( + Compare { + left: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "i", + filename: "", + line: 1, + column: 44, + end_line: 1, + end_column: 45, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 44, + end_line: 1, + end_column: 45, + }, + ops: [ + Gt, + ], + comparators: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 48, + end_line: 1, + end_column: 49, + }, + ], + }, + ), + filename: "", + line: 1, + column: 44, + end_line: 1, + end_column: 49, + }, + ), + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 51, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_0.snap new file mode 100644 index 000000000..a95a63c1e --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_0.snap @@ -0,0 +1,50 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"Schema {}\"####)" +--- +Node { + node: Schema( + SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "Schema", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + args: [], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [], + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 9, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 9, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_1.snap new file mode 100644 index 000000000..4f86eeb3e --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_1.snap @@ -0,0 +1,109 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"Schema {k=v}\"####)" +--- +Node { + node: Schema( + SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "Schema", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + args: [], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "k", + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + ), + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "v", + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 11, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 11, + }, + ], + }, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 12, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 12, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_2.snap new file mode 100644 index 000000000..710fd56b1 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_2.snap @@ -0,0 +1,109 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"Schema () {k=v}\"####)" +--- +Node { + node: Schema( + SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "Schema", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + args: [], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "k", + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 12, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 12, + }, + ), + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "v", + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 13, + end_line: 1, + end_column: 14, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 14, + }, + ], + }, + ), + filename: "", + line: 1, + column: 10, + end_line: 1, + end_column: 15, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 15, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_3.snap new file mode 100644 index 000000000..b2f7353f9 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_3.snap @@ -0,0 +1,140 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"Schema (1, 2) {k=v}\"####)" +--- +Node { + node: Schema( + SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "Schema", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 12, + }, + ], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "k", + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 16, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 16, + }, + ), + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "v", + filename: "", + line: 1, + column: 17, + end_line: 1, + end_column: 18, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 17, + end_line: 1, + end_column: 18, + }, + operation: Override, + }, + filename: "", + line: 1, + column: 15, + end_line: 1, + end_column: 18, + }, + ], + }, + ), + filename: "", + line: 1, + column: 14, + end_line: 1, + end_column: 19, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 19, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_4.snap new file mode 100644 index 000000000..32de4aeaf --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__schema_expr_4.snap @@ -0,0 +1,140 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"Schema (1, 2) {\n k=v\n}\"####)" +--- +Node { + node: Schema( + SchemaExpr { + name: Node { + node: Identifier { + names: [ + Node { + node: "Schema", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + args: [ + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 8, + end_line: 1, + end_column: 9, + }, + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 11, + end_line: 1, + end_column: 12, + }, + ], + kwargs: [], + config: Node { + node: Config( + ConfigExpr { + items: [ + Node { + node: ConfigEntry { + key: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "k", + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 5, + }, + ), + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "v", + filename: "", + line: 2, + column: 6, + end_line: 2, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 2, + column: 6, + end_line: 2, + end_column: 7, + }, + operation: Override, + }, + filename: "", + line: 2, + column: 4, + end_line: 2, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 1, + column: 14, + end_line: 3, + end_column: 1, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 3, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__smoke_test_parsing_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__smoke_test_parsing_expr_0.snap new file mode 100644 index 000000000..0201ef9bb --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__smoke_test_parsing_expr_0.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(\"1\\n\")" +--- +Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__smoke_test_parsing_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__smoke_test_parsing_expr_1.snap new file mode 100644 index 000000000..2fb32bd66 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__smoke_test_parsing_expr_1.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(\"\\\"1\\\"\\n\")" +--- +Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"1\"", + value: "1", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__string_literal_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__string_literal_expr_0.snap new file mode 100644 index 000000000..545a73f1f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__string_literal_expr_0.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"'1234'\"####)" +--- +Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "'1234'", + value: "1234", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__string_literal_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__string_literal_expr_1.snap new file mode 100644 index 000000000..da756257e --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__string_literal_expr_1.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"\"1234\"\"####)" +--- +Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"1234\"", + value: "1234", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__string_literal_expr_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__string_literal_expr_2.snap new file mode 100644 index 000000000..fe0a7ac50 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__string_literal_expr_2.snap @@ -0,0 +1,18 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"\"1234\\n\"\"####)" +--- +Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"1234\\n\"", + value: "1234\n", + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_0.snap new file mode 100644 index 000000000..b7d84eb0a --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_0.snap @@ -0,0 +1,60 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a[0]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_1.snap new file mode 100644 index 000000000..44e2b4d98 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_1.snap @@ -0,0 +1,59 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"b[\"k\"]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "b", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: Some( + Node { + node: StringLit( + StringLit { + is_long_string: false, + raw_value: "\"k\"", + value: "k", + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 5, + }, + ), + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_10.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_10.snap new file mode 100644 index 000000000..9cd790239 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_10.snap @@ -0,0 +1,72 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a[::-1]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: None, + lower: None, + upper: None, + step: Some( + Node { + node: Unary( + UnaryExpr { + op: USub, + operand: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 6, + }, + ), + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_11.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_11.snap new file mode 100644 index 000000000..b584c8457 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_11.snap @@ -0,0 +1,76 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a[1::2]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: None, + lower: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + upper: None, + step: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ), + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_12.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_12.snap new file mode 100644 index 000000000..1cad355e3 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_12.snap @@ -0,0 +1,76 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a[:2:1]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: None, + lower: None, + upper: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ), + step: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + ), + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_13.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_13.snap new file mode 100644 index 000000000..12a9889c4 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_13.snap @@ -0,0 +1,76 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a[1:2:]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: None, + lower: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + upper: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 2, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_14.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_14.snap new file mode 100644 index 000000000..5554252be --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_14.snap @@ -0,0 +1,92 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a[1:3:1]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: None, + lower: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + upper: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 3, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + ), + step: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 7, + }, + ), + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_2.snap new file mode 100644 index 000000000..b1f39d92c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_2.snap @@ -0,0 +1,60 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"c?[1]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "c", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ), + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: true, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_3.snap new file mode 100644 index 000000000..89e777b5b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_3.snap @@ -0,0 +1,60 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a[1:]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: None, + lower: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_4.snap new file mode 100644 index 000000000..bcdae060c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_4.snap @@ -0,0 +1,72 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a[:-1]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: None, + lower: None, + upper: Some( + Node { + node: Unary( + UnaryExpr { + op: USub, + operand: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 5, + }, + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 5, + }, + ), + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_5.snap new file mode 100644 index 000000000..f50998de2 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_5.snap @@ -0,0 +1,84 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a[1:len]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: None, + lower: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + upper: Some( + Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "len", + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ), + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 8, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_6.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_6.snap new file mode 100644 index 000000000..207bc6208 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_6.snap @@ -0,0 +1,88 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a[0:-1]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: None, + lower: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + upper: Some( + Node { + node: Unary( + UnaryExpr { + op: USub, + operand: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 6, + }, + }, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 6, + }, + ), + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_7.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_7.snap new file mode 100644 index 000000000..0f0b0b88b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_7.snap @@ -0,0 +1,44 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a[::]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: None, + lower: None, + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_8.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_8.snap new file mode 100644 index 000000000..b08dd8f69 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_8.snap @@ -0,0 +1,60 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a[1::]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: None, + lower: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 3, + }, + ), + upper: None, + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_9.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_9.snap new file mode 100644 index 000000000..4cf7f6f91 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__subscript_expr_9.snap @@ -0,0 +1,60 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"a[:0:]\"####)" +--- +Node { + node: Subscript( + Subscript { + value: Node { + node: Identifier( + Identifier { + names: [ + Node { + node: "a", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 1, + }, + index: None, + lower: None, + upper: Some( + Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 0, + ), + }, + ), + filename: "", + line: 1, + column: 3, + end_line: 1, + end_column: 4, + }, + ), + step: None, + ctx: Load, + has_question: false, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__unary_expr.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__unary_expr.snap new file mode 100644 index 000000000..c6497a101 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__expr__unary_expr.snap @@ -0,0 +1,31 @@ +--- +source: crates/parser/src/tests/expr.rs +expression: "$crate :: tests :: parsing_expr_string(r####\"+1\"####)" +--- +Node { + node: Unary( + UnaryExpr { + op: UAdd, + operand: Node { + node: NumberLit( + NumberLit { + binary_suffix: None, + value: Int( + 1, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 2, + }, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_1.snap new file mode 100644 index 000000000..4f789770d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_1.snap @@ -0,0 +1,100 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/assert-01.k\")" +--- +{ + "filename": "assert-01.k", + "doc": null, + "body": [ + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "assert-01.k", + "line": 1, + "column": 7, + "end_line": 1, + "end_column": 8 + }, + "if_cond": null, + "msg": null + }, + "filename": "assert-01.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 8 + }, + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 2 + } + }, + "filename": "assert-01.k", + "line": 2, + "column": 7, + "end_line": 2, + "end_column": 8 + }, + "if_cond": null, + "msg": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"msg\"", + "value": "msg" + }, + "filename": "assert-01.k", + "line": 2, + "column": 10, + "end_line": 2, + "end_column": 15 + } + }, + "filename": "assert-01.k", + "line": 2, + "column": 0, + "end_line": 2, + "end_column": 15 + }, + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "NameConstantLit", + "value": "True" + }, + "filename": "assert-01.k", + "line": 3, + "column": 7, + "end_line": 3, + "end_column": 11 + }, + "if_cond": null, + "msg": null + }, + "filename": "assert-01.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 11 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_2.snap new file mode 100644 index 000000000..eb174893b --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_2.snap @@ -0,0 +1,198 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/assert-02.k\")" +--- +{ + "filename": "assert-02.k", + "doc": null, + "body": [ + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "NameConstantLit", + "value": "True" + }, + "filename": "assert-02.k", + "line": 1, + "column": 7, + "end_line": 1, + "end_column": 11 + }, + "if_cond": null, + "msg": null + }, + "filename": "assert-02.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 11 + }, + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "assert-02.k", + "line": 2, + "column": 7, + "end_line": 2, + "end_column": 8 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "assert-02.k", + "line": 2, + "column": 12, + "end_line": 2, + "end_column": 13 + } + ] + }, + "filename": "assert-02.k", + "line": 2, + "column": 7, + "end_line": 2, + "end_column": 13 + }, + "if_cond": null, + "msg": null + }, + "filename": "assert-02.k", + "line": 2, + "column": 0, + "end_line": 2, + "end_column": 13 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "_x", + "filename": "assert-02.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 2 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "assert-02.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 2 + } + ], + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"good case\"", + "value": "good case" + }, + "filename": "assert-02.k", + "line": 3, + "column": 5, + "end_line": 3, + "end_column": 16 + }, + "ty": null + }, + "filename": "assert-02.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 16 + }, + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "_x", + "filename": "assert-02.k", + "line": 4, + "column": 7, + "end_line": 4, + "end_column": 9 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "assert-02.k", + "line": 4, + "column": 7, + "end_line": 4, + "end_column": 9 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"good case\"", + "value": "good case" + }, + "filename": "assert-02.k", + "line": 4, + "column": 13, + "end_line": 4, + "end_column": 24 + } + ] + }, + "filename": "assert-02.k", + "line": 4, + "column": 7, + "end_line": 4, + "end_column": 24 + }, + "if_cond": null, + "msg": null + }, + "filename": "assert-02.k", + "line": 4, + "column": 0, + "end_line": 4, + "end_column": 24 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_3.snap new file mode 100644 index 000000000..352822412 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_3.snap @@ -0,0 +1,270 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/assert-03.k\")" +--- +{ + "filename": "assert-03.k", + "doc": null, + "body": [ + { + "node": { + "type": "If", + "body": [ + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "NameConstantLit", + "value": "True" + }, + "filename": "assert-03.k", + "line": 2, + "column": 11, + "end_line": 2, + "end_column": 15 + }, + "if_cond": null, + "msg": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"Error messgae\"", + "value": "Error messgae" + }, + "filename": "assert-03.k", + "line": 2, + "column": 17, + "end_line": 2, + "end_column": 32 + } + }, + "filename": "assert-03.k", + "line": 2, + "column": 4, + "end_line": 2, + "end_column": 32 + }, + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "assert-03.k", + "line": 3, + "column": 11, + "end_line": 3, + "end_column": 12 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "assert-03.k", + "line": 3, + "column": 16, + "end_line": 3, + "end_column": 17 + } + ] + }, + "filename": "assert-03.k", + "line": 3, + "column": 11, + "end_line": 3, + "end_column": 17 + }, + "if_cond": null, + "msg": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"\"", + "value": "" + }, + "filename": "assert-03.k", + "line": 3, + "column": 19, + "end_line": 3, + "end_column": 21 + } + }, + "filename": "assert-03.k", + "line": 3, + "column": 4, + "end_line": 3, + "end_column": 21 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "_x", + "filename": "assert-03.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 6 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "assert-03.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 6 + } + ], + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"good case\"", + "value": "good case" + }, + "filename": "assert-03.k", + "line": 4, + "column": 9, + "end_line": 4, + "end_column": 20 + }, + "ty": null + }, + "filename": "assert-03.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 20 + }, + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "_x", + "filename": "assert-03.k", + "line": 5, + "column": 11, + "end_line": 5, + "end_column": 13 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "assert-03.k", + "line": 5, + "column": 11, + "end_line": 5, + "end_column": 13 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"good case\"", + "value": "good case" + }, + "filename": "assert-03.k", + "line": 5, + "column": 17, + "end_line": 5, + "end_column": 28 + } + ] + }, + "filename": "assert-03.k", + "line": 5, + "column": 11, + "end_line": 5, + "end_column": 28 + }, + "if_cond": null, + "msg": null + }, + "filename": "assert-03.k", + "line": 5, + "column": 4, + "end_line": 5, + "end_column": 28 + } + ], + "cond": { + "node": { + "type": "NameConstantLit", + "value": "True" + }, + "filename": "assert-03.k", + "line": 1, + "column": 3, + "end_line": 1, + "end_column": 7 + }, + "orelse": [ + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "NameConstantLit", + "value": "False" + }, + "filename": "assert-03.k", + "line": 7, + "column": 11, + "end_line": 7, + "end_column": 16 + }, + "if_cond": null, + "msg": null + }, + "filename": "assert-03.k", + "line": 7, + "column": 4, + "end_line": 7, + "end_column": 16 + } + ] + }, + "filename": "assert-03.k", + "line": 1, + "column": 0, + "end_line": 8, + "end_column": 1 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_if_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_if_0.snap new file mode 100644 index 000000000..956e3ad06 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_if_0.snap @@ -0,0 +1,241 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/assert-if-0.k\")" +--- +{ + "filename": "assert-if-0.k", + "doc": null, + "body": [ + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "NameConstantLit", + "value": "True" + }, + "filename": "assert-if-0.k", + "line": 1, + "column": 7, + "end_line": 1, + "end_column": 11 + }, + "if_cond": null, + "msg": null + }, + "filename": "assert-if-0.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 11 + }, + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "assert-if-0.k", + "line": 2, + "column": 7, + "end_line": 2, + "end_column": 8 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "assert-if-0.k", + "line": 2, + "column": 12, + "end_line": 2, + "end_column": 13 + } + ] + }, + "filename": "assert-if-0.k", + "line": 2, + "column": 7, + "end_line": 2, + "end_column": 13 + }, + "if_cond": { + "node": { + "type": "NameConstantLit", + "value": "True" + }, + "filename": "assert-if-0.k", + "line": 2, + "column": 17, + "end_line": 2, + "end_column": 21 + }, + "msg": null + }, + "filename": "assert-if-0.k", + "line": 2, + "column": 0, + "end_line": 2, + "end_column": 21 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "_x", + "filename": "assert-if-0.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 2 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "assert-if-0.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 2 + } + ], + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"good case\"", + "value": "good case" + }, + "filename": "assert-if-0.k", + "line": 3, + "column": 5, + "end_line": 3, + "end_column": 16 + }, + "ty": null + }, + "filename": "assert-if-0.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 16 + }, + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "_x", + "filename": "assert-if-0.k", + "line": 4, + "column": 7, + "end_line": 4, + "end_column": 9 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "assert-if-0.k", + "line": 4, + "column": 7, + "end_line": 4, + "end_column": 9 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"good case\"", + "value": "good case" + }, + "filename": "assert-if-0.k", + "line": 4, + "column": 13, + "end_line": 4, + "end_column": 24 + } + ] + }, + "filename": "assert-if-0.k", + "line": 4, + "column": 7, + "end_line": 4, + "end_column": 24 + }, + "if_cond": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "_x", + "filename": "assert-if-0.k", + "line": 4, + "column": 28, + "end_line": 4, + "end_column": 30 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "assert-if-0.k", + "line": 4, + "column": 28, + "end_line": 4, + "end_column": 30 + }, + "msg": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"_x need to be 'good case'\"", + "value": "_x need to be 'good case'" + }, + "filename": "assert-if-0.k", + "line": 4, + "column": 32, + "end_line": 4, + "end_column": 59 + } + }, + "filename": "assert-if-0.k", + "line": 4, + "column": 0, + "end_line": 4, + "end_column": 59 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_if_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_if_1.snap new file mode 100644 index 000000000..2342954bc --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_if_1.snap @@ -0,0 +1,262 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/assert-if-1.k\")" +--- +{ + "filename": "assert-if-1.k", + "doc": null, + "body": [ + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "NameConstantLit", + "value": "True" + }, + "filename": "assert-if-1.k", + "line": 1, + "column": 7, + "end_line": 1, + "end_column": 11 + }, + "if_cond": { + "node": { + "type": "NameConstantLit", + "value": "False" + }, + "filename": "assert-if-1.k", + "line": 1, + "column": 15, + "end_line": 1, + "end_column": 20 + }, + "msg": null + }, + "filename": "assert-if-1.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 20 + }, + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "assert-if-1.k", + "line": 2, + "column": 7, + "end_line": 2, + "end_column": 8 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "assert-if-1.k", + "line": 2, + "column": 12, + "end_line": 2, + "end_column": 13 + } + ] + }, + "filename": "assert-if-1.k", + "line": 2, + "column": 7, + "end_line": 2, + "end_column": 13 + }, + "if_cond": { + "node": { + "type": "NameConstantLit", + "value": "False" + }, + "filename": "assert-if-1.k", + "line": 2, + "column": 17, + "end_line": 2, + "end_column": 22 + }, + "msg": null + }, + "filename": "assert-if-1.k", + "line": 2, + "column": 0, + "end_line": 2, + "end_column": 22 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "_x", + "filename": "assert-if-1.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 2 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "assert-if-1.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 2 + } + ], + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"good case\"", + "value": "good case" + }, + "filename": "assert-if-1.k", + "line": 3, + "column": 5, + "end_line": 3, + "end_column": 16 + }, + "ty": null + }, + "filename": "assert-if-1.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 16 + }, + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "_x", + "filename": "assert-if-1.k", + "line": 4, + "column": 7, + "end_line": 4, + "end_column": 9 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "assert-if-1.k", + "line": 4, + "column": 7, + "end_line": 4, + "end_column": 9 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"good case\"", + "value": "good case" + }, + "filename": "assert-if-1.k", + "line": 4, + "column": 13, + "end_line": 4, + "end_column": 24 + } + ] + }, + "filename": "assert-if-1.k", + "line": 4, + "column": 7, + "end_line": 4, + "end_column": 24 + }, + "if_cond": { + "node": { + "type": "Unary", + "op": "Not", + "operand": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "_x", + "filename": "assert-if-1.k", + "line": 4, + "column": 32, + "end_line": 4, + "end_column": 34 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "assert-if-1.k", + "line": 4, + "column": 32, + "end_line": 4, + "end_column": 34 + } + }, + "filename": "assert-if-1.k", + "line": 4, + "column": 28, + "end_line": 4, + "end_column": 34 + }, + "msg": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"_x need to be 'good case'\"", + "value": "_x need to be 'good case'" + }, + "filename": "assert-if-1.k", + "line": 4, + "column": 36, + "end_line": 4, + "end_column": 63 + } + }, + "filename": "assert-if-1.k", + "line": 4, + "column": 0, + "end_line": 4, + "end_column": 63 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_if_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_if_2.snap new file mode 100644 index 000000000..e1549351e --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assert_if_2.snap @@ -0,0 +1,368 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/assert-if-2.k\")" +--- +{ + "filename": "assert-if-2.k", + "doc": null, + "body": [ + { + "node": { + "type": "Schema", + "doc": null, + "name": { + "node": "Data", + "filename": "assert-if-2.k", + "line": 1, + "column": 7, + "end_line": 1, + "end_column": 11 + }, + "parent_name": null, + "for_host_name": null, + "is_mixin": false, + "is_protocol": false, + "args": null, + "mixins": [], + "body": [ + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "NameConstantLit", + "value": "True" + }, + "filename": "assert-if-2.k", + "line": 2, + "column": 11, + "end_line": 2, + "end_column": 15 + }, + "if_cond": { + "node": { + "type": "NameConstantLit", + "value": "False" + }, + "filename": "assert-if-2.k", + "line": 2, + "column": 19, + "end_line": 2, + "end_column": 24 + }, + "msg": null + }, + "filename": "assert-if-2.k", + "line": 2, + "column": 4, + "end_line": 2, + "end_column": 24 + }, + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "assert-if-2.k", + "line": 3, + "column": 11, + "end_line": 3, + "end_column": 12 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "assert-if-2.k", + "line": 3, + "column": 16, + "end_line": 3, + "end_column": 17 + } + ] + }, + "filename": "assert-if-2.k", + "line": 3, + "column": 11, + "end_line": 3, + "end_column": 17 + }, + "if_cond": { + "node": { + "type": "NameConstantLit", + "value": "False" + }, + "filename": "assert-if-2.k", + "line": 3, + "column": 21, + "end_line": 3, + "end_column": 26 + }, + "msg": null + }, + "filename": "assert-if-2.k", + "line": 3, + "column": 4, + "end_line": 3, + "end_column": 26 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "_x", + "filename": "assert-if-2.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 6 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "assert-if-2.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 6 + } + ], + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"good case\"", + "value": "good case" + }, + "filename": "assert-if-2.k", + "line": 4, + "column": 9, + "end_line": 4, + "end_column": 20 + }, + "ty": null + }, + "filename": "assert-if-2.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 20 + }, + { + "node": { + "type": "Assert", + "test": { + "node": { + "type": "Compare", + "left": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "_x", + "filename": "assert-if-2.k", + "line": 5, + "column": 11, + "end_line": 5, + "end_column": 13 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "assert-if-2.k", + "line": 5, + "column": 11, + "end_line": 5, + "end_column": 13 + }, + "ops": [ + "Eq" + ], + "comparators": [ + { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"good case\"", + "value": "good case" + }, + "filename": "assert-if-2.k", + "line": 5, + "column": 17, + "end_line": 5, + "end_column": 28 + } + ] + }, + "filename": "assert-if-2.k", + "line": 5, + "column": 11, + "end_line": 5, + "end_column": 28 + }, + "if_cond": { + "node": { + "type": "Unary", + "op": "Not", + "operand": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "_x", + "filename": "assert-if-2.k", + "line": 5, + "column": 36, + "end_line": 5, + "end_column": 38 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "assert-if-2.k", + "line": 5, + "column": 36, + "end_line": 5, + "end_column": 38 + } + }, + "filename": "assert-if-2.k", + "line": 5, + "column": 32, + "end_line": 5, + "end_column": 38 + }, + "msg": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"_x need to be 'good case'\"", + "value": "_x need to be 'good case'" + }, + "filename": "assert-if-2.k", + "line": 5, + "column": 40, + "end_line": 5, + "end_column": 67 + } + }, + "filename": "assert-if-2.k", + "line": 5, + "column": 4, + "end_line": 5, + "end_column": 67 + } + ], + "decorators": [], + "checks": [], + "index_signature": null + }, + "filename": "assert-if-2.k", + "line": 1, + "column": 0, + "end_line": 7, + "end_column": 0 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "data", + "filename": "assert-if-2.k", + "line": 7, + "column": 0, + "end_line": 7, + "end_column": 4 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "assert-if-2.k", + "line": 7, + "column": 0, + "end_line": 7, + "end_column": 4 + } + ], + "value": { + "node": { + "type": "Schema", + "name": { + "node": { + "names": [ + { + "node": "Data", + "filename": "assert-if-2.k", + "line": 7, + "column": 7, + "end_line": 7, + "end_column": 11 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "assert-if-2.k", + "line": 7, + "column": 7, + "end_line": 7, + "end_column": 11 + }, + "args": [], + "kwargs": [], + "config": { + "node": { + "type": "Config", + "items": [] + }, + "filename": "assert-if-2.k", + "line": 7, + "column": 12, + "end_line": 7, + "end_column": 14 + } + }, + "filename": "assert-if-2.k", + "line": 7, + "column": 7, + "end_line": 7, + "end_column": 14 + }, + "ty": null + }, + "filename": "assert-if-2.k", + "line": 7, + "column": 0, + "end_line": 7, + "end_column": 14 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assign_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assign_1.snap new file mode 100644 index 000000000..0ed4c141f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__assign_1.snap @@ -0,0 +1,230 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/assign-01.k\")" +--- +{ + "filename": "assign-01.k", + "doc": null, + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "a", + "filename": "assign-01.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 1 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "assign-01.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 1 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "assign-01.k", + "line": 1, + "column": 2, + "end_line": 1, + "end_column": 3 + }, + "ty": null + }, + "filename": "assign-01.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 3 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "b", + "filename": "assign-01.k", + "line": 2, + "column": 0, + "end_line": 2, + "end_column": 1 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "assign-01.k", + "line": 2, + "column": 0, + "end_line": 2, + "end_column": 1 + } + ], + "value": { + "node": { + "type": "Binary", + "left": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "assign-01.k", + "line": 2, + "column": 4, + "end_line": 2, + "end_column": 5 + }, + "op": "Add", + "right": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 2 + } + }, + "filename": "assign-01.k", + "line": 2, + "column": 8, + "end_line": 2, + "end_column": 9 + } + }, + "filename": "assign-01.k", + "line": 2, + "column": 4, + "end_line": 2, + "end_column": 9 + }, + "ty": null + }, + "filename": "assign-01.k", + "line": 2, + "column": 0, + "end_line": 2, + "end_column": 9 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "c", + "filename": "assign-01.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 1 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "assign-01.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 1 + } + ], + "value": { + "node": { + "type": "Binary", + "left": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 2 + } + }, + "filename": "assign-01.k", + "line": 3, + "column": 4, + "end_line": 3, + "end_column": 5 + }, + "op": "Add", + "right": { + "node": { + "type": "Binary", + "left": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 2 + } + }, + "filename": "assign-01.k", + "line": 3, + "column": 8, + "end_line": 3, + "end_column": 9 + }, + "op": "Mul", + "right": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 3 + } + }, + "filename": "assign-01.k", + "line": 3, + "column": 10, + "end_line": 3, + "end_column": 11 + } + }, + "filename": "assign-01.k", + "line": 3, + "column": 8, + "end_line": 3, + "end_column": 11 + } + }, + "filename": "assign-01.k", + "line": 3, + "column": 4, + "end_line": 3, + "end_column": 11 + }, + "ty": null + }, + "filename": "assign-01.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 11 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__config_expr_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__config_expr_1.snap new file mode 100644 index 000000000..2e85514be --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__config_expr_1.snap @@ -0,0 +1,54 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/config_expr-01.k\")" +--- +{ + "filename": "config_expr-01.k", + "doc": null, + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "config", + "filename": "config_expr-01.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 6 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "config_expr-01.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 6 + } + ], + "value": { + "node": { + "type": "Config", + "items": [] + }, + "filename": "config_expr-01.k", + "line": 1, + "column": 9, + "end_line": 2, + "end_column": 1 + }, + "ty": null + }, + "filename": "config_expr-01.k", + "line": 1, + "column": 0, + "end_line": 2, + "end_column": 1 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__config_expr_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__config_expr_2.snap new file mode 100644 index 000000000..ac8084253 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__config_expr_2.snap @@ -0,0 +1,149 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/config_expr-02.k\")" +--- +{ + "filename": "config_expr-02.k", + "doc": null, + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "config", + "filename": "config_expr-02.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 6 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "config_expr-02.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 6 + } + ], + "value": { + "node": { + "type": "Config", + "items": [ + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "k1", + "filename": "config_expr-02.k", + "line": 2, + "column": 4, + "end_line": 2, + "end_column": 6 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-02.k", + "line": 2, + "column": 4, + "end_line": 2, + "end_column": 6 + }, + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 111 + } + }, + "filename": "config_expr-02.k", + "line": 2, + "column": 9, + "end_line": 2, + "end_column": 12 + }, + "operation": "Override" + }, + "filename": "config_expr-02.k", + "line": 2, + "column": 4, + "end_line": 2, + "end_column": 12 + }, + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "k2", + "filename": "config_expr-02.k", + "line": 3, + "column": 4, + "end_line": 3, + "end_column": 6 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-02.k", + "line": 3, + "column": 4, + "end_line": 3, + "end_column": 6 + }, + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 222 + } + }, + "filename": "config_expr-02.k", + "line": 3, + "column": 9, + "end_line": 3, + "end_column": 12 + }, + "operation": "Override" + }, + "filename": "config_expr-02.k", + "line": 3, + "column": 4, + "end_line": 3, + "end_column": 12 + } + ] + }, + "filename": "config_expr-02.k", + "line": 1, + "column": 9, + "end_line": 4, + "end_column": 1 + }, + "ty": null + }, + "filename": "config_expr-02.k", + "line": 1, + "column": 0, + "end_line": 4, + "end_column": 1 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__config_expr_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__config_expr_3.snap new file mode 100644 index 000000000..6652aacc7 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__config_expr_3.snap @@ -0,0 +1,448 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/config_expr-03.k\")" +--- +{ + "filename": "config_expr-03.k", + "doc": null, + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "config", + "filename": "config_expr-03.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 6 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "config_expr-03.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 6 + } + ], + "value": { + "node": { + "type": "Config", + "items": [ + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "main", + "filename": "config_expr-03.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 8 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-03.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 8 + }, + "value": { + "node": { + "type": "Config", + "items": [ + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "env", + "filename": "config_expr-03.k", + "line": 5, + "column": 8, + "end_line": 5, + "end_column": 11 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-03.k", + "line": 5, + "column": 8, + "end_line": 5, + "end_column": 11 + }, + "value": { + "node": { + "type": "List", + "elts": [ + { + "node": { + "type": "Config", + "items": [ + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "name", + "filename": "config_expr-03.k", + "line": 6, + "column": 13, + "end_line": 6, + "end_column": 17 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-03.k", + "line": 6, + "column": 13, + "end_line": 6, + "end_column": 17 + }, + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"ENV_1\"", + "value": "ENV_1" + }, + "filename": "config_expr-03.k", + "line": 6, + "column": 19, + "end_line": 6, + "end_column": 26 + }, + "operation": "Union" + }, + "filename": "config_expr-03.k", + "line": 6, + "column": 13, + "end_line": 6, + "end_column": 26 + }, + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "value", + "filename": "config_expr-03.k", + "line": 6, + "column": 28, + "end_line": 6, + "end_column": 33 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-03.k", + "line": 6, + "column": 28, + "end_line": 6, + "end_column": 33 + }, + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"1\"", + "value": "1" + }, + "filename": "config_expr-03.k", + "line": 6, + "column": 35, + "end_line": 6, + "end_column": 38 + }, + "operation": "Union" + }, + "filename": "config_expr-03.k", + "line": 6, + "column": 28, + "end_line": 6, + "end_column": 38 + } + ] + }, + "filename": "config_expr-03.k", + "line": 6, + "column": 12, + "end_line": 6, + "end_column": 39 + } + ], + "ctx": "Load" + }, + "filename": "config_expr-03.k", + "line": 5, + "column": 13, + "end_line": 7, + "end_column": 9 + }, + "operation": "Union" + }, + "filename": "config_expr-03.k", + "line": 5, + "column": 8, + "end_line": 7, + "end_column": 9 + } + ] + }, + "filename": "config_expr-03.k", + "line": 4, + "column": 10, + "end_line": 8, + "end_column": 5 + }, + "operation": "Union" + }, + "filename": "config_expr-03.k", + "line": 4, + "column": 4, + "end_line": 8, + "end_column": 5 + }, + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "main", + "filename": "config_expr-03.k", + "line": 9, + "column": 4, + "end_line": 9, + "end_column": 8 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-03.k", + "line": 9, + "column": 4, + "end_line": 9, + "end_column": 8 + }, + "value": { + "node": { + "type": "Config", + "items": [ + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "env", + "filename": "config_expr-03.k", + "line": 10, + "column": 8, + "end_line": 10, + "end_column": 11 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-03.k", + "line": 10, + "column": 8, + "end_line": 10, + "end_column": 11 + }, + "value": { + "node": { + "type": "List", + "elts": [ + { + "node": { + "type": "Config", + "items": [ + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "name", + "filename": "config_expr-03.k", + "line": 11, + "column": 13, + "end_line": 11, + "end_column": 17 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-03.k", + "line": 11, + "column": 13, + "end_line": 11, + "end_column": 17 + }, + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"ENV_2\"", + "value": "ENV_2" + }, + "filename": "config_expr-03.k", + "line": 11, + "column": 19, + "end_line": 11, + "end_column": 26 + }, + "operation": "Union" + }, + "filename": "config_expr-03.k", + "line": 11, + "column": 13, + "end_line": 11, + "end_column": 26 + }, + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "value", + "filename": "config_expr-03.k", + "line": 11, + "column": 28, + "end_line": 11, + "end_column": 33 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-03.k", + "line": 11, + "column": 28, + "end_line": 11, + "end_column": 33 + }, + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"2\"", + "value": "2" + }, + "filename": "config_expr-03.k", + "line": 11, + "column": 35, + "end_line": 11, + "end_column": 38 + }, + "operation": "Union" + }, + "filename": "config_expr-03.k", + "line": 11, + "column": 28, + "end_line": 11, + "end_column": 38 + } + ] + }, + "filename": "config_expr-03.k", + "line": 11, + "column": 12, + "end_line": 11, + "end_column": 39 + } + ], + "ctx": "Load" + }, + "filename": "config_expr-03.k", + "line": 10, + "column": 15, + "end_line": 12, + "end_column": 9 + }, + "operation": "Insert" + }, + "filename": "config_expr-03.k", + "line": 10, + "column": 8, + "end_line": 12, + "end_column": 9 + } + ] + }, + "filename": "config_expr-03.k", + "line": 9, + "column": 10, + "end_line": 13, + "end_column": 5 + }, + "operation": "Union" + }, + "filename": "config_expr-03.k", + "line": 9, + "column": 4, + "end_line": 13, + "end_column": 5 + } + ] + }, + "filename": "config_expr-03.k", + "line": 3, + "column": 9, + "end_line": 14, + "end_column": 1 + }, + "ty": null + }, + "filename": "config_expr-03.k", + "line": 3, + "column": 0, + "end_line": 14, + "end_column": 1 + } + ], + "comments": [ + { + "node": { + "text": "# test/grammar/attr_operator/config_inside/insert/dict_0/main.k" + }, + "filename": "config_expr-03.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 63 + } + ] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__config_expr_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__config_expr_4.snap new file mode 100644 index 000000000..e0a50035f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__config_expr_4.snap @@ -0,0 +1,865 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/config_expr-04.k\")" +--- +{ + "filename": "config_expr-04.k", + "doc": null, + "body": [ + { + "node": { + "type": "Schema", + "doc": null, + "name": { + "node": "Env", + "filename": "config_expr-04.k", + "line": 3, + "column": 7, + "end_line": 3, + "end_column": 10 + }, + "parent_name": null, + "for_host_name": null, + "is_mixin": false, + "is_protocol": false, + "args": null, + "mixins": [], + "body": [ + { + "node": { + "type": "SchemaAttr", + "doc": "", + "name": { + "node": "name", + "filename": "config_expr-04.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 8 + }, + "op": null, + "value": null, + "is_optional": false, + "decorators": [], + "ty": { + "node": { + "type": "Basic", + "value": "Str" + }, + "filename": "config_expr-04.k", + "line": 4, + "column": 10, + "end_line": 4, + "end_column": 13 + } + }, + "filename": "config_expr-04.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 13 + }, + { + "node": { + "type": "SchemaAttr", + "doc": "", + "name": { + "node": "value", + "filename": "config_expr-04.k", + "line": 5, + "column": 4, + "end_line": 5, + "end_column": 9 + }, + "op": null, + "value": null, + "is_optional": false, + "decorators": [], + "ty": { + "node": { + "type": "Basic", + "value": "Str" + }, + "filename": "config_expr-04.k", + "line": 5, + "column": 11, + "end_line": 5, + "end_column": 14 + } + }, + "filename": "config_expr-04.k", + "line": 5, + "column": 4, + "end_line": 5, + "end_column": 14 + } + ], + "decorators": [], + "checks": [], + "index_signature": null + }, + "filename": "config_expr-04.k", + "line": 3, + "column": 0, + "end_line": 7, + "end_column": 0 + }, + { + "node": { + "type": "Schema", + "doc": null, + "name": { + "node": "Main", + "filename": "config_expr-04.k", + "line": 7, + "column": 7, + "end_line": 7, + "end_column": 11 + }, + "parent_name": null, + "for_host_name": null, + "is_mixin": false, + "is_protocol": false, + "args": null, + "mixins": [], + "body": [ + { + "node": { + "type": "SchemaAttr", + "doc": "", + "name": { + "node": "env", + "filename": "config_expr-04.k", + "line": 8, + "column": 4, + "end_line": 8, + "end_column": 7 + }, + "op": null, + "value": null, + "is_optional": false, + "decorators": [], + "ty": { + "node": { + "type": "List", + "value": { + "inner_type": { + "node": { + "type": "Named", + "value": { + "names": [ + { + "node": "Env", + "filename": "config_expr-04.k", + "line": 8, + "column": 10, + "end_line": 8, + "end_column": 13 + } + ], + "pkgpath": "", + "ctx": "Load" + } + }, + "filename": "config_expr-04.k", + "line": 8, + "column": 10, + "end_line": 8, + "end_column": 13 + } + } + }, + "filename": "config_expr-04.k", + "line": 8, + "column": 9, + "end_line": 8, + "end_column": 14 + } + }, + "filename": "config_expr-04.k", + "line": 8, + "column": 4, + "end_line": 8, + "end_column": 14 + } + ], + "decorators": [], + "checks": [], + "index_signature": null + }, + "filename": "config_expr-04.k", + "line": 7, + "column": 0, + "end_line": 10, + "end_column": 0 + }, + { + "node": { + "type": "Schema", + "doc": null, + "name": { + "node": "Config", + "filename": "config_expr-04.k", + "line": 10, + "column": 7, + "end_line": 10, + "end_column": 13 + }, + "parent_name": null, + "for_host_name": null, + "is_mixin": false, + "is_protocol": false, + "args": null, + "mixins": [], + "body": [ + { + "node": { + "type": "SchemaAttr", + "doc": "", + "name": { + "node": "main", + "filename": "config_expr-04.k", + "line": 11, + "column": 4, + "end_line": 11, + "end_column": 8 + }, + "op": null, + "value": null, + "is_optional": false, + "decorators": [], + "ty": { + "node": { + "type": "Named", + "value": { + "names": [ + { + "node": "Main", + "filename": "config_expr-04.k", + "line": 11, + "column": 10, + "end_line": 11, + "end_column": 14 + } + ], + "pkgpath": "", + "ctx": "Load" + } + }, + "filename": "config_expr-04.k", + "line": 11, + "column": 10, + "end_line": 11, + "end_column": 14 + } + }, + "filename": "config_expr-04.k", + "line": 11, + "column": 4, + "end_line": 11, + "end_column": 14 + } + ], + "decorators": [], + "checks": [], + "index_signature": null + }, + "filename": "config_expr-04.k", + "line": 10, + "column": 0, + "end_line": 13, + "end_column": 0 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "_main", + "filename": "config_expr-04.k", + "line": 13, + "column": 0, + "end_line": 13, + "end_column": 5 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "config_expr-04.k", + "line": 13, + "column": 0, + "end_line": 13, + "end_column": 5 + } + ], + "value": { + "node": { + "type": "Schema", + "name": { + "node": { + "names": [ + { + "node": "Main", + "filename": "config_expr-04.k", + "line": 13, + "column": 8, + "end_line": 13, + "end_column": 12 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-04.k", + "line": 13, + "column": 8, + "end_line": 13, + "end_column": 12 + }, + "args": [], + "kwargs": [], + "config": { + "node": { + "type": "Config", + "items": [ + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "env", + "filename": "config_expr-04.k", + "line": 14, + "column": 4, + "end_line": 14, + "end_column": 7 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-04.k", + "line": 14, + "column": 4, + "end_line": 14, + "end_column": 7 + }, + "value": { + "node": { + "type": "List", + "elts": [ + { + "node": { + "type": "Config", + "items": [ + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "name", + "filename": "config_expr-04.k", + "line": 15, + "column": 9, + "end_line": 15, + "end_column": 13 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-04.k", + "line": 15, + "column": 9, + "end_line": 15, + "end_column": 13 + }, + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"ENV_1\"", + "value": "ENV_1" + }, + "filename": "config_expr-04.k", + "line": 15, + "column": 15, + "end_line": 15, + "end_column": 22 + }, + "operation": "Union" + }, + "filename": "config_expr-04.k", + "line": 15, + "column": 9, + "end_line": 15, + "end_column": 22 + }, + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "value", + "filename": "config_expr-04.k", + "line": 15, + "column": 24, + "end_line": 15, + "end_column": 29 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-04.k", + "line": 15, + "column": 24, + "end_line": 15, + "end_column": 29 + }, + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"1\"", + "value": "1" + }, + "filename": "config_expr-04.k", + "line": 15, + "column": 31, + "end_line": 15, + "end_column": 34 + }, + "operation": "Union" + }, + "filename": "config_expr-04.k", + "line": 15, + "column": 24, + "end_line": 15, + "end_column": 34 + } + ] + }, + "filename": "config_expr-04.k", + "line": 15, + "column": 8, + "end_line": 15, + "end_column": 35 + } + ], + "ctx": "Load" + }, + "filename": "config_expr-04.k", + "line": 14, + "column": 9, + "end_line": 16, + "end_column": 5 + }, + "operation": "Union" + }, + "filename": "config_expr-04.k", + "line": 14, + "column": 4, + "end_line": 16, + "end_column": 5 + } + ] + }, + "filename": "config_expr-04.k", + "line": 13, + "column": 13, + "end_line": 17, + "end_column": 1 + } + }, + "filename": "config_expr-04.k", + "line": 13, + "column": 8, + "end_line": 17, + "end_column": 1 + }, + "ty": null + }, + "filename": "config_expr-04.k", + "line": 13, + "column": 0, + "end_line": 17, + "end_column": 1 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "config", + "filename": "config_expr-04.k", + "line": 19, + "column": 0, + "end_line": 19, + "end_column": 6 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "config_expr-04.k", + "line": 19, + "column": 0, + "end_line": 19, + "end_column": 6 + } + ], + "value": { + "node": { + "type": "Schema", + "name": { + "node": { + "names": [ + { + "node": "Config", + "filename": "config_expr-04.k", + "line": 19, + "column": 9, + "end_line": 19, + "end_column": 15 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-04.k", + "line": 19, + "column": 9, + "end_line": 19, + "end_column": 15 + }, + "args": [], + "kwargs": [], + "config": { + "node": { + "type": "Config", + "items": [ + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "main", + "filename": "config_expr-04.k", + "line": 20, + "column": 4, + "end_line": 20, + "end_column": 8 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-04.k", + "line": 20, + "column": 4, + "end_line": 20, + "end_column": 8 + }, + "value": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "_main", + "filename": "config_expr-04.k", + "line": 20, + "column": 10, + "end_line": 20, + "end_column": 15 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-04.k", + "line": 20, + "column": 10, + "end_line": 20, + "end_column": 15 + }, + "operation": "Union" + }, + "filename": "config_expr-04.k", + "line": 20, + "column": 4, + "end_line": 20, + "end_column": 15 + }, + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "main", + "filename": "config_expr-04.k", + "line": 21, + "column": 4, + "end_line": 21, + "end_column": 8 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-04.k", + "line": 21, + "column": 4, + "end_line": 21, + "end_column": 8 + }, + "value": { + "node": { + "type": "Schema", + "name": { + "node": { + "names": [ + { + "node": "Main", + "filename": "config_expr-04.k", + "line": 21, + "column": 10, + "end_line": 21, + "end_column": 14 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-04.k", + "line": 21, + "column": 10, + "end_line": 21, + "end_column": 14 + }, + "args": [], + "kwargs": [], + "config": { + "node": { + "type": "Config", + "items": [ + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "env", + "filename": "config_expr-04.k", + "line": 22, + "column": 8, + "end_line": 22, + "end_column": 11 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-04.k", + "line": 22, + "column": 8, + "end_line": 22, + "end_column": 11 + }, + "value": { + "node": { + "type": "List", + "elts": [ + { + "node": { + "type": "Config", + "items": [ + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "name", + "filename": "config_expr-04.k", + "line": 23, + "column": 13, + "end_line": 23, + "end_column": 17 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-04.k", + "line": 23, + "column": 13, + "end_line": 23, + "end_column": 17 + }, + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"ENV_2\"", + "value": "ENV_2" + }, + "filename": "config_expr-04.k", + "line": 23, + "column": 19, + "end_line": 23, + "end_column": 26 + }, + "operation": "Union" + }, + "filename": "config_expr-04.k", + "line": 23, + "column": 13, + "end_line": 23, + "end_column": 26 + }, + { + "node": { + "key": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "value", + "filename": "config_expr-04.k", + "line": 23, + "column": 28, + "end_line": 23, + "end_column": 33 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "config_expr-04.k", + "line": 23, + "column": 28, + "end_line": 23, + "end_column": 33 + }, + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"2\"", + "value": "2" + }, + "filename": "config_expr-04.k", + "line": 23, + "column": 35, + "end_line": 23, + "end_column": 38 + }, + "operation": "Union" + }, + "filename": "config_expr-04.k", + "line": 23, + "column": 28, + "end_line": 23, + "end_column": 38 + } + ] + }, + "filename": "config_expr-04.k", + "line": 23, + "column": 12, + "end_line": 23, + "end_column": 39 + } + ], + "ctx": "Load" + }, + "filename": "config_expr-04.k", + "line": 22, + "column": 15, + "end_line": 24, + "end_column": 9 + }, + "operation": "Insert" + }, + "filename": "config_expr-04.k", + "line": 22, + "column": 8, + "end_line": 24, + "end_column": 9 + } + ] + }, + "filename": "config_expr-04.k", + "line": 21, + "column": 15, + "end_line": 25, + "end_column": 5 + } + }, + "filename": "config_expr-04.k", + "line": 21, + "column": 10, + "end_line": 25, + "end_column": 5 + }, + "operation": "Union" + }, + "filename": "config_expr-04.k", + "line": 21, + "column": 4, + "end_line": 25, + "end_column": 5 + } + ] + }, + "filename": "config_expr-04.k", + "line": 19, + "column": 16, + "end_line": 26, + "end_column": 1 + } + }, + "filename": "config_expr-04.k", + "line": 19, + "column": 9, + "end_line": 26, + "end_column": 1 + }, + "ty": null + }, + "filename": "config_expr-04.k", + "line": 19, + "column": 0, + "end_line": 26, + "end_column": 1 + } + ], + "comments": [ + { + "node": { + "text": "# test/grammar/attr_operator/config_inside/insert/schema_0/main.k" + }, + "filename": "config_expr-04.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 65 + } + ] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__hello_win.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__hello_win.snap new file mode 100644 index 000000000..1a2d56238 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__hello_win.snap @@ -0,0 +1,163 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/hello_win.k\")" +--- +{ + "filename": "hello_win.k", + "doc": null, + "body": [ + { + "node": { + "type": "Schema", + "doc": null, + "name": { + "node": "Person", + "filename": "hello_win.k", + "line": 2, + "column": 7, + "end_line": 2, + "end_column": 13 + }, + "parent_name": null, + "for_host_name": null, + "is_mixin": false, + "is_protocol": false, + "args": null, + "mixins": [], + "body": [ + { + "node": { + "type": "SchemaAttr", + "doc": "", + "name": { + "node": "name", + "filename": "hello_win.k", + "line": 3, + "column": 4, + "end_line": 3, + "end_column": 8 + }, + "op": "Assign", + "value": { + "node": { + "type": "StringLit", + "is_long_string": false, + "raw_value": "\"kcl\"", + "value": "kcl" + }, + "filename": "hello_win.k", + "line": 3, + "column": 16, + "end_line": 3, + "end_column": 21 + }, + "is_optional": false, + "decorators": [], + "ty": { + "node": { + "type": "Basic", + "value": "Str" + }, + "filename": "hello_win.k", + "line": 3, + "column": 10, + "end_line": 3, + "end_column": 13 + } + }, + "filename": "hello_win.k", + "line": 3, + "column": 4, + "end_line": 3, + "end_column": 21 + } + ], + "decorators": [], + "checks": [], + "index_signature": null + }, + "filename": "hello_win.k", + "line": 2, + "column": 0, + "end_line": 5, + "end_column": 0 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "x0", + "filename": "hello_win.k", + "line": 5, + "column": 0, + "end_line": 5, + "end_column": 2 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "hello_win.k", + "line": 5, + "column": 0, + "end_line": 5, + "end_column": 2 + } + ], + "value": { + "node": { + "type": "Schema", + "name": { + "node": { + "names": [ + { + "node": "Person", + "filename": "hello_win.k", + "line": 5, + "column": 5, + "end_line": 5, + "end_column": 11 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "hello_win.k", + "line": 5, + "column": 5, + "end_line": 5, + "end_column": 11 + }, + "args": [], + "kwargs": [], + "config": { + "node": { + "type": "Config", + "items": [] + }, + "filename": "hello_win.k", + "line": 5, + "column": 12, + "end_line": 5, + "end_column": 14 + } + }, + "filename": "hello_win.k", + "line": 5, + "column": 5, + "end_line": 5, + "end_column": 14 + }, + "ty": null + }, + "filename": "hello_win.k", + "line": 5, + "column": 0, + "end_line": 5, + "end_column": 14 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__if_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__if_1.snap new file mode 100644 index 000000000..2ad7aae60 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__if_1.snap @@ -0,0 +1,140 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/if-01.k\")" +--- +{ + "filename": "if-01.k", + "doc": null, + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "a", + "filename": "if-01.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 1 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "if-01.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 1 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "if-01.k", + "line": 1, + "column": 4, + "end_line": 1, + "end_column": 5 + }, + "ty": null + }, + "filename": "if-01.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 5 + }, + { + "node": { + "type": "If", + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "bbb", + "filename": "if-01.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 7 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "if-01.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 7 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 2 + } + }, + "filename": "if-01.k", + "line": 4, + "column": 10, + "end_line": 4, + "end_column": 11 + }, + "ty": null + }, + "filename": "if-01.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 11 + } + ], + "cond": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "a", + "filename": "if-01.k", + "line": 3, + "column": 3, + "end_line": 3, + "end_column": 4 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "if-01.k", + "line": 3, + "column": 3, + "end_line": 3, + "end_column": 4 + }, + "orelse": [] + }, + "filename": "if-01.k", + "line": 3, + "column": 0, + "end_line": 4, + "end_column": 12 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__if_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__if_2.snap new file mode 100644 index 000000000..24e034b2d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__if_2.snap @@ -0,0 +1,453 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/if-02.k\")" +--- +{ + "filename": "if-02.k", + "doc": null, + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "a", + "filename": "if-02.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 1 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "if-02.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 1 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "if-02.k", + "line": 1, + "column": 4, + "end_line": 1, + "end_column": 5 + }, + "ty": null + }, + "filename": "if-02.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 5 + }, + { + "node": { + "type": "If", + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "bbb", + "filename": "if-02.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 7 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "if-02.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 7 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 2 + } + }, + "filename": "if-02.k", + "line": 4, + "column": 10, + "end_line": 4, + "end_column": 11 + }, + "ty": null + }, + "filename": "if-02.k", + "line": 4, + "column": 4, + "end_line": 4, + "end_column": 11 + } + ], + "cond": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "a", + "filename": "if-02.k", + "line": 3, + "column": 3, + "end_line": 3, + "end_column": 4 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "if-02.k", + "line": 3, + "column": 3, + "end_line": 3, + "end_column": 4 + }, + "orelse": [ + { + "node": { + "type": "If", + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "ccc", + "filename": "if-02.k", + "line": 6, + "column": 4, + "end_line": 6, + "end_column": 7 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "if-02.k", + "line": 6, + "column": 4, + "end_line": 6, + "end_column": 7 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 3 + } + }, + "filename": "if-02.k", + "line": 6, + "column": 10, + "end_line": 6, + "end_column": 11 + }, + "ty": null + }, + "filename": "if-02.k", + "line": 6, + "column": 4, + "end_line": 6, + "end_column": 11 + } + ], + "cond": { + "node": { + "type": "Binary", + "left": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "a", + "filename": "if-02.k", + "line": 5, + "column": 5, + "end_line": 5, + "end_column": 6 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "if-02.k", + "line": 5, + "column": 5, + "end_line": 5, + "end_column": 6 + }, + "op": "Add", + "right": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 10 + } + }, + "filename": "if-02.k", + "line": 5, + "column": 9, + "end_line": 5, + "end_column": 11 + } + }, + "filename": "if-02.k", + "line": 5, + "column": 5, + "end_line": 5, + "end_column": 11 + }, + "orelse": [ + { + "node": { + "type": "If", + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "ddd", + "filename": "if-02.k", + "line": 8, + "column": 4, + "end_line": 8, + "end_column": 7 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "if-02.k", + "line": 8, + "column": 4, + "end_line": 8, + "end_column": 7 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 4 + } + }, + "filename": "if-02.k", + "line": 8, + "column": 10, + "end_line": 8, + "end_column": 11 + }, + "ty": null + }, + "filename": "if-02.k", + "line": 8, + "column": 4, + "end_line": 8, + "end_column": 11 + } + ], + "cond": { + "node": { + "type": "Binary", + "left": { + "node": { + "type": "Identifier", + "names": [ + { + "node": "a", + "filename": "if-02.k", + "line": 7, + "column": 5, + "end_line": 7, + "end_column": 6 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "if-02.k", + "line": 7, + "column": 5, + "end_line": 7, + "end_column": 6 + }, + "op": "Add", + "right": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 100 + } + }, + "filename": "if-02.k", + "line": 7, + "column": 9, + "end_line": 7, + "end_column": 12 + } + }, + "filename": "if-02.k", + "line": 7, + "column": 5, + "end_line": 7, + "end_column": 12 + }, + "orelse": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "eee", + "filename": "if-02.k", + "line": 10, + "column": 4, + "end_line": 10, + "end_column": 7 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "if-02.k", + "line": 10, + "column": 4, + "end_line": 10, + "end_column": 7 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 5 + } + }, + "filename": "if-02.k", + "line": 10, + "column": 10, + "end_line": 10, + "end_column": 11 + }, + "ty": null + }, + "filename": "if-02.k", + "line": 10, + "column": 4, + "end_line": 10, + "end_column": 11 + }, + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "fff", + "filename": "if-02.k", + "line": 11, + "column": 4, + "end_line": 11, + "end_column": 7 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "if-02.k", + "line": 11, + "column": 4, + "end_line": 11, + "end_column": 7 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 6 + } + }, + "filename": "if-02.k", + "line": 11, + "column": 10, + "end_line": 11, + "end_column": 11 + }, + "ty": null + }, + "filename": "if-02.k", + "line": 11, + "column": 4, + "end_line": 11, + "end_column": 11 + } + ] + }, + "filename": "if-02.k", + "line": 7, + "column": 0, + "end_line": 11, + "end_column": 11 + } + ] + }, + "filename": "if-02.k", + "line": 5, + "column": 0, + "end_line": 11, + "end_column": 11 + } + ] + }, + "filename": "if-02.k", + "line": 3, + "column": 0, + "end_line": 11, + "end_column": 12 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__if_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__if_3.snap new file mode 100644 index 000000000..1f8844cfd --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__if_3.snap @@ -0,0 +1,82 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/if-03.k\")" +--- +{ + "filename": "if-03.k", + "doc": null, + "body": [ + { + "node": { + "type": "If", + "body": [ + { + "node": { + "type": "Assign", + "targets": [ + { + "node": { + "name": { + "node": "a", + "filename": "if-03.k", + "line": 1, + "column": 9, + "end_line": 1, + "end_column": 10 + }, + "paths": [], + "pkgpath": "" + }, + "filename": "if-03.k", + "line": 1, + "column": 9, + "end_line": 1, + "end_column": 10 + } + ], + "value": { + "node": { + "type": "NumberLit", + "binary_suffix": null, + "value": { + "type": "Int", + "value": 1 + } + }, + "filename": "if-03.k", + "line": 1, + "column": 13, + "end_line": 1, + "end_column": 14 + }, + "ty": null + }, + "filename": "if-03.k", + "line": 1, + "column": 9, + "end_line": 1, + "end_column": 14 + } + ], + "cond": { + "node": { + "type": "NameConstantLit", + "value": "True" + }, + "filename": "if-03.k", + "line": 1, + "column": 3, + "end_line": 1, + "end_column": 7 + }, + "orelse": [] + }, + "filename": "if-03.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 15 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__import_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__import_1.snap new file mode 100644 index 000000000..3de92c88c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__import_1.snap @@ -0,0 +1,106 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/import-01.k\")" +--- +{ + "filename": "import-01.k", + "doc": null, + "body": [ + { + "node": { + "type": "Import", + "path": { + "node": "a1", + "filename": "import-01.k", + "line": 1, + "column": 7, + "end_line": 1, + "end_column": 9 + }, + "rawpath": "a1", + "name": "a1", + "asname": null, + "pkg_name": "__main__" + }, + "filename": "import-01.k", + "line": 1, + "column": 0, + "end_line": 1, + "end_column": 9 + }, + { + "node": { + "type": "Import", + "path": { + "node": "a2", + "filename": "import-01.k", + "line": 3, + "column": 7, + "end_line": 3, + "end_column": 9 + }, + "rawpath": "a2", + "name": "a2_pkg", + "asname": { + "node": "a2_pkg", + "filename": "import-01.k", + "line": 3, + "column": 13, + "end_line": 3, + "end_column": 19 + }, + "pkg_name": "__main__" + }, + "filename": "import-01.k", + "line": 3, + "column": 0, + "end_line": 3, + "end_column": 19 + }, + { + "node": { + "type": "Import", + "path": { + "node": "subpkg.b1.c1", + "filename": "import-01.k", + "line": 5, + "column": 7, + "end_line": 5, + "end_column": 19 + }, + "rawpath": "subpkg.b1.c1", + "name": "c1", + "asname": null, + "pkg_name": "__main__" + }, + "filename": "import-01.k", + "line": 5, + "column": 0, + "end_line": 5, + "end_column": 19 + }, + { + "node": { + "type": "Import", + "path": { + "node": "a3", + "filename": "import-01.k", + "line": 7, + "column": 7, + "end_line": 7, + "end_column": 10 + }, + "rawpath": ".a3", + "name": "a3", + "asname": null, + "pkg_name": "__main__" + }, + "filename": "import-01.k", + "line": 7, + "column": 0, + "end_line": 7, + "end_column": 10 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__file__type_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__type_1.snap new file mode 100644 index 000000000..be6a30e80 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__file__type_1.snap @@ -0,0 +1,540 @@ +--- +source: crates/parser/src/tests/file.rs +expression: "$crate :: tests :: parsing_file_string(\"testdata/type-01.k\")" +--- +{ + "filename": "type-01.k", + "doc": null, + "body": [ + { + "node": { + "type": "TypeAlias", + "type_name": { + "node": { + "names": [ + { + "node": "a", + "filename": "type-01.k", + "line": 1, + "column": 5, + "end_line": 1, + "end_column": 6 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "type-01.k", + "line": 1, + "column": 5, + "end_line": 1, + "end_column": 6 + }, + "type_value": { + "node": "any", + "filename": "type-01.k", + "line": 1, + "column": 9, + "end_line": 1, + "end_column": 12 + }, + "ty": { + "node": { + "type": "Any" + }, + "filename": "type-01.k", + "line": 1, + "column": 9, + "end_line": 1, + "end_column": 12 + } + }, + "filename": "type-01.k", + "line": 1, + "column": 5, + "end_line": 1, + "end_column": 12 + }, + { + "node": { + "type": "TypeAlias", + "type_name": { + "node": { + "names": [ + { + "node": "b", + "filename": "type-01.k", + "line": 3, + "column": 5, + "end_line": 3, + "end_column": 6 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "type-01.k", + "line": 3, + "column": 5, + "end_line": 3, + "end_column": 6 + }, + "type_value": { + "node": "bool", + "filename": "type-01.k", + "line": 3, + "column": 9, + "end_line": 3, + "end_column": 13 + }, + "ty": { + "node": { + "type": "Basic", + "value": "Bool" + }, + "filename": "type-01.k", + "line": 3, + "column": 9, + "end_line": 3, + "end_column": 13 + } + }, + "filename": "type-01.k", + "line": 3, + "column": 5, + "end_line": 3, + "end_column": 13 + }, + { + "node": { + "type": "TypeAlias", + "type_name": { + "node": { + "names": [ + { + "node": "c", + "filename": "type-01.k", + "line": 4, + "column": 5, + "end_line": 4, + "end_column": 6 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "type-01.k", + "line": 4, + "column": 5, + "end_line": 4, + "end_column": 6 + }, + "type_value": { + "node": "int", + "filename": "type-01.k", + "line": 4, + "column": 9, + "end_line": 4, + "end_column": 12 + }, + "ty": { + "node": { + "type": "Basic", + "value": "Int" + }, + "filename": "type-01.k", + "line": 4, + "column": 9, + "end_line": 4, + "end_column": 12 + } + }, + "filename": "type-01.k", + "line": 4, + "column": 5, + "end_line": 4, + "end_column": 12 + }, + { + "node": { + "type": "TypeAlias", + "type_name": { + "node": { + "names": [ + { + "node": "d", + "filename": "type-01.k", + "line": 5, + "column": 5, + "end_line": 5, + "end_column": 6 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "type-01.k", + "line": 5, + "column": 5, + "end_line": 5, + "end_column": 6 + }, + "type_value": { + "node": "float", + "filename": "type-01.k", + "line": 5, + "column": 9, + "end_line": 5, + "end_column": 14 + }, + "ty": { + "node": { + "type": "Basic", + "value": "Float" + }, + "filename": "type-01.k", + "line": 5, + "column": 9, + "end_line": 5, + "end_column": 14 + } + }, + "filename": "type-01.k", + "line": 5, + "column": 5, + "end_line": 5, + "end_column": 14 + }, + { + "node": { + "type": "TypeAlias", + "type_name": { + "node": { + "names": [ + { + "node": "e", + "filename": "type-01.k", + "line": 6, + "column": 5, + "end_line": 6, + "end_column": 6 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "type-01.k", + "line": 6, + "column": 5, + "end_line": 6, + "end_column": 6 + }, + "type_value": { + "node": "str", + "filename": "type-01.k", + "line": 6, + "column": 9, + "end_line": 6, + "end_column": 12 + }, + "ty": { + "node": { + "type": "Basic", + "value": "Str" + }, + "filename": "type-01.k", + "line": 6, + "column": 9, + "end_line": 6, + "end_column": 12 + } + }, + "filename": "type-01.k", + "line": 6, + "column": 5, + "end_line": 6, + "end_column": 12 + }, + { + "node": { + "type": "TypeAlias", + "type_name": { + "node": { + "names": [ + { + "node": "type_list1", + "filename": "type-01.k", + "line": 8, + "column": 5, + "end_line": 8, + "end_column": 15 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "type-01.k", + "line": 8, + "column": 5, + "end_line": 8, + "end_column": 15 + }, + "type_value": { + "node": "[]", + "filename": "type-01.k", + "line": 8, + "column": 18, + "end_line": 8, + "end_column": 20 + }, + "ty": { + "node": { + "type": "List", + "value": { + "inner_type": null + } + }, + "filename": "type-01.k", + "line": 8, + "column": 18, + "end_line": 8, + "end_column": 20 + } + }, + "filename": "type-01.k", + "line": 8, + "column": 5, + "end_line": 8, + "end_column": 20 + }, + { + "node": { + "type": "TypeAlias", + "type_name": { + "node": { + "names": [ + { + "node": "type_list2", + "filename": "type-01.k", + "line": 9, + "column": 5, + "end_line": 9, + "end_column": 15 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "type-01.k", + "line": 9, + "column": 5, + "end_line": 9, + "end_column": 15 + }, + "type_value": { + "node": "[[]]", + "filename": "type-01.k", + "line": 9, + "column": 18, + "end_line": 9, + "end_column": 22 + }, + "ty": { + "node": { + "type": "List", + "value": { + "inner_type": { + "node": { + "type": "List", + "value": { + "inner_type": null + } + }, + "filename": "type-01.k", + "line": 9, + "column": 19, + "end_line": 9, + "end_column": 21 + } + } + }, + "filename": "type-01.k", + "line": 9, + "column": 18, + "end_line": 9, + "end_column": 22 + } + }, + "filename": "type-01.k", + "line": 9, + "column": 5, + "end_line": 9, + "end_column": 22 + }, + { + "node": { + "type": "TypeAlias", + "type_name": { + "node": { + "names": [ + { + "node": "type_list3", + "filename": "type-01.k", + "line": 10, + "column": 5, + "end_line": 10, + "end_column": 15 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "type-01.k", + "line": 10, + "column": 5, + "end_line": 10, + "end_column": 15 + }, + "type_value": { + "node": "[int]", + "filename": "type-01.k", + "line": 10, + "column": 18, + "end_line": 10, + "end_column": 23 + }, + "ty": { + "node": { + "type": "List", + "value": { + "inner_type": { + "node": { + "type": "Basic", + "value": "Int" + }, + "filename": "type-01.k", + "line": 10, + "column": 19, + "end_line": 10, + "end_column": 22 + } + } + }, + "filename": "type-01.k", + "line": 10, + "column": 18, + "end_line": 10, + "end_column": 23 + } + }, + "filename": "type-01.k", + "line": 10, + "column": 5, + "end_line": 10, + "end_column": 23 + }, + { + "node": { + "type": "TypeAlias", + "type_name": { + "node": { + "names": [ + { + "node": "b", + "filename": "type-01.k", + "line": 12, + "column": 5, + "end_line": 12, + "end_column": 6 + } + ], + "pkgpath": "", + "ctx": "Load" + }, + "filename": "type-01.k", + "line": 12, + "column": 5, + "end_line": 12, + "end_column": 6 + }, + "type_value": { + "node": "int | str | [] | {:}", + "filename": "type-01.k", + "line": 12, + "column": 9, + "end_line": 12, + "end_column": 29 + }, + "ty": { + "node": { + "type": "Union", + "value": { + "type_elements": [ + { + "node": { + "type": "Basic", + "value": "Int" + }, + "filename": "type-01.k", + "line": 12, + "column": 9, + "end_line": 12, + "end_column": 12 + }, + { + "node": { + "type": "Basic", + "value": "Str" + }, + "filename": "type-01.k", + "line": 12, + "column": 15, + "end_line": 12, + "end_column": 18 + }, + { + "node": { + "type": "List", + "value": { + "inner_type": null + } + }, + "filename": "type-01.k", + "line": 12, + "column": 21, + "end_line": 12, + "end_column": 23 + }, + { + "node": { + "type": "Dict", + "value": { + "key_type": null, + "value_type": null + } + }, + "filename": "type-01.k", + "line": 12, + "column": 26, + "end_line": 12, + "end_column": 29 + } + ] + } + }, + "filename": "type-01.k", + "line": 12, + "column": 9, + "end_line": 12, + "end_column": 29 + } + }, + "filename": "type-01.k", + "line": 12, + "column": 5, + "end_line": 12, + "end_column": 29 + } + ], + "comments": [] +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__any_type.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__any_type.snap new file mode 100644 index 000000000..a7ce8e656 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__any_type.snap @@ -0,0 +1,12 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"any\"####)" +--- +Node { + node: Any, + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__basic_type_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__basic_type_0.snap new file mode 100644 index 000000000..38a1e0831 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__basic_type_0.snap @@ -0,0 +1,14 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"bool\"####)" +--- +Node { + node: Basic( + Bool, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__basic_type_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__basic_type_1.snap new file mode 100644 index 000000000..d09ce639f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__basic_type_1.snap @@ -0,0 +1,14 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"int\"####)" +--- +Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__basic_type_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__basic_type_2.snap new file mode 100644 index 000000000..34e6bb36c --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__basic_type_2.snap @@ -0,0 +1,14 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"float\"####)" +--- +Node { + node: Basic( + Float, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__basic_type_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__basic_type_3.snap new file mode 100644 index 000000000..8cd373dd8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__basic_type_3.snap @@ -0,0 +1,14 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"str\"####)" +--- +Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_0.snap new file mode 100644 index 000000000..db7473290 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_0.snap @@ -0,0 +1,17 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"{:}\"####)" +--- +Node { + node: Dict( + DictType { + key_type: None, + value_type: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_1.snap new file mode 100644 index 000000000..2695e0bf0 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_1.snap @@ -0,0 +1,28 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"{str:}\"####)" +--- +Node { + node: Dict( + DictType { + key_type: Some( + Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 4, + }, + ), + value_type: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_2.snap new file mode 100644 index 000000000..f3477490a --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_2.snap @@ -0,0 +1,30 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"{:[]}\"####)" +--- +Node { + node: Dict( + DictType { + key_type: None, + value_type: Some( + Node { + node: List( + ListType { + inner_type: None, + }, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 4, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_3.snap new file mode 100644 index 000000000..53cab4ed5 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_3.snap @@ -0,0 +1,53 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"{str:{:float}}\"####)" +--- +Node { + node: Dict( + DictType { + key_type: Some( + Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 4, + }, + ), + value_type: Some( + Node { + node: Dict( + DictType { + key_type: None, + value_type: Some( + Node { + node: Basic( + Float, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 12, + }, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 13, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 14, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_4.snap new file mode 100644 index 000000000..9e5948c60 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__dict_type_4.snap @@ -0,0 +1,53 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"{str:{:float}, int:[]}\"####)" +--- +Node { + node: Dict( + DictType { + key_type: Some( + Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 4, + }, + ), + value_type: Some( + Node { + node: Dict( + DictType { + key_type: None, + value_type: Some( + Node { + node: Basic( + Float, + ), + filename: "", + line: 1, + column: 7, + end_line: 1, + end_column: 12, + }, + ), + }, + ), + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 13, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 14, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_0.snap new file mode 100644 index 000000000..4a2b2b4cd --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_0.snap @@ -0,0 +1,16 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"[]\"####)" +--- +Node { + node: List( + ListType { + inner_type: None, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_1.snap new file mode 100644 index 000000000..59527b6c7 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_1.snap @@ -0,0 +1,27 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"[int]\"####)" +--- +Node { + node: List( + ListType { + inner_type: Some( + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 4, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_2.snap new file mode 100644 index 000000000..10937af39 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_2.snap @@ -0,0 +1,25 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"[any]\"####)" +--- +Node { + node: List( + ListType { + inner_type: Some( + Node { + node: Any, + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 4, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_3.snap new file mode 100644 index 000000000..f73c089a4 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_3.snap @@ -0,0 +1,29 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"[[]]\"####)" +--- +Node { + node: List( + ListType { + inner_type: Some( + Node { + node: List( + ListType { + inner_type: None, + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 3, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_4.snap new file mode 100644 index 000000000..75bdf7a04 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__list_type_4.snap @@ -0,0 +1,40 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"[[str]]\"####)" +--- +Node { + node: List( + ListType { + inner_type: Some( + Node { + node: List( + ListType { + inner_type: Some( + Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 2, + end_line: 1, + end_column: 5, + }, + ), + }, + ), + filename: "", + line: 1, + column: 1, + end_line: 1, + end_column: 6, + }, + ), + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_0.snap new file mode 100644 index 000000000..398a00869 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_0.snap @@ -0,0 +1,16 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"True\"####)" +--- +Node { + node: Literal( + Bool( + true, + ), + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_1.snap new file mode 100644 index 000000000..64b44d4f7 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_1.snap @@ -0,0 +1,16 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"False\"####)" +--- +Node { + node: Literal( + Bool( + false, + ), + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_2.snap new file mode 100644 index 000000000..0261aaacc --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_2.snap @@ -0,0 +1,19 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"123\"####)" +--- +Node { + node: Literal( + Int( + IntLiteralType { + value: 123, + suffix: None, + }, + ), + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_3.snap new file mode 100644 index 000000000..2bf077020 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_3.snap @@ -0,0 +1,16 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"123.0\"####)" +--- +Node { + node: Literal( + Float( + 123.0, + ), + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_4.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_4.snap new file mode 100644 index 000000000..a4ed409aa --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_4.snap @@ -0,0 +1,16 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"\"abc\"\"####)" +--- +Node { + node: Literal( + Str( + "abc", + ), + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 5, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_5.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_5.snap new file mode 100644 index 000000000..7d260c98d --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__literal_type_5.snap @@ -0,0 +1,16 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"''\"####)" +--- +Node { + node: Literal( + Str( + "", + ), + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 2, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__named_type_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__named_type_0.snap new file mode 100644 index 000000000..5d665c025 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__named_type_0.snap @@ -0,0 +1,27 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"Person\"####)" +--- +Node { + node: Named( + Identifier { + names: [ + Node { + node: "Person", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 6, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__named_type_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__named_type_1.snap new file mode 100644 index 000000000..3ab8fbb60 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__named_type_1.snap @@ -0,0 +1,43 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"some.pkg.Person\"####)" +--- +Node { + node: Named( + Identifier { + names: [ + Node { + node: "some", + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 4, + }, + Node { + node: "pkg", + filename: "", + line: 1, + column: 5, + end_line: 1, + end_column: 8, + }, + Node { + node: "Person", + filename: "", + line: 1, + column: 9, + end_line: 1, + end_column: 15, + }, + ], + pkgpath: "", + ctx: Load, + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 15, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__type_str_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__type_str_0.snap new file mode 100644 index 000000000..18354bf48 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__type_str_0.snap @@ -0,0 +1,5 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_node_string(r####\"int\"####)" +--- +int diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__type_str_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__type_str_1.snap new file mode 100644 index 000000000..be36c6996 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__type_str_1.snap @@ -0,0 +1,5 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_node_string(r####\" int \"####)" +--- +int diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__type_str_2.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__type_str_2.snap new file mode 100644 index 000000000..2cd02390a --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__type_str_2.snap @@ -0,0 +1,5 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests ::\nparsing_type_node_string(r####\"bool | True | int | str|str\"####)" +--- +bool | True | int | str | str diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__type_str_3.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__type_str_3.snap new file mode 100644 index 000000000..65d273aa8 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__type_str_3.snap @@ -0,0 +1,5 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests ::\nparsing_type_node_string(r####\"[ [{str: float}] | int]\"####)" +--- +[[{str:float}] | int] diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__union_type_0.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__union_type_0.snap new file mode 100644 index 000000000..0b347b879 --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__union_type_0.snap @@ -0,0 +1,37 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"int|str\"####)" +--- +Node { + node: Union( + UnionType { + type_elements: [ + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 4, + end_line: 1, + end_column: 7, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 7, +} diff --git a/crates/parser/src/tests/snapshots/kcl_parser__tests__types__union_type_1.snap b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__union_type_1.snap new file mode 100644 index 000000000..37c328d7f --- /dev/null +++ b/crates/parser/src/tests/snapshots/kcl_parser__tests__types__union_type_1.snap @@ -0,0 +1,62 @@ +--- +source: crates/parser/src/tests/types.rs +expression: "$crate :: tests :: parsing_type_string(r####\"int | str | [] | {:}\"####)" +--- +Node { + node: Union( + UnionType { + type_elements: [ + Node { + node: Basic( + Int, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 3, + }, + Node { + node: Basic( + Str, + ), + filename: "", + line: 1, + column: 6, + end_line: 1, + end_column: 9, + }, + Node { + node: List( + ListType { + inner_type: None, + }, + ), + filename: "", + line: 1, + column: 12, + end_line: 1, + end_column: 14, + }, + Node { + node: Dict( + DictType { + key_type: None, + value_type: None, + }, + ), + filename: "", + line: 1, + column: 17, + end_line: 1, + end_column: 20, + }, + ], + }, + ), + filename: "", + line: 1, + column: 0, + end_line: 1, + end_column: 20, +} diff --git a/kclvm/parser/src/tests/types.rs b/crates/parser/src/tests/types.rs similarity index 100% rename from kclvm/parser/src/tests/types.rs rename to crates/parser/src/tests/types.rs diff --git a/kclvm/parser/testdata/assert-01.k b/crates/parser/testdata/assert-01.k similarity index 100% rename from kclvm/parser/testdata/assert-01.k rename to crates/parser/testdata/assert-01.k diff --git a/kclvm/parser/testdata/assert-02.k b/crates/parser/testdata/assert-02.k similarity index 100% rename from kclvm/parser/testdata/assert-02.k rename to crates/parser/testdata/assert-02.k diff --git a/kclvm/parser/testdata/assert-03.k b/crates/parser/testdata/assert-03.k similarity index 100% rename from kclvm/parser/testdata/assert-03.k rename to crates/parser/testdata/assert-03.k diff --git a/kclvm/parser/testdata/assert-if-0.k b/crates/parser/testdata/assert-if-0.k similarity index 100% rename from kclvm/parser/testdata/assert-if-0.k rename to crates/parser/testdata/assert-if-0.k diff --git a/kclvm/parser/testdata/assert-if-1.k b/crates/parser/testdata/assert-if-1.k similarity index 100% rename from kclvm/parser/testdata/assert-if-1.k rename to crates/parser/testdata/assert-if-1.k diff --git a/kclvm/parser/testdata/assert-if-2.k b/crates/parser/testdata/assert-if-2.k similarity index 100% rename from kclvm/parser/testdata/assert-if-2.k rename to crates/parser/testdata/assert-if-2.k diff --git a/kclvm/parser/testdata/assign-01.k b/crates/parser/testdata/assign-01.k similarity index 100% rename from kclvm/parser/testdata/assign-01.k rename to crates/parser/testdata/assign-01.k diff --git a/kclvm/parser/testdata/config_expr-01.k b/crates/parser/testdata/config_expr-01.k similarity index 100% rename from kclvm/parser/testdata/config_expr-01.k rename to crates/parser/testdata/config_expr-01.k diff --git a/kclvm/parser/testdata/config_expr-02.k b/crates/parser/testdata/config_expr-02.k similarity index 100% rename from kclvm/parser/testdata/config_expr-02.k rename to crates/parser/testdata/config_expr-02.k diff --git a/kclvm/parser/testdata/config_expr-03.k b/crates/parser/testdata/config_expr-03.k similarity index 100% rename from kclvm/parser/testdata/config_expr-03.k rename to crates/parser/testdata/config_expr-03.k diff --git a/kclvm/parser/testdata/config_expr-04.k b/crates/parser/testdata/config_expr-04.k similarity index 100% rename from kclvm/parser/testdata/config_expr-04.k rename to crates/parser/testdata/config_expr-04.k diff --git a/kclvm/parser/testdata/expand_file_pattern/KCL_MOD b/crates/parser/testdata/expand_file_pattern/KCL_MOD similarity index 100% rename from kclvm/parser/testdata/expand_file_pattern/KCL_MOD rename to crates/parser/testdata/expand_file_pattern/KCL_MOD diff --git a/kclvm/parser/testdata/expand_file_pattern/kcl.mod b/crates/parser/testdata/expand_file_pattern/kcl.mod similarity index 100% rename from kclvm/parser/testdata/expand_file_pattern/kcl.mod rename to crates/parser/testdata/expand_file_pattern/kcl.mod diff --git a/kclvm/parser/testdata/expand_file_pattern/kcl1/kcl.mod b/crates/parser/testdata/expand_file_pattern/kcl1/kcl.mod similarity index 100% rename from kclvm/parser/testdata/expand_file_pattern/kcl1/kcl.mod rename to crates/parser/testdata/expand_file_pattern/kcl1/kcl.mod diff --git a/kclvm/parser/testdata/expand_file_pattern/kcl1/kcl2/kcl.mod b/crates/parser/testdata/expand_file_pattern/kcl1/kcl2/kcl.mod similarity index 100% rename from kclvm/parser/testdata/expand_file_pattern/kcl1/kcl2/kcl.mod rename to crates/parser/testdata/expand_file_pattern/kcl1/kcl2/kcl.mod diff --git a/kclvm/parser/testdata/expand_file_pattern/kcl1/kcl2/main.k b/crates/parser/testdata/expand_file_pattern/kcl1/kcl2/main.k similarity index 100% rename from kclvm/parser/testdata/expand_file_pattern/kcl1/kcl2/main.k rename to crates/parser/testdata/expand_file_pattern/kcl1/kcl2/main.k diff --git a/kclvm/parser/testdata/expand_file_pattern/kcl1/kcl4/kcl.mod b/crates/parser/testdata/expand_file_pattern/kcl1/kcl4/kcl.mod similarity index 100% rename from kclvm/parser/testdata/expand_file_pattern/kcl1/kcl4/kcl.mod rename to crates/parser/testdata/expand_file_pattern/kcl1/kcl4/kcl.mod diff --git a/kclvm/parser/testdata/expand_file_pattern/kcl1/kcl4/main.k b/crates/parser/testdata/expand_file_pattern/kcl1/kcl4/main.k similarity index 100% rename from kclvm/parser/testdata/expand_file_pattern/kcl1/kcl4/main.k rename to crates/parser/testdata/expand_file_pattern/kcl1/kcl4/main.k diff --git a/kclvm/parser/testdata/expand_file_pattern/kcl1/main.k b/crates/parser/testdata/expand_file_pattern/kcl1/main.k similarity index 100% rename from kclvm/parser/testdata/expand_file_pattern/kcl1/main.k rename to crates/parser/testdata/expand_file_pattern/kcl1/main.k diff --git a/kclvm/parser/testdata/expand_file_pattern/kcl3/kcl.mod b/crates/parser/testdata/expand_file_pattern/kcl3/kcl.mod similarity index 100% rename from kclvm/parser/testdata/expand_file_pattern/kcl3/kcl.mod rename to crates/parser/testdata/expand_file_pattern/kcl3/kcl.mod diff --git a/kclvm/parser/testdata/expand_file_pattern/kcl3/main.k b/crates/parser/testdata/expand_file_pattern/kcl3/main.k similarity index 100% rename from kclvm/parser/testdata/expand_file_pattern/kcl3/main.k rename to crates/parser/testdata/expand_file_pattern/kcl3/main.k diff --git a/kclvm/parser/testdata/expand_file_pattern/main.k b/crates/parser/testdata/expand_file_pattern/main.k similarity index 100% rename from kclvm/parser/testdata/expand_file_pattern/main.k rename to crates/parser/testdata/expand_file_pattern/main.k diff --git a/kclvm/parser/testdata/hello_win.k b/crates/parser/testdata/hello_win.k similarity index 100% rename from kclvm/parser/testdata/hello_win.k rename to crates/parser/testdata/hello_win.k diff --git a/kclvm/parser/testdata/if-01.k b/crates/parser/testdata/if-01.k similarity index 100% rename from kclvm/parser/testdata/if-01.k rename to crates/parser/testdata/if-01.k diff --git a/kclvm/parser/testdata/if-02.k b/crates/parser/testdata/if-02.k similarity index 100% rename from kclvm/parser/testdata/if-02.k rename to crates/parser/testdata/if-02.k diff --git a/kclvm/parser/testdata/if-03.k b/crates/parser/testdata/if-03.k similarity index 100% rename from kclvm/parser/testdata/if-03.k rename to crates/parser/testdata/if-03.k diff --git a/kclvm/parser/testdata/import-01.k b/crates/parser/testdata/import-01.k similarity index 100% rename from kclvm/parser/testdata/import-01.k rename to crates/parser/testdata/import-01.k diff --git a/kclvm/parser/testdata/import_vendor/assign.k b/crates/parser/testdata/import_vendor/assign.k similarity index 100% rename from kclvm/parser/testdata/import_vendor/assign.k rename to crates/parser/testdata/import_vendor/assign.k diff --git a/kclvm/parser/testdata/import_vendor/config_expr.k b/crates/parser/testdata/import_vendor/config_expr.k similarity index 100% rename from kclvm/parser/testdata/import_vendor/config_expr.k rename to crates/parser/testdata/import_vendor/config_expr.k diff --git a/kclvm/parser/testdata/import_vendor/nested_vendor.k b/crates/parser/testdata/import_vendor/nested_vendor.k similarity index 100% rename from kclvm/parser/testdata/import_vendor/nested_vendor.k rename to crates/parser/testdata/import_vendor/nested_vendor.k diff --git a/kclvm/parser/testdata/import_vendor/same_name.k b/crates/parser/testdata/import_vendor/same_name.k similarity index 100% rename from kclvm/parser/testdata/import_vendor/same_name.k rename to crates/parser/testdata/import_vendor/same_name.k diff --git a/kclvm/parser/testdata/import_vendor/subpkg.k b/crates/parser/testdata/import_vendor/subpkg.k similarity index 100% rename from kclvm/parser/testdata/import_vendor/subpkg.k rename to crates/parser/testdata/import_vendor/subpkg.k diff --git a/kclvm/parser/testdata/kcl.mod b/crates/parser/testdata/kcl.mod similarity index 100% rename from kclvm/parser/testdata/kcl.mod rename to crates/parser/testdata/kcl.mod diff --git a/kclvm/parser/testdata/parse_all_modules/a/kcl.mod b/crates/parser/testdata/parse_all_modules/a/kcl.mod similarity index 100% rename from kclvm/parser/testdata/parse_all_modules/a/kcl.mod rename to crates/parser/testdata/parse_all_modules/a/kcl.mod diff --git a/kclvm/parser/testdata/parse_all_modules/a/main.k b/crates/parser/testdata/parse_all_modules/a/main.k similarity index 100% rename from kclvm/parser/testdata/parse_all_modules/a/main.k rename to crates/parser/testdata/parse_all_modules/a/main.k diff --git a/kclvm/parser/testdata/parse_all_modules/a/sub/sub.k b/crates/parser/testdata/parse_all_modules/a/sub/sub.k similarity index 100% rename from kclvm/parser/testdata/parse_all_modules/a/sub/sub.k rename to crates/parser/testdata/parse_all_modules/a/sub/sub.k diff --git a/kclvm/parser/testdata/parse_all_modules/b/kcl.mod b/crates/parser/testdata/parse_all_modules/b/kcl.mod similarity index 100% rename from kclvm/parser/testdata/parse_all_modules/b/kcl.mod rename to crates/parser/testdata/parse_all_modules/b/kcl.mod diff --git a/kclvm/parser/testdata/parse_all_modules/b/main.k b/crates/parser/testdata/parse_all_modules/b/main.k similarity index 100% rename from kclvm/parser/testdata/parse_all_modules/b/main.k rename to crates/parser/testdata/parse_all_modules/b/main.k diff --git a/kclvm/parser/testdata/parse_all_modules/helloworld_0.0.1/README.md b/crates/parser/testdata/parse_all_modules/helloworld_0.0.1/README.md similarity index 100% rename from kclvm/parser/testdata/parse_all_modules/helloworld_0.0.1/README.md rename to crates/parser/testdata/parse_all_modules/helloworld_0.0.1/README.md diff --git a/kclvm/parser/testdata/parse_all_modules/helloworld_0.0.1/kcl.mod b/crates/parser/testdata/parse_all_modules/helloworld_0.0.1/kcl.mod similarity index 100% rename from kclvm/parser/testdata/parse_all_modules/helloworld_0.0.1/kcl.mod rename to crates/parser/testdata/parse_all_modules/helloworld_0.0.1/kcl.mod diff --git a/kclvm/parser/testdata/parse_all_modules/helloworld_0.0.1/main.k b/crates/parser/testdata/parse_all_modules/helloworld_0.0.1/main.k similarity index 100% rename from kclvm/parser/testdata/parse_all_modules/helloworld_0.0.1/main.k rename to crates/parser/testdata/parse_all_modules/helloworld_0.0.1/main.k diff --git a/kclvm/parser/testdata/same_vendor/kcl.mod b/crates/parser/testdata/same_vendor/kcl.mod similarity index 100% rename from kclvm/parser/testdata/same_vendor/kcl.mod rename to crates/parser/testdata/same_vendor/kcl.mod diff --git a/kclvm/parser/testdata/same_vendor/same_vendor.k b/crates/parser/testdata/same_vendor/same_vendor.k similarity index 100% rename from kclvm/parser/testdata/same_vendor/same_vendor.k rename to crates/parser/testdata/same_vendor/same_vendor.k diff --git a/kclvm/parser/testdata/subpkg/a1.k b/crates/parser/testdata/subpkg/a1.k similarity index 100% rename from kclvm/parser/testdata/subpkg/a1.k rename to crates/parser/testdata/subpkg/a1.k diff --git a/kclvm/parser/testdata/subpkg/a2.k b/crates/parser/testdata/subpkg/a2.k similarity index 100% rename from kclvm/parser/testdata/subpkg/a2.k rename to crates/parser/testdata/subpkg/a2.k diff --git a/kclvm/parser/testdata/subpkg/a3.k b/crates/parser/testdata/subpkg/a3.k similarity index 100% rename from kclvm/parser/testdata/subpkg/a3.k rename to crates/parser/testdata/subpkg/a3.k diff --git a/kclvm/parser/testdata/subpkg/b1/c1.k b/crates/parser/testdata/subpkg/b1/c1.k similarity index 100% rename from kclvm/parser/testdata/subpkg/b1/c1.k rename to crates/parser/testdata/subpkg/b1/c1.k diff --git a/kclvm/parser/testdata/test_vendor/assign/assign.k b/crates/parser/testdata/test_vendor/assign/assign.k similarity index 100% rename from kclvm/parser/testdata/test_vendor/assign/assign.k rename to crates/parser/testdata/test_vendor/assign/assign.k diff --git a/kclvm/parser/testdata/test_vendor/assign/kcl.mod b/crates/parser/testdata/test_vendor/assign/kcl.mod similarity index 100% rename from kclvm/parser/testdata/test_vendor/assign/kcl.mod rename to crates/parser/testdata/test_vendor/assign/kcl.mod diff --git a/kclvm/parser/testdata/test_vendor/config_expr/config_expr_02.k b/crates/parser/testdata/test_vendor/config_expr/config_expr_02.k similarity index 100% rename from kclvm/parser/testdata/test_vendor/config_expr/config_expr_02.k rename to crates/parser/testdata/test_vendor/config_expr/config_expr_02.k diff --git a/kclvm/parser/testdata/test_vendor/config_expr/kcl.mod b/crates/parser/testdata/test_vendor/config_expr/kcl.mod similarity index 100% rename from kclvm/parser/testdata/test_vendor/config_expr/kcl.mod rename to crates/parser/testdata/test_vendor/config_expr/kcl.mod diff --git a/kclvm/parser/testdata/test_vendor/nested_vendor/kcl.mod b/crates/parser/testdata/test_vendor/nested_vendor/kcl.mod similarity index 100% rename from kclvm/parser/testdata/test_vendor/nested_vendor/kcl.mod rename to crates/parser/testdata/test_vendor/nested_vendor/kcl.mod diff --git a/kclvm/parser/testdata/test_vendor/nested_vendor/nested_vendor.k b/crates/parser/testdata/test_vendor/nested_vendor/nested_vendor.k similarity index 100% rename from kclvm/parser/testdata/test_vendor/nested_vendor/nested_vendor.k rename to crates/parser/testdata/test_vendor/nested_vendor/nested_vendor.k diff --git a/kclvm/parser/testdata/test_vendor/nested_vendor/sub/sub.k b/crates/parser/testdata/test_vendor/nested_vendor/sub/sub.k similarity index 100% rename from kclvm/parser/testdata/test_vendor/nested_vendor/sub/sub.k rename to crates/parser/testdata/test_vendor/nested_vendor/sub/sub.k diff --git a/kclvm/parser/testdata/test_vendor/nested_vendor/sub/sub1.k b/crates/parser/testdata/test_vendor/nested_vendor/sub/sub1.k similarity index 100% rename from kclvm/parser/testdata/test_vendor/nested_vendor/sub/sub1.k rename to crates/parser/testdata/test_vendor/nested_vendor/sub/sub1.k diff --git a/kclvm/parser/testdata/test_vendor/nested_vendor/sub/sub2/sub2.k b/crates/parser/testdata/test_vendor/nested_vendor/sub/sub2/sub2.k similarity index 100% rename from kclvm/parser/testdata/test_vendor/nested_vendor/sub/sub2/sub2.k rename to crates/parser/testdata/test_vendor/nested_vendor/sub/sub2/sub2.k diff --git a/kclvm/parser/testdata/test_vendor/same_vendor/kcl.mod b/crates/parser/testdata/test_vendor/same_vendor/kcl.mod similarity index 100% rename from kclvm/parser/testdata/test_vendor/same_vendor/kcl.mod rename to crates/parser/testdata/test_vendor/same_vendor/kcl.mod diff --git a/kclvm/parser/testdata/test_vendor/same_vendor/same_vendor.k b/crates/parser/testdata/test_vendor/same_vendor/same_vendor.k similarity index 100% rename from kclvm/parser/testdata/test_vendor/same_vendor/same_vendor.k rename to crates/parser/testdata/test_vendor/same_vendor/same_vendor.k diff --git a/kclvm/parser/testdata/test_vendor/vendor_subpkg/kcl.mod b/crates/parser/testdata/test_vendor/vendor_subpkg/kcl.mod similarity index 100% rename from kclvm/parser/testdata/test_vendor/vendor_subpkg/kcl.mod rename to crates/parser/testdata/test_vendor/vendor_subpkg/kcl.mod diff --git a/kclvm/parser/testdata/test_vendor/vendor_subpkg/sub/sub.k b/crates/parser/testdata/test_vendor/vendor_subpkg/sub/sub.k similarity index 100% rename from kclvm/parser/testdata/test_vendor/vendor_subpkg/sub/sub.k rename to crates/parser/testdata/test_vendor/vendor_subpkg/sub/sub.k diff --git a/kclvm/parser/testdata/test_vendor/vendor_subpkg/sub/sub1.k b/crates/parser/testdata/test_vendor/vendor_subpkg/sub/sub1.k similarity index 100% rename from kclvm/parser/testdata/test_vendor/vendor_subpkg/sub/sub1.k rename to crates/parser/testdata/test_vendor/vendor_subpkg/sub/sub1.k diff --git a/kclvm/parser/testdata/test_vendor/vendor_subpkg/sub/sub2/sub2.k b/crates/parser/testdata/test_vendor/vendor_subpkg/sub/sub2/sub2.k similarity index 100% rename from kclvm/parser/testdata/test_vendor/vendor_subpkg/sub/sub2/sub2.k rename to crates/parser/testdata/test_vendor/vendor_subpkg/sub/sub2/sub2.k diff --git a/kclvm/parser/testdata/test_vendor/vendor_subpkg/vendor_subpkg.k b/crates/parser/testdata/test_vendor/vendor_subpkg/vendor_subpkg.k similarity index 100% rename from kclvm/parser/testdata/test_vendor/vendor_subpkg/vendor_subpkg.k rename to crates/parser/testdata/test_vendor/vendor_subpkg/vendor_subpkg.k diff --git a/kclvm/parser/testdata/type-01.k b/crates/parser/testdata/type-01.k similarity index 100% rename from kclvm/parser/testdata/type-01.k rename to crates/parser/testdata/type-01.k diff --git a/kclvm/parser/testdata_without_kclmod/import_by_external_assign.k b/crates/parser/testdata_without_kclmod/import_by_external_assign.k similarity index 100% rename from kclvm/parser/testdata_without_kclmod/import_by_external_assign.k rename to crates/parser/testdata_without_kclmod/import_by_external_assign.k diff --git a/kclvm/parser/testdata_without_kclmod/import_by_external_config_expr.k b/crates/parser/testdata_without_kclmod/import_by_external_config_expr.k similarity index 100% rename from kclvm/parser/testdata_without_kclmod/import_by_external_config_expr.k rename to crates/parser/testdata_without_kclmod/import_by_external_config_expr.k diff --git a/kclvm/parser/testdata_without_kclmod/import_by_external_nested_vendor.k b/crates/parser/testdata_without_kclmod/import_by_external_nested_vendor.k similarity index 100% rename from kclvm/parser/testdata_without_kclmod/import_by_external_nested_vendor.k rename to crates/parser/testdata_without_kclmod/import_by_external_nested_vendor.k diff --git a/kclvm/parser/testdata_without_kclmod/import_by_external_vendor_subpkg.k b/crates/parser/testdata_without_kclmod/import_by_external_vendor_subpkg.k similarity index 100% rename from kclvm/parser/testdata_without_kclmod/import_by_external_vendor_subpkg.k rename to crates/parser/testdata_without_kclmod/import_by_external_vendor_subpkg.k diff --git a/kclvm/parser/testdata_without_kclmod/import_vendor.k b/crates/parser/testdata_without_kclmod/import_vendor.k similarity index 100% rename from kclvm/parser/testdata_without_kclmod/import_vendor.k rename to crates/parser/testdata_without_kclmod/import_vendor.k diff --git a/kclvm/parser/testdata_without_kclmod/same_name/assign.k b/crates/parser/testdata_without_kclmod/same_name/assign.k similarity index 100% rename from kclvm/parser/testdata_without_kclmod/same_name/assign.k rename to crates/parser/testdata_without_kclmod/same_name/assign.k diff --git a/crates/primitives/Cargo.toml b/crates/primitives/Cargo.toml new file mode 100644 index 000000000..84b8241af --- /dev/null +++ b/crates/primitives/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "kcl-primitives" +version.workspace = true +edition.workspace = true + +[dependencies] +indexmap = "2.9.0" +rustc-hash = "2.1.1" diff --git a/kclvm/primitives/src/lib.rs b/crates/primitives/src/lib.rs similarity index 100% rename from kclvm/primitives/src/lib.rs rename to crates/primitives/src/lib.rs diff --git a/kclvm/primitives/src/map.rs b/crates/primitives/src/map.rs similarity index 100% rename from kclvm/primitives/src/map.rs rename to crates/primitives/src/map.rs diff --git a/crates/query/Cargo.toml b/crates/query/Cargo.toml new file mode 100644 index 000000000..f4ff12cb5 --- /dev/null +++ b/crates/query/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "kcl-query" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +anyhow = "1.0" +compiler_base_session = "0.1.3" +compiler_base_macros = "0.1.1" + +kcl-ast = { path = "../ast" } +kcl-ast-pretty = { path = "../ast_pretty" } +kcl-parser = { path = "../parser" } +kcl-sema = { path = "../sema" } +kcl-error = { path = "../error" } +kcl-utils = { path = "../utils" } +kcl-primitives = { path = "../primitives" } +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +fancy-regex = "0.7.1" +maplit = "1.0.2" + +[dev-dependencies] +pretty_assertions = "1.2.1" +insta = "1.8.0" diff --git a/crates/query/src/lib.rs b/crates/query/src/lib.rs new file mode 100644 index 000000000..97586964c --- /dev/null +++ b/crates/query/src/lib.rs @@ -0,0 +1,113 @@ +//! This package is mainly the implementation of the KCL query tool, mainly including +//! KCL code modification `override` and other implementations. We can call the `override_file` +//! function to modify the file. The main principle is to parse the AST according to the +//! input file name, and according to the ast::OverrideSpec transforms the nodes in the +//! AST, recursively modifying or deleting the values of the nodes in the AST. +pub mod node; +pub mod r#override; +pub mod path; +pub mod query; +pub mod selector; + +#[cfg(test)] +mod tests; +mod util; + +use anyhow::{Result, anyhow}; +use kcl_ast_pretty::print_ast_module; +use kcl_error::diagnostic::Errors; +use kcl_parser::parse_single_file; + +use kcl_sema::pre_process::fix_config_expr_nest_attr; +pub use r#override::{apply_override_on_module, apply_overrides}; +pub use query::{GetSchemaOption, get_schema_type}; + +/// Override and rewrite a file with override specifications. Please note that this is an external user API, +/// and it can directly modify the KCL file in place. +/// +/// # Parameters +/// +/// `file`: [&str] +/// The File that need to be overridden +/// +/// `specs`: &\[[String]\] +/// List of specs that need to be overridden. +/// Each spec string satisfies the form: := or :- +/// When the pkgpath is '__main__', `:` can be omitted. +/// +/// `import_paths`: &\[[String]\] +/// List of import paths that are need to be added. +/// +/// # Returns +/// +/// result: [Result] +/// Whether the file has been modified. +/// +/// # Examples +/// +/// ```no_run +/// use kcl_query::override_file; +/// +/// let result = override_file( +/// "test.k", +/// &["alice.age=18".to_string()], +/// &[] +/// ).unwrap(); +/// ``` +/// +/// - test.k (before override) +/// +/// ```kcl +/// schema Person: +/// age: int +/// +/// alice = Person { +/// age = 10 +/// } +/// ``` +/// +/// - test.k (after override) +/// +/// ```kcl +/// schema Person: +/// age: int +/// +/// alice = Person { +/// age = 18 +/// } +/// ``` +pub fn override_file( + file: &str, + specs: &[String], + import_paths: &[String], +) -> Result { + // Parse file to AST module. + let mut parse_result = match parse_single_file(file, None) { + Ok(module) => module, + Err(msg) => return Err(anyhow!("{}", msg)), + }; + let mut result = false; + // Override AST module. + for s in specs { + if apply_override_on_module(&mut parse_result.module, s, import_paths)? { + result = true; + } + } + + // Transform config expr to simplify the config path query and override. + fix_config_expr_nest_attr(&mut parse_result.module); + // Print AST module. + if result { + let code_str = print_ast_module(&parse_result.module); + std::fs::write(file, code_str)? + } + Ok(OverrideFileResult { + result, + parse_errors: parse_result.errors, + }) +} + +pub struct OverrideFileResult { + pub result: bool, + pub parse_errors: Errors, +} diff --git a/kclvm/query/src/main.k b/crates/query/src/main.k similarity index 100% rename from kclvm/query/src/main.k rename to crates/query/src/main.k diff --git a/crates/query/src/node.rs b/crates/query/src/node.rs new file mode 100644 index 000000000..b06e5fef2 --- /dev/null +++ b/crates/query/src/node.rs @@ -0,0 +1,765 @@ +use kcl_ast::{ + ast::{self}, + walker::MutSelfMutWalker, +}; + +use kcl_ast::walk_if_mut; +use kcl_ast::walk_list_mut; + +/// `AstNodeMover` will move the AST node by offset +pub struct AstNodeMover { + pub line_offset: usize, +} + +impl<'ctx> MutSelfMutWalker<'ctx> for AstNodeMover { + fn walk_expr_stmt(&mut self, expr_stmt: &'ctx mut ast::ExprStmt) { + for expr in expr_stmt.exprs.iter_mut() { + expr.line += self.line_offset as u64; + expr.end_line += self.line_offset as u64; + } + + for expr in expr_stmt.exprs.iter_mut() { + self.walk_expr(&mut expr.node) + } + } + fn walk_type_alias_stmt(&mut self, type_alias_stmt: &'ctx mut ast::TypeAliasStmt) { + type_alias_stmt.type_name.line += self.line_offset as u64; + type_alias_stmt.type_name.end_line += self.line_offset as u64; + + type_alias_stmt.ty.line += self.line_offset as u64; + type_alias_stmt.ty.end_line += self.line_offset as u64; + + self.walk_identifier(&mut type_alias_stmt.type_name.node); + self.walk_type(&mut type_alias_stmt.ty.node); + } + fn walk_unification_stmt(&mut self, unification_stmt: &'ctx mut ast::UnificationStmt) { + unification_stmt.target.line += self.line_offset as u64; + unification_stmt.target.end_line += self.line_offset as u64; + + unification_stmt.value.line += self.line_offset as u64; + unification_stmt.value.end_line += self.line_offset as u64; + + self.walk_identifier(&mut unification_stmt.target.node); + self.walk_schema_expr(&mut unification_stmt.value.node); + } + fn walk_assign_stmt(&mut self, assign_stmt: &'ctx mut ast::AssignStmt) { + for target in assign_stmt.targets.iter_mut() { + target.line += self.line_offset as u64; + target.end_line += self.line_offset as u64; + } + + assign_stmt.value.line += self.line_offset as u64; + assign_stmt.value.end_line += self.line_offset as u64; + + match assign_stmt.ty.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + for target in assign_stmt.targets.iter_mut() { + self.walk_target(&mut target.node) + } + self.walk_expr(&mut assign_stmt.value.node); + walk_if_mut!(self, walk_type, assign_stmt.ty) + } + fn walk_aug_assign_stmt(&mut self, aug_assign_stmt: &'ctx mut ast::AugAssignStmt) { + aug_assign_stmt.target.line += self.line_offset as u64; + aug_assign_stmt.target.end_line += self.line_offset as u64; + + aug_assign_stmt.value.line += self.line_offset as u64; + aug_assign_stmt.value.end_line += self.line_offset as u64; + + self.walk_target(&mut aug_assign_stmt.target.node); + self.walk_expr(&mut aug_assign_stmt.value.node); + } + fn walk_assert_stmt(&mut self, assert_stmt: &'ctx mut ast::AssertStmt) { + assert_stmt.test.line += self.line_offset as u64; + assert_stmt.test.end_line += self.line_offset as u64; + + match assert_stmt.if_cond.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + match assert_stmt.msg.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + self.walk_expr(&mut assert_stmt.test.node); + walk_if_mut!(self, walk_expr, assert_stmt.if_cond); + walk_if_mut!(self, walk_expr, assert_stmt.msg); + } + fn walk_if_stmt(&mut self, if_stmt: &'ctx mut ast::IfStmt) { + if_stmt.cond.line += self.line_offset as u64; + if_stmt.cond.end_line += self.line_offset as u64; + + for stmt in if_stmt.body.iter_mut() { + stmt.line += self.line_offset as u64; + stmt.end_line += self.line_offset as u64; + } + + for stmt in if_stmt.orelse.iter_mut() { + stmt.line += self.line_offset as u64; + stmt.end_line += self.line_offset as u64; + } + + self.walk_expr(&mut if_stmt.cond.node); + walk_list_mut!(self, walk_stmt, if_stmt.body); + walk_list_mut!(self, walk_stmt, if_stmt.orelse); + } + fn walk_import_stmt(&mut self, _import_stmt: &'ctx mut ast::ImportStmt) { + // Nothing to do + } + fn walk_schema_attr(&mut self, schema_attr: &'ctx mut ast::SchemaAttr) { + schema_attr.name.line += self.line_offset as u64; + schema_attr.name.end_line += self.line_offset as u64; + + match schema_attr.value.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + schema_attr.decorators.iter_mut().for_each(|d| { + d.line += self.line_offset as u64; + d.end_line += self.line_offset as u64; + }); + + schema_attr.ty.line += self.line_offset as u64; + schema_attr.ty.end_line += self.line_offset as u64; + + walk_list_mut!(self, walk_call_expr, schema_attr.decorators); + walk_if_mut!(self, walk_expr, schema_attr.value); + self.walk_type(&mut schema_attr.ty.node); + } + + fn walk_type(&mut self, ty: &'ctx mut ast::Type) { + match ty { + ast::Type::Named(id) => self.walk_identifier(id), + ast::Type::List(list_ty) => { + if let Some(ty) = &mut list_ty.inner_type { + ty.line += self.line_offset as u64; + ty.end_line += self.line_offset as u64; + self.walk_type(&mut ty.node) + } + } + ast::Type::Dict(dict_ty) => { + if let Some(ty) = &mut dict_ty.key_type { + ty.line += self.line_offset as u64; + ty.end_line += self.line_offset as u64; + self.walk_type(&mut ty.node) + } + if let Some(ty) = &mut dict_ty.value_type { + ty.line += self.line_offset as u64; + ty.end_line += self.line_offset as u64; + self.walk_type(&mut ty.node) + } + } + ast::Type::Union(union_ty) => { + union_ty.type_elements.iter_mut().for_each(|ty| { + ty.line += self.line_offset as u64; + ty.end_line += self.line_offset as u64; + self.walk_type(&mut ty.node) + }); + } + _ => {} + } + } + fn walk_schema_stmt(&mut self, schema_stmt: &'ctx mut ast::SchemaStmt) { + schema_stmt.name.line += self.line_offset as u64; + schema_stmt.name.end_line += self.line_offset as u64; + + match schema_stmt.parent_name.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + match schema_stmt.for_host_name.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + for arg in schema_stmt.args.iter_mut() { + arg.line += self.line_offset as u64; + arg.end_line += self.line_offset as u64; + } + + if let Some(schema_index_signature) = schema_stmt.index_signature.as_deref_mut() { + let value = &mut schema_index_signature.node.value; + match value.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + } + + schema_stmt.mixins.iter_mut().for_each(|m| { + m.line += self.line_offset as u64; + m.end_line += self.line_offset as u64; + }); + + schema_stmt.decorators.iter_mut().for_each(|d| { + d.line += self.line_offset as u64; + d.end_line += self.line_offset as u64; + }); + + schema_stmt.checks.iter_mut().for_each(|c| { + c.line += self.line_offset as u64; + c.end_line += self.line_offset as u64; + }); + + schema_stmt.body.iter_mut().for_each(|s| { + s.line += self.line_offset as u64; + s.end_line += self.line_offset as u64; + }); + + walk_if_mut!(self, walk_identifier, schema_stmt.parent_name); + walk_if_mut!(self, walk_identifier, schema_stmt.for_host_name); + walk_if_mut!(self, walk_arguments, schema_stmt.args); + if let Some(schema_index_signature) = schema_stmt.index_signature.as_deref_mut() { + let value = &mut schema_index_signature.node.value; + walk_if_mut!(self, walk_expr, value); + } + walk_list_mut!(self, walk_identifier, schema_stmt.mixins); + walk_list_mut!(self, walk_call_expr, schema_stmt.decorators); + walk_list_mut!(self, walk_check_expr, schema_stmt.checks); + walk_list_mut!(self, walk_stmt, schema_stmt.body); + } + fn walk_rule_stmt(&mut self, rule_stmt: &'ctx mut ast::RuleStmt) { + rule_stmt.name.line += self.line_offset as u64; + rule_stmt.name.end_line += self.line_offset as u64; + + rule_stmt.parent_rules.iter_mut().for_each(|p| { + p.line += self.line_offset as u64; + p.end_line += self.line_offset as u64; + }); + + rule_stmt.decorators.iter_mut().for_each(|d| { + d.line += self.line_offset as u64; + d.end_line += self.line_offset as u64; + }); + + rule_stmt.checks.iter_mut().for_each(|c| { + c.line += self.line_offset as u64; + c.end_line += self.line_offset as u64; + }); + + rule_stmt.args.iter_mut().for_each(|a| { + a.line += self.line_offset as u64; + a.end_line += self.line_offset as u64; + }); + + match rule_stmt.for_host_name.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + walk_list_mut!(self, walk_identifier, rule_stmt.parent_rules); + walk_list_mut!(self, walk_call_expr, rule_stmt.decorators); + walk_list_mut!(self, walk_check_expr, rule_stmt.checks); + walk_if_mut!(self, walk_arguments, rule_stmt.args); + walk_if_mut!(self, walk_identifier, rule_stmt.for_host_name); + } + fn walk_quant_expr(&mut self, quant_expr: &'ctx mut ast::QuantExpr) { + quant_expr.target.line += self.line_offset as u64; + quant_expr.target.end_line += self.line_offset as u64; + + quant_expr.variables.iter_mut().for_each(|v| { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + }); + + quant_expr.test.line += self.line_offset as u64; + quant_expr.test.end_line += self.line_offset as u64; + + match quant_expr.if_cond.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + self.walk_expr(&mut quant_expr.target.node); + walk_list_mut!(self, walk_identifier, quant_expr.variables); + self.walk_expr(&mut quant_expr.test.node); + walk_if_mut!(self, walk_expr, quant_expr.if_cond); + } + fn walk_if_expr(&mut self, if_expr: &'ctx mut ast::IfExpr) { + if_expr.cond.line += self.line_offset as u64; + if_expr.cond.end_line += self.line_offset as u64; + + if_expr.body.line += self.line_offset as u64; + if_expr.body.end_line += self.line_offset as u64; + + if_expr.orelse.line += self.line_offset as u64; + if_expr.orelse.end_line += self.line_offset as u64; + + self.walk_expr(&mut if_expr.cond.node); + self.walk_expr(&mut if_expr.body.node); + self.walk_expr(&mut if_expr.orelse.node); + } + fn walk_unary_expr(&mut self, unary_expr: &'ctx mut ast::UnaryExpr) { + unary_expr.operand.line += self.line_offset as u64; + unary_expr.operand.end_line += self.line_offset as u64; + + self.walk_expr(&mut unary_expr.operand.node); + } + fn walk_binary_expr(&mut self, binary_expr: &'ctx mut ast::BinaryExpr) { + binary_expr.left.line += self.line_offset as u64; + binary_expr.left.end_line += self.line_offset as u64; + + self.walk_expr(&mut binary_expr.left.node); + self.walk_expr(&mut binary_expr.right.node); + } + fn walk_selector_expr(&mut self, selector_expr: &'ctx mut ast::SelectorExpr) { + selector_expr.value.line += self.line_offset as u64; + selector_expr.value.end_line += self.line_offset as u64; + + self.walk_expr(&mut selector_expr.value.node); + self.walk_identifier(&mut selector_expr.attr.node); + } + fn walk_call_expr(&mut self, call_expr: &'ctx mut ast::CallExpr) { + call_expr.func.line += self.line_offset as u64; + call_expr.func.end_line += self.line_offset as u64; + + call_expr.args.iter_mut().for_each(|a| { + a.line += self.line_offset as u64; + a.end_line += self.line_offset as u64; + }); + + call_expr.keywords.iter_mut().for_each(|k| { + k.line += self.line_offset as u64; + k.end_line += self.line_offset as u64; + }); + + self.walk_expr(&mut call_expr.func.node); + walk_list_mut!(self, walk_expr, call_expr.args); + walk_list_mut!(self, walk_keyword, call_expr.keywords); + } + fn walk_subscript(&mut self, subscript: &'ctx mut ast::Subscript) { + subscript.value.line += self.line_offset as u64; + subscript.value.end_line += self.line_offset as u64; + + match subscript.index.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + match subscript.lower.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + match subscript.upper.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + match subscript.step.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + self.walk_expr(&mut subscript.value.node); + walk_if_mut!(self, walk_expr, subscript.index); + walk_if_mut!(self, walk_expr, subscript.lower); + walk_if_mut!(self, walk_expr, subscript.upper); + walk_if_mut!(self, walk_expr, subscript.step); + } + fn walk_paren_expr(&mut self, paren_expr: &'ctx mut ast::ParenExpr) { + paren_expr.expr.line += self.line_offset as u64; + paren_expr.expr.end_line += self.line_offset as u64; + + self.walk_expr(&mut paren_expr.expr.node); + } + fn walk_list_expr(&mut self, list_expr: &'ctx mut ast::ListExpr) { + list_expr.elts.iter_mut().for_each(|e| { + e.line += self.line_offset as u64; + e.end_line += self.line_offset as u64; + }); + walk_list_mut!(self, walk_expr, list_expr.elts); + } + fn walk_list_comp(&mut self, list_comp: &'ctx mut ast::ListComp) { + list_comp.elt.line += self.line_offset as u64; + list_comp.elt.end_line += self.line_offset as u64; + + list_comp.generators.iter_mut().for_each(|g| { + g.line += self.line_offset as u64; + g.end_line += self.line_offset as u64; + }); + + self.walk_expr(&mut list_comp.elt.node); + walk_list_mut!(self, walk_comp_clause, list_comp.generators); + } + fn walk_list_if_item_expr(&mut self, list_if_item_expr: &'ctx mut ast::ListIfItemExpr) { + list_if_item_expr.if_cond.line += self.line_offset as u64; + list_if_item_expr.if_cond.end_line += self.line_offset as u64; + + list_if_item_expr.exprs.iter_mut().for_each(|e| { + e.line += self.line_offset as u64; + e.end_line += self.line_offset as u64; + }); + + match list_if_item_expr.orelse.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + self.walk_expr(&mut list_if_item_expr.if_cond.node); + walk_list_mut!(self, walk_expr, list_if_item_expr.exprs); + walk_if_mut!(self, walk_expr, list_if_item_expr.orelse); + } + fn walk_starred_expr(&mut self, starred_expr: &'ctx mut ast::StarredExpr) { + starred_expr.value.line += self.line_offset as u64; + starred_expr.value.end_line += self.line_offset as u64; + self.walk_expr(&mut starred_expr.value.node); + } + fn walk_dict_comp(&mut self, dict_comp: &'ctx mut ast::DictComp) { + if let Some(key) = &mut dict_comp.entry.key { + key.line += self.line_offset as u64; + key.end_line += self.line_offset as u64; + } + + dict_comp.entry.value.line += self.line_offset as u64; + dict_comp.entry.value.end_line += self.line_offset as u64; + + dict_comp.generators.iter_mut().for_each(|g| { + g.line += self.line_offset as u64; + g.end_line += self.line_offset as u64; + }); + + if let Some(key) = &mut dict_comp.entry.key { + self.walk_expr(&mut key.node); + } + self.walk_expr(&mut dict_comp.entry.value.node); + walk_list_mut!(self, walk_comp_clause, dict_comp.generators); + } + fn walk_config_if_entry_expr( + &mut self, + config_if_entry_expr: &'ctx mut ast::ConfigIfEntryExpr, + ) { + config_if_entry_expr.if_cond.line += self.line_offset as u64; + config_if_entry_expr.if_cond.end_line += self.line_offset as u64; + + for config_entry in config_if_entry_expr.items.iter_mut() { + match config_entry.node.key.as_deref_mut() { + Some(k) => { + k.line += self.line_offset as u64; + k.end_line += self.line_offset as u64; + } + None => (), + } + + config_entry.node.value.line += self.line_offset as u64; + } + + match config_if_entry_expr.orelse.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + self.walk_expr(&mut config_if_entry_expr.if_cond.node); + for config_entry in config_if_entry_expr.items.iter_mut() { + walk_if_mut!(self, walk_expr, config_entry.node.key); + self.walk_expr(&mut config_entry.node.value.node); + } + walk_if_mut!(self, walk_expr, config_if_entry_expr.orelse); + } + fn walk_comp_clause(&mut self, comp_clause: &'ctx mut ast::CompClause) { + comp_clause.iter.line += self.line_offset as u64; + comp_clause.iter.end_line += self.line_offset as u64; + + comp_clause.targets.iter_mut().for_each(|t| { + t.line += self.line_offset as u64; + t.end_line += self.line_offset as u64; + }); + + comp_clause.ifs.iter_mut().for_each(|i| { + i.line += self.line_offset as u64; + i.end_line += self.line_offset as u64; + }); + + walk_list_mut!(self, walk_identifier, comp_clause.targets); + self.walk_expr(&mut comp_clause.iter.node); + walk_list_mut!(self, walk_expr, comp_clause.ifs); + } + fn walk_schema_expr(&mut self, schema_expr: &'ctx mut ast::SchemaExpr) { + schema_expr.name.line += self.line_offset as u64; + schema_expr.name.end_line += self.line_offset as u64; + + schema_expr.args.iter_mut().for_each(|a| { + a.line += self.line_offset as u64; + a.end_line += self.line_offset as u64; + }); + + schema_expr.kwargs.iter_mut().for_each(|k| { + k.line += self.line_offset as u64; + k.end_line += self.line_offset as u64; + }); + + schema_expr.config.line += self.line_offset as u64; + schema_expr.config.end_line += self.line_offset as u64; + + self.walk_identifier(&mut schema_expr.name.node); + walk_list_mut!(self, walk_expr, schema_expr.args); + walk_list_mut!(self, walk_keyword, schema_expr.kwargs); + self.walk_expr(&mut schema_expr.config.node); + } + fn walk_config_expr(&mut self, config_expr: &'ctx mut ast::ConfigExpr) { + for config_entry in config_expr.items.iter_mut() { + match config_entry.node.key.as_deref_mut() { + Some(k) => { + k.line += self.line_offset as u64; + k.end_line += self.line_offset as u64; + } + None => (), + } + + config_entry.node.value.line += self.line_offset as u64; + } + + for config_entry in config_expr.items.iter_mut() { + walk_if_mut!(self, walk_expr, config_entry.node.key); + self.walk_expr(&mut config_entry.node.value.node); + } + } + fn walk_check_expr(&mut self, check_expr: &'ctx mut ast::CheckExpr) { + check_expr.test.line += self.line_offset as u64; + check_expr.test.end_line += self.line_offset as u64; + + match check_expr.if_cond.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + match check_expr.msg.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + self.walk_expr(&mut check_expr.test.node); + walk_if_mut!(self, walk_expr, check_expr.if_cond); + walk_if_mut!(self, walk_expr, check_expr.msg); + } + fn walk_lambda_expr(&mut self, lambda_expr: &'ctx mut ast::LambdaExpr) { + match lambda_expr.args.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + for stmt in lambda_expr.body.iter_mut() { + stmt.line += self.line_offset as u64; + stmt.end_line += self.line_offset as u64; + } + + match lambda_expr.return_ty.as_deref_mut() { + Some(v) => { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + None => (), + } + + walk_if_mut!(self, walk_arguments, lambda_expr.args); + walk_list_mut!(self, walk_stmt, lambda_expr.body); + walk_if_mut!(self, walk_type, lambda_expr.return_ty); + } + fn walk_keyword(&mut self, keyword: &'ctx mut ast::Keyword) { + keyword.arg.line += self.line_offset as u64; + keyword.arg.end_line += self.line_offset as u64; + + if let Some(v) = keyword.value.as_deref_mut() { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + } + + self.walk_identifier(&mut keyword.arg.node); + if let Some(v) = keyword.value.as_deref_mut() { + self.walk_expr(&mut v.node) + } + } + fn walk_arguments(&mut self, arguments: &'ctx mut ast::Arguments) { + arguments.args.iter_mut().for_each(|a| { + a.line += self.line_offset as u64; + a.end_line += self.line_offset as u64; + }); + + for default in arguments.defaults.iter_mut() { + if let Some(d) = default.as_deref_mut() { + d.line += self.line_offset as u64; + d.end_line += self.line_offset as u64; + } + } + for ty in arguments.ty_list.iter_mut() { + if let Some(ty) = ty.as_deref_mut() { + ty.line += self.line_offset as u64; + ty.end_line += self.line_offset as u64; + } + } + + walk_list_mut!(self, walk_identifier, arguments.args); + for default in arguments.defaults.iter_mut() { + if let Some(d) = default.as_deref_mut() { + self.walk_expr(&mut d.node) + } + } + for ty in arguments.ty_list.iter_mut() { + if let Some(ty) = ty.as_deref_mut() { + self.walk_type(&mut ty.node); + } + } + } + fn walk_compare(&mut self, compare: &'ctx mut ast::Compare) { + compare.left.line += self.line_offset as u64; + compare.left.end_line += self.line_offset as u64; + + for comparator in compare.comparators.iter_mut() { + comparator.line += self.line_offset as u64; + comparator.end_line += self.line_offset as u64; + } + + self.walk_expr(&mut compare.left.node); + walk_list_mut!(self, walk_expr, compare.comparators); + } + fn walk_joined_string(&mut self, joined_string: &'ctx mut ast::JoinedString) { + joined_string.values.iter_mut().for_each(|v| { + v.line += self.line_offset as u64; + v.end_line += self.line_offset as u64; + }); + + walk_list_mut!(self, walk_expr, joined_string.values); + } + fn walk_formatted_value(&mut self, formatted_value: &'ctx mut ast::FormattedValue) { + formatted_value.value.line += self.line_offset as u64; + formatted_value.value.end_line += self.line_offset as u64; + + self.walk_expr(&mut formatted_value.value.node); + } + fn walk_module(&mut self, module: &'ctx mut ast::Module) { + module.comments.iter_mut().for_each(|c| { + c.line += self.line_offset as u64; + c.end_line += self.line_offset as u64; + }); + + for stmt in module.body.iter_mut() { + if let ast::Stmt::Import(_) = stmt.node { + continue; + } + + stmt.line += self.line_offset as u64; + stmt.end_line += self.line_offset as u64; + + self.walk_stmt(&mut stmt.node) + } + } + fn walk_stmt(&mut self, stmt: &'ctx mut ast::Stmt) { + match stmt { + ast::Stmt::TypeAlias(type_alias) => self.walk_type_alias_stmt(type_alias), + ast::Stmt::Expr(expr_stmt) => self.walk_expr_stmt(expr_stmt), + ast::Stmt::Unification(unification_stmt) => { + self.walk_unification_stmt(unification_stmt) + } + ast::Stmt::Assign(assign_stmt) => self.walk_assign_stmt(assign_stmt), + ast::Stmt::AugAssign(aug_assign_stmt) => self.walk_aug_assign_stmt(aug_assign_stmt), + ast::Stmt::Assert(assert_stmt) => self.walk_assert_stmt(assert_stmt), + ast::Stmt::If(if_stmt) => self.walk_if_stmt(if_stmt), + ast::Stmt::Import(import_stmt) => self.walk_import_stmt(import_stmt), + ast::Stmt::SchemaAttr(schema_attr) => self.walk_schema_attr(schema_attr), + ast::Stmt::Schema(schema_stmt) => self.walk_schema_stmt(schema_stmt), + ast::Stmt::Rule(rule_stmt) => self.walk_rule_stmt(rule_stmt), + } + } + fn walk_expr(&mut self, expr: &'ctx mut ast::Expr) { + match expr { + ast::Expr::Target(target) => self.walk_target(target), + ast::Expr::Identifier(identifier) => self.walk_identifier(identifier), + ast::Expr::Unary(unary_expr) => self.walk_unary_expr(unary_expr), + ast::Expr::Binary(binary_expr) => self.walk_binary_expr(binary_expr), + ast::Expr::If(if_expr) => self.walk_if_expr(if_expr), + ast::Expr::Selector(selector_expr) => self.walk_selector_expr(selector_expr), + ast::Expr::Call(call_expr) => self.walk_call_expr(call_expr), + ast::Expr::Paren(paren_expr) => self.walk_paren_expr(paren_expr), + ast::Expr::Quant(quant_expr) => self.walk_quant_expr(quant_expr), + ast::Expr::List(list_expr) => self.walk_list_expr(list_expr), + ast::Expr::ListIfItem(list_if_item_expr) => { + self.walk_list_if_item_expr(list_if_item_expr) + } + ast::Expr::ListComp(list_comp) => self.walk_list_comp(list_comp), + ast::Expr::Starred(starred_expr) => self.walk_starred_expr(starred_expr), + ast::Expr::DictComp(dict_comp) => self.walk_dict_comp(dict_comp), + ast::Expr::ConfigIfEntry(config_if_entry_expr) => { + self.walk_config_if_entry_expr(config_if_entry_expr) + } + ast::Expr::CompClause(comp_clause) => self.walk_comp_clause(comp_clause), + ast::Expr::Schema(schema_expr) => self.walk_schema_expr(schema_expr), + ast::Expr::Config(config_expr) => self.walk_config_expr(config_expr), + ast::Expr::Check(check) => self.walk_check_expr(check), + ast::Expr::Lambda(lambda) => self.walk_lambda_expr(lambda), + ast::Expr::Subscript(subscript) => self.walk_subscript(subscript), + ast::Expr::Keyword(keyword) => self.walk_keyword(keyword), + ast::Expr::Arguments(arguments) => self.walk_arguments(arguments), + ast::Expr::Compare(compare) => self.walk_compare(compare), + ast::Expr::NumberLit(number_lit) => self.walk_number_lit(number_lit), + ast::Expr::StringLit(string_lit) => self.walk_string_lit(string_lit), + ast::Expr::NameConstantLit(name_constant_lit) => { + self.walk_name_constant_lit(name_constant_lit) + } + ast::Expr::JoinedString(joined_string) => self.walk_joined_string(joined_string), + ast::Expr::FormattedValue(formatted_value) => { + self.walk_formatted_value(formatted_value) + } + ast::Expr::Missing(missing_expr) => self.walk_missing_expr(missing_expr), + } + } +} diff --git a/kclvm/query/src/override.rs b/crates/query/src/override.rs similarity index 98% rename from kclvm/query/src/override.rs rename to crates/query/src/override.rs index 68cc7f47d..d9eeebe67 100644 --- a/kclvm/query/src/override.rs +++ b/crates/query/src/override.rs @@ -1,17 +1,17 @@ use std::collections::HashSet; -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use compiler_base_macros::bug; -use kclvm_ast::config::try_get_config_expr_mut; -use kclvm_ast::path::{get_key_parts, get_key_path}; -use kclvm_ast::walk_list_mut; -use kclvm_ast::walker::MutSelfMutWalker; -use kclvm_ast::MAIN_PKG; -use kclvm_ast::{ast, path::get_target_path}; -use kclvm_ast_pretty::print_ast_module; -use kclvm_parser::parse_expr; -use kclvm_sema::pre_process::{fix_config_expr_nest_attr, transform_multi_assign}; +use kcl_ast::MAIN_PKG; +use kcl_ast::config::try_get_config_expr_mut; +use kcl_ast::path::{get_key_parts, get_key_path}; +use kcl_ast::walk_list_mut; +use kcl_ast::walker::MutSelfMutWalker; +use kcl_ast::{ast, path::get_target_path}; +use kcl_ast_pretty::print_ast_module; +use kcl_parser::parse_expr; +use kcl_sema::pre_process::{fix_config_expr_nest_attr, transform_multi_assign}; use crate::{node::AstNodeMover, path::parse_attribute_path}; @@ -30,8 +30,8 @@ const IMPORT_STMT_COLUMN_OFFSET: u64 = 1; /// # Examples /// /// ```no_check -/// use kclvm_parser::load_program; -/// use kclvm_tools::query::r#override::apply_overrides; +/// use kcl_parser::load_program; +/// use kcl_tools::query::r#override::apply_overrides; /// /// let mut prog = load_program(&["config.k"], None, None).unwrap(); /// let overrides = vec![parse_override_spec("config.id=1").unwrap()]; @@ -92,8 +92,8 @@ pub fn build_expr_from_string(value: &str) -> Option> { /// # Examples /// /// ```no_check -/// use kclvm_parser::parse_file_force_errors; -/// use kclvm_tools::query::apply_override_on_module; +/// use kcl_parser::parse_file_force_errors; +/// use kcl_tools::query::apply_override_on_module; /// /// let mut module = parse_file_force_errors("", None).unwrap(); /// let override_spec = parse_override_spec("config.id=1").unwrap(); diff --git a/kclvm/query/src/path.rs b/crates/query/src/path.rs similarity index 100% rename from kclvm/query/src/path.rs rename to crates/query/src/path.rs diff --git a/kclvm/query/src/query.rs b/crates/query/src/query.rs similarity index 94% rename from kclvm/query/src/query.rs rename to crates/query/src/query.rs index 828083c39..a299b89d6 100644 --- a/kclvm/query/src/query.rs +++ b/crates/query/src/query.rs @@ -1,13 +1,12 @@ use std::{cell::RefCell, rc::Rc, sync::Arc}; use anyhow::Result; -use kclvm_parser::{load_all_files_under_paths, load_program, LoadProgramOptions, ParseSession}; -use kclvm_primitives::{DefaultHashBuilder, IndexMap}; -use kclvm_sema::{ +use kcl_parser::{LoadProgramOptions, ParseSession, load_all_files_under_paths, load_program}; +use kcl_primitives::{DefaultHashBuilder, IndexMap}; +use kcl_sema::{ resolver::{ - resolve_program_with_opts, + Options, resolve_program_with_opts, scope::{ProgramScope, Scope}, - Options, }, ty::SchemaType, }; @@ -41,7 +40,7 @@ impl Default for GetSchemaOption { /// # Examples /// /// ``` -/// use kclvm_query::query::{get_schema_type, GetSchemaOption}; +/// use kcl_query::query::{get_schema_type, GetSchemaOption}; /// /// let file = "schema.k"; /// let code = r#" @@ -134,9 +133,9 @@ pub struct CompilationOptions { /// # Examples /// /// ``` -/// use kclvm_parser::LoadProgramOptions; -/// use kclvm_query::query::CompilationOptions; -/// use kclvm_query::query::get_full_schema_type; +/// use kcl_parser::LoadProgramOptions; +/// use kcl_query::query::CompilationOptions; +/// use kcl_query::query::get_full_schema_type; /// use std::path::Path; /// use maplit::hashmap; /// @@ -200,12 +199,12 @@ pub fn get_full_schema_type( /// # Examples /// /// ``` -/// use kclvm_parser::LoadProgramOptions; -/// use kclvm_query::query::CompilationOptions; -/// use kclvm_query::query::get_full_schema_type_under_path; +/// use kcl_parser::LoadProgramOptions; +/// use kcl_query::query::CompilationOptions; +/// use kcl_query::query::get_full_schema_type_under_path; /// use std::path::Path; /// use maplit::hashmap; -/// use kclvm_ast::MAIN_PKG; +/// use kcl_ast::MAIN_PKG; /// /// let work_dir_parent = Path::new(env!("CARGO_MANIFEST_DIR")).join("src").join("test_data").join("get_schema_ty_under_path"); /// diff --git a/kclvm/query/src/selector.rs b/crates/query/src/selector.rs similarity index 98% rename from kclvm/query/src/selector.rs rename to crates/query/src/selector.rs index 420142d98..b3cb2484e 100644 --- a/kclvm/query/src/selector.rs +++ b/crates/query/src/selector.rs @@ -2,9 +2,9 @@ use crate::r#override::build_expr_from_string; use super::util::{invalid_symbol_selector_spec_error, split_field_path}; use anyhow::Result; -use kclvm_ast::{ast, path::get_target_path}; -use kclvm_error::diagnostic::Errors; -use kclvm_parser::ParseSession; +use kcl_ast::{ast, path::get_target_path}; +use kcl_error::diagnostic::Errors; +use kcl_parser::ParseSession; use serde::{Deserialize, Serialize}; use std::{ @@ -14,14 +14,14 @@ use std::{ vec, }; -use kclvm_ast::path::get_key_path; +use kcl_ast::path::get_key_path; -use kclvm_ast::walker::MutSelfWalker; -use kclvm_ast_pretty::{print_ast_node, ASTNode}; -use kclvm_parser::load_program; +use kcl_ast::walker::MutSelfWalker; +use kcl_ast_pretty::{ASTNode, print_ast_node}; +use kcl_parser::load_program; -use kclvm_sema::pre_process::pre_process_program; -use kclvm_sema::resolver::Options; +use kcl_sema::pre_process::pre_process_program; +use kcl_sema::resolver::Options; #[derive(Debug, Default)] /// UnsupportedSelectee is used to store the unsupported selectee, such as if, for, etc. pub struct UnsupportedSelectee { @@ -748,7 +748,7 @@ pub fn list_variables( /// # Examples /// /// ``` -/// use kclvm_query::selector::parse_symbol_selector_spec; +/// use kcl_query::selector::parse_symbol_selector_spec; /// /// if let Ok(spec) = parse_symbol_selector_spec("", "alice.age") { /// assert_eq!(spec.pkgpath, "".to_string()); diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables-10.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-10.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-10.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables-11.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-11.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-11.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables-12.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-12.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-12.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables-13.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-13.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-13.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables-14.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-14.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-14.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables-15.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-15.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-15.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables-2.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-2.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-2.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables-3.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-3.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-3.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables-4.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-4.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-4.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables-5.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-5.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-5.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables-6.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-6.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-6.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables-7.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-7.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-7.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables-8.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-8.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-8.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables-9.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-9.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables-9.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_all_variables.snap b/crates/query/src/snapshots/kcl_query__tests__list_all_variables.snap new file mode 100644 index 000000000..0b7009fa2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_all_variables.snap @@ -0,0 +1,734 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "_list0": [ + { + "name": "_list0", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_list1": [ + { + "name": "_list1", + "type_name": "", + "op_sym": "=", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "_part1": [ + { + "name": "_part1", + "type_name": "", + "op_sym": "=", + "value": "{\n a = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "_part2": [ + { + "name": "_part2", + "type_name": "", + "op_sym": "=", + "value": "{\n c = \"d\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": "=", + "value": "\"d\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ], + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ], + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ], + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ], + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ], + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ], + "c": [ + { + "name": "c", + "type_name": "C", + "op_sym": "=", + "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + }, + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ], + "job": [ + { + "name": "job", + "type_name": "Job", + "op_sym": "=", + "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ], + "select": [ + { + "name": "select", + "type_name": "a.b.c", + "op_sym": "=", + "value": "a.b.c {\n a: 1\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ], + "uconfa": [ + { + "name": "uconfa", + "type_name": "UnificationConf", + "op_sym": ":", + "value": "UnificationConf {\n name = \"b\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ], + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-10.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-10.snap new file mode 100644 index 000000000..396651e6d --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-10.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "dict1.b": [ + { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-11.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-11.snap new file mode 100644 index 000000000..cbc34de77 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-11.snap @@ -0,0 +1,62 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "dict2": [ + { + "name": "dict2", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-12.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-12.snap new file mode 100644 index 000000000..52866d103 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-12.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "dict2.a": [ + { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-13.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-13.snap new file mode 100644 index 000000000..4ca026f35 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-13.snap @@ -0,0 +1,39 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "dict2.b": [ + { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n \"d\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-14.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-14.snap new file mode 100644 index 000000000..7bab762bf --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-14.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "dict2.b.c": [ + { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-15.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-15.snap new file mode 100644 index 000000000..093ae08c2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-15.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "dict2.b.d": [ + { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-16.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-16.snap new file mode 100644 index 000000000..71da3b280 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-16.snap @@ -0,0 +1,111 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "sha": [ + { + "name": "sha", + "type_name": "A", + "op_sym": "=", + "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-17.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-17.snap new file mode 100644 index 000000000..8c92d123d --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-17.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "sha.name": [ + { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-18.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-18.snap new file mode 100644 index 000000000..23fa238e7 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-18.snap @@ -0,0 +1,41 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "sha.ids": [ + { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-19.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-19.snap new file mode 100644 index 000000000..daa25b95a --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-19.snap @@ -0,0 +1,52 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "sha.data": [ + { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-2.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-2.snap new file mode 100644 index 000000000..9972cb43a --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-2.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "a1": [ + { + "name": "a1", + "type_name": "", + "op_sym": "=", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-20.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-20.snap new file mode 100644 index 000000000..f823861db --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-20.snap @@ -0,0 +1,40 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "sha.data.a": [ + { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n \"b\": {\n \"c\": 2\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-21.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-21.snap new file mode 100644 index 000000000..ca40200ab --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-21.snap @@ -0,0 +1,28 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "sha.data.a.b": [ + { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "{\n \"c\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "c", + "value": { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-22.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-22.snap new file mode 100644 index 000000000..383227c20 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-22.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "sha.data.a.b.c": [ + { + "name": "c", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-23.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-23.snap new file mode 100644 index 000000000..e20c6f821 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-23.snap @@ -0,0 +1,123 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "shb": [ + { + "name": "shb", + "type_name": "B", + "op_sym": "=", + "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-24.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-24.snap new file mode 100644 index 000000000..5131cc4cf --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-24.snap @@ -0,0 +1,111 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "shb.a": [ + { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + }, + { + "key": "data", + "value": { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + } + ] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-25.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-25.snap new file mode 100644 index 000000000..59220032b --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-25.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "shb.a.name": [ + { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"HelloB\"", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-26.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-26.snap new file mode 100644 index 000000000..048e0e961 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-26.snap @@ -0,0 +1,41 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "shb.a.ids": [ + { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 4\n 5\n 6\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "4", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "5", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "6", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-27.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-27.snap new file mode 100644 index 000000000..4a99a30b6 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-27.snap @@ -0,0 +1,52 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "shb.a.data": [ + { + "name": "data", + "type_name": "", + "op_sym": ":", + "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "d", + "value": { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + } + ] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-28.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-28.snap new file mode 100644 index 000000000..97c199870 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-28.snap @@ -0,0 +1,40 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "shb.a.data.d": [ + { + "name": "d", + "type_name": "", + "op_sym": ":", + "value": "{\n \"e\": {\n \"f\": 3\n }\n}", + "list_items": [], + "dict_entries": [ + { + "key": "e", + "value": { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + } + ] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-29.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-29.snap new file mode 100644 index 000000000..34caa5db2 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-29.snap @@ -0,0 +1,28 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "shb.a.data.d.e": [ + { + "name": "e", + "type_name": "", + "op_sym": ":", + "value": "{\n \"f\": 3\n}", + "list_items": [], + "dict_entries": [ + { + "key": "f", + "value": { + "name": "f", + "type_name": "", + "op_sym": ":", + "value": "3", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-3.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-3.snap new file mode 100644 index 000000000..6fcb1eed4 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-3.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "a3": [ + { + "name": "a3", + "type_name": "", + "op_sym": "=", + "value": "3m", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-30.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-30.snap new file mode 100644 index 000000000..ae99eee8a --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-30.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "uconfa.name": [ + { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"b\"", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-31.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-31.snap new file mode 100644 index 000000000..3c35373f1 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-31.snap @@ -0,0 +1,73 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "c.a": [ + { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n name: \"Hello\"\n}", + "list_items": [], + "dict_entries": [ + { + "key": "name", + "value": { + "name": "name", + "type_name": "", + "op_sym": ":", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + } + ] + }, + { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "{\n ids: [7, 8, 9]\n}", + "list_items": [], + "dict_entries": [ + { + "key": "ids", + "value": { + "name": "ids", + "type_name": "", + "op_sym": ":", + "value": "[\n 7\n 8\n 9\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "7", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "8", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "9", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + } + ] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-32.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-32.snap new file mode 100644 index 000000000..81e54c628 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-32.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "job.name": [ + { + "name": "name", + "type_name": "", + "op_sym": "=", + "value": "\"{}-{}\".format(\"app\", \"test\").lower()", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-33.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-33.snap new file mode 100644 index 000000000..d88810e1a --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-33.snap @@ -0,0 +1,33 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "union_list": [ + { + "name": "union_list", + "type_name": "", + "op_sym": "=", + "value": "[\n *_list0\n *_list1\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list0", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "*_list1", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-34.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-34.snap new file mode 100644 index 000000000..c7c41e613 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-34.snap @@ -0,0 +1,39 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "a_dict": [ + { + "name": "a_dict", + "type_name": "", + "op_sym": "=", + "value": "{\n **_part1\n **_part2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "", + "value": { + "name": "", + "type_name": "", + "op_sym": ":", + "value": "_part2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-4.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-4.snap new file mode 100644 index 000000000..99189bbbe --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-4.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "b1": [ + { + "name": "b1", + "type_name": "", + "op_sym": "=", + "value": "True", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-5.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-5.snap new file mode 100644 index 000000000..8eeb16eeb --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-5.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "b2": [ + { + "name": "b2", + "type_name": "", + "op_sym": "=", + "value": "False", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-6.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-6.snap new file mode 100644 index 000000000..1c1672631 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-6.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "s1": [ + { + "name": "s1", + "type_name": "", + "op_sym": "=", + "value": "\"Hello\"", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-7.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-7.snap new file mode 100644 index 000000000..5240cdaa6 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-7.snap @@ -0,0 +1,41 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "array1": [ + { + "name": "array1", + "type_name": "", + "op_sym": "=", + "value": "[\n 1\n 2\n 3\n]", + "list_items": [ + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "1", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "2", + "list_items": [], + "dict_entries": [] + }, + { + "name": "", + "type_name": "", + "op_sym": "", + "value": "3", + "list_items": [], + "dict_entries": [] + } + ], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-8.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-8.snap new file mode 100644 index 000000000..9857995d3 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-8.snap @@ -0,0 +1,39 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "dict1": [ + { + "name": "dict1", + "type_name": "", + "op_sym": "=", + "value": "{\n \"a\": 1\n \"b\": 2\n}", + "list_items": [], + "dict_entries": [ + { + "key": "a", + "value": { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + }, + { + "key": "b", + "value": { + "name": "b", + "type_name": "", + "op_sym": ":", + "value": "2", + "list_items": [], + "dict_entries": [] + } + } + ] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables-9.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables-9.snap new file mode 100644 index 000000000..41799ef61 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables-9.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "dict1.a": [ + { + "name": "a", + "type_name": "", + "op_sym": ":", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/crates/query/src/snapshots/kcl_query__tests__list_variables.snap b/crates/query/src/snapshots/kcl_query__tests__list_variables.snap new file mode 100644 index 000000000..dcdf0c649 --- /dev/null +++ b/crates/query/src/snapshots/kcl_query__tests__list_variables.snap @@ -0,0 +1,16 @@ +--- +source: crates/query/src/tests.rs +expression: got_json +--- +{ + "a": [ + { + "name": "a", + "type_name": "", + "op_sym": "=", + "value": "1", + "list_items": [], + "dict_entries": [] + } + ] +} diff --git a/kclvm/query/src/test_data/config.k b/crates/query/src/test_data/config.k similarity index 85% rename from kclvm/query/src/test_data/config.k rename to crates/query/src/test_data/config.k index a29c47a19..c1b976302 100644 --- a/kclvm/query/src/test_data/config.k +++ b/crates/query/src/test_data/config.k @@ -19,8 +19,8 @@ schema AppConfiguration: probe?: Probe appConfiguration = AppConfiguration { - appName: "kclvm" - image: "kclvm/kclvm:v0.1.0" + appName: "kcl" + image: "kcl/kcl:v0.1.0" resource: { cpu: "4" disk: "50Gi" @@ -32,7 +32,7 @@ appConfiguration = AppConfiguration { } } mainContainer: Main { - name: "kclvm" + name: "kcl" } overQuota = True overQuota = True @@ -40,8 +40,8 @@ appConfiguration = AppConfiguration { } appConfigurationUnification: AppConfiguration { - appName: "kclvm" - image: "kclvm/kclvm:v0.1.0" + appName: "kcl" + image: "kcl/kcl:v0.1.0" resource: { cpu: "4" disk: "50Gi" @@ -53,7 +53,7 @@ appConfigurationUnification: AppConfiguration { } } mainContainer: Main { - name: "kclvm" + name: "kcl" } overQuota: True } diff --git a/kclvm/query/src/test_data/expect.k b/crates/query/src/test_data/expect.k similarity index 100% rename from kclvm/query/src/test_data/expect.k rename to crates/query/src/test_data/expect.k diff --git a/kclvm/query/src/test_data/get_schema_ty/aaa/kcl.mod b/crates/query/src/test_data/get_schema_ty/aaa/kcl.mod similarity index 100% rename from kclvm/query/src/test_data/get_schema_ty/aaa/kcl.mod rename to crates/query/src/test_data/get_schema_ty/aaa/kcl.mod diff --git a/kclvm/query/src/test_data/get_schema_ty/aaa/main.k b/crates/query/src/test_data/get_schema_ty/aaa/main.k similarity index 100% rename from kclvm/query/src/test_data/get_schema_ty/aaa/main.k rename to crates/query/src/test_data/get_schema_ty/aaa/main.k diff --git a/kclvm/query/src/test_data/get_schema_ty/bbb/kcl.mod b/crates/query/src/test_data/get_schema_ty/bbb/kcl.mod similarity index 100% rename from kclvm/query/src/test_data/get_schema_ty/bbb/kcl.mod rename to crates/query/src/test_data/get_schema_ty/bbb/kcl.mod diff --git a/kclvm/query/src/test_data/get_schema_ty/bbb/main.k b/crates/query/src/test_data/get_schema_ty/bbb/main.k similarity index 100% rename from kclvm/query/src/test_data/get_schema_ty/bbb/main.k rename to crates/query/src/test_data/get_schema_ty/bbb/main.k diff --git a/kclvm/query/src/test_data/get_schema_ty_under_path/aaa/kcl.mod b/crates/query/src/test_data/get_schema_ty_under_path/aaa/kcl.mod similarity index 100% rename from kclvm/query/src/test_data/get_schema_ty_under_path/aaa/kcl.mod rename to crates/query/src/test_data/get_schema_ty_under_path/aaa/kcl.mod diff --git a/kclvm/query/src/test_data/get_schema_ty_under_path/aaa/main.k b/crates/query/src/test_data/get_schema_ty_under_path/aaa/main.k similarity index 100% rename from kclvm/query/src/test_data/get_schema_ty_under_path/aaa/main.k rename to crates/query/src/test_data/get_schema_ty_under_path/aaa/main.k diff --git a/kclvm/query/src/test_data/get_schema_ty_under_path/aaa/sub/sub.k b/crates/query/src/test_data/get_schema_ty_under_path/aaa/sub/sub.k similarity index 100% rename from kclvm/query/src/test_data/get_schema_ty_under_path/aaa/sub/sub.k rename to crates/query/src/test_data/get_schema_ty_under_path/aaa/sub/sub.k diff --git a/kclvm/query/src/test_data/get_schema_ty_under_path/bbb/kcl.mod b/crates/query/src/test_data/get_schema_ty_under_path/bbb/kcl.mod similarity index 100% rename from kclvm/query/src/test_data/get_schema_ty_under_path/bbb/kcl.mod rename to crates/query/src/test_data/get_schema_ty_under_path/bbb/kcl.mod diff --git a/kclvm/query/src/test_data/get_schema_ty_under_path/bbb/main.k b/crates/query/src/test_data/get_schema_ty_under_path/bbb/main.k similarity index 100% rename from kclvm/query/src/test_data/get_schema_ty_under_path/bbb/main.k rename to crates/query/src/test_data/get_schema_ty_under_path/bbb/main.k diff --git a/kclvm/query/src/test_data/get_schema_ty_under_path/helloworld_0.0.1/README.md b/crates/query/src/test_data/get_schema_ty_under_path/helloworld_0.0.1/README.md similarity index 100% rename from kclvm/query/src/test_data/get_schema_ty_under_path/helloworld_0.0.1/README.md rename to crates/query/src/test_data/get_schema_ty_under_path/helloworld_0.0.1/README.md diff --git a/kclvm/query/src/test_data/get_schema_ty_under_path/helloworld_0.0.1/kcl.mod b/crates/query/src/test_data/get_schema_ty_under_path/helloworld_0.0.1/kcl.mod similarity index 100% rename from kclvm/query/src/test_data/get_schema_ty_under_path/helloworld_0.0.1/kcl.mod rename to crates/query/src/test_data/get_schema_ty_under_path/helloworld_0.0.1/kcl.mod diff --git a/kclvm/query/src/test_data/get_schema_ty_under_path/helloworld_0.0.1/main.k b/crates/query/src/test_data/get_schema_ty_under_path/helloworld_0.0.1/main.k similarity index 100% rename from kclvm/query/src/test_data/get_schema_ty_under_path/helloworld_0.0.1/main.k rename to crates/query/src/test_data/get_schema_ty_under_path/helloworld_0.0.1/main.k diff --git a/kclvm/query/src/test_data/import_paths.k b/crates/query/src/test_data/import_paths.k similarity index 100% rename from kclvm/query/src/test_data/import_paths.k rename to crates/query/src/test_data/import_paths.k diff --git a/kclvm/query/src/test_data/invalid.bk.k b/crates/query/src/test_data/invalid.bk.k similarity index 100% rename from kclvm/query/src/test_data/invalid.bk.k rename to crates/query/src/test_data/invalid.bk.k diff --git a/kclvm/query/src/test_data/kcl.mod b/crates/query/src/test_data/kcl.mod similarity index 100% rename from kclvm/query/src/test_data/kcl.mod rename to crates/query/src/test_data/kcl.mod diff --git a/kclvm/query/src/test_data/simple.bk.k b/crates/query/src/test_data/simple.bk.k similarity index 100% rename from kclvm/query/src/test_data/simple.bk.k rename to crates/query/src/test_data/simple.bk.k diff --git a/kclvm/query/src/test_data/simple.k b/crates/query/src/test_data/simple.k similarity index 100% rename from kclvm/query/src/test_data/simple.k rename to crates/query/src/test_data/simple.k diff --git a/kclvm/query/src/test_data/test_list_variables/invalid.k b/crates/query/src/test_data/test_list_variables/invalid.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/invalid.k rename to crates/query/src/test_data/test_list_variables/invalid.k diff --git a/kclvm/query/src/test_data/test_list_variables/supported.k b/crates/query/src/test_data/test_list_variables/supported.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/supported.k rename to crates/query/src/test_data/test_list_variables/supported.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/a.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/a.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/a.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/a.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/a1.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/a1.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/a1.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/a1.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/a3.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/a3.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/a3.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/a3.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/a_dict.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/a_dict.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/a_dict.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/a_dict.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/array1.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/array1.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/array1.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/array1.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/b1.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/b1.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/b1.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/b1.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/b2.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/b2.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/b2.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/b2.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/dict1.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/dict1.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/dict1.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/dict1.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/dict2.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/dict2.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/dict2.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/dict2.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/job.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/job.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/job.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/job.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/s1.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/s1.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/s1.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/s1.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/select.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/select.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/select.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/select.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/sha.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/sha.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/sha.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/sha.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/shb.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/shb.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/shb.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/shb.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_all_variables/union_list.json b/crates/query/src/test_data/test_list_variables/test_list_all_variables/union_list.json similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_all_variables/union_list.json rename to crates/query/src/test_data/test_list_variables/test_list_all_variables/union_list.json diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/kcl.mod b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/kcl.mod similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/kcl.mod rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/kcl.mod diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/main.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/main.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/main.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/main.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_1/base.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_1/base.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_1/base.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_1/base.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_1/main.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_1/main.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_1/main.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_1/main.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_10/main.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_10/main.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_10/main.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_10/main.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_11/main.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_11/main.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_11/main.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_11/main.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_2/base.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_2/base.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_2/base.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_2/base.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_2/main.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_2/main.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_2/main.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_2/main.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_3/base.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_3/base.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_3/base.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_3/base.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_3/main.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_3/main.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_3/main.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_3/main.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_4/base.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_4/base.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_4/base.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_4/base.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_4/main.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_4/main.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_4/main.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_4/main.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_5/base.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_5/base.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_5/base.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_5/base.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_5/main.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_5/main.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_5/main.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_5/main.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_6/base.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_6/base.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_6/base.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_6/base.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_6/main.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_6/main.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_6/main.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_6/main.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_7/base.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_7/base.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_7/base.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_7/base.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_7/main.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_7/main.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_7/main.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_7/main.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_8/main.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_8/main.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_8/main.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_8/main.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_9/main.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_9/main.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/merge_9/main.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/merge_9/main.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/override/base.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/override/base.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/override/base.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/override/base.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/override/main.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/override/main.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/override/main.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/override/main.k diff --git a/kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/test.k b/crates/query/src/test_data/test_list_variables/test_list_merged_variables/test.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/test_list_merged_variables/test.k rename to crates/query/src/test_data/test_list_variables/test_list_merged_variables/test.k diff --git a/kclvm/query/src/test_data/test_list_variables/unsupported.k b/crates/query/src/test_data/test_list_variables/unsupported.k similarity index 100% rename from kclvm/query/src/test_data/test_list_variables/unsupported.k rename to crates/query/src/test_data/test_list_variables/unsupported.k diff --git a/kclvm/query/src/test_data/test_override_file/expect.k b/crates/query/src/test_data/test_override_file/expect.k similarity index 100% rename from kclvm/query/src/test_data/test_override_file/expect.k rename to crates/query/src/test_data/test_override_file/expect.k diff --git a/kclvm/query/src/test_data/test_override_file/invalid.k b/crates/query/src/test_data/test_override_file/invalid.k similarity index 100% rename from kclvm/query/src/test_data/test_override_file/invalid.k rename to crates/query/src/test_data/test_override_file/invalid.k diff --git a/kclvm/query/src/test_data/test_override_file/main.bk.k b/crates/query/src/test_data/test_override_file/main.bk.k similarity index 100% rename from kclvm/query/src/test_data/test_override_file/main.bk.k rename to crates/query/src/test_data/test_override_file/main.bk.k diff --git a/kclvm/query/src/test_data/test_override_file/main.k b/crates/query/src/test_data/test_override_file/main.k similarity index 100% rename from kclvm/query/src/test_data/test_override_file/main.k rename to crates/query/src/test_data/test_override_file/main.k diff --git a/crates/query/src/tests.rs b/crates/query/src/tests.rs new file mode 100644 index 000000000..77a02cced --- /dev/null +++ b/crates/query/src/tests.rs @@ -0,0 +1,1105 @@ +use std::{fs, path::PathBuf}; + +use super::{r#override::apply_override_on_module, *}; +use crate::{ + r#override::parse_override_spec, path::parse_attribute_path, selector::list_variables, +}; +use kcl_error::{DiagnosticId, ErrorKind, Level}; +use kcl_parser::parse_file_force_errors; +use kcl_utils::path::PathPrefix; +use pretty_assertions::assert_eq; +use selector::ListOptions; + +const CARGO_FILE_PATH: &str = env!("CARGO_MANIFEST_DIR"); + +fn get_test_dir(sub: String) -> PathBuf { + let mut cargo_file_path = PathBuf::from(CARGO_FILE_PATH); + cargo_file_path.push("src"); + cargo_file_path.push("test_data"); + // Split unix and windows path + for part in sub.split("/") { + for p in part.split("\\") { + cargo_file_path.push(p); + } + } + cargo_file_path +} + +/// Test override_file result. +#[test] +fn test_override_file_simple() { + let specs = vec![ + "config.image=image/image".to_string(), + "config.image=\"image/image:v1\"".to_string(), + "config.data={id=1,value=\"override_value\"}".to_string(), + "dict_config={\"image\": \"image/image:v2\" \"data\":{\"id\":2 \"value2\": \"override_value2\"}}".to_string(), + "envs=[{key=\"key1\" value=\"value1\"} {key=\"key2\" value=\"value2\"}]".to_string(), + "isfilter=False".to_string(), + "count=2".to_string(), + "msg=\"Hi World\"".to_string(), + "delete-".to_string(), + "dict_delete.image-".to_string(), + "dict_delete_whole-".to_string(), + "insert_config.key=1".to_string(), + "uni_config.labels.key1=1".to_string(), + "config_unification=Config {\"image\": \"image/image:v4\"}".to_string(), + "config_unification:Config {\"env\": {\"aaa\": \"aaa\"}}".to_string(), + "config_unification.env: {\"bbb\": \"bbb\"}}".to_string(), + "config_unification_delete-".to_string() + ]; + + let simple_path = get_test_dir("simple.k".to_string()); + let simple_bk_path = get_test_dir("simple.bk.k".to_string()); + let expect_path = get_test_dir("expect.k".to_string()); + fs::copy(simple_bk_path.clone(), simple_path.clone()).unwrap(); + if simple_path.exists() { + fs::remove_file(simple_path.clone()).unwrap(); + } + + fs::copy(simple_bk_path.clone(), simple_path.clone()).unwrap(); + + let import_paths = vec![]; + assert_eq!( + override_file(simple_path.clone().to_str().unwrap(), &specs, &import_paths) + .unwrap() + .result, + true + ); + + let simple_content = fs::read_to_string(simple_path.clone()).unwrap(); + let expect_content = fs::read_to_string(expect_path).unwrap(); + + let simple_content = simple_content.replace("\r\n", "\n"); + let expect_content = expect_content.replace("\r\n", "\n"); + + assert_eq!(simple_content, expect_content); + + fs::copy(simple_bk_path.clone(), simple_path.clone()).unwrap(); +} +/// Test override_file result. +#[test] +fn test_override_file_import_paths() { + let specs = vec!["data.value=\"override_value\"".to_string()]; + let import_paths = vec![ + "pkg".to_string(), + "pkg.pkg".to_string(), + "pkg.pkg as alias_pkg1".to_string(), + "pkg.pkg as alias_pkg2".to_string(), + ]; + + let mut cargo_file_path = PathBuf::from(CARGO_FILE_PATH); + cargo_file_path.push("src/test_data/import_paths.k"); + let abs_path = cargo_file_path.to_str().unwrap(); + + assert_eq!( + override_file(abs_path, &specs, &import_paths) + .unwrap() + .result, + true + ) +} + +/// Test override_file result with the expected modified AST. +#[test] +fn test_override_file_config() { + let specs = vec![ + "appConfiguration.image=\"kcl/kcl:{}\".format(version)".to_string(), + r#"appConfiguration.mainContainer.name="override_name""#.to_string(), + "appConfiguration.labels.key.key=\"override_value\"".to_string(), + "appConfiguration.labels.key.str-key=\"override_value\"".to_string(), + "appConfiguration.labels.key['dot.key']=\"override_value\"".to_string(), + "appConfiguration.overQuota=False".to_string(), + "appConfiguration.probe={periodSeconds=20}".to_string(), + "appConfiguration.resource-".to_string(), + "appConfiguration.svc=s.Service {}".to_string(), + "appConfigurationUnification.image=\"kcl/kcl:v0.1\"".to_string(), + r#"appConfigurationUnification.mainContainer.name="override_name""#.to_string(), + "appConfigurationUnification.labels.key.key=\"override_value\"".to_string(), + "appConfigurationUnification.overQuota=False".to_string(), + "appConfigurationUnification.resource.cpu-".to_string(), + "appConfigurationUnification.svc=s.Service {}".to_string(), + "appConfigurationUnification:{name=\"name\"}".to_string(), + "config.x:{a:1}".to_string(), + "config.x:{b:2}".to_string(), + "config.x:{b:3}".to_string(), + "config.x:{c.d:4}".to_string(), + "config.y=1".to_string(), + "config.z+=[1,2,3]".to_string(), + "config.z+=[4,5,6]".to_string(), + "var1:1".to_string(), + "var2=1".to_string(), + "var3+=[1,2,3]".to_string(), + "var3+=[4,5,6]".to_string(), + "var4:AppConfiguration {image:'image'}".to_string(), + ]; + let import_paths = vec!["service as s".to_string()]; + + let mut cargo_file_path = PathBuf::from(CARGO_FILE_PATH); + cargo_file_path.push("src/test_data/config.k"); + let abs_path = cargo_file_path.to_str().unwrap(); + + let mut module = parse_file_force_errors(abs_path, None).unwrap(); + for s in &specs { + apply_override_on_module(&mut module, s, &import_paths).unwrap(); + } + let expected_code = print_ast_module(&module); + assert_eq!( + expected_code, + r#"import service as s + +schema Main: + name?: str + env?: [{str:}] + +schema Probe: + initialDelaySeconds?: int + timeoutSeconds?: int + periodSeconds?: int = 10 + successThreshold?: int + failureThreshold?: int + +schema AppConfiguration: + appName: str + image: str + overQuota: bool = False + resource: {str:} + mainContainer?: Main + labels: {str:} + probe?: Probe + +appConfiguration = AppConfiguration { + appName: "kcl" + image: "kcl/kcl:{}".format(version) + labels: { + key: { + key: "override_value" + "str-key" = "override_value" + "dot.key" = "override_value" + } + } + mainContainer: Main {name: "override_name"} + overQuota = False + overQuota = False + probe: { + periodSeconds = 20 + } + svc = s.Service {} +} + +appConfigurationUnification: AppConfiguration { + appName: "kcl" + image: "kcl/kcl:v0.1" + resource: { + disk: "50Gi" + memory: "12Gi" + } + labels: { + key: {key: "override_value"} + } + mainContainer: Main {name: "override_name"} + overQuota: False + svc = s.Service {} + name = "name" +} +config = { + x: { + a: 1 + b: 3 + c: { + d: 4 + } + } + y = 1 + z += [ + 1 + 2 + 3 + 4 + 5 + 6 + ] +} +var1 = 1 +var2 = 1 +var3 += [ + 1 + 2 + 3 + 4 + 5 + 6 +] +var4: AppConfiguration { + image: 'image' +} +"# + ); +} + +/// Test override spec parser. +#[test] +fn test_parse_override_spec_invalid() { + let specs = vec![":a:", "=a=", ":a", "a-1"]; + for spec in specs { + assert!(parse_override_spec(spec).is_err(), "{spec} test failed"); + } +} + +#[test] +fn test_parse_property_path() { + assert_eq!(parse_attribute_path("a.b.c").unwrap(), vec!["a", "b", "c"]); + assert_eq!( + parse_attribute_path(r#"a["b"].c"#).unwrap(), + vec!["a", "b", "c"] + ); + assert_eq!( + parse_attribute_path(r#"a.["b"].c"#).unwrap(), + vec!["a", "b", "c"] + ); + assert_eq!( + parse_attribute_path(r#"a['b'].c"#).unwrap(), + vec!["a", "b", "c"] + ); + assert_eq!( + parse_attribute_path(r#"a.b['c.d']"#).unwrap(), + vec!["a", "b", "c.d"] + ); + assert_eq!( + parse_attribute_path(r#"a.b.['c.d']"#).unwrap(), + vec!["a", "b", "c.d"] + ); + assert_eq!( + parse_attribute_path(r#"a.b['c.d'].e"#).unwrap(), + vec!["a", "b", "c.d", "e"] + ); + assert_eq!( + parse_attribute_path(r#"a.b.['c.d'].e"#).unwrap(), + vec!["a", "b", "c.d", "e"] + ); + assert_eq!( + parse_attribute_path(r#"a.b.c-d.e"#).unwrap(), + vec!["a", "b", "c-d", "e"] + ); + assert!(parse_attribute_path(r#"a.[b.c-d.e"#).is_err(),); + assert!(parse_attribute_path(r#"a.[b.c]-d.e"#).is_err(),); +} + +#[test] +fn test_list_variables() { + let file = PathBuf::from("./src/test_data/test_list_variables/supported.k") + .canonicalize() + .unwrap() + .display() + .to_string(); + let test_cases = vec![ + ("a", "1", "", "="), + ("a1", "2", "", "="), + ("a3", "3m", "", "="), + ("b1", "True", "", "="), + ("b2", "False", "", "="), + ("s1", "\"Hello\"", "", "="), + ( + "array1", + r#"[ + 1 + 2 + 3 +]"#, + "", + "=", + ), + ( + "dict1", + r#"{ + "a": 1 + "b": 2 +}"#, + "", + "=", + ), + ("dict1.a", "1", "", ":"), + ("dict1.b", "2", "", ":"), + ( + "dict2", + r#"{ + "a": 1 + "b": { + "c": 2 + "d": 3 + } +}"#, + "", + "=", + ), + ("dict2.a", "1", "", ":"), + ( + "dict2.b", + r#"{ + "c": 2 + "d": 3 +}"#, + "", + ":", + ), + ("dict2.b.c", "2", "", ":"), + ("dict2.b.d", "3", "", ":"), + ( + "sha", + r#"A { + name: "Hello" + ids: [1, 2, 3] + data: { + "a": { + "b": { + "c": 2 + } + } + } +}"#, + "A", + "=", + ), + ("sha.name", "\"Hello\"", "", ":"), + ( + "sha.ids", + r#"[ + 1 + 2 + 3 +]"#, + "", + ":", + ), + ( + "sha.data", + r#"{ + "a": { + "b": { + "c": 2 + } + } +}"#, + "", + ":", + ), + ( + "sha.data.a", + r#"{ + "b": { + "c": 2 + } +}"#, + "", + ":", + ), + ( + "sha.data.a.b", + r#"{ + "c": 2 +}"#, + "", + ":", + ), + ("sha.data.a.b.c", "2", "", ":"), + ( + "shb", + r#"B { + a: { + name: "HelloB" + ids: [4, 5, 6] + data: { + "d": { + "e": { + "f": 3 + } + } + } + } +}"#, + "B", + "=", + ), + ( + "shb.a", + r#"{ + name: "HelloB" + ids: [4, 5, 6] + data: { + "d": { + "e": { + "f": 3 + } + } + } +}"#, + "", + ":", + ), + ("shb.a.name", "\"HelloB\"", "", ":"), + ( + "shb.a.ids", + r#"[ + 4 + 5 + 6 +]"#, + "", + ":", + ), + ( + "shb.a.data", + r#"{ + "d": { + "e": { + "f": 3 + } + } +}"#, + "", + ":", + ), + ( + "shb.a.data.d", + r#"{ + "e": { + "f": 3 + } +}"#, + "", + ":", + ), + ( + "shb.a.data.d.e", + r#"{ + "f": 3 +}"#, + "", + ":", + ), + ("uconfa.name", "\"b\"", "", "="), + ( + "c.a", + r#"{ + name: "Hello" +}"#, + "", + ":", + ), + ( + "job.name", + r#""{}-{}".format("app", "test").lower()"#, + "", + "=", + ), + ( + "union_list", + r#"[ + *_list0 + *_list1 +]"#, + "", + "=", + ), + ( + "a_dict", + r#"{ + **_part1 + **_part2 +}"#, + "", + "=", + ), + ]; + + for (spec, expected, expected_name, op_sym) in test_cases { + let specs = vec![spec.to_string()]; + let result = list_variables(vec![file.clone()], specs, None).unwrap(); + assert_eq!( + result.variables.get(spec).unwrap().get(0).unwrap().value, + expected, + "{spec}" + ); + assert_eq!( + result + .variables + .get(spec) + .unwrap() + .get(0) + .unwrap() + .type_name, + expected_name, + "{spec}" + ); + assert_eq!( + result.variables.get(spec).unwrap().get(0).unwrap().op_sym, + op_sym, + "{spec}" + ); + + let got_json = serde_json::to_string_pretty(&result.variables).unwrap(); + insta::assert_snapshot!(got_json); + } +} + +#[test] +fn test_list_all_variables() { + let file = PathBuf::from("./src/test_data/test_list_variables/supported.k") + .canonicalize() + .unwrap() + .display() + .to_string(); + let test_cases = vec![ + ("a", "1", "", "="), + ("a1", "2", "", "="), + ("a3", "3m", "", "="), + ("b1", "True", "", "="), + ("b2", "False", "", "="), + ("s1", "\"Hello\"", "", "="), + ( + "array1", + r#"[ + 1 + 2 + 3 +]"#, + "", + "=", + ), + ( + "dict1", + r#"{ + "a": 1 + "b": 2 +}"#, + "", + "=", + ), + ( + "dict2", + r#"{ + "a": 1 + "b": { + "c": 2 + "d": 3 + } +}"#, + "", + "=", + ), + ( + "sha", + r#"A { + name: "Hello" + ids: [1, 2, 3] + data: { + "a": { + "b": { + "c": 2 + } + } + } +}"#, + "A", + "=", + ), + ( + "shb", + r#"B { + a: { + name: "HelloB" + ids: [4, 5, 6] + data: { + "d": { + "e": { + "f": 3 + } + } + } + } +}"#, + "B", + "=", + ), + ( + "job", + r#"Job { + name = "{}-{}".format("app", "test").lower() +}"#, + "Job", + "=", + ), + ( + "select", + r#"a.b.c { + a: 1 +}"#, + "a.b.c", + "=", + ), + ( + "union_list", + r#"[ + *_list0 + *_list1 +]"#, + "", + "=", + ), + ( + "a_dict", + r#"{ + **_part1 + **_part2 +}"#, + "", + "=", + ), + ]; + + for (spec, expected, expected_name, op_sym) in test_cases { + println!("{:?}", spec); + let result = list_variables(vec![file.clone()], vec![], None).unwrap(); + assert_eq!( + result.variables.get(spec).unwrap().get(0).unwrap().value, + expected, + "{spec}" + ); + assert_eq!( + result + .variables + .get(spec) + .unwrap() + .get(0) + .unwrap() + .type_name, + expected_name, + "{spec}" + ); + assert_eq!( + result.variables.get(spec).unwrap().get(0).unwrap().op_sym, + op_sym, + "{spec}" + ); + assert_eq!(result.parse_errors.len(), 0); + + let got_json = serde_json::to_string_pretty(&result.variables).unwrap(); + insta::assert_snapshot!(got_json); + } +} + +#[test] +fn test_list_unsupported_variables() { + let file = PathBuf::from("./src/test_data/test_list_variables/unsupported.k") + .canonicalize() + .unwrap() + .display() + .to_string(); + + // test unsupport code + let test_cases = vec![ + ("list", "[_x for _x in range(20) if _x % 2 == 0]"), + ("list1", "[i if i > 2 else i + 1 for i in [1, 2, 3]]"), + ("dict", "{str(i): 2 * i for i in range(3)}"), + ( + "func", + r#"lambda x: int, y: int -> int { + x + y +}"#, + ), + ( + "if_schema.falseValue", + "if True:\n trueValue: 1\nelse:\n falseValue: 2", + ), + ( + "if_schema.trueValue", + "if True:\n trueValue: 1\nelse:\n falseValue: 2", + ), + ]; + + for (spec, expected_code) in test_cases { + let specs = vec![spec.to_string()]; + let result = list_variables(vec![file.clone()], specs, None).unwrap(); + assert_eq!(result.variables.get(spec), None); + assert_eq!(result.unsupported[0].code, expected_code); + assert_eq!(result.parse_errors.len(), 0); + } + + // test list variables from unsupported code + let test_cases = vec![ + ("if_schema.name", r#""name""#), + ("if_schema.age", "1"), + ( + "if_schema.inner", + r#"IfSchemaInner { + innerValue: 1 +}"#, + ), + ("if_schema.inner.innerValue", "1"), + ( + "if_schema.inner2", + r#"{ + innerValue: 2 +}"#, + ), + ("if_schema.inner2.innerValue", "2"), + ("if_schema1.name", r#""name""#), + ("if_schema1.age", "1"), + ( + "if_schema1.inner", + r#"IfSchemaInner { + innerValue: 1 +}"#, + ), + ("if_schema1.inner.innerValue", "1"), + ( + "if_schema1.inner2", + r#"{ + innerValue: 2 +}"#, + ), + ("if_schema1.inner2.innerValue", "2"), + ]; + + for (spec, expected_code) in test_cases { + let specs = vec![spec.to_string()]; + let result = list_variables(vec![file.clone()], specs, None).unwrap(); + assert_eq!( + result.variables.get(spec).unwrap().get(0).unwrap().value, + expected_code, + "{spec}", + ); + } +} + +#[test] +fn test_override_file_insert() { + let specs = vec![ + r#"b={ + "c": 2 + }"# + .to_string(), + r#"c.b={"a": "b"}"#.to_string(), + r#"d.e.f.g=3"#.to_string(), + r#"_access3=test.ServiceAccess { + iType = "kkkkkkk" + sType = dsType + TestStr = ["${test_str}"] + ports = [80, 443] + booltest = True +}"# + .to_string(), + r#"_access4=test.ServiceAccess { + iType = "kkkkkkk" + sType = dsType + TestStr = ["${test_str}"] + ports = [80, 443] + booltest = True +}"# + .to_string(), + r#"_access.iType="kkkkkkk""#.to_string(), + r#"_access5.iType="dddddd""#.to_string(), + r#"a=b"#.to_string(), + r#"_access6 ="a6""#.to_string(), + r#"_access.mergedattr=1"#.to_string(), + r#"_access.a.b.c=2"#.to_string(), + r#"_access.a.c.b=3"#.to_string(), + ]; + + let simple_path = get_test_dir("test_override_file/main.k".to_string()); + let simple_bk_path = get_test_dir("test_override_file/main.bk.k".to_string()); + let expect_path = get_test_dir("test_override_file/expect.k".to_string()); + fs::copy(simple_bk_path.clone(), simple_path.clone()).unwrap(); + let import_paths = vec![ + "base.pkg.kusion_models.app".to_string(), + "base.pkg.kusion_models.app.vip as vip".to_string(), + "base.pkg.kusion_models.app.container".to_string(), + "base.pkg.kusion_models.app.resource as res".to_string(), + "base.pkg.kusion_models.app.sidecar".to_string(), + ".values".to_string(), + ]; + + // test insert multiple times + for _ in 1..=5 { + assert_eq!( + override_file(&simple_path.display().to_string(), &specs, &import_paths) + .unwrap() + .result, + true + ); + + let simple_content = fs::read_to_string(simple_path.clone()).unwrap(); + let expect_content = fs::read_to_string(expect_path.clone()).unwrap(); + + let simple_content = simple_content.replace("\r\n", "\n"); + let expect_content = expect_content.replace("\r\n", "\n"); + + assert_eq!(simple_content, expect_content); + } + + fs::copy(simple_bk_path.clone(), simple_path.clone()).unwrap(); +} + +#[test] +fn test_list_variable_with_invalid_kcl() { + let file = PathBuf::from("./src/test_data/test_list_variables/invalid.k") + .canonicalize() + .unwrap() + .display() + .to_string(); + let specs = vec!["a".to_string()]; + let result = list_variables(vec![file.clone()], specs, None).unwrap(); + assert_eq!(result.variables.get("a"), None); + assert_eq!(result.parse_errors.len(), 2); + assert_eq!(result.parse_errors[0].level, Level::Error); + assert_eq!( + result.parse_errors[0].code, + Some(DiagnosticId::Error(ErrorKind::InvalidSyntax)) + ); + assert_eq!( + result.parse_errors[0].messages[0].message, + "expected one of [\"=\"] got eof", + ); + assert_eq!( + result.parse_errors[0].messages[0].range.0.filename, + file.adjust_canonicalization() + ); + assert_eq!(result.parse_errors[0].messages[0].range.0.line, 1); + assert_eq!(result.parse_errors[0].messages[0].range.0.column, Some(8)); +} + +#[test] +fn test_overridefile_with_invalid_kcl() { + let simple_path = get_test_dir("test_override_file/invalid.k".to_string()); + let simple_bk_path = get_test_dir("invalid.bk.k".to_string()); + fs::copy(simple_bk_path.clone(), simple_path.clone()).unwrap(); + + let result = override_file( + &simple_path.display().to_string(), + &vec!["a=b".to_string()], + &vec![], + ) + .unwrap(); + + fs::copy(simple_bk_path.clone(), simple_path.clone()).unwrap(); + assert_eq!(result.result, true); + assert_eq!(result.parse_errors.len(), 2); + assert_eq!(result.parse_errors[0].level, Level::Error); + assert_eq!( + result.parse_errors[0].code, + Some(DiagnosticId::Error(ErrorKind::InvalidSyntax)) + ); + assert_eq!( + result.parse_errors[0].messages[0].message, + "expected one of [\"=\"] got eof" + ); + assert_eq!( + result.parse_errors[0].messages[0] + .range + .0 + .filename + .adjust_canonicalization(), + simple_path.display().to_string().adjust_canonicalization() + ); + assert_eq!(result.parse_errors[0].messages[0].range.0.line, 1); + assert_eq!(result.parse_errors[0].messages[0].range.0.column, Some(8)); +} + +#[test] +fn test_list_variables_with_file_noexist() { + let file = PathBuf::from("./src/test_data/test_list_variables/noexist.k") + .display() + .to_string(); + let specs = vec!["a".to_string()]; + let result = list_variables(vec![file.clone()], specs, None); + assert!(result.is_err()); + let err = result.err().unwrap(); + assert_eq!( + err.to_string(), + "Cannot find the kcl file, please check the file path ./src/test_data/test_list_variables/noexist.k" + ); +} + +#[test] +fn test_override_file_with_invalid_spec() { + let specs = vec!["....".to_string()]; + let import_paths = vec![]; + let file = PathBuf::from("./src/test_data/test_override_file/main.k") + .canonicalize() + .unwrap() + .display() + .to_string(); + let result = override_file(&file, &specs, &import_paths); + assert!(result.is_err()); + let err = result.err().unwrap(); + assert_eq!( + err.to_string(), + "Invalid spec format '....', expected =, :, += or -" + ); +} + +#[test] +fn test_list_merged_variables() { + let file = PathBuf::from("./src/test_data/test_list_variables/test_list_merged_variables") + .canonicalize() + .unwrap(); + + file.join("path").display().to_string(); + + let test_cases = vec![ + ( + vec![ + file.join("merge_1/base.k").display().to_string(), + file.join("merge_1/main.k").display().to_string(), + ], + vec!["appConfiguration.resource".to_string()], + vec![r#"res.Resource {cpu = "2", disk = "35Gi", memory = "4Gi"}"#.to_string()], + ), + ( + vec![ + file.join("merge_2/base.k").display().to_string(), + file.join("merge_2/main.k").display().to_string(), + ], + vec!["appConfiguration.resource".to_string()], + vec![r#"res.Resource { + cpu = "2" + memory = "4Gi" +}"#.to_string()], + ), + ( + vec![ + file.join("merge_3/base.k").display().to_string(), + file.join("merge_3/main.k").display().to_string(), + ], + vec!["appConfiguration.resource".to_string()], + vec![r#"res.Resource {cpu = "2", disk = "35Gi", memory = "4Gi"}"#.to_string()], + ), + ( + vec![ + file.join("merge_4/base.k").display().to_string(), + file.join("merge_4/main.k").display().to_string(), + ], + vec!["appConfiguration.resource".to_string()], + vec![r#"res.Resource { + cpu = "2" + memory = "4Gi" +}"#.to_string()], + ), + ( + vec![ + file.join("merge_5/base.k").display().to_string(), + file.join("merge_5/main.k").display().to_string(), + ], + vec!["appConfiguration.resource".to_string()], + vec![r#"res.Resource {cpu = {limit: "200m", limit_plus: "20000m", request: "100m"}, disk = "35Gi", memory = "4Gi"}"#.to_string()], + ), + ( + vec![ + file.join("merge_6/main.k").display().to_string(), + file.join("merge_6/base.k").display().to_string(), + ], + vec!["config".to_string()], + vec![r#"Config { + name = "config2" + args: ["kcl", "main.k"] + labels: {key1: "value1"} +}"#.to_string()], + ), + ( + vec![ + file.join("merge_7/main.k").display().to_string(), + file.join("merge_7/base.k").display().to_string(), + ], + vec!["config".to_string()], + vec![r#"Config { + name = _NAME + args: ["kcl", "main.k"] + labels: {key1: "value1"} +}"#.to_string()], + ), + ( + vec![ + file.join("merge_8/main.k").display().to_string(), + ], + vec!["config".to_string()], + vec![r#"Config { + args: [ + "kcl" + "main.k" + ] + labels: { + key1: "value1" + } + labels: { + key2: "value2" + } + "labels": { + "key3": "value3" + } +}"#.to_string()], + ), + ( + vec![ + file.join("merge_9/main.k").display().to_string(), + ], + vec!["config".to_string()], + vec![r#"Config { + args: [ + "kcl" + "main.k" + ] + labels: { + key1: "value1" + } + labels: { + key2: "value2" + } + name: { + name: { + name: "name" + } + } + name: { + name: Name0 {data: 1} + } +}"#.to_string()], + ), + ( + vec![ + file.join("merge_10/main.k").display().to_string(), + ], + vec!["alice.hc".to_string()], + vec![r#"[ + 2 +]"#.to_string()], + ), + ( + vec![ + file.join("merge_11/main.k").display().to_string(), + ], + vec!["config.main".to_string()], + vec![r#"Main {args: ["1"], env: ["789", "456"]}"#.to_string()], + ), + ]; + + for (files, specs, expected_values) in test_cases { + println!("{:?}", files); + let result = list_variables( + files, + specs.clone(), + Some(&ListOptions { + merge_program: true, + }), + ) + .unwrap(); + for (i, expected_value) in expected_values.iter().enumerate() { + let variables = result + .variables + .get(&specs.get(i).unwrap().to_string()) + .unwrap(); + assert_eq!(variables.len(), 1); + for variable in variables { + assert_eq!(variable.value.to_string(), expected_value.to_string()); + } + } + } +} diff --git a/crates/query/src/util.rs b/crates/query/src/util.rs new file mode 100644 index 000000000..d4dbbda5d --- /dev/null +++ b/crates/query/src/util.rs @@ -0,0 +1,41 @@ +use anyhow::{Result, anyhow}; + +/// Get field package path and identifier name from the path. +/// (TODO: Needs to be a package related to the language specification +/// and move this function into it.) +/// +/// split_field_path("pkg.to.path:field") -> ("pkg.to.path", "field") +pub(crate) fn split_field_path(path: &str) -> Result<(String, String)> { + let err = Err(anyhow!("Invalid field path {:?}", path)); + let paths = path.splitn(2, ':').collect::>(); + let (pkgpath, field_path) = if paths.len() == 1 { + ("".to_string(), paths[0].to_string()) + } else if paths.len() == 2 { + (paths[0].to_string(), paths[1].to_string()) + } else { + return err; + }; + if field_path.is_empty() { + err + } else { + Ok((pkgpath, field_path)) + } +} + +/// Get the invalid spec error message. +#[inline] +pub(crate) fn invalid_spec_error(spec: &str) -> anyhow::Error { + anyhow!( + "Invalid spec format '{}', expected =, :, += or -", + spec + ) +} + +/// Get the invalid symbol selector spec error message. +#[inline] +pub(crate) fn invalid_symbol_selector_spec_error(spec: &str) -> anyhow::Error { + anyhow!( + "Invalid spec format '{}', expected :", + spec + ) +} diff --git a/crates/runner/Cargo.toml b/crates/runner/Cargo.toml new file mode 100644 index 000000000..1a3422fc3 --- /dev/null +++ b/crates/runner/Cargo.toml @@ -0,0 +1,48 @@ +[package] +name = "kcl-runner" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[build-dependencies] +cc = "1.0" + +[dependencies] +serde_json = "1.0" +serde = { version = "1", features = ["derive"] } +glob = "0.3.0" +walkdir = "2" +libc = "0.2.112" +libloading = "0.7.3" +threadpool = "1.0" +chrono = "0.4.19" +tempfile = "3.5.0" +anyhow = "1.0" +once_cell = "1.10" +cc = "1.0" +uuid = "1.7.0" +compiler_base_session = "0.1.3" +compiler_base_macros = "0.1.1" + +kcl-ast = { path = "../ast" } +kcl-parser = { path = "../parser" } +kcl-compiler = { path = "../compiler" } +kcl-config = { path = "../config" } +kcl-runtime = { path = "../runtime" } +kcl-sema = { path = "../sema" } +kcl-version = { path = "../version" } +kcl-error = { path = "../error" } +kcl-query = { path = "../query" } +kcl-utils = { path = "../utils" } +kcl-driver = { path = "../driver" } +kcl-evaluator = { path = "../evaluator" } +kcl-primitives = { path = "../primitives" } + +[dev-dependencies] +kcl-parser = { path = "../parser" } +criterion = "0.5" + +[[bench]] +name = "bench_runner" +harness = false diff --git a/kclvm/runner/benches/bench_runner.rs b/crates/runner/benches/bench_runner.rs similarity index 89% rename from kclvm/runner/benches/bench_runner.rs rename to crates/runner/benches/bench_runner.rs index 399033d4b..c59c07238 100644 --- a/kclvm/runner/benches/bench_runner.rs +++ b/crates/runner/benches/bench_runner.rs @@ -2,16 +2,16 @@ use anyhow::Result; use std::path::Path; use std::sync::Arc; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; use walkdir::WalkDir; -use kclvm_parser::{load_program, ParseSession}; -use kclvm_runner::{execute, runner::ExecProgramArgs}; +use kcl_parser::{ParseSession, load_program}; +use kcl_runner::{execute, runner::ExecProgramArgs}; const EXEC_DATA_PATH: &str = "./src/exec_data/"; pub fn criterion_benchmark(c: &mut Criterion) { - c.bench_function("refactor kclvm-runner", |b| { + c.bench_function("refactor kcl-runner", |b| { b.iter(|| { let prev_hook = std::panic::take_hook(); // disable print panic info diff --git a/crates/runner/build.rs b/crates/runner/build.rs new file mode 100644 index 000000000..7e8231078 --- /dev/null +++ b/crates/runner/build.rs @@ -0,0 +1,11 @@ +fn main() { + setup_target(); +} + +/// Set rustc TARGET to KCL_DEFAULT_TARGET +fn setup_target() { + println!( + "cargo:rustc-env=KCL_DEFAULT_TARGET={}", + std::env::var("TARGET").unwrap() + ); +} diff --git a/kclvm/runner/src/custom_manifests_data/dict.k b/crates/runner/src/custom_manifests_data/dict.k similarity index 100% rename from kclvm/runner/src/custom_manifests_data/dict.k rename to crates/runner/src/custom_manifests_data/dict.k diff --git a/kclvm/runner/src/custom_manifests_data/dict.stdout.golden b/crates/runner/src/custom_manifests_data/dict.stdout.golden similarity index 100% rename from kclvm/runner/src/custom_manifests_data/dict.stdout.golden rename to crates/runner/src/custom_manifests_data/dict.stdout.golden diff --git a/kclvm/runner/src/custom_manifests_data/dict_ignore_none.k b/crates/runner/src/custom_manifests_data/dict_ignore_none.k similarity index 100% rename from kclvm/runner/src/custom_manifests_data/dict_ignore_none.k rename to crates/runner/src/custom_manifests_data/dict_ignore_none.k diff --git a/kclvm/runner/src/custom_manifests_data/dict_ignore_none.stdout.golden b/crates/runner/src/custom_manifests_data/dict_ignore_none.stdout.golden similarity index 100% rename from kclvm/runner/src/custom_manifests_data/dict_ignore_none.stdout.golden rename to crates/runner/src/custom_manifests_data/dict_ignore_none.stdout.golden diff --git a/kclvm/runner/src/custom_manifests_data/dict_sort_key.k b/crates/runner/src/custom_manifests_data/dict_sort_key.k similarity index 100% rename from kclvm/runner/src/custom_manifests_data/dict_sort_key.k rename to crates/runner/src/custom_manifests_data/dict_sort_key.k diff --git a/kclvm/runner/src/custom_manifests_data/dict_sort_key.stdout.golden b/crates/runner/src/custom_manifests_data/dict_sort_key.stdout.golden similarity index 100% rename from kclvm/runner/src/custom_manifests_data/dict_sort_key.stdout.golden rename to crates/runner/src/custom_manifests_data/dict_sort_key.stdout.golden diff --git a/kclvm/runner/src/custom_manifests_data/list.k b/crates/runner/src/custom_manifests_data/list.k similarity index 100% rename from kclvm/runner/src/custom_manifests_data/list.k rename to crates/runner/src/custom_manifests_data/list.k diff --git a/kclvm/runner/src/custom_manifests_data/list.stdout.golden b/crates/runner/src/custom_manifests_data/list.stdout.golden similarity index 100% rename from kclvm/runner/src/custom_manifests_data/list.stdout.golden rename to crates/runner/src/custom_manifests_data/list.stdout.golden diff --git a/kclvm/runner/src/custom_manifests_data/schema.k b/crates/runner/src/custom_manifests_data/schema.k similarity index 100% rename from kclvm/runner/src/custom_manifests_data/schema.k rename to crates/runner/src/custom_manifests_data/schema.k diff --git a/kclvm/runner/src/custom_manifests_data/schema.stdout.golden b/crates/runner/src/custom_manifests_data/schema.stdout.golden similarity index 100% rename from kclvm/runner/src/custom_manifests_data/schema.stdout.golden rename to crates/runner/src/custom_manifests_data/schema.stdout.golden diff --git a/kclvm/runner/src/custom_manifests_data/schema_ignore_none.k b/crates/runner/src/custom_manifests_data/schema_ignore_none.k similarity index 100% rename from kclvm/runner/src/custom_manifests_data/schema_ignore_none.k rename to crates/runner/src/custom_manifests_data/schema_ignore_none.k diff --git a/kclvm/runner/src/custom_manifests_data/schema_ignore_none.stdout.golden b/crates/runner/src/custom_manifests_data/schema_ignore_none.stdout.golden similarity index 100% rename from kclvm/runner/src/custom_manifests_data/schema_ignore_none.stdout.golden rename to crates/runner/src/custom_manifests_data/schema_ignore_none.stdout.golden diff --git a/kclvm/runner/src/custom_manifests_data/schema_sort_key.k b/crates/runner/src/custom_manifests_data/schema_sort_key.k similarity index 100% rename from kclvm/runner/src/custom_manifests_data/schema_sort_key.k rename to crates/runner/src/custom_manifests_data/schema_sort_key.k diff --git a/kclvm/runner/src/custom_manifests_data/schema_sort_key.stdout.golden b/crates/runner/src/custom_manifests_data/schema_sort_key.stdout.golden similarity index 100% rename from kclvm/runner/src/custom_manifests_data/schema_sort_key.stdout.golden rename to crates/runner/src/custom_manifests_data/schema_sort_key.stdout.golden diff --git a/kclvm/runner/src/exec_data/assert.k b/crates/runner/src/exec_data/assert.k similarity index 100% rename from kclvm/runner/src/exec_data/assert.k rename to crates/runner/src/exec_data/assert.k diff --git a/kclvm/runner/src/exec_data/aug_assign.k b/crates/runner/src/exec_data/aug_assign.k similarity index 100% rename from kclvm/runner/src/exec_data/aug_assign.k rename to crates/runner/src/exec_data/aug_assign.k diff --git a/kclvm/runner/src/exec_data/calculation.k b/crates/runner/src/exec_data/calculation.k similarity index 100% rename from kclvm/runner/src/exec_data/calculation.k rename to crates/runner/src/exec_data/calculation.k diff --git a/kclvm/runner/src/exec_data/collection_if.k b/crates/runner/src/exec_data/collection_if.k similarity index 100% rename from kclvm/runner/src/exec_data/collection_if.k rename to crates/runner/src/exec_data/collection_if.k diff --git a/kclvm/runner/src/exec_data/compare.k b/crates/runner/src/exec_data/compare.k similarity index 100% rename from kclvm/runner/src/exec_data/compare.k rename to crates/runner/src/exec_data/compare.k diff --git a/kclvm/runner/src/exec_data/complex.k b/crates/runner/src/exec_data/complex.k similarity index 100% rename from kclvm/runner/src/exec_data/complex.k rename to crates/runner/src/exec_data/complex.k diff --git a/kclvm/runner/src/exec_data/convert_collection_value.k b/crates/runner/src/exec_data/convert_collection_value.k similarity index 100% rename from kclvm/runner/src/exec_data/convert_collection_value.k rename to crates/runner/src/exec_data/convert_collection_value.k diff --git a/kclvm/runner/src/exec_data/for.k b/crates/runner/src/exec_data/for.k similarity index 100% rename from kclvm/runner/src/exec_data/for.k rename to crates/runner/src/exec_data/for.k diff --git a/kclvm/runner/src/exec_data/if.k b/crates/runner/src/exec_data/if.k similarity index 100% rename from kclvm/runner/src/exec_data/if.k rename to crates/runner/src/exec_data/if.k diff --git a/kclvm/runner/src/exec_data/index_signature.k b/crates/runner/src/exec_data/index_signature.k similarity index 100% rename from kclvm/runner/src/exec_data/index_signature.k rename to crates/runner/src/exec_data/index_signature.k diff --git a/kclvm/runner/src/exec_data/kcl.mod b/crates/runner/src/exec_data/kcl.mod similarity index 100% rename from kclvm/runner/src/exec_data/kcl.mod rename to crates/runner/src/exec_data/kcl.mod diff --git a/kclvm/runner/src/exec_data/lambda.k.fixme b/crates/runner/src/exec_data/lambda.k.fixme similarity index 100% rename from kclvm/runner/src/exec_data/lambda.k.fixme rename to crates/runner/src/exec_data/lambda.k.fixme diff --git a/kclvm/runner/src/exec_data/lambda_return_undefined.k b/crates/runner/src/exec_data/lambda_return_undefined.k similarity index 100% rename from kclvm/runner/src/exec_data/lambda_return_undefined.k rename to crates/runner/src/exec_data/lambda_return_undefined.k diff --git a/kclvm/runner/src/exec_data/list.k b/crates/runner/src/exec_data/list.k similarity index 100% rename from kclvm/runner/src/exec_data/list.k rename to crates/runner/src/exec_data/list.k diff --git a/kclvm/runner/src/exec_data/member_ship.k b/crates/runner/src/exec_data/member_ship.k similarity index 100% rename from kclvm/runner/src/exec_data/member_ship.k rename to crates/runner/src/exec_data/member_ship.k diff --git a/kclvm/runner/src/exec_data/nest_var.k b/crates/runner/src/exec_data/nest_var.k similarity index 100% rename from kclvm/runner/src/exec_data/nest_var.k rename to crates/runner/src/exec_data/nest_var.k diff --git a/kclvm/runner/src/exec_data/plus.k b/crates/runner/src/exec_data/plus.k similarity index 100% rename from kclvm/runner/src/exec_data/plus.k rename to crates/runner/src/exec_data/plus.k diff --git a/kclvm/runner/src/exec_data/quant_expr.k b/crates/runner/src/exec_data/quant_expr.k similarity index 100% rename from kclvm/runner/src/exec_data/quant_expr.k rename to crates/runner/src/exec_data/quant_expr.k diff --git a/kclvm/runner/src/exec_data/regex.k b/crates/runner/src/exec_data/regex.k similarity index 100% rename from kclvm/runner/src/exec_data/regex.k rename to crates/runner/src/exec_data/regex.k diff --git a/kclvm/runner/src/exec_data/rule.k b/crates/runner/src/exec_data/rule.k similarity index 100% rename from kclvm/runner/src/exec_data/rule.k rename to crates/runner/src/exec_data/rule.k diff --git a/kclvm/runner/src/exec_data/schema.k b/crates/runner/src/exec_data/schema.k similarity index 100% rename from kclvm/runner/src/exec_data/schema.k rename to crates/runner/src/exec_data/schema.k diff --git a/kclvm/runner/src/exec_data/schema_args.k b/crates/runner/src/exec_data/schema_args.k similarity index 100% rename from kclvm/runner/src/exec_data/schema_args.k rename to crates/runner/src/exec_data/schema_args.k diff --git a/kclvm/runner/src/exec_data/str.k b/crates/runner/src/exec_data/str.k similarity index 100% rename from kclvm/runner/src/exec_data/str.k rename to crates/runner/src/exec_data/str.k diff --git a/kclvm/runner/src/exec_data/type_alias.k b/crates/runner/src/exec_data/type_alias.k similarity index 100% rename from kclvm/runner/src/exec_data/type_alias.k rename to crates/runner/src/exec_data/type_alias.k diff --git a/kclvm/runner/src/exec_data/type_as.k b/crates/runner/src/exec_data/type_as.k similarity index 100% rename from kclvm/runner/src/exec_data/type_as.k rename to crates/runner/src/exec_data/type_as.k diff --git a/kclvm/runner/src/exec_data/types.k b/crates/runner/src/exec_data/types.k similarity index 100% rename from kclvm/runner/src/exec_data/types.k rename to crates/runner/src/exec_data/types.k diff --git a/kclvm/runner/src/exec_data/unary.k b/crates/runner/src/exec_data/unary.k similarity index 100% rename from kclvm/runner/src/exec_data/unary.k rename to crates/runner/src/exec_data/unary.k diff --git a/kclvm/runner/src/exec_data/unification.k b/crates/runner/src/exec_data/unification.k similarity index 100% rename from kclvm/runner/src/exec_data/unification.k rename to crates/runner/src/exec_data/unification.k diff --git a/kclvm/runner/src/exec_data/unification_with_mixin.k b/crates/runner/src/exec_data/unification_with_mixin.k similarity index 100% rename from kclvm/runner/src/exec_data/unification_with_mixin.k rename to crates/runner/src/exec_data/unification_with_mixin.k diff --git a/kclvm/runner/src/exec_data/units.k b/crates/runner/src/exec_data/units.k similarity index 100% rename from kclvm/runner/src/exec_data/units.k rename to crates/runner/src/exec_data/units.k diff --git a/kclvm/runner/src/exec_err_data/attr_not_found.k b/crates/runner/src/exec_err_data/attr_not_found.k similarity index 100% rename from kclvm/runner/src/exec_err_data/attr_not_found.k rename to crates/runner/src/exec_err_data/attr_not_found.k diff --git a/kclvm/runner/src/exec_err_data/attr_not_found.stderr.json b/crates/runner/src/exec_err_data/attr_not_found.stderr.json similarity index 100% rename from kclvm/runner/src/exec_err_data/attr_not_found.stderr.json rename to crates/runner/src/exec_err_data/attr_not_found.stderr.json diff --git a/crates/runner/src/lib.rs b/crates/runner/src/lib.rs new file mode 100644 index 000000000..e5a26123b --- /dev/null +++ b/crates/runner/src/lib.rs @@ -0,0 +1,216 @@ +use std::{ + collections::HashMap, + sync::{Arc, RwLock}, +}; + +use anyhow::{Result, bail}; +use kcl_ast::{ + MAIN_PKG, + ast::{Module, Program}, +}; +use kcl_parser::{KCLModuleCache, ParseSessionRef, load_program}; +use kcl_query::apply_overrides; +use kcl_sema::resolver::{ + Options, resolve_program, resolve_program_with_opts, scope::ProgramScope, +}; +pub use runner::{ExecProgramArgs, ExecProgramResult, MapErrorResult}; +use runner::{FastRunner, RunnerOptions}; + +pub mod linker; +pub mod runner; + +#[cfg(test)] +pub mod tests; + +/// After the kcl program passed through kcl-parser in the compiler frontend, +/// KCL needs to resolve ast, generate corresponding LLVM IR, dynamic link library or +/// executable file for kcl program in the compiler backend. +/// +/// Method “execute” is the entry point for the compiler backend. +/// +/// It returns the KCL program executing result as Result, +/// and mainly takes "program" (ast.Program returned by kcl-parser) as input. +/// +/// "args" is the items selected by the user in the KCL CLI. +/// +/// This method will first resolve “program” (ast.Program) and save the result to the "scope" (ProgramScope). +/// +/// Then, dynamic link libraries is generated by KclAssembler, and method "KclAssembler::gen_libs" +/// will return dynamic link library paths in a "Vec"; +/// +/// KclAssembler is mainly responsible for concurrent compilation of multiple files. +/// Single-file compilation in each thread in concurrent compilation is the responsibility of KclLibAssembler. +/// In the future, it may support the dynamic link library generation of multiple intermediate language. +/// KclLibAssembler currently only supports LLVM IR. +/// +/// After linking all dynamic link libraries by KclLinker, method "KclLinker::link_all_libs" will return a path +/// for dynamic link library after linking. +/// +/// At last, KclLibRunner will be constructed and call method "run" to execute the kcl program. +/// +/// **Note that it is not thread safe.** +/// +/// # Examples +/// +/// ``` +/// use kcl_runner::{exec_program, ExecProgramArgs}; +/// use kcl_parser::ParseSession; +/// use std::sync::Arc; +/// +/// // Create sessions +/// let sess = Arc::new(ParseSession::default()); +/// // Get default args +/// let mut args = ExecProgramArgs::default(); +/// args.k_filename_list = vec!["./src/test_datas/init_check_order_0/main.k".to_string()]; +/// +/// // Resolve ast, generate libs, link libs and execute. +/// // Result is the kcl in json format. +/// let result = exec_program(sess, &args).unwrap(); +/// ``` +pub fn exec_program(sess: ParseSessionRef, args: &ExecProgramArgs) -> Result { + // parse args from json string + let opts = args.get_load_program_options(); + let kcl_paths_str = args + .k_filename_list + .iter() + .map(|s| s.as_str()) + .collect::>(); + let module_cache = KCLModuleCache::default(); + let mut program = load_program( + sess.clone(), + kcl_paths_str.as_slice(), + Some(opts), + Some(module_cache), + )? + .program; + apply_overrides( + &mut program, + &args.overrides, + &[], + args.print_override_ast || args.debug > 0, + )?; + execute(sess, program, args) +} + +/// After the kcl program passed through kcl-parser in the compiler frontend, +/// KCL needs to resolve ast, generate corresponding LLVM IR, dynamic link library or +/// executable file for kcl program in the compiler backend. +/// +/// Method “execute” is the entry point for the compiler backend. +/// +/// It returns the KCL program executing result as Result, +/// and mainly takes "program" (ast.Program returned by kcl-parser) as input. +/// +/// "args" is the items selected by the user in the KCL CLI. +/// +/// This method will first resolve “program” (ast.Program) and save the result to the "scope" (ProgramScope). +/// +/// Then, dynamic link libraries is generated by KclAssembler, and method "KclAssembler::gen_libs" +/// will return dynamic link library paths in a "Vec"; +/// +/// KclAssembler is mainly responsible for concurrent compilation of multiple files. +/// Single-file compilation in each thread in concurrent compilation is the responsibility of KclLibAssembler. +/// In the future, it may support the dynamic link library generation of multiple intermediate language. +/// KclLibAssembler currently only supports LLVM IR. +/// +/// After linking all dynamic link libraries by KclLinker, method "KclLinker::link_all_libs" will return a path +/// for dynamic link library after linking. +/// +/// At last, KclLibRunner will be constructed and call method "run" to execute the kcl program. +/// +/// **Note that it is not thread safe.** +/// +/// # Examples +/// +/// ``` +/// use kcl_runner::{execute, runner::ExecProgramArgs}; +/// use kcl_parser::{load_program, ParseSession}; +/// use kcl_ast::ast::Program; +/// use std::sync::Arc; +/// +/// // Create sessions +/// let sess = Arc::new(ParseSession::default()); +/// // Get default args +/// let args = ExecProgramArgs::default(); +/// let opts = args.get_load_program_options(); +/// +/// // Parse kcl file +/// let kcl_path = "./src/test_datas/init_check_order_0/main.k"; +/// let prog = load_program(sess.clone(), &[kcl_path], Some(opts), None).unwrap().program; +/// +/// // Resolve ast, generate libs, link libs and execute. +/// // Result is the kcl in json format. +/// let result = execute(sess, prog, &args).unwrap(); +/// ``` +pub fn execute( + sess: ParseSessionRef, + mut program: Program, + args: &ExecProgramArgs, +) -> Result { + // If the user only wants to compile the kcl program, the following code will only resolve ast. + if args.compile_only { + let mut resolve_opts = Options::default(); + resolve_opts.merge_program = false; + // Resolve ast + let scope = resolve_program_with_opts(&mut program, resolve_opts, None); + emit_compile_diag_to_string(sess, &scope, args.compile_only)?; + return Ok(ExecProgramResult::default()); + } + // Resolve ast + let scope = resolve_program(&mut program); + // Emit parse and resolve errors if exists. + emit_compile_diag_to_string(sess, &scope, false)?; + Ok(FastRunner::new(Some(RunnerOptions { + plugin_agent_ptr: args.plugin_agent, + })) + .run(&program, args)?) +} + +/// `execute_module` can directly execute the ast `Module`. +/// `execute_module` constructs `Program` with default pkg name `MAIN_PKG`, +/// and calls method `execute` with default `plugin_agent` and `ExecProgramArgs`. +/// For more information, see doc above method `execute`. +/// +/// **Note that it is not thread safe.** +pub fn execute_module(m: Module) -> Result { + let mut pkgs = HashMap::new(); + let mut modules = HashMap::new(); + pkgs.insert(MAIN_PKG.to_string(), vec![m.filename.clone()]); + modules.insert(m.filename.clone(), Arc::new(RwLock::new(m))); + + let prog = Program { + root: MAIN_PKG.to_string(), + pkgs, + modules, + pkgs_not_imported: HashMap::new(), + modules_not_imported: HashMap::new(), + }; + + execute( + ParseSessionRef::default(), + prog, + &ExecProgramArgs::default(), + ) +} + +// [`emit_compile_diag_to_string`] will emit compile diagnostics to string, including parsing and resolving diagnostics. +fn emit_compile_diag_to_string( + sess: ParseSessionRef, + scope: &ProgramScope, + include_warnings: bool, +) -> Result<()> { + let mut res_str = sess.1.write().emit_to_string()?; + let sema_err = scope.emit_diagnostics_to_string(sess.0.clone(), include_warnings); + if let Err(err) = &sema_err { + #[cfg(not(target_os = "windows"))] + res_str.push('\n'); + #[cfg(target_os = "windows")] + res_str.push_str("\r\n"); + res_str.push_str(err); + } + + res_str + .is_empty() + .then(|| Ok(())) + .unwrap_or_else(|| bail!(res_str)) +} diff --git a/kclvm/runner/src/linker.rs b/crates/runner/src/linker.rs similarity index 87% rename from kclvm/runner/src/linker.rs rename to crates/runner/src/linker.rs index e6aefa782..a3761f162 100644 --- a/kclvm/runner/src/linker.rs +++ b/crates/runner/src/linker.rs @@ -1,16 +1,16 @@ use anyhow::Result; -use kclvm_utils::path::PathPrefix; +use kcl_utils::path::PathPrefix; use std::env::consts::DLL_SUFFIX; use std::path::PathBuf; -const KCLVM_CLI_BIN_PATH_ENV_VAR: &str = "KCLVM_CLI_BIN_PATH"; -const KCLVM_LIB_LINK_PATH_ENV_VAR: &str = "KCLVM_LIB_LINK_PATH"; -const KCLVM_LIB_SHORT_NAME: &str = "kclvm_cli_cdylib"; +const KCL_CLI_BIN_PATH_ENV_VAR: &str = "KCL_CLI_BIN_PATH"; +const KCL_LIB_LINK_PATH_ENV_VAR: &str = "KCL_LIB_LINK_PATH"; +const KCL_LIB_SHORT_NAME: &str = "kcl"; const EXEC_ROOT_NOT_FOUND_MSG: &str = "Internal error: the executable root is not found"; -/// KclvmLinker is mainly responsible for linking the libs generated by KclvmAssembler. -pub struct KclvmLinker; -impl KclvmLinker { +/// KclLinker is mainly responsible for linking the libs generated by KclAssembler. +pub struct KclLinker; +impl KclLinker { /// Link the libs generated by method "gen_bc_or_ll_file". pub fn link_all_libs(lib_paths: Vec, lib_path: String) -> Result { // In the final stage of link, we can't ignore any undefined symbols and do @@ -107,7 +107,7 @@ impl Command { .arg(&format!("-Wl,-rpath,{}", &path)) .arg(&format!("-L{}", &path)) .arg(&format!("-I{}/include", self.executable_root)) - .arg(&format!("-l{KCLVM_LIB_SHORT_NAME}")); + .arg(&format!("-l{KCL_LIB_SHORT_NAME}")); Ok(()) } @@ -120,7 +120,7 @@ impl Command { cmd: &mut std::process::Command, ) -> Result<()> { cmd.args(libs) - .arg(&format!("{KCLVM_LIB_SHORT_NAME}.lib")) + .arg(&format!("{KCL_LIB_SHORT_NAME}.lib")) .arg("/link") .arg("/NOENTRY") .arg("/NOLOGO") @@ -130,20 +130,20 @@ impl Command { .arg("/DLL") .arg(format!("/OUT:{}", lib_path)) .arg("/EXPORT:_kcl_run") - .arg("/EXPORT:kclvm_main") - .arg("/EXPORT:kclvm_plugin_init"); + .arg("/EXPORT:kcl_main") + .arg("/EXPORT:kcl_plugin_init"); Ok(()) } /// Get the executable root. fn get_executable_root() -> Result { - if let Ok(path) = std::env::var(KCLVM_CLI_BIN_PATH_ENV_VAR) { + if let Ok(path) = std::env::var(KCL_CLI_BIN_PATH_ENV_VAR) { return Ok(path); } let bin_name = if Self::is_windows() { - "kclvm_cli.exe" + "libkcl.exe" } else { - "kclvm_cli" + "libkcl" }; let p = if let Some(x) = Self::find_it(bin_name) { x @@ -161,7 +161,7 @@ impl Command { Ok(p.to_str().ok_or(anyhow::anyhow!(err))?.to_string()) } - /// Get KCLVM lib link path + /// Get KCL lib link path pub(crate) fn get_lib_link_path(&self) -> Result { let mut default_path = None; for folder in ["lib", "bin"] { @@ -178,19 +178,19 @@ impl Command { break; } } - Ok(std::env::var(KCLVM_LIB_LINK_PATH_ENV_VAR) + Ok(std::env::var(KCL_LIB_LINK_PATH_ENV_VAR) .ok() .or(default_path) .unwrap_or(self.executable_root.clone())) } - /// Get KCLVM lib name + /// Get KCL lib name pub(crate) fn get_lib_name() -> String { let suffix = Self::get_lib_suffix(); if Self::is_windows() { - format!("{KCLVM_LIB_SHORT_NAME}{suffix}") + format!("{KCL_LIB_SHORT_NAME}{suffix}") } else { - format!("lib{KCLVM_LIB_SHORT_NAME}{suffix}") + format!("lib{KCL_LIB_SHORT_NAME}{suffix}") } } diff --git a/crates/runner/src/runner.rs b/crates/runner/src/runner.rs new file mode 100644 index 000000000..09ae008e8 --- /dev/null +++ b/crates/runner/src/runner.rs @@ -0,0 +1,406 @@ +use anyhow::{Result, anyhow}; +use kcl_evaluator::Evaluator; +use std::collections::HashMap; +use std::{cell::RefCell, rc::Rc}; + +use kcl_ast::ast; +use kcl_config::{ + modfile::get_vendor_home, + settings::{SettingsFile, SettingsPathBuf}, +}; +use kcl_error::{Diagnostic, Handler}; +#[cfg(not(target_arch = "wasm32"))] +use kcl_runtime::kcl_plugin_init; +use kcl_runtime::{Context, PanicInfo, RuntimePanicRecord}; +#[cfg(target_arch = "wasm32")] +use once_cell::sync::Lazy; +use serde::{Deserialize, Serialize}; +use std::os::raw::c_char; + +const RESULT_SIZE: usize = 2048 * 2048; +const KCL_DEBUG_ERROR_ENV_VAR: &str = "KCL_DEBUG_ERROR"; + +#[allow(non_camel_case_types)] +pub type kcl_char_t = c_char; +#[allow(non_camel_case_types)] +pub type kcl_size_t = i32; +#[allow(non_camel_case_types)] +pub type kcl_context_t = std::ffi::c_void; +#[allow(non_camel_case_types)] +pub type kcl_value_ref_t = std::ffi::c_void; + +/// ExecProgramArgs denotes the configuration required to execute the KCL program. +#[derive(Serialize, Deserialize, Debug, Default, Clone)] +pub struct ExecProgramArgs { + pub work_dir: Option, + pub k_filename_list: Vec, + /// -E key=value + pub external_pkgs: Vec, + pub k_code_list: Vec, + /// -D key=value + pub args: Vec, + /// -O override_spec + pub overrides: Vec, + /// -S path_selector + pub path_selector: Vec, + pub disable_yaml_result: bool, + /// Whether to apply overrides on the source code. + pub print_override_ast: bool, + /// -r --strict-range-check + pub strict_range_check: bool, + /// -n --disable-none + pub disable_none: bool, + /// -v --verbose + pub verbose: i32, + /// -d --debug + pub debug: i32, + /// yaml/json: sort keys + pub sort_keys: bool, + /// Show hidden attributes + pub show_hidden: bool, + /// Whether including schema type in JSON/YAML result + pub include_schema_type_path: bool, + /// Whether to compile only. + pub compile_only: bool, + /// plugin_agent is the address of plugin. + #[serde(skip)] + pub plugin_agent: u64, + /// fast_eval denotes directly executing at the AST level to obtain + /// the result without any form of compilation. + #[serde(skip)] + pub fast_eval: bool, +} + +impl ExecProgramArgs { + /// [`get_package_maps_from_external_pkg`] gets the package name to package path mapping. + pub fn get_package_maps_from_external_pkg(&self) -> HashMap { + let mut package_maps = HashMap::new(); + for external_pkg in &self.external_pkgs { + package_maps.insert(external_pkg.pkg_name.clone(), external_pkg.pkg_path.clone()); + } + package_maps + } + + /// [`set_external_pkg_from_package_maps`] sets the package name to package path mapping. + pub fn set_external_pkg_from_package_maps(&mut self, package_maps: HashMap) { + self.external_pkgs = package_maps + .iter() + .map(|(pkg_name, pkg_path)| ast::ExternalPkg { + pkg_name: pkg_name.clone(), + pkg_path: pkg_path.clone(), + }) + .collect(); + } +} + +/// ExecProgramResult denotes the running result of the KCL program. +#[derive(Serialize, Deserialize, Debug, Default, Clone)] +pub struct ExecProgramResult { + pub json_result: String, + pub yaml_result: String, + pub log_message: String, + pub err_message: String, +} + +pub trait MapErrorResult { + /// Map execute error message into the [`Result::Err`] + fn map_err_to_result(self) -> Result + where + Self: Sized; +} + +impl MapErrorResult for ExecProgramResult { + /// Map execute error message into the [`Result::Err`] + fn map_err_to_result(self) -> Result + where + Self: Sized, + { + if self.err_message.is_empty() { + Ok(self) + } else { + Err(anyhow!(self.err_message)) + } + } +} + +impl MapErrorResult for Result { + /// Map execute error message into the [`Result::Err`] + fn map_err_to_result(self) -> Result + where + Self: Sized, + { + match self { + Ok(result) => result.map_err_to_result(), + Err(err) => Err(err), + } + } +} + +impl ExecProgramArgs { + /// Deserialize an instance of type [ExecProgramArgs] from a string of JSON text. + pub fn from_str(s: &str) -> Self { + if s.trim().is_empty() { + return Default::default(); + } + serde_json::from_str::(s).expect(s) + } + + /// Serialize the [ExecProgramArgs] structure as a String of JSON. + pub fn to_json(&self) -> String { + serde_json::ser::to_string(self).unwrap() + } + + /// Get the input file list. + pub fn get_files(&self) -> Vec<&str> { + self.k_filename_list.iter().map(|s| s.as_str()).collect() + } + + /// Get the [`kcl_parser::LoadProgramOptions`] from the [`kcl_runner::ExecProgramArgs`] + pub fn get_load_program_options(&self) -> kcl_parser::LoadProgramOptions { + kcl_parser::LoadProgramOptions { + work_dir: self.work_dir.clone().unwrap_or_default(), + vendor_dirs: vec![get_vendor_home()], + package_maps: self.get_package_maps_from_external_pkg(), + k_code_list: self.k_code_list.clone(), + load_plugins: self.plugin_agent > 0, + ..Default::default() + } + } +} + +impl TryFrom for ExecProgramArgs { + type Error = anyhow::Error; + fn try_from(settings: SettingsFile) -> Result { + let mut args = Self::default(); + if let Some(cli_configs) = settings.kcl_cli_configs { + args.k_filename_list = cli_configs.files.unwrap_or_default(); + if args.k_filename_list.is_empty() { + args.k_filename_list = cli_configs.file.unwrap_or_default(); + } + args.strict_range_check = cli_configs.strict_range_check.unwrap_or_default(); + args.disable_none = cli_configs.disable_none.unwrap_or_default(); + args.verbose = cli_configs.verbose.unwrap_or_default() as i32; + args.debug = cli_configs.debug.unwrap_or_default() as i32; + args.sort_keys = cli_configs.sort_keys.unwrap_or_default(); + args.show_hidden = cli_configs.show_hidden.unwrap_or_default(); + args.fast_eval = cli_configs.fast_eval.unwrap_or_default(); + args.include_schema_type_path = + cli_configs.include_schema_type_path.unwrap_or_default(); + for override_str in cli_configs.overrides.unwrap_or_default() { + args.overrides.push(override_str); + } + args.path_selector = cli_configs.path_selector.unwrap_or_default(); + args.set_external_pkg_from_package_maps( + cli_configs.package_maps.unwrap_or(HashMap::default()), + ) + } + if let Some(options) = settings.kcl_options { + args.args = options + .iter() + .map(|o| ast::Argument { + name: o.key.to_string(), + value: o.value.to_string(), + }) + .collect(); + } + Ok(args) + } +} + +impl TryFrom for ExecProgramArgs { + type Error = anyhow::Error; + fn try_from(s: SettingsPathBuf) -> Result { + let mut args: ExecProgramArgs = s.settings().clone().try_into()?; + args.work_dir = s.path().clone().map(|p| p.to_string_lossy().to_string()); + Ok(args) + } +} + +#[derive(Debug, Default)] +pub struct RunnerOptions { + pub plugin_agent_ptr: u64, +} + +pub trait ProgramRunner { + /// Run with the arguments [ExecProgramArgs] and return the program execute result that + /// contains the planning result and the evaluation errors if any. + fn run(&self, args: &ExecProgramArgs) -> Result; +} + +thread_local! { + pub static KCL_RUNTIME_PANIC_RECORD: RefCell = RefCell::new(RuntimePanicRecord::default()) +} + +#[cfg(target_arch = "wasm32")] +static ONCE_PANIC_HOOK: Lazy<()> = Lazy::new(|| { + std::panic::set_hook(Box::new(|info: &std::panic::PanicHookInfo| { + KCL_RUNTIME_PANIC_RECORD.with(|record| { + let mut record = record.borrow_mut(); + record.kcl_panic_info = true; + record.message = if let Some(s) = info.payload().downcast_ref::<&str>() { + s.to_string() + } else if let Some(s) = info.payload().downcast_ref::<&String>() { + (*s).clone() + } else if let Some(s) = info.payload().downcast_ref::() { + (*s).clone() + } else { + "unknown runtime error".to_string() + }; + if let Some(location) = info.location() { + record.rust_file = location.file().to_string(); + record.rust_line = location.line() as i32; + record.rust_col = location.column() as i32; + } + }) + })); +}); + +pub struct FastRunner { + opts: RunnerOptions, +} + +impl FastRunner { + /// New a runner using the lib path and options. + pub fn new(opts: Option) -> Self { + Self { + opts: opts.unwrap_or_default(), + } + } + + /// Run kcl library with exec arguments. + pub fn run(&self, program: &ast::Program, args: &ExecProgramArgs) -> Result { + let ctx = Rc::new(RefCell::new(args_to_ctx(program, args))); + let evaluator = Evaluator::new_with_runtime_ctx(program, ctx.clone()); + #[cfg(target_arch = "wasm32")] + // Ensure the panic hook is set (this will only happen once) for the WASM target, + // because it is single threaded. + Lazy::force(&ONCE_PANIC_HOOK); + #[cfg(not(target_arch = "wasm32"))] + let prev_hook = std::panic::take_hook(); + #[cfg(not(target_arch = "wasm32"))] + std::panic::set_hook(Box::new(|info: &std::panic::PanicHookInfo| { + KCL_RUNTIME_PANIC_RECORD.with(|record| { + let mut record = record.borrow_mut(); + record.kcl_panic_info = true; + record.message = if let Some(s) = info.payload().downcast_ref::<&str>() { + s.to_string() + } else if let Some(s) = info.payload().downcast_ref::<&String>() { + (*s).clone() + } else if let Some(s) = info.payload().downcast_ref::() { + (*s).clone() + } else { + "unknown runtime error".to_string() + }; + if let Some(location) = info.location() { + record.rust_file = location.file().to_string(); + record.rust_line = location.line() as i32; + record.rust_col = location.column() as i32; + } + }) + })); + let evaluator_result = std::panic::catch_unwind(|| { + if self.opts.plugin_agent_ptr > 0 { + #[cfg(not(target_arch = "wasm32"))] + unsafe { + let plugin_method: extern "C-unwind" fn( + method: *const c_char, + args: *const c_char, + kwargs: *const c_char, + ) -> *const c_char = std::mem::transmute(self.opts.plugin_agent_ptr); + kcl_plugin_init(plugin_method); + } + } + evaluator.run() + }); + #[cfg(not(target_arch = "wasm32"))] + std::panic::set_hook(prev_hook); + KCL_RUNTIME_PANIC_RECORD.with(|record| { + let record = record.borrow(); + ctx.borrow_mut().set_panic_info(&record); + }); + let mut result = ExecProgramResult { + log_message: ctx.borrow().log_message.clone(), + ..Default::default() + }; + let is_err = evaluator_result.is_err(); + match evaluator_result { + Ok(r) => match r { + Ok((json, yaml)) => { + result.json_result = json; + result.yaml_result = yaml; + } + Err(err) => { + result.err_message = err.to_string(); + } + }, + Err(err) => { + result.err_message = if is_err { + ctx.borrow() + .get_panic_info_json_string() + .unwrap_or_default() + } else { + kcl_error::err_to_str(err) + }; + } + } + // Wrap runtime JSON Panic error string into diagnostic style string. + if !result.err_message.is_empty() && std::env::var(KCL_DEBUG_ERROR_ENV_VAR).is_err() { + result.err_message = match Handler::default() + .add_diagnostic(>::into(PanicInfo::from( + result.err_message.as_str(), + ))) + .emit_to_string() + { + Ok(msg) => msg, + Err(err) => err.to_string(), + }; + } + // Free all value references at runtime. This is because the runtime context marks + // all KCL objects and holds their copies, so it is necessary to actively GC them. + ctx.borrow().gc(); + Ok(result) + } +} + +pub(crate) fn args_to_ctx(program: &ast::Program, args: &ExecProgramArgs) -> Context { + let mut ctx = Context::new(); + ctx.cfg.strict_range_check = args.strict_range_check; + ctx.cfg.debug_mode = args.debug != 0; + ctx.plan_opts.disable_none = args.disable_none; + ctx.plan_opts.show_hidden = args.show_hidden; + ctx.plan_opts.sort_keys = args.sort_keys; + ctx.plan_opts.include_schema_type_path = args.include_schema_type_path; + ctx.plan_opts.query_paths = args.path_selector.clone(); + for arg in &args.args { + ctx.builtin_option_init(&arg.name, &arg.value); + } + ctx.set_kcl_workdir(&args.work_dir.clone().unwrap_or_default()); + ctx.set_kcl_module_path(&program.root); + ctx +} + +#[repr(C)] +pub struct Buffer(Vec, i32); + +impl Buffer { + #[inline] + pub fn make() -> Self { + let buffer = vec![0u8; RESULT_SIZE]; + Self(buffer, RESULT_SIZE as i32 - 1) + } + + #[inline] + pub fn to_string(&self) -> anyhow::Result { + Ok(String::from_utf8(self.0[0..self.1 as usize].to_vec())?) + } + + #[inline] + pub fn mut_ptr(&mut self) -> *mut c_char { + self.0.as_mut_ptr() as *mut c_char + } + + #[inline] + pub fn mut_len(&mut self) -> &mut i32 { + &mut self.1 + } +} diff --git a/kclvm/runner/src/test_datas/compile_recursive/kcl1/main.k b/crates/runner/src/test_datas/compile_recursive/kcl1/main.k similarity index 100% rename from kclvm/runner/src/test_datas/compile_recursive/kcl1/main.k rename to crates/runner/src/test_datas/compile_recursive/kcl1/main.k diff --git a/kclvm/runner/src/test_datas/compile_recursive/kcl2/main.k b/crates/runner/src/test_datas/compile_recursive/kcl2/main.k similarity index 100% rename from kclvm/runner/src/test_datas/compile_recursive/kcl2/main.k rename to crates/runner/src/test_datas/compile_recursive/kcl2/main.k diff --git a/kclvm/runner/src/test_datas/compile_recursive/main.k b/crates/runner/src/test_datas/compile_recursive/main.k similarity index 100% rename from kclvm/runner/src/test_datas/compile_recursive/main.k rename to crates/runner/src/test_datas/compile_recursive/main.k diff --git a/kclvm/runner/src/test_datas/exec_prog_args/default.json b/crates/runner/src/test_datas/exec_prog_args/default.json similarity index 100% rename from kclvm/runner/src/test_datas/exec_prog_args/default.json rename to crates/runner/src/test_datas/exec_prog_args/default.json diff --git a/kclvm/runner/src/test_datas/init_check_order_0/main.k b/crates/runner/src/test_datas/init_check_order_0/main.k similarity index 100% rename from kclvm/runner/src/test_datas/init_check_order_0/main.k rename to crates/runner/src/test_datas/init_check_order_0/main.k diff --git a/kclvm/runner/src/test_datas/init_check_order_0/stdout.golden.json b/crates/runner/src/test_datas/init_check_order_0/stdout.golden.json similarity index 100% rename from kclvm/runner/src/test_datas/init_check_order_0/stdout.golden.json rename to crates/runner/src/test_datas/init_check_order_0/stdout.golden.json diff --git a/kclvm/runner/src/test_datas/init_check_order_1/main.k b/crates/runner/src/test_datas/init_check_order_1/main.k similarity index 100% rename from kclvm/runner/src/test_datas/init_check_order_1/main.k rename to crates/runner/src/test_datas/init_check_order_1/main.k diff --git a/kclvm/runner/src/test_datas/init_check_order_1/stdout.golden.json b/crates/runner/src/test_datas/init_check_order_1/stdout.golden.json similarity index 100% rename from kclvm/runner/src/test_datas/init_check_order_1/stdout.golden.json rename to crates/runner/src/test_datas/init_check_order_1/stdout.golden.json diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/import_abs_path/app-main/main.k b/crates/runner/src/test_datas/multi_file_compilation/import_abs_path/app-main/main.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/import_abs_path/app-main/main.k rename to crates/runner/src/test_datas/multi_file_compilation/import_abs_path/app-main/main.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/import_abs_path/app-main/some1/pkg1/pkg1.k b/crates/runner/src/test_datas/multi_file_compilation/import_abs_path/app-main/some1/pkg1/pkg1.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/import_abs_path/app-main/some1/pkg1/pkg1.k rename to crates/runner/src/test_datas/multi_file_compilation/import_abs_path/app-main/some1/pkg1/pkg1.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/import_abs_path/kcl.mod b/crates/runner/src/test_datas/multi_file_compilation/import_abs_path/kcl.mod similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/import_abs_path/kcl.mod rename to crates/runner/src/test_datas/multi_file_compilation/import_abs_path/kcl.mod diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/import_abs_path/some0/pkg1/pkg1.k b/crates/runner/src/test_datas/multi_file_compilation/import_abs_path/some0/pkg1/pkg1.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/import_abs_path/some0/pkg1/pkg1.k rename to crates/runner/src/test_datas/multi_file_compilation/import_abs_path/some0/pkg1/pkg1.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/import_abs_path/some1/pkg1/pkg1.k b/crates/runner/src/test_datas/multi_file_compilation/import_abs_path/some1/pkg1/pkg1.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/import_abs_path/some1/pkg1/pkg1.k rename to crates/runner/src/test_datas/multi_file_compilation/import_abs_path/some1/pkg1/pkg1.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/import_regular_module/kcl.mod b/crates/runner/src/test_datas/multi_file_compilation/import_regular_module/kcl.mod similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/import_regular_module/kcl.mod rename to crates/runner/src/test_datas/multi_file_compilation/import_regular_module/kcl.mod diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/import_regular_module/main.k b/crates/runner/src/test_datas/multi_file_compilation/import_regular_module/main.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/import_regular_module/main.k rename to crates/runner/src/test_datas/multi_file_compilation/import_regular_module/main.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/import_regular_module/mymodule.k b/crates/runner/src/test_datas/multi_file_compilation/import_regular_module/mymodule.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/import_regular_module/mymodule.k rename to crates/runner/src/test_datas/multi_file_compilation/import_regular_module/mymodule.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/import_regular_module_as/kcl.mod b/crates/runner/src/test_datas/multi_file_compilation/import_regular_module_as/kcl.mod similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/import_regular_module_as/kcl.mod rename to crates/runner/src/test_datas/multi_file_compilation/import_regular_module_as/kcl.mod diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/import_regular_module_as/main.k b/crates/runner/src/test_datas/multi_file_compilation/import_regular_module_as/main.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/import_regular_module_as/main.k rename to crates/runner/src/test_datas/multi_file_compilation/import_regular_module_as/main.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/import_regular_module_as/mymodule.k b/crates/runner/src/test_datas/multi_file_compilation/import_regular_module_as/mymodule.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/import_regular_module_as/mymodule.k rename to crates/runner/src/test_datas/multi_file_compilation/import_regular_module_as/mymodule.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/main.k b/crates/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/main.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/main.k rename to crates/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/main.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/pkg1/pkg.k b/crates/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/pkg1/pkg.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/pkg1/pkg.k rename to crates/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/pkg1/pkg.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/pkg2.k b/crates/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/pkg2.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/pkg2.k rename to crates/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/pkg2.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/stdout.golden b/crates/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/stdout.golden similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/stdout.golden rename to crates/runner/src/test_datas/multi_file_compilation/no_kcl_mod_file/stdout.golden diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/relative_import/main.k b/crates/runner/src/test_datas/multi_file_compilation/relative_import/main.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/relative_import/main.k rename to crates/runner/src/test_datas/multi_file_compilation/relative_import/main.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/relative_import/mydir/mydir2/mymodule2.k b/crates/runner/src/test_datas/multi_file_compilation/relative_import/mydir/mydir2/mymodule2.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/relative_import/mydir/mydir2/mymodule2.k rename to crates/runner/src/test_datas/multi_file_compilation/relative_import/mydir/mydir2/mymodule2.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/relative_import/mydir/mymodule.k b/crates/runner/src/test_datas/multi_file_compilation/relative_import/mydir/mymodule.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/relative_import/mydir/mymodule.k rename to crates/runner/src/test_datas/multi_file_compilation/relative_import/mydir/mymodule.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/relative_import_as/main.k b/crates/runner/src/test_datas/multi_file_compilation/relative_import_as/main.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/relative_import_as/main.k rename to crates/runner/src/test_datas/multi_file_compilation/relative_import_as/main.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/relative_import_as/mydir/mydir2/mymodule2.k b/crates/runner/src/test_datas/multi_file_compilation/relative_import_as/mydir/mydir2/mymodule2.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/relative_import_as/mydir/mydir2/mymodule2.k rename to crates/runner/src/test_datas/multi_file_compilation/relative_import_as/mydir/mydir2/mymodule2.k diff --git a/kclvm/runner/src/test_datas/multi_file_compilation/relative_import_as/mydir/mymodule.k b/crates/runner/src/test_datas/multi_file_compilation/relative_import_as/mydir/mymodule.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_file_compilation/relative_import_as/mydir/mymodule.k rename to crates/runner/src/test_datas/multi_file_compilation/relative_import_as/mydir/mymodule.k diff --git a/kclvm/runner/src/test_datas/multi_vars_0/main.k b/crates/runner/src/test_datas/multi_vars_0/main.k similarity index 100% rename from kclvm/runner/src/test_datas/multi_vars_0/main.k rename to crates/runner/src/test_datas/multi_vars_0/main.k diff --git a/kclvm/runner/src/test_datas/multi_vars_0/stdout.golden.json b/crates/runner/src/test_datas/multi_vars_0/stdout.golden.json similarity index 100% rename from kclvm/runner/src/test_datas/multi_vars_0/stdout.golden.json rename to crates/runner/src/test_datas/multi_vars_0/stdout.golden.json diff --git a/kclvm/runner/src/test_datas/normal_2/main.k b/crates/runner/src/test_datas/normal_2/main.k similarity index 100% rename from kclvm/runner/src/test_datas/normal_2/main.k rename to crates/runner/src/test_datas/normal_2/main.k diff --git a/kclvm/runner/src/test_datas/normal_2/stdout.golden.json b/crates/runner/src/test_datas/normal_2/stdout.golden.json similarity index 100% rename from kclvm/runner/src/test_datas/normal_2/stdout.golden.json rename to crates/runner/src/test_datas/normal_2/stdout.golden.json diff --git a/crates/runner/src/test_datas/settings_file/settings.json b/crates/runner/src/test_datas/settings_file/settings.json new file mode 100644 index 000000000..c877606e1 --- /dev/null +++ b/crates/runner/src/test_datas/settings_file/settings.json @@ -0,0 +1 @@ +{"work_dir":null,"k_filename_list":["../main.k","./before/base.k","./main.k","./sub/sub.k"],"external_pkgs":[],"k_code_list":[],"args":[{"name":"app-name","value":"\"kcl\""},{"name":"image","value":"\"kcl:v0.0.1\""}],"overrides":[],"path_selector":[],"disable_yaml_result":false,"print_override_ast":false,"strict_range_check":false,"disable_none":false,"verbose":0,"debug":0,"sort_keys":false,"show_hidden":false,"include_schema_type_path":false,"compile_only":false} \ No newline at end of file diff --git a/crates/runner/src/test_datas/settings_file/settings.yaml b/crates/runner/src/test_datas/settings_file/settings.yaml new file mode 100644 index 000000000..8e5af5910 --- /dev/null +++ b/crates/runner/src/test_datas/settings_file/settings.yaml @@ -0,0 +1,14 @@ +kcl_cli_configs: + files: + - ../main.k + - ./before/base.k + - ./main.k + - ./sub/sub.k + disable_none: false + strict_range_check: false + debug: false +kcl_options: + - key: app-name + value: kcl + - key: image + value: kcl:v0.0.1 diff --git a/kclvm/runner/src/test_datas/type_annotation_not_full_2/main.k b/crates/runner/src/test_datas/type_annotation_not_full_2/main.k similarity index 100% rename from kclvm/runner/src/test_datas/type_annotation_not_full_2/main.k rename to crates/runner/src/test_datas/type_annotation_not_full_2/main.k diff --git a/kclvm/runner/src/test_datas/type_annotation_not_full_2/stdout.golden.json b/crates/runner/src/test_datas/type_annotation_not_full_2/stdout.golden.json similarity index 100% rename from kclvm/runner/src/test_datas/type_annotation_not_full_2/stdout.golden.json rename to crates/runner/src/test_datas/type_annotation_not_full_2/stdout.golden.json diff --git a/kclvm/runner/src/test_file_pattern/kcl1/kcl.mod b/crates/runner/src/test_file_pattern/kcl1/kcl.mod similarity index 100% rename from kclvm/runner/src/test_file_pattern/kcl1/kcl.mod rename to crates/runner/src/test_file_pattern/kcl1/kcl.mod diff --git a/kclvm/runner/src/test_file_pattern/kcl1/kcl3/kcl.mod b/crates/runner/src/test_file_pattern/kcl1/kcl3/kcl.mod similarity index 100% rename from kclvm/runner/src/test_file_pattern/kcl1/kcl3/kcl.mod rename to crates/runner/src/test_file_pattern/kcl1/kcl3/kcl.mod diff --git a/kclvm/runner/src/test_file_pattern/kcl1/kcl3/main.k b/crates/runner/src/test_file_pattern/kcl1/kcl3/main.k similarity index 100% rename from kclvm/runner/src/test_file_pattern/kcl1/kcl3/main.k rename to crates/runner/src/test_file_pattern/kcl1/kcl3/main.k diff --git a/kclvm/runner/src/test_file_pattern/kcl1/main.k b/crates/runner/src/test_file_pattern/kcl1/main.k similarity index 100% rename from kclvm/runner/src/test_file_pattern/kcl1/main.k rename to crates/runner/src/test_file_pattern/kcl1/main.k diff --git a/kclvm/runner/src/test_file_pattern/kcl2/kcl.mod b/crates/runner/src/test_file_pattern/kcl2/kcl.mod similarity index 100% rename from kclvm/runner/src/test_file_pattern/kcl2/kcl.mod rename to crates/runner/src/test_file_pattern/kcl2/kcl.mod diff --git a/kclvm/runner/src/test_file_pattern/kcl2/main.k b/crates/runner/src/test_file_pattern/kcl2/main.k similarity index 100% rename from kclvm/runner/src/test_file_pattern/kcl2/main.k rename to crates/runner/src/test_file_pattern/kcl2/main.k diff --git a/kclvm/runner/src/test_indent_error/if_indent_err.k b/crates/runner/src/test_indent_error/if_indent_err.k similarity index 100% rename from kclvm/runner/src/test_indent_error/if_indent_err.k rename to crates/runner/src/test_indent_error/if_indent_err.k diff --git a/kclvm/runner/src/test_indent_error/if_indent_err.stderr b/crates/runner/src/test_indent_error/if_indent_err.stderr similarity index 100% rename from kclvm/runner/src/test_indent_error/if_indent_err.stderr rename to crates/runner/src/test_indent_error/if_indent_err.stderr diff --git a/kclvm/runner/src/test_indent_error/schema_indent_err.k b/crates/runner/src/test_indent_error/schema_indent_err.k similarity index 100% rename from kclvm/runner/src/test_indent_error/schema_indent_err.k rename to crates/runner/src/test_indent_error/schema_indent_err.k diff --git a/kclvm/runner/src/test_indent_error/schema_indent_err.stderr b/crates/runner/src/test_indent_error/schema_indent_err.stderr similarity index 100% rename from kclvm/runner/src/test_indent_error/schema_indent_err.stderr rename to crates/runner/src/test_indent_error/schema_indent_err.stderr diff --git a/kclvm/runner/src/test_issues/github.com/kcl-lang/kcl/1799/main.k b/crates/runner/src/test_issues/github.com/kcl-lang/kcl/1799/main.k similarity index 100% rename from kclvm/runner/src/test_issues/github.com/kcl-lang/kcl/1799/main.k rename to crates/runner/src/test_issues/github.com/kcl-lang/kcl/1799/main.k diff --git a/kclvm/runner/src/test_symbolic_link/test_pkg/aaa/kcl.mod b/crates/runner/src/test_symbolic_link/test_pkg/aaa/kcl.mod similarity index 100% rename from kclvm/runner/src/test_symbolic_link/test_pkg/aaa/kcl.mod rename to crates/runner/src/test_symbolic_link/test_pkg/aaa/kcl.mod diff --git a/kclvm/runner/src/test_symbolic_link/test_pkg/aaa/sub/main.k b/crates/runner/src/test_symbolic_link/test_pkg/aaa/sub/main.k similarity index 100% rename from kclvm/runner/src/test_symbolic_link/test_pkg/aaa/sub/main.k rename to crates/runner/src/test_symbolic_link/test_pkg/aaa/sub/main.k diff --git a/kclvm/runner/src/test_symbolic_link/test_pkg/aaa/sub/sub.k b/crates/runner/src/test_symbolic_link/test_pkg/aaa/sub/sub.k similarity index 100% rename from kclvm/runner/src/test_symbolic_link/test_pkg/aaa/sub/sub.k rename to crates/runner/src/test_symbolic_link/test_pkg/aaa/sub/sub.k diff --git a/kclvm/runner/src/test_symbolic_link/test_pkg/bbb/kcl.mod b/crates/runner/src/test_symbolic_link/test_pkg/bbb/kcl.mod similarity index 100% rename from kclvm/runner/src/test_symbolic_link/test_pkg/bbb/kcl.mod rename to crates/runner/src/test_symbolic_link/test_pkg/bbb/kcl.mod diff --git a/kclvm/runner/src/test_symbolic_link/test_pkg/bbb/main.k b/crates/runner/src/test_symbolic_link/test_pkg/bbb/main.k similarity index 100% rename from kclvm/runner/src/test_symbolic_link/test_pkg/bbb/main.k rename to crates/runner/src/test_symbolic_link/test_pkg/bbb/main.k diff --git a/kclvm/runner/src/test_symbolic_link/test_pkg/bbb/sub.k b/crates/runner/src/test_symbolic_link/test_pkg/bbb/sub.k similarity index 100% rename from kclvm/runner/src/test_symbolic_link/test_pkg/bbb/sub.k rename to crates/runner/src/test_symbolic_link/test_pkg/bbb/sub.k diff --git a/kclvm/runner/src/test_uuid/main.k b/crates/runner/src/test_uuid/main.k similarity index 100% rename from kclvm/runner/src/test_uuid/main.k rename to crates/runner/src/test_uuid/main.k diff --git a/crates/runner/src/tests.rs b/crates/runner/src/tests.rs new file mode 100644 index 000000000..3e6e23dc7 --- /dev/null +++ b/crates/runner/src/tests.rs @@ -0,0 +1,447 @@ +use crate::exec_program; +use crate::{execute, runner::ExecProgramArgs}; +use anyhow::Result; +use kcl_ast::ast::{Module, Program}; +use kcl_config::settings::load_file; +use kcl_parser::ParseSession; +use kcl_parser::load_program; +use kcl_utils::path::PathPrefix; +use serde_json::Value; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::RwLock; +use std::{ + collections::HashMap, + fs::{self, File}, +}; +use uuid::Uuid; +use walkdir::WalkDir; + +const TEST_CASES: &[&str; 5] = &[ + "init_check_order_0", + "init_check_order_1", + "normal_2", + "type_annotation_not_full_2", + "multi_vars_0", +]; + +fn exec_data_path() -> String { + Path::new("src").join("exec_data").display().to_string() +} + +fn exec_err_data_path() -> String { + Path::new("src").join("exec_err_data").display().to_string() +} + +fn custom_manifests_data_path() -> String { + Path::new("src") + .join("custom_manifests_data") + .display() + .to_string() +} + +fn exec_prog_args_test_case() -> Vec { + vec![ + Path::new("exec_prog_args") + .join("default.json") + .display() + .to_string(), + ] +} + +fn settings_file_test_case() -> Vec<(String, String)> { + vec![( + Path::new("settings_file") + .join("settings.yaml") + .display() + .to_string(), + Path::new("settings_file") + .join("settings.json") + .display() + .to_string(), + )] +} + +const EXPECTED_JSON_FILE_NAME: &str = "stdout.golden.json"; + +fn test_case_path() -> String { + Path::new("src").join("test_datas").display().to_string() +} + +const KCL_FILE_NAME: &str = "main.k"; +const MAIN_PKG_NAME: &str = "__main__"; + +#[derive(serde::Deserialize, serde::Serialize)] +struct SimplePanicInfo { + line: i32, + col: i32, + message: String, +} + +/// Load test kcl file to ast.Program +fn load_test_program(filename: String) -> Program { + let module = kcl_parser::parse_file_force_errors(&filename, None).unwrap(); + construct_program(module) +} + +/// Construct ast.Program by ast.Module and default configuration. +/// Default configuration: +/// module.pkg = "__main__" +/// Program.root = "__main__" +fn construct_program(module: Module) -> Program { + let mut pkgs_ast = HashMap::new(); + pkgs_ast.insert(MAIN_PKG_NAME.to_string(), vec![module.filename.clone()]); + let mut modules = HashMap::new(); + modules.insert(module.filename.clone(), Arc::new(RwLock::new(module))); + Program { + root: MAIN_PKG_NAME.to_string(), + pkgs: pkgs_ast, + modules, + pkgs_not_imported: HashMap::new(), + modules_not_imported: HashMap::new(), + } +} + +/// Load the expect result from stdout.golden.json +fn load_expect_file(filename: String) -> String { + let f = File::open(filename).unwrap(); + let v: serde_json::Value = serde_json::from_reader(f).unwrap(); + v.to_string() +} + +/// Format str by json str +fn format_str_by_json(str: String) -> String { + let v: serde_json::Value = serde_json::from_str(&str).unwrap(); + v.to_string() +} + +fn execute_for_test(kcl_path: &String) -> String { + let args = ExecProgramArgs::default(); + // Parse kcl file + let program = load_test_program(kcl_path.to_string()); + // Generate libs, link libs and execute. + execute(Arc::new(ParseSession::default()), program, &args) + .unwrap() + .json_result +} + +fn test_kcl_runner_execute() { + for case in TEST_CASES { + let kcl_path = &Path::new(&test_case_path()) + .join(case) + .join(KCL_FILE_NAME) + .display() + .to_string(); + let expected_path = &Path::new(&test_case_path()) + .join(case) + .join(EXPECTED_JSON_FILE_NAME) + .display() + .to_string(); + let result = execute_for_test(kcl_path); + let expected_result = load_expect_file(expected_path.to_string()); + assert_eq!(expected_result, format_str_by_json(result)); + } +} + +#[test] +fn test_to_json_program_arg() { + for case in exec_prog_args_test_case() { + let test_case_json_file = &Path::new(&test_case_path()) + .join(case) + .display() + .to_string(); + let expected_json_str = fs::read_to_string(test_case_json_file).unwrap(); + let exec_prog_args = ExecProgramArgs::default(); + assert_eq!(expected_json_str.trim(), exec_prog_args.to_json().trim()); + } +} + +#[test] +fn test_from_str_program_arg() { + for case in exec_prog_args_test_case() { + let test_case_json_file = &Path::new(&test_case_path()) + .join(case) + .display() + .to_string(); + let expected_json_str = fs::read_to_string(test_case_json_file).unwrap(); + let exec_prog_args = ExecProgramArgs::from_str(&expected_json_str); + assert_eq!(expected_json_str.trim(), exec_prog_args.to_json().trim()); + } +} + +#[test] +fn test_from_setting_file_program_arg() { + for (case_yaml, case_json) in settings_file_test_case() { + let test_case_yaml_file = &Path::new(&test_case_path()) + .join(case_yaml) + .display() + .to_string(); + let settings_file = load_file(test_case_yaml_file).unwrap(); + + let test_case_json_file = &Path::new(&test_case_path()) + .join(case_json) + .display() + .to_string(); + let expected_json_str = fs::read_to_string(test_case_json_file).unwrap(); + + let exec_prog_args = ExecProgramArgs::try_from(settings_file).unwrap(); + assert_eq!(expected_json_str.trim(), exec_prog_args.to_json().trim()); + } +} + +fn test_exec_file() { + let result = std::panic::catch_unwind(|| { + for file in get_files(exec_data_path(), false, true, ".k") { + exec(&file).unwrap(); + println!("{} - PASS", file); + } + }); + assert!(result.is_ok()); +} + +fn test_custom_manifests_output() { + exec_with_result_at(&custom_manifests_data_path()); +} + +fn test_exec_with_err_result() { + exec_with_err_result_at(&exec_err_data_path()); +} + +fn clean_dir(path: String) { + if let Ok(_) = fs::remove_dir_all(path) {} +} + +#[test] +fn test_exec() { + clean_dir( + Path::new(".") + .join("src") + .join("exec_data") + .join(".kcl") + .display() + .to_string(), + ); + + clean_dir( + Path::new(".") + .join("src") + .join("exec_err_data") + .join(".kcl") + .display() + .to_string(), + ); + + test_exec_file(); + println!("test_exec_file - PASS"); + + test_kcl_runner_execute(); + println!("test_kcl_runner_execute - PASS"); + + test_custom_manifests_output(); + println!("test_custom_manifests_output - PASS"); + + test_exec_with_err_result(); + println!("test_exec_with_err_result - PASS"); + + test_indent_error(); + println!("test_indent_error - PASS"); + + test_compile_with_file_pattern(); + println!("test_compile_with_file_pattern - PASS"); + + test_uuid(); + println!("test_uuid - PASS"); +} + +fn test_indent_error() { + let test_path = PathBuf::from("./src/test_indent_error"); + let kcl_files = get_files(test_path.clone(), false, true, ".k"); + let output_files = get_files(test_path, false, true, ".stderr"); + + for (kcl_file, err_file) in kcl_files.iter().zip(&output_files) { + let mut args = ExecProgramArgs::default(); + args.k_filename_list.push(kcl_file.to_string()); + let res = exec_program(Arc::new(ParseSession::default()), &args); + assert!(res.is_err()); + if let Err(err_msg) = res { + let expect_err = fs::read_to_string(err_file).expect("Failed to read file"); + assert!(err_msg.to_string().contains(&expect_err)); + } + } +} + +fn exec(file: &str) -> Result { + let mut args = ExecProgramArgs::default(); + args.k_filename_list.push(file.to_string()); + let opts = args.get_load_program_options(); + let sess = Arc::new(ParseSession::default()); + // Load AST program + let program = load_program(sess.clone(), &[file], Some(opts), None) + .unwrap() + .program; + // Resolve ATS, generate libs, link libs and execute. + match execute(sess, program, &args) { + Ok(result) => { + if result.err_message.is_empty() { + Ok(result.json_result) + } else { + Err(result.err_message) + } + } + Err(err) => Err(err.to_string()), + } +} + +/// Run all kcl files at path and compare the exec result with the expect output. +fn exec_with_result_at(path: &str) { + let kcl_files = get_files(path, false, true, ".k"); + let output_files = get_files(path, false, true, ".stdout.golden"); + for (kcl_file, output_file) in kcl_files.iter().zip(&output_files) { + let mut args = ExecProgramArgs::default(); + args.k_filename_list.push(kcl_file.to_string()); + let result = exec_program(Arc::new(ParseSession::default()), &args).unwrap(); + + #[cfg(not(target_os = "windows"))] + let newline = "\n"; + #[cfg(target_os = "windows")] + let newline = "\r\n"; + + let expected = std::fs::read_to_string(output_file) + .unwrap() + .strip_suffix(newline) + .unwrap() + .to_string(); + + #[cfg(target_os = "windows")] + let expected = expected.replace("\r\n", "\n"); + + assert_eq!( + result.yaml_result, expected, + "test case {} {} failed", + path, kcl_file + ); + } +} + +/// Run all kcl files at path and compare the exec error result with the expect error output. +fn exec_with_err_result_at(path: &str) { + let kcl_files = get_files(path, false, true, ".k"); + let output_files = get_files(path, false, true, ".stderr.json"); + + let prev_hook = std::panic::take_hook(); + // disable print panic info + std::panic::set_hook(Box::new(|_| {})); + let result = std::panic::catch_unwind(|| { + for (kcl_file, _) in kcl_files.iter().zip(&output_files) { + let mut args = ExecProgramArgs::default(); + args.k_filename_list.push(kcl_file.to_string()); + let result = exec_program(Arc::new(ParseSession::default()), &args); + if let Ok(result) = result { + assert!(!result.err_message.is_empty(), "{}", result.err_message); + } else { + assert!(result.is_err()); + } + } + }); + assert!(result.is_ok()); + std::panic::set_hook(prev_hook); +} + +/// Get kcl files from path. +fn get_files>( + path: P, + recursively: bool, + sorted: bool, + suffix: &str, +) -> Vec { + let mut files = vec![]; + for entry in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) { + let path = entry.path(); + if path.is_file() { + let file = path.to_str().unwrap(); + if file.ends_with(suffix) && (recursively || entry.depth() == 1) { + files.push(file.to_string()) + } + } + } + if sorted { + files.sort(); + } + files +} + +fn test_compile_with_file_pattern() { + let test_path = PathBuf::from("./src/test_file_pattern/**/main.k"); + let mut args = ExecProgramArgs::default(); + args.k_filename_list.push(test_path.display().to_string()); + let res = exec_program(Arc::new(ParseSession::default()), &args); + assert!(res.is_ok()); + assert_eq!( + res.as_ref().unwrap().yaml_result, + "k3: Hello World!\nk1: Hello World!\nk2: Hello World!" + ); + assert_eq!( + res.as_ref().unwrap().json_result, + "{\"k3\": \"Hello World!\", \"k1\": \"Hello World!\", \"k2\": \"Hello World!\"}" + ); +} + +fn test_uuid() { + let res = exec( + &PathBuf::from(".") + .join("src") + .join("test_uuid") + .join("main.k") + .canonicalize() + .unwrap() + .display() + .to_string(), + ); + + let v: Value = serde_json::from_str(res.clone().unwrap().as_str()).unwrap(); + assert!(v["a"].as_str().is_some()); + if let Some(uuid_str) = v["a"].as_str() { + assert!(Uuid::parse_str(uuid_str).is_ok()); + } +} + +#[test] +fn test_compile_with_symbolic_link() { + let main_test_path = PathBuf::from("./src/test_symbolic_link/test_pkg/bbb/main.k"); + let mut args = ExecProgramArgs::default(); + args.k_filename_list + .push(main_test_path.display().to_string()); + let res = exec_program(Arc::new(ParseSession::default()), &args); + assert!(res.is_ok()); + assert_eq!( + res.as_ref().unwrap().yaml_result, + "The_first_kcl_program: Hello World!\nb: 1" + ); + assert_eq!( + res.as_ref().unwrap().json_result, + "{\"The_first_kcl_program\": \"Hello World!\", \"b\": 1}" + ); +} + +#[test] +fn test_kcl_issue_1799() { + let main_test_path = PathBuf::from("./src/test_issues/github.com/kcl-lang/kcl/1799/main.k"); + let mut args = ExecProgramArgs::default(); + args.k_filename_list + .push(main_test_path.display().to_string()); + args.work_dir = Some(".".to_string()); + let res = exec_program(Arc::new(ParseSession::default()), &args); + assert!(res.is_ok()); + assert_eq!( + res.as_ref().unwrap().yaml_result, + format!( + "a: {}", + main_test_path + .parent() + .unwrap() + .canonicalize() + .unwrap() + .adjust_canonicalization() + ) + ); +} diff --git a/kclvm/runtime/.gitignore b/crates/runtime/.gitignore similarity index 100% rename from kclvm/runtime/.gitignore rename to crates/runtime/.gitignore diff --git a/crates/runtime/Cargo.toml b/crates/runtime/Cargo.toml new file mode 100644 index 000000000..11ddcb209 --- /dev/null +++ b/crates/runtime/Cargo.toml @@ -0,0 +1,45 @@ +[package] +name = "kcl-runtime" +version.workspace = true +edition.workspace = true + +[dependencies] +kcl-primitives.workspace = true +kcl_runtime_internal_macros = { path = "./internal_macros" } +serde_json = "1.0.132" +serde = { version = "1", features = ["derive"] } +serde_yaml_ng = "0.10.0" +lazy_static = "1.4.0" +generational-arena = "0.2.9" +base64 = "0.13.0" +base32 = "0.4.0" +cidr = "0.3.1" +libc = "0.2.112" +itertools = "0.10.3" +unic-ucd-bidi = "0.9" +unic-ucd-category = "0.9" +unicode-casing = "0.1" +bstr = "0.2.16" +regex = "1.5.5" +md5 = "0.7.0" +sha2 = "0.9.8" +sha1 = "0.6.0" +chrono = "0.4.19" +phf = { version = "0.9", features = ["macros"] } +fancy-regex = "0.7.1" +num-integer = "0.1.44" +glob = "0.3.0" +uuid = { version = "1.7.0", features = ["serde", "v4"] } +handlebars = "5.1.2" +walkdir = "2.5.0" +anyhow = "1" +blake3 = "1.5.4" +encoding_rs = "0.8.35" + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +hostname = "0.4.0" +dns-lookup = "2.0.4" + +[[bin]] +name = "gen-api-spec" +path = "scripts/gen-api-spec.rs" diff --git a/crates/runtime/Makefile b/crates/runtime/Makefile new file mode 100644 index 000000000..c0322fb9d --- /dev/null +++ b/crates/runtime/Makefile @@ -0,0 +1,16 @@ +default: + make gen-api-spec + +gen-api-spec: + mkdir -p target + + cargo clean -q + + KCL_RUNTIME_GEN_API_SPEC= cargo build -r > ./src/_kcl_api_spec.rs.tmp + + echo "// Copyright The KCL Authors. All rights reserved.\n" > ./src/_kcl_api_spec.rs + echo "// Auto generated by command, DONOT EDIT!!!\n" >> ./src/_kcl_api_spec.rs + cat ./src/_kcl_api_spec.rs.tmp >> ./src/_kcl_api_spec.rs + rm ./src/_kcl_api_spec.rs.tmp + + cargo run -r --bin gen-api-spec diff --git a/crates/runtime/internal_macros/Cargo.toml b/crates/runtime/internal_macros/Cargo.toml new file mode 100644 index 000000000..9190d17a6 --- /dev/null +++ b/crates/runtime/internal_macros/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "kcl_runtime_internal_macros" +version.workspace = true +edition.workspace = true + +[dependencies] +syn = { version = "1.0", features = ["full"] } +proc-macro2 = "1.0" +quote = "1.0" + +[lib] +proc-macro = true + +[features] +default = [] diff --git a/crates/runtime/internal_macros/src/lib.rs b/crates/runtime/internal_macros/src/lib.rs new file mode 100644 index 000000000..bc71aa65c --- /dev/null +++ b/crates/runtime/internal_macros/src/lib.rs @@ -0,0 +1,220 @@ +use proc_macro::TokenStream; +use quote::quote; +use syn::{FnArg, parse_macro_input}; + +// ---------------------------------------------------------------------------- + +#[proc_macro_attribute] +pub fn runtime_fn(_attr: TokenStream, item: TokenStream) -> TokenStream { + let parsed_fn = parse_macro_input!(item as syn::ItemFn); + + if std::env::var("KCL_RUNTIME_GEN_API_SPEC").is_ok() { + print_api_spec(&parsed_fn); + } + + let x = quote! { + #parsed_fn + }; + x.into() +} + +// ---------------------------------------------------------------------------- +#[allow(clippy::upper_case_acronyms)] +#[derive(Debug)] +enum TargetName { + C, + LLVM, +} + +fn print_api_spec(fn_item: &syn::ItemFn) { + let fn_name = get_fn_name(fn_item); + let fn_c_sig = get_fn_sig(fn_item, &TargetName::C); + let fn_llvm_sig = get_fn_sig(fn_item, &TargetName::LLVM); + + // skip _fn_name() + if !fn_name.starts_with('_') { + println!("// api-spec: {}", fn_name); + println!("// api-spec(c): {};", fn_c_sig); + println!("// api-spec(llvm): {};", fn_llvm_sig); + println!(); + } +} + +// ---------------------------------------------------------------------------- + +fn get_fn_name(fn_item: &syn::ItemFn) -> String { + fn_item.sig.ident.to_string() +} + +fn get_fn_sig(fn_item: &syn::ItemFn, target: &TargetName) -> String { + let fn_name = get_fn_name(fn_item); + let args_type = get_fn_args_type(fn_item, target); + let output_type = get_fn_output_type(fn_item, target); + + match target { + TargetName::C => format!("{} {}({})", output_type, fn_name, args_type), + TargetName::LLVM => format!("declare {} @{}({})", output_type, fn_name, args_type), + } +} + +fn get_fn_output_type(fn_item: &syn::ItemFn, target: &TargetName) -> String { + match target { + TargetName::C => match &fn_item.sig.output { + syn::ReturnType::Type(_, ty) => build_c_type(ty), + syn::ReturnType::Default => "void".to_string(), + }, + TargetName::LLVM => match &fn_item.sig.output { + syn::ReturnType::Type(_, ty) => build_llvm_type(ty), + syn::ReturnType::Default => "void".to_string(), + }, + } +} + +// ---------------------------------------------------------------------------- + +fn get_fn_args_type(fn_item: &syn::ItemFn, target: &TargetName) -> String { + let fn_name = get_fn_name(fn_item); + let inputs = &fn_item.sig.inputs; + + let mut result = String::new(); + for (i, arg) in inputs.iter().enumerate() { + let arg_name = get_fn_arg_name(arg, target); + let arg_typ = get_fn_arg_type(arg, target); + + if arg_name.is_empty() { + panic!("{}", format!("{}, arg{}: invalid arg type", fn_name, i)); + } + if arg_typ.is_empty() { + panic!("{}", format!("{}, arg{}: invalid arg type", fn_name, i)); + } + + if i > 0 { + result.push_str(", "); + } + result.push_str(format!("{} {}", arg_typ, arg_name).as_str()); + } + + result +} + +// ---------------------------------------------------------------------------- + +fn get_fn_arg_name(arg: &FnArg, target: &TargetName) -> String { + match arg { + syn::FnArg::Typed(ty) => { + let syn::PatType { pat, .. } = ty; + match &**pat { + syn::Pat::Ident(x) => match target { + TargetName::C => x.ident.to_string(), + TargetName::LLVM => format!("%{}", x.ident), + }, + _ => panic!("unsupported type: {}", quote!(#ty)), + } + } + _ => panic!("unsupported arg: {}", quote!(#arg)), + } +} + +fn get_fn_arg_type(arg: &FnArg, target: &TargetName) -> String { + match arg { + syn::FnArg::Typed(ty) => { + let syn::PatType { ty, .. } = ty; + match target { + TargetName::C => build_c_type(ty), + TargetName::LLVM => build_llvm_type(ty), + } + } + _ => panic!("unsupported fn arg: {}", quote!(#arg)), + } +} + +// ---------------------------------------------------------------------------- + +fn build_c_type(ty: &syn::Type) -> String { + match ty { + syn::Type::Path(ty_path) => { + let ty_name = ty_path.path.segments[0].ident.to_string(); + + match ty_name.as_str() { + "c_void" => "void".to_string(), + "c_char" => "char".to_string(), + + "bool" => "uint8_t".to_string(), + + "i8" => "int8_t".to_string(), + "u8" => "uint8_t".to_string(), + + "i16" => "int16_t".to_string(), + "u16" => "uint16_t".to_string(), + + "i32" => "int32_t".to_string(), + "u32" => "uint32_t".to_string(), + + "i64" => "int64_t".to_string(), + "u64" => "uint64_t".to_string(), + "i128" | "u128" => "".to_string(), + + "f32" => "float".to_string(), + "f64" => "double".to_string(), + + _ => ty_name, + } + } + syn::Type::Ptr(ty_ptr) => { + let base_ty = &ty_ptr.elem; + let base_constr = build_c_type(base_ty); + format!("{}*", base_constr) + } + syn::Type::Reference(ty_ref) => { + let base_ty = &ty_ref.elem; + let base_constr = build_c_type(base_ty); + format!("{}*", base_constr) + } + syn::Type::BareFn(_) => "void*".to_string(), + syn::Type::Never(_) => "void".to_string(), + _ => panic!("unsupported type: {}", quote!(#ty)), + } +} + +fn build_llvm_type(ty: &syn::Type) -> String { + match ty { + syn::Type::Path(ty_path) => { + let ty_name = ty_path.path.segments[0].ident.to_string(); + + match ty_name.as_str() { + "c_void" => "void".to_string(), + "c_char" => "i8".to_string(), + + "bool" => "i8".to_string(), + + "i8" | "u8" => "i8".to_string(), + "i16" | "u16" => "i16".to_string(), + "i32" | "u32" => "i32".to_string(), + "i64" | "u64" => "i64".to_string(), + "i128" | "u128" => "i128".to_string(), + + "f32" => "float".to_string(), + "f64" => "double".to_string(), + + _ => format!("%{}", ty_name), + } + } + syn::Type::Ptr(ty_ptr) => { + let base_ty = &ty_ptr.elem; + let base_constr = build_llvm_type(base_ty); + format!("{}*", base_constr) + } + syn::Type::Reference(ty_ref) => { + let base_ty = &ty_ref.elem; + let base_constr = build_llvm_type(base_ty); + format!("{}*", base_constr) + } + syn::Type::BareFn(_) => "i8*".to_string(), + syn::Type::Never(_) => "void".to_string(), + _ => panic!("unsupported type: {}", quote!(#ty)), + } +} + +// ---------------------------------------------------------------------------- +// END +// ---------------------------------------------------------------------------- diff --git a/kclvm/runtime/scripts/gen-api-spec.rs b/crates/runtime/scripts/gen-api-spec.rs similarity index 92% rename from kclvm/runtime/scripts/gen-api-spec.rs rename to crates/runtime/scripts/gen-api-spec.rs index 28513805b..73806fc87 100644 --- a/kclvm/runtime/scripts/gen-api-spec.rs +++ b/crates/runtime/scripts/gen-api-spec.rs @@ -7,10 +7,10 @@ use std::process::ExitStatus; use walkdir::WalkDir; const ROOT: &str = "./src"; -const C_API_FILE: &str = "./src/_kclvm.h"; -const LL_API_FILE: &str = "./src/_kclvm.ll"; -const RUST_API_ENUM: &str = "./src/_kclvm.rs"; -const RUST_API_ADDR: &str = "./src/_kclvm_addr.rs"; +const C_API_FILE: &str = "./src/_kcl.h"; +const LL_API_FILE: &str = "./src/_kcl.ll"; +const RUST_API_ENUM: &str = "./src/_kcl.rs"; +const RUST_API_ADDR: &str = "./src/_kcl_addr.rs"; #[derive(Debug, Default)] struct ApiSpec { @@ -23,7 +23,9 @@ struct ApiSpec { } fn main() -> Result<(), Box> { - std::env::set_var("KCLVM_RUNTIME_GEN_API_SPEC", "1"); + unsafe { + std::env::set_var("KCL_RUNTIME_GEN_API_SPEC", "1"); + } let specs = load_all_api_spec(ROOT); let src = gen_c_api(&specs); fs::write(C_API_FILE, src).unwrap_or_else(|err| { @@ -126,12 +128,12 @@ fn gen_c_api(specs: &[ApiSpec]) -> String { buf.push_str("// Copyright The KCL Authors. All rights reserved.\n\n"); buf.push_str("// Auto generated, DONOT EDIT!!!\n\n"); buf.push_str("#pragma once\n\n"); - buf.push_str("#ifndef _kclvm_h_\n#define _kclvm_h_\n\n"); + buf.push_str("#ifndef _kcl_h_\n#define _kcl_h_\n\n"); buf.push_str("#include \n#include \n#include \n\n"); buf.push_str("#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n"); - buf.push_str("// please keep same as 'kclvm/runtime/src/kind/mod.rs#Kind'\n\n"); - buf.push_str("enum kclvm_kind_t {\n"); + buf.push_str("// please keep same as 'kcl/runtime/src/kind/mod.rs#Kind'\n\n"); + buf.push_str("enum kcl_kind_t {\n"); buf.push_str(" Invalid = 0,\n"); buf.push_str(" Undefined = 1,\n"); buf.push_str(" None = 2,\n"); @@ -168,7 +170,7 @@ fn gen_c_api(specs: &[ApiSpec]) -> String { } buf.push_str("#ifdef __cplusplus\n} // extern \"C\"\n#endif\n\n"); - buf.push_str("#endif // _kclvm_h_\n"); + buf.push_str("#endif // _kcl_h_\n"); fmt_code(&buf) } @@ -194,9 +196,9 @@ fn gen_ll_api(specs: &[ApiSpec]) -> String { } buf.push_str( - "define void @__kcl_keep_link_runtime(%kclvm_value_ref_t* %_a, %kclvm_context_t* %_b) {\n", + "define void @__kcl_keep_link_runtime(%kcl_value_ref_t* %_a, %kcl_context_t* %_b) {\n", ); - buf.push_str(" call %kclvm_value_ref_t* @kclvm_value_None(%kclvm_context_t* %_b)\n"); + buf.push_str(" call %kcl_value_ref_t* @kcl_value_None(%kcl_context_t* %_b)\n"); buf.push_str(" ret void\n"); buf.push_str("}\n"); @@ -219,7 +221,7 @@ fn gen_rust_api_enum(specs: &[ApiSpec]) -> String { buf.push_str("impl std::fmt::Display for ApiType {\n"); buf.push_str(" fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n"); buf.push_str(" match self {\n"); - buf.push_str(" ApiType::Value => write!(f, \"{:?}\", \"api::kclvm::Value\"),\n"); + buf.push_str(" ApiType::Value => write!(f, \"{:?}\", \"api::kcl::Value\"),\n"); buf.push_str(" }\n"); buf.push_str(" }\n"); buf.push_str("}\n"); @@ -269,7 +271,7 @@ fn gen_rust_api_addr(specs: &[ApiSpec]) -> String { buf.push_str("// Auto generated, DONOT EDIT!!!\n\n"); buf.push_str("#[allow(dead_code)]\n"); - buf.push_str("pub fn _kclvm_get_fn_ptr_by_name(name: &str) -> u64 {\n"); + buf.push_str("pub fn _kcl_get_fn_ptr_by_name(name: &str) -> u64 {\n"); buf.push_str(" match name {\n"); for spec in specs { diff --git a/crates/runtime/src/_kcl.bc b/crates/runtime/src/_kcl.bc new file mode 100644 index 000000000..36a7658e1 Binary files /dev/null and b/crates/runtime/src/_kcl.bc differ diff --git a/crates/runtime/src/_kcl.h b/crates/runtime/src/_kcl.h new file mode 100644 index 000000000..e85a5ea5b --- /dev/null +++ b/crates/runtime/src/_kcl.h @@ -0,0 +1,738 @@ +// Copyright The KCL Authors. All rights reserved. + +// Auto generated, DONOT EDIT!!! + +#pragma once + +#ifndef _kcl_h_ +#define _kcl_h_ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// please keep same as 'kcl/runtime/src/kind/mod.rs#Kind' + +enum kcl_kind_t { + Invalid = 0, + Undefined = 1, + None = 2, + Bool = 3, + Int = 4, + Float = 5, + Str = 6, + List = 7, + Dict = 8, + Schema = 9, + Error = 10, + Any = 11, + Union = 12, + BoolLit = 13, + IntLit = 14, + FloatLit = 15, + StrLit = 16, + Func = 17, + Max = 18, +}; + +typedef int8_t kcl_bool_t; + +typedef struct kcl_buffer_t kcl_buffer_t; + +typedef char kcl_char_t; + +typedef struct kcl_context_t kcl_context_t; + +typedef struct kcl_decorator_value_t kcl_decorator_value_t; + +typedef struct kcl_eval_scope_t kcl_eval_scope_t; + +typedef double kcl_float_t; + +typedef int64_t kcl_int_t; + +typedef struct kcl_iterator_t kcl_iterator_t; + +typedef enum kcl_kind_t kcl_kind_t; + +typedef int32_t kcl_size_t; + +typedef struct kcl_type_t kcl_type_t; + +typedef struct kcl_value_ref_t kcl_value_ref_t; + +typedef struct kcl_value_t kcl_value_t; + +void kcl_assert(kcl_context_t* ctx, kcl_value_ref_t* value, kcl_value_ref_t* msg); + +kcl_value_ref_t* kcl_base32_decode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_base32_encode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_base64_decode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_base64_encode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_abs(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_all_true(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_any_true(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_bin(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_bool(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_dict(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_float(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_hex(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_int(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_isnullish(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_isunique(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_len(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_list(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_max(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_min(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_multiplyof(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_oct(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_option(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +void kcl_builtin_option_init(kcl_context_t* ctx, char* key, char* value); + +kcl_value_ref_t* kcl_builtin_option_reset(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_ord(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_pow(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_print(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_range(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_round(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_sorted(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_str(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_str_capitalize(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_chars(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_count(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_endswith(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_find(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_format(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_str_index(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_isalnum(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_isalpha(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_isdigit(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_islower(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_isspace(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_istitle(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_isupper(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_join(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_lower(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_lstrip(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_removeprefix(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_removesuffix(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_replace(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_rfind(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_rindex(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_rsplit(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_str_rstrip(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_split(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_str_splitlines(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_str_startswith(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_strip(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_title(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_str_upper(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_builtin_sum(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_typeof(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_builtin_zip(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +void kcl_config_attr_map(kcl_value_ref_t* value, kcl_char_t* name, kcl_char_t* type_str); + +void kcl_context_delete(kcl_context_t* p); + +char* kcl_context_invoke(kcl_context_t* p, char* method, char* args, char* kwargs); + +kcl_context_t* kcl_context_new(); + +kcl_bool_t kcl_context_pkgpath_is_imported(kcl_context_t* ctx, kcl_char_t* pkgpath); + +void kcl_context_set_debug_mode(kcl_context_t* p, kcl_bool_t v); + +void kcl_context_set_disable_none(kcl_context_t* p, kcl_bool_t v); + +void kcl_context_set_disable_schema_check(kcl_context_t* p, kcl_bool_t v); + +void kcl_context_set_import_names(kcl_context_t* p, kcl_value_ref_t* import_names); + +void kcl_context_set_kcl_filename(kcl_context_t* ctx, char* filename); + +void kcl_context_set_kcl_line_col(kcl_context_t* ctx, int32_t line, int32_t col); + +void kcl_context_set_kcl_location(kcl_context_t* p, char* filename, int32_t line, int32_t col); + +void kcl_context_set_kcl_modpath(kcl_context_t* p, char* module_path); + +void kcl_context_set_kcl_pkgpath(kcl_context_t* p, char* pkgpath); + +void kcl_context_set_kcl_workdir(kcl_context_t* p, char* workdir); + +void kcl_context_set_strict_range_check(kcl_context_t* p, kcl_bool_t v); + +kcl_value_ref_t* kcl_convert_collection_value(kcl_context_t* ctx, kcl_value_ref_t* value, kcl_char_t* tpe, kcl_value_ref_t* is_in_schema); + +kcl_value_ref_t* kcl_crypto_blake3(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_crypto_fileblake3(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_crypto_filesha256(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_crypto_filesha512(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_crypto_md5(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_crypto_sha1(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_crypto_sha224(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_crypto_sha256(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_crypto_sha384(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_crypto_sha512(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_crypto_uuid(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_datetime_date(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_datetime_now(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_datetime_ticks(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_datetime_today(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_datetime_validate(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +void kcl_default_collection_insert_int_pointer(kcl_value_ref_t* p, kcl_char_t* key, uint64_t* ptr); + +void kcl_default_collection_insert_value(kcl_value_ref_t* p, kcl_char_t* key, kcl_value_ref_t* value); + +void kcl_dict_clear(kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_dict_get(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_value_ref_t* key); + +kcl_value_ref_t* kcl_dict_get_entry(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key); + +kcl_value_ref_t* kcl_dict_get_value(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key); + +kcl_value_ref_t* kcl_dict_get_value_by_path(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* path); + +kcl_bool_t kcl_dict_has_value(kcl_value_ref_t* p, kcl_char_t* key); + +void kcl_dict_insert(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key, kcl_value_ref_t* v, kcl_size_t op, kcl_size_t insert_index, kcl_bool_t has_insert_index); + +void kcl_dict_insert_unpack(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_value_ref_t* v); + +void kcl_dict_insert_value(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_value_ref_t* key, kcl_value_ref_t* v, kcl_size_t op, kcl_size_t insert_index, kcl_bool_t has_insert_index); + +kcl_bool_t kcl_dict_is_override_attr(kcl_value_ref_t* p, kcl_char_t* key); + +kcl_value_ref_t* kcl_dict_keys(kcl_context_t* ctx, kcl_value_ref_t* p); + +kcl_size_t kcl_dict_len(kcl_value_ref_t* p); + +void kcl_dict_merge(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key, kcl_value_ref_t* v, kcl_size_t op, kcl_size_t insert_index, kcl_bool_t has_insert_index); + +void kcl_dict_remove(kcl_value_ref_t* p, kcl_char_t* key); + +void kcl_dict_safe_insert(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key, kcl_value_ref_t* v, kcl_size_t op, kcl_size_t insert_index, kcl_bool_t has_insert_index); + +void kcl_dict_set_value(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key, kcl_value_ref_t* val); + +void kcl_dict_update(kcl_value_ref_t* p, kcl_value_ref_t* v); + +void kcl_dict_update_key_value(kcl_value_ref_t* p, kcl_value_ref_t* key, kcl_value_ref_t* v); + +kcl_value_ref_t* kcl_dict_values(kcl_context_t* ctx, kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_file_abs(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_file_append(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_file_cp(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_file_current(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_file_delete(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_file_exists(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_file_glob(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_file_mkdir(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_file_modpath(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_file_mv(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_file_read(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_file_read_env(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_file_size(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_file_workdir(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_file_write(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_iterator_cur_key(kcl_iterator_t* p); + +kcl_value_ref_t* kcl_iterator_cur_value(kcl_iterator_t* p); + +void kcl_iterator_delete(kcl_iterator_t* p); + +kcl_bool_t kcl_iterator_is_end(kcl_iterator_t* p); + +kcl_value_ref_t* kcl_iterator_next_value(kcl_iterator_t* p, kcl_value_ref_t* host); + +kcl_value_ref_t* kcl_json_decode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_json_dump_to_file(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_json_encode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_json_validate(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +void kcl_list_append(kcl_value_ref_t* p, kcl_value_ref_t* v); + +void kcl_list_append_bool(kcl_value_ref_t* p, kcl_bool_t v); + +void kcl_list_append_float(kcl_value_ref_t* p, kcl_float_t v); + +void kcl_list_append_int(kcl_value_ref_t* p, kcl_int_t v); + +void kcl_list_append_str(kcl_value_ref_t* p, kcl_char_t* v); + +void kcl_list_append_unpack(kcl_value_ref_t* p, kcl_value_ref_t* v); + +void kcl_list_clear(kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_list_count(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_value_ref_t* item); + +kcl_value_ref_t* kcl_list_find(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_value_ref_t* item); + +kcl_value_ref_t* kcl_list_get(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_size_t i); + +kcl_value_ref_t* kcl_list_get_option(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_size_t i); + +void kcl_list_insert(kcl_value_ref_t* p, kcl_value_ref_t* index, kcl_value_ref_t* value); + +kcl_size_t kcl_list_len(kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_list_pop(kcl_context_t* ctx, kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_list_pop_first(kcl_context_t* ctx, kcl_value_ref_t* p); + +void kcl_list_remove_at(kcl_value_ref_t* p, kcl_size_t i); + +void kcl_list_resize(kcl_value_ref_t* p, kcl_size_t newsize); + +void kcl_list_set(kcl_value_ref_t* p, kcl_size_t i, kcl_value_ref_t* v); + +kcl_value_ref_t* kcl_manifests_yaml_stream(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_ceil(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_exp(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_expm1(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_factorial(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_floor(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_gcd(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_isfinite(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_isinf(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_isnan(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_log(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_log10(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_log1p(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_log2(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_modf(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_pow(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_math_sqrt(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_CIDR_host(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_CIDR_netmask(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_CIDR_subnet(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_CIDR_subnets(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_IP_string(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_fqdn(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_is_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_is_IP_in_CIDR(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_is_IPv4(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_is_global_unicast_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_is_interface_local_multicast_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_is_link_local_multicast_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_is_link_local_unicast_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_is_loopback_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_is_multicast_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_is_unspecified_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_join_host_port(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_parse_CIDR(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_parse_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_split_host_port(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_to_IP4(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_net_to_IP6(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +void kcl_plugin_init(void* fn_ptr); + +kcl_value_ref_t* kcl_plugin_invoke(kcl_context_t* ctx, char* method, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +char* kcl_plugin_invoke_json(char* method, char* args, char* kwargs); + +kcl_value_ref_t* kcl_regex_compile(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_regex_findall(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_regex_match(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_regex_replace(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_regex_search(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_regex_split(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_runtime_catch(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +void kcl_schema_assert(kcl_context_t* ctx, kcl_value_ref_t* value, kcl_value_ref_t* msg, kcl_value_ref_t* config_meta); + +void kcl_schema_backtrack_cache(kcl_context_t* ctx, kcl_value_ref_t* schema, kcl_value_ref_t* cache, kcl_value_ref_t* cal_map, kcl_char_t* name, kcl_value_ref_t* runtime_type); + +void kcl_schema_default_settings(kcl_value_ref_t* schema_value, kcl_value_ref_t* _config_value, kcl_value_ref_t* args, kcl_value_ref_t* kwargs, kcl_char_t* runtime_type); + +void kcl_schema_do_check_with_index_sign_attr(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs, uint64_t* check_fn_ptr, kcl_char_t* attr_name); + +kcl_value_ref_t* kcl_schema_get_value(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key, kcl_value_ref_t* config, kcl_value_ref_t* config_meta, kcl_value_ref_t* cal_map, kcl_char_t* target_attr, kcl_value_ref_t* backtrack_level_map, kcl_value_ref_t* backtrack_cache, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_schema_instances(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +void kcl_schema_optional_check(kcl_context_t* ctx, kcl_value_ref_t* p); + +void kcl_schema_value_check(kcl_context_t* ctx, kcl_value_ref_t* schema_value, kcl_value_ref_t* schema_config, kcl_value_ref_t* _config_meta, kcl_char_t* schema_name, kcl_value_ref_t* index_sign_value, kcl_char_t* key_name, kcl_char_t* key_type, kcl_char_t* value_type, kcl_bool_t _any_other); + +kcl_value_ref_t* kcl_schema_value_new(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs, kcl_value_ref_t* schema_value_or_func, kcl_value_ref_t* config, kcl_value_ref_t* config_meta, kcl_char_t* pkgpath); + +void kcl_scope_add_setter(kcl_context_t* _ctx, kcl_eval_scope_t* scope, char* pkg, char* name, uint64_t* setter); + +void kcl_scope_delete(kcl_eval_scope_t* scope); + +kcl_value_ref_t* kcl_scope_get(kcl_context_t* ctx, kcl_eval_scope_t* scope, char* pkg, char* name, char* target, kcl_value_ref_t* default); + +kcl_eval_scope_t* kcl_scope_new(); + +void kcl_scope_set(kcl_context_t* _ctx, kcl_eval_scope_t* scope, char* pkg, char* name, kcl_value_ref_t* value); + +kcl_value_ref_t* kcl_template_execute(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_template_html_escape(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_units_to_G(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_units_to_Gi(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_units_to_K(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_units_to_Ki(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_units_to_M(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_units_to_Mi(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_units_to_P(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_units_to_Pi(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_units_to_T(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_units_to_Ti(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_units_to_m(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_units_to_n(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_units_to_u(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_value_Bool(kcl_context_t* ctx, kcl_bool_t v); + +kcl_decorator_value_t* kcl_value_Decorator(kcl_context_t* ctx, kcl_char_t* name, kcl_value_ref_t* args, kcl_value_ref_t* kwargs, kcl_value_ref_t* config_meta, kcl_char_t* attr_name, kcl_value_ref_t* config_value, kcl_value_ref_t* is_schema_target); + +kcl_value_ref_t* kcl_value_Dict(kcl_context_t* ctx); + +kcl_value_ref_t* kcl_value_False(kcl_context_t* ctx); + +kcl_value_ref_t* kcl_value_Float(kcl_context_t* ctx, kcl_float_t v); + +kcl_value_ref_t* kcl_value_Function(kcl_context_t* ctx, uint64_t* fn_ptr, kcl_value_ref_t* closure, kcl_char_t* name, kcl_bool_t is_external); + +kcl_value_ref_t* kcl_value_Function_using_ptr(kcl_context_t* ctx, uint64_t* fn_ptr, kcl_char_t* name); + +kcl_value_ref_t* kcl_value_Int(kcl_context_t* ctx, kcl_int_t v); + +kcl_value_ref_t* kcl_value_List(kcl_context_t* ctx); + +kcl_value_ref_t* kcl_value_List10(kcl_context_t* ctx, kcl_value_ref_t* v1, kcl_value_ref_t* v2, kcl_value_ref_t* v3, kcl_value_ref_t* v4, kcl_value_ref_t* v5, kcl_value_ref_t* v6, kcl_value_ref_t* v7, kcl_value_ref_t* v8, kcl_value_ref_t* v9, kcl_value_ref_t* v10); + +kcl_value_ref_t* kcl_value_List6(kcl_context_t* ctx, kcl_value_ref_t* v1, kcl_value_ref_t* v2, kcl_value_ref_t* v3, kcl_value_ref_t* v4, kcl_value_ref_t* v5, kcl_value_ref_t* v6); + +kcl_value_ref_t* kcl_value_None(kcl_context_t* ctx); + +kcl_value_ref_t* kcl_value_Schema(kcl_context_t* ctx); + +kcl_value_ref_t* kcl_value_Str(kcl_context_t* ctx, kcl_char_t* v); + +kcl_char_t* kcl_value_Str_ptr(kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_value_True(kcl_context_t* ctx); + +kcl_value_ref_t* kcl_value_Undefined(kcl_context_t* ctx); + +kcl_value_ref_t* kcl_value_Unit(kcl_context_t* ctx, kcl_float_t v, kcl_int_t raw, kcl_char_t* unit); + +kcl_value_ref_t* kcl_value_as(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +uint64_t* kcl_value_check_function_ptr(kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_value_cmp_equal_to(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_cmp_greater_than(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_cmp_greater_than_or_equal(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_cmp_less_than(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_cmp_less_than_or_equal(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_cmp_not_equal_to(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_deep_copy(kcl_context_t* ctx, kcl_value_ref_t* p); + +void kcl_value_delete(kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_value_from_json(kcl_context_t* ctx, kcl_char_t* s); + +kcl_value_ref_t* kcl_value_function_invoke(kcl_value_ref_t* p, kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs, kcl_char_t* pkgpath, kcl_value_ref_t* is_in_schema); + +uint64_t* kcl_value_function_ptr(kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_value_in(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_is(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_is_not(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_bool_t kcl_value_is_truthy(kcl_value_ref_t* p); + +kcl_iterator_t* kcl_value_iter(kcl_value_ref_t* p); + +kcl_size_t kcl_value_len(kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_value_load_attr(kcl_context_t* ctx, kcl_value_ref_t* obj, kcl_char_t* key); + +kcl_value_ref_t* kcl_value_load_attr_option(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key); + +kcl_value_ref_t* kcl_value_logic_and(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_logic_or(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_not_in(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_add(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_aug_add(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_aug_bit_and(kcl_context_t* _ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_aug_bit_lshift(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_aug_bit_or(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_aug_bit_rshift(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_aug_bit_xor(kcl_context_t* _ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_aug_div(kcl_context_t* _ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_aug_floor_div(kcl_context_t* _ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_aug_mod(kcl_context_t* _ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_aug_mul(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_aug_pow(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_aug_sub(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_bit_and(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_bit_lshift(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_bit_or(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_bit_rshift(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_bit_xor(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_div(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_floor_div(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_mod(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_mul(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_pow(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_op_sub(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_plan_to_json(kcl_context_t* ctx, kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_value_plan_to_yaml(kcl_context_t* ctx, kcl_value_ref_t* p); + +void kcl_value_remove_item(kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_schema_function(kcl_context_t* ctx, uint64_t* fn_ptr, uint64_t* check_fn_ptr, kcl_value_ref_t* attr_map, kcl_char_t* tpe); + +kcl_value_ref_t* kcl_value_schema_with_config(kcl_context_t* ctx, kcl_value_ref_t* schema_dict, kcl_value_ref_t* config, kcl_value_ref_t* config_meta, kcl_char_t* name, kcl_char_t* pkgpath, kcl_value_ref_t* is_sub_schema, kcl_value_ref_t* record_instance, kcl_value_ref_t* instance_pkgpath, kcl_value_ref_t* optional_mapping, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_value_slice(kcl_context_t* ctx, kcl_value_ref_t* x, kcl_value_ref_t* a, kcl_value_ref_t* b, kcl_value_ref_t* step); + +kcl_value_ref_t* kcl_value_slice_option(kcl_context_t* ctx, kcl_value_ref_t* x, kcl_value_ref_t* a, kcl_value_ref_t* b, kcl_value_ref_t* step); + +kcl_value_ref_t* kcl_value_subscr(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_subscr_option(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); + +void kcl_value_subscr_set(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_value_ref_t* index, kcl_value_ref_t* val); + +kcl_value_ref_t* kcl_value_to_json_value(kcl_context_t* ctx, kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_value_to_json_value_with_null(kcl_context_t* ctx, kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_value_to_str_value(kcl_context_t* ctx, kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_value_to_yaml_value(kcl_context_t* ctx, kcl_value_ref_t* p); + +kcl_value_ref_t* kcl_value_unary_l_not(kcl_context_t* ctx, kcl_value_ref_t* a); + +kcl_value_ref_t* kcl_value_unary_minus(kcl_context_t* ctx, kcl_value_ref_t* a); + +kcl_value_ref_t* kcl_value_unary_not(kcl_context_t* ctx, kcl_value_ref_t* a); + +kcl_value_ref_t* kcl_value_unary_plus(kcl_context_t* ctx, kcl_value_ref_t* a); + +kcl_value_ref_t* kcl_value_union(kcl_context_t* ctx, kcl_value_ref_t* schema, kcl_value_ref_t* b); + +kcl_value_ref_t* kcl_value_union_all(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); + +kcl_value_ref_t* kcl_yaml_decode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_yaml_decode_all(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_yaml_dump_all_to_file(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_yaml_dump_to_file(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_yaml_encode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_yaml_encode_all(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +kcl_value_ref_t* kcl_yaml_validate(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif // _kcl_h_ diff --git a/crates/runtime/src/_kcl.rs b/crates/runtime/src/_kcl.rs new file mode 100644 index 000000000..488146b08 --- /dev/null +++ b/crates/runtime/src/_kcl.rs @@ -0,0 +1,374 @@ +// Copyright The KCL Authors. All rights reserved. + +// Auto generated, DONOT EDIT!!! + +#[allow(dead_code, non_camel_case_types)] +#[derive(Clone, PartialEq, Eq, Debug, Hash)] +pub enum ApiType { + Value, +} + +impl std::fmt::Display for ApiType { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + match self { + ApiType::Value => write!(f, "{:?}", "api::kcl::Value"), + } + } +} + +impl ApiType { + #[allow(dead_code)] + pub fn name(&self) -> String { + format!("{self:?}") + } +} + +#[allow(dead_code, non_camel_case_types)] +#[derive(Clone, PartialEq, Eq, Debug, Hash)] +pub enum ApiFunc { + kcl_assert, + kcl_base32_decode, + kcl_base32_encode, + kcl_base64_decode, + kcl_base64_encode, + kcl_builtin_abs, + kcl_builtin_all_true, + kcl_builtin_any_true, + kcl_builtin_bin, + kcl_builtin_bool, + kcl_builtin_dict, + kcl_builtin_float, + kcl_builtin_hex, + kcl_builtin_int, + kcl_builtin_isnullish, + kcl_builtin_isunique, + kcl_builtin_len, + kcl_builtin_list, + kcl_builtin_max, + kcl_builtin_min, + kcl_builtin_multiplyof, + kcl_builtin_oct, + kcl_builtin_option, + kcl_builtin_option_init, + kcl_builtin_option_reset, + kcl_builtin_ord, + kcl_builtin_pow, + kcl_builtin_print, + kcl_builtin_range, + kcl_builtin_round, + kcl_builtin_sorted, + kcl_builtin_str, + kcl_builtin_str_capitalize, + kcl_builtin_str_chars, + kcl_builtin_str_count, + kcl_builtin_str_endswith, + kcl_builtin_str_find, + kcl_builtin_str_format, + kcl_builtin_str_index, + kcl_builtin_str_isalnum, + kcl_builtin_str_isalpha, + kcl_builtin_str_isdigit, + kcl_builtin_str_islower, + kcl_builtin_str_isspace, + kcl_builtin_str_istitle, + kcl_builtin_str_isupper, + kcl_builtin_str_join, + kcl_builtin_str_lower, + kcl_builtin_str_lstrip, + kcl_builtin_str_removeprefix, + kcl_builtin_str_removesuffix, + kcl_builtin_str_replace, + kcl_builtin_str_rfind, + kcl_builtin_str_rindex, + kcl_builtin_str_rsplit, + kcl_builtin_str_rstrip, + kcl_builtin_str_split, + kcl_builtin_str_splitlines, + kcl_builtin_str_startswith, + kcl_builtin_str_strip, + kcl_builtin_str_title, + kcl_builtin_str_upper, + kcl_builtin_sum, + kcl_builtin_typeof, + kcl_builtin_zip, + kcl_config_attr_map, + kcl_context_delete, + kcl_context_invoke, + kcl_context_new, + kcl_context_pkgpath_is_imported, + kcl_context_set_debug_mode, + kcl_context_set_disable_none, + kcl_context_set_disable_schema_check, + kcl_context_set_import_names, + kcl_context_set_kcl_filename, + kcl_context_set_kcl_line_col, + kcl_context_set_kcl_location, + kcl_context_set_kcl_modpath, + kcl_context_set_kcl_pkgpath, + kcl_context_set_kcl_workdir, + kcl_context_set_strict_range_check, + kcl_convert_collection_value, + kcl_crypto_blake3, + kcl_crypto_fileblake3, + kcl_crypto_filesha256, + kcl_crypto_filesha512, + kcl_crypto_md5, + kcl_crypto_sha1, + kcl_crypto_sha224, + kcl_crypto_sha256, + kcl_crypto_sha384, + kcl_crypto_sha512, + kcl_crypto_uuid, + kcl_datetime_date, + kcl_datetime_now, + kcl_datetime_ticks, + kcl_datetime_today, + kcl_datetime_validate, + kcl_default_collection_insert_int_pointer, + kcl_default_collection_insert_value, + kcl_dict_clear, + kcl_dict_get, + kcl_dict_get_entry, + kcl_dict_get_value, + kcl_dict_get_value_by_path, + kcl_dict_has_value, + kcl_dict_insert, + kcl_dict_insert_unpack, + kcl_dict_insert_value, + kcl_dict_is_override_attr, + kcl_dict_keys, + kcl_dict_len, + kcl_dict_merge, + kcl_dict_remove, + kcl_dict_safe_insert, + kcl_dict_set_value, + kcl_dict_update, + kcl_dict_update_key_value, + kcl_dict_values, + kcl_file_abs, + kcl_file_append, + kcl_file_cp, + kcl_file_current, + kcl_file_delete, + kcl_file_exists, + kcl_file_glob, + kcl_file_mkdir, + kcl_file_modpath, + kcl_file_mv, + kcl_file_read, + kcl_file_read_env, + kcl_file_size, + kcl_file_workdir, + kcl_file_write, + kcl_iterator_cur_key, + kcl_iterator_cur_value, + kcl_iterator_delete, + kcl_iterator_is_end, + kcl_iterator_next_value, + kcl_json_decode, + kcl_json_dump_to_file, + kcl_json_encode, + kcl_json_validate, + kcl_list_append, + kcl_list_append_bool, + kcl_list_append_float, + kcl_list_append_int, + kcl_list_append_str, + kcl_list_append_unpack, + kcl_list_clear, + kcl_list_count, + kcl_list_find, + kcl_list_get, + kcl_list_get_option, + kcl_list_insert, + kcl_list_len, + kcl_list_pop, + kcl_list_pop_first, + kcl_list_remove_at, + kcl_list_resize, + kcl_list_set, + kcl_manifests_yaml_stream, + kcl_math_ceil, + kcl_math_exp, + kcl_math_expm1, + kcl_math_factorial, + kcl_math_floor, + kcl_math_gcd, + kcl_math_isfinite, + kcl_math_isinf, + kcl_math_isnan, + kcl_math_log, + kcl_math_log10, + kcl_math_log1p, + kcl_math_log2, + kcl_math_modf, + kcl_math_pow, + kcl_math_sqrt, + kcl_net_CIDR_host, + kcl_net_CIDR_netmask, + kcl_net_CIDR_subnet, + kcl_net_CIDR_subnets, + kcl_net_IP_string, + kcl_net_fqdn, + kcl_net_is_IP, + kcl_net_is_IP_in_CIDR, + kcl_net_is_IPv4, + kcl_net_is_global_unicast_IP, + kcl_net_is_interface_local_multicast_IP, + kcl_net_is_link_local_multicast_IP, + kcl_net_is_link_local_unicast_IP, + kcl_net_is_loopback_IP, + kcl_net_is_multicast_IP, + kcl_net_is_unspecified_IP, + kcl_net_join_host_port, + kcl_net_parse_CIDR, + kcl_net_parse_IP, + kcl_net_split_host_port, + kcl_net_to_IP4, + kcl_net_to_IP6, + kcl_plugin_init, + kcl_plugin_invoke, + kcl_plugin_invoke_json, + kcl_regex_compile, + kcl_regex_findall, + kcl_regex_match, + kcl_regex_replace, + kcl_regex_search, + kcl_regex_split, + kcl_runtime_catch, + kcl_schema_assert, + kcl_schema_backtrack_cache, + kcl_schema_default_settings, + kcl_schema_do_check_with_index_sign_attr, + kcl_schema_get_value, + kcl_schema_instances, + kcl_schema_optional_check, + kcl_schema_value_check, + kcl_schema_value_new, + kcl_scope_add_setter, + kcl_scope_delete, + kcl_scope_get, + kcl_scope_new, + kcl_scope_set, + kcl_template_execute, + kcl_template_html_escape, + kcl_units_to_G, + kcl_units_to_Gi, + kcl_units_to_K, + kcl_units_to_Ki, + kcl_units_to_M, + kcl_units_to_Mi, + kcl_units_to_P, + kcl_units_to_Pi, + kcl_units_to_T, + kcl_units_to_Ti, + kcl_units_to_m, + kcl_units_to_n, + kcl_units_to_u, + kcl_value_Bool, + kcl_value_Decorator, + kcl_value_Dict, + kcl_value_False, + kcl_value_Float, + kcl_value_Function, + kcl_value_Function_using_ptr, + kcl_value_Int, + kcl_value_List, + kcl_value_List10, + kcl_value_List6, + kcl_value_None, + kcl_value_Schema, + kcl_value_Str, + kcl_value_Str_ptr, + kcl_value_True, + kcl_value_Undefined, + kcl_value_Unit, + kcl_value_as, + kcl_value_check_function_ptr, + kcl_value_cmp_equal_to, + kcl_value_cmp_greater_than, + kcl_value_cmp_greater_than_or_equal, + kcl_value_cmp_less_than, + kcl_value_cmp_less_than_or_equal, + kcl_value_cmp_not_equal_to, + kcl_value_deep_copy, + kcl_value_delete, + kcl_value_from_json, + kcl_value_function_invoke, + kcl_value_function_ptr, + kcl_value_in, + kcl_value_is, + kcl_value_is_not, + kcl_value_is_truthy, + kcl_value_iter, + kcl_value_len, + kcl_value_load_attr, + kcl_value_load_attr_option, + kcl_value_logic_and, + kcl_value_logic_or, + kcl_value_not_in, + kcl_value_op_add, + kcl_value_op_aug_add, + kcl_value_op_aug_bit_and, + kcl_value_op_aug_bit_lshift, + kcl_value_op_aug_bit_or, + kcl_value_op_aug_bit_rshift, + kcl_value_op_aug_bit_xor, + kcl_value_op_aug_div, + kcl_value_op_aug_floor_div, + kcl_value_op_aug_mod, + kcl_value_op_aug_mul, + kcl_value_op_aug_pow, + kcl_value_op_aug_sub, + kcl_value_op_bit_and, + kcl_value_op_bit_lshift, + kcl_value_op_bit_or, + kcl_value_op_bit_rshift, + kcl_value_op_bit_xor, + kcl_value_op_div, + kcl_value_op_floor_div, + kcl_value_op_mod, + kcl_value_op_mul, + kcl_value_op_pow, + kcl_value_op_sub, + kcl_value_plan_to_json, + kcl_value_plan_to_yaml, + kcl_value_remove_item, + kcl_value_schema_function, + kcl_value_schema_with_config, + kcl_value_slice, + kcl_value_slice_option, + kcl_value_subscr, + kcl_value_subscr_option, + kcl_value_subscr_set, + kcl_value_to_json_value, + kcl_value_to_json_value_with_null, + kcl_value_to_str_value, + kcl_value_to_yaml_value, + kcl_value_unary_l_not, + kcl_value_unary_minus, + kcl_value_unary_not, + kcl_value_unary_plus, + kcl_value_union, + kcl_value_union_all, + kcl_yaml_decode, + kcl_yaml_decode_all, + kcl_yaml_dump_all_to_file, + kcl_yaml_dump_to_file, + kcl_yaml_encode, + kcl_yaml_encode_all, + kcl_yaml_validate, +} + +impl std::fmt::Display for ApiFunc { + fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + write!(f, "{self:?}") + } +} + +impl ApiFunc { + #[allow(dead_code)] + pub fn name(&self) -> String { + format!("{self:?}") + } +} diff --git a/crates/runtime/src/_kcl_addr.rs b/crates/runtime/src/_kcl_addr.rs new file mode 100644 index 000000000..210a8cbc8 --- /dev/null +++ b/crates/runtime/src/_kcl_addr.rs @@ -0,0 +1,366 @@ +// Copyright The KCL Authors. All rights reserved. + +// Auto generated, DONOT EDIT!!! + +#[allow(dead_code)] +pub fn _kcl_get_fn_ptr_by_name(name: &str) -> u64 { + match name { + "kcl_assert" => crate::kcl_assert as *const () as u64, + "kcl_base32_decode" => crate::kcl_base32_decode as *const () as u64, + "kcl_base32_encode" => crate::kcl_base32_encode as *const () as u64, + "kcl_base64_decode" => crate::kcl_base64_decode as *const () as u64, + "kcl_base64_encode" => crate::kcl_base64_encode as *const () as u64, + "kcl_builtin_abs" => crate::kcl_builtin_abs as *const () as u64, + "kcl_builtin_all_true" => crate::kcl_builtin_all_true as *const () as u64, + "kcl_builtin_any_true" => crate::kcl_builtin_any_true as *const () as u64, + "kcl_builtin_bin" => crate::kcl_builtin_bin as *const () as u64, + "kcl_builtin_bool" => crate::kcl_builtin_bool as *const () as u64, + "kcl_builtin_dict" => crate::kcl_builtin_dict as *const () as u64, + "kcl_builtin_float" => crate::kcl_builtin_float as *const () as u64, + "kcl_builtin_hex" => crate::kcl_builtin_hex as *const () as u64, + "kcl_builtin_int" => crate::kcl_builtin_int as *const () as u64, + "kcl_builtin_isnullish" => crate::kcl_builtin_isnullish as *const () as u64, + "kcl_builtin_isunique" => crate::kcl_builtin_isunique as *const () as u64, + "kcl_builtin_len" => crate::kcl_builtin_len as *const () as u64, + "kcl_builtin_list" => crate::kcl_builtin_list as *const () as u64, + "kcl_builtin_max" => crate::kcl_builtin_max as *const () as u64, + "kcl_builtin_min" => crate::kcl_builtin_min as *const () as u64, + "kcl_builtin_multiplyof" => crate::kcl_builtin_multiplyof as *const () as u64, + "kcl_builtin_oct" => crate::kcl_builtin_oct as *const () as u64, + "kcl_builtin_option" => crate::kcl_builtin_option as *const () as u64, + "kcl_builtin_option_init" => crate::kcl_builtin_option_init as *const () as u64, + "kcl_builtin_option_reset" => crate::kcl_builtin_option_reset as *const () as u64, + "kcl_builtin_ord" => crate::kcl_builtin_ord as *const () as u64, + "kcl_builtin_pow" => crate::kcl_builtin_pow as *const () as u64, + "kcl_builtin_print" => crate::kcl_builtin_print as *const () as u64, + "kcl_builtin_range" => crate::kcl_builtin_range as *const () as u64, + "kcl_builtin_round" => crate::kcl_builtin_round as *const () as u64, + "kcl_builtin_sorted" => crate::kcl_builtin_sorted as *const () as u64, + "kcl_builtin_str" => crate::kcl_builtin_str as *const () as u64, + "kcl_builtin_str_capitalize" => crate::kcl_builtin_str_capitalize as *const () as u64, + "kcl_builtin_str_chars" => crate::kcl_builtin_str_chars as *const () as u64, + "kcl_builtin_str_count" => crate::kcl_builtin_str_count as *const () as u64, + "kcl_builtin_str_endswith" => crate::kcl_builtin_str_endswith as *const () as u64, + "kcl_builtin_str_find" => crate::kcl_builtin_str_find as *const () as u64, + "kcl_builtin_str_format" => crate::kcl_builtin_str_format as *const () as u64, + "kcl_builtin_str_index" => crate::kcl_builtin_str_index as *const () as u64, + "kcl_builtin_str_isalnum" => crate::kcl_builtin_str_isalnum as *const () as u64, + "kcl_builtin_str_isalpha" => crate::kcl_builtin_str_isalpha as *const () as u64, + "kcl_builtin_str_isdigit" => crate::kcl_builtin_str_isdigit as *const () as u64, + "kcl_builtin_str_islower" => crate::kcl_builtin_str_islower as *const () as u64, + "kcl_builtin_str_isspace" => crate::kcl_builtin_str_isspace as *const () as u64, + "kcl_builtin_str_istitle" => crate::kcl_builtin_str_istitle as *const () as u64, + "kcl_builtin_str_isupper" => crate::kcl_builtin_str_isupper as *const () as u64, + "kcl_builtin_str_join" => crate::kcl_builtin_str_join as *const () as u64, + "kcl_builtin_str_lower" => crate::kcl_builtin_str_lower as *const () as u64, + "kcl_builtin_str_lstrip" => crate::kcl_builtin_str_lstrip as *const () as u64, + "kcl_builtin_str_removeprefix" => crate::kcl_builtin_str_removeprefix as *const () as u64, + "kcl_builtin_str_removesuffix" => crate::kcl_builtin_str_removesuffix as *const () as u64, + "kcl_builtin_str_replace" => crate::kcl_builtin_str_replace as *const () as u64, + "kcl_builtin_str_rfind" => crate::kcl_builtin_str_rfind as *const () as u64, + "kcl_builtin_str_rindex" => crate::kcl_builtin_str_rindex as *const () as u64, + "kcl_builtin_str_rsplit" => crate::kcl_builtin_str_rsplit as *const () as u64, + "kcl_builtin_str_rstrip" => crate::kcl_builtin_str_rstrip as *const () as u64, + "kcl_builtin_str_split" => crate::kcl_builtin_str_split as *const () as u64, + "kcl_builtin_str_splitlines" => crate::kcl_builtin_str_splitlines as *const () as u64, + "kcl_builtin_str_startswith" => crate::kcl_builtin_str_startswith as *const () as u64, + "kcl_builtin_str_strip" => crate::kcl_builtin_str_strip as *const () as u64, + "kcl_builtin_str_title" => crate::kcl_builtin_str_title as *const () as u64, + "kcl_builtin_str_upper" => crate::kcl_builtin_str_upper as *const () as u64, + "kcl_builtin_sum" => crate::kcl_builtin_sum as *const () as u64, + "kcl_builtin_typeof" => crate::kcl_builtin_typeof as *const () as u64, + "kcl_builtin_zip" => crate::kcl_builtin_zip as *const () as u64, + "kcl_config_attr_map" => crate::kcl_config_attr_map as *const () as u64, + "kcl_context_delete" => crate::kcl_context_delete as *const () as u64, + "kcl_context_invoke" => crate::kcl_context_invoke as *const () as u64, + "kcl_context_new" => crate::kcl_context_new as *const () as u64, + "kcl_context_pkgpath_is_imported" => { + crate::kcl_context_pkgpath_is_imported as *const () as u64 + } + "kcl_context_set_debug_mode" => crate::kcl_context_set_debug_mode as *const () as u64, + "kcl_context_set_disable_none" => crate::kcl_context_set_disable_none as *const () as u64, + "kcl_context_set_disable_schema_check" => { + crate::kcl_context_set_disable_schema_check as *const () as u64 + } + "kcl_context_set_import_names" => crate::kcl_context_set_import_names as *const () as u64, + "kcl_context_set_kcl_filename" => crate::kcl_context_set_kcl_filename as *const () as u64, + "kcl_context_set_kcl_line_col" => crate::kcl_context_set_kcl_line_col as *const () as u64, + "kcl_context_set_kcl_location" => crate::kcl_context_set_kcl_location as *const () as u64, + "kcl_context_set_kcl_modpath" => crate::kcl_context_set_kcl_modpath as *const () as u64, + "kcl_context_set_kcl_pkgpath" => crate::kcl_context_set_kcl_pkgpath as *const () as u64, + "kcl_context_set_kcl_workdir" => crate::kcl_context_set_kcl_workdir as *const () as u64, + "kcl_context_set_strict_range_check" => { + crate::kcl_context_set_strict_range_check as *const () as u64 + } + "kcl_convert_collection_value" => crate::kcl_convert_collection_value as *const () as u64, + "kcl_crypto_blake3" => crate::kcl_crypto_blake3 as *const () as u64, + "kcl_crypto_fileblake3" => crate::kcl_crypto_fileblake3 as *const () as u64, + "kcl_crypto_filesha256" => crate::kcl_crypto_filesha256 as *const () as u64, + "kcl_crypto_filesha512" => crate::kcl_crypto_filesha512 as *const () as u64, + "kcl_crypto_md5" => crate::kcl_crypto_md5 as *const () as u64, + "kcl_crypto_sha1" => crate::kcl_crypto_sha1 as *const () as u64, + "kcl_crypto_sha224" => crate::kcl_crypto_sha224 as *const () as u64, + "kcl_crypto_sha256" => crate::kcl_crypto_sha256 as *const () as u64, + "kcl_crypto_sha384" => crate::kcl_crypto_sha384 as *const () as u64, + "kcl_crypto_sha512" => crate::kcl_crypto_sha512 as *const () as u64, + "kcl_crypto_uuid" => crate::kcl_crypto_uuid as *const () as u64, + "kcl_datetime_date" => crate::kcl_datetime_date as *const () as u64, + "kcl_datetime_now" => crate::kcl_datetime_now as *const () as u64, + "kcl_datetime_ticks" => crate::kcl_datetime_ticks as *const () as u64, + "kcl_datetime_today" => crate::kcl_datetime_today as *const () as u64, + "kcl_datetime_validate" => crate::kcl_datetime_validate as *const () as u64, + "kcl_default_collection_insert_int_pointer" => { + crate::kcl_default_collection_insert_int_pointer as *const () as u64 + } + "kcl_default_collection_insert_value" => { + crate::kcl_default_collection_insert_value as *const () as u64 + } + "kcl_dict_clear" => crate::kcl_dict_clear as *const () as u64, + "kcl_dict_get" => crate::kcl_dict_get as *const () as u64, + "kcl_dict_get_entry" => crate::kcl_dict_get_entry as *const () as u64, + "kcl_dict_get_value" => crate::kcl_dict_get_value as *const () as u64, + "kcl_dict_get_value_by_path" => crate::kcl_dict_get_value_by_path as *const () as u64, + "kcl_dict_has_value" => crate::kcl_dict_has_value as *const () as u64, + "kcl_dict_insert" => crate::kcl_dict_insert as *const () as u64, + "kcl_dict_insert_unpack" => crate::kcl_dict_insert_unpack as *const () as u64, + "kcl_dict_insert_value" => crate::kcl_dict_insert_value as *const () as u64, + "kcl_dict_is_override_attr" => crate::kcl_dict_is_override_attr as *const () as u64, + "kcl_dict_keys" => crate::kcl_dict_keys as *const () as u64, + "kcl_dict_len" => crate::kcl_dict_len as *const () as u64, + "kcl_dict_merge" => crate::kcl_dict_merge as *const () as u64, + "kcl_dict_remove" => crate::kcl_dict_remove as *const () as u64, + "kcl_dict_safe_insert" => crate::kcl_dict_safe_insert as *const () as u64, + "kcl_dict_set_value" => crate::kcl_dict_set_value as *const () as u64, + "kcl_dict_update" => crate::kcl_dict_update as *const () as u64, + "kcl_dict_update_key_value" => crate::kcl_dict_update_key_value as *const () as u64, + "kcl_dict_values" => crate::kcl_dict_values as *const () as u64, + "kcl_file_abs" => crate::kcl_file_abs as *const () as u64, + "kcl_file_append" => crate::kcl_file_append as *const () as u64, + "kcl_file_cp" => crate::kcl_file_cp as *const () as u64, + "kcl_file_current" => crate::kcl_file_current as *const () as u64, + "kcl_file_delete" => crate::kcl_file_delete as *const () as u64, + "kcl_file_exists" => crate::kcl_file_exists as *const () as u64, + "kcl_file_glob" => crate::kcl_file_glob as *const () as u64, + "kcl_file_mkdir" => crate::kcl_file_mkdir as *const () as u64, + "kcl_file_modpath" => crate::kcl_file_modpath as *const () as u64, + "kcl_file_mv" => crate::kcl_file_mv as *const () as u64, + "kcl_file_read" => crate::kcl_file_read as *const () as u64, + "kcl_file_read_env" => crate::kcl_file_read_env as *const () as u64, + "kcl_file_size" => crate::kcl_file_size as *const () as u64, + "kcl_file_workdir" => crate::kcl_file_workdir as *const () as u64, + "kcl_file_write" => crate::kcl_file_write as *const () as u64, + "kcl_iterator_cur_key" => crate::kcl_iterator_cur_key as *const () as u64, + "kcl_iterator_cur_value" => crate::kcl_iterator_cur_value as *const () as u64, + "kcl_iterator_delete" => crate::kcl_iterator_delete as *const () as u64, + "kcl_iterator_is_end" => crate::kcl_iterator_is_end as *const () as u64, + "kcl_iterator_next_value" => crate::kcl_iterator_next_value as *const () as u64, + "kcl_json_decode" => crate::kcl_json_decode as *const () as u64, + "kcl_json_dump_to_file" => crate::kcl_json_dump_to_file as *const () as u64, + "kcl_json_encode" => crate::kcl_json_encode as *const () as u64, + "kcl_json_validate" => crate::kcl_json_validate as *const () as u64, + "kcl_list_append" => crate::kcl_list_append as *const () as u64, + "kcl_list_append_bool" => crate::kcl_list_append_bool as *const () as u64, + "kcl_list_append_float" => crate::kcl_list_append_float as *const () as u64, + "kcl_list_append_int" => crate::kcl_list_append_int as *const () as u64, + "kcl_list_append_str" => crate::kcl_list_append_str as *const () as u64, + "kcl_list_append_unpack" => crate::kcl_list_append_unpack as *const () as u64, + "kcl_list_clear" => crate::kcl_list_clear as *const () as u64, + "kcl_list_count" => crate::kcl_list_count as *const () as u64, + "kcl_list_find" => crate::kcl_list_find as *const () as u64, + "kcl_list_get" => crate::kcl_list_get as *const () as u64, + "kcl_list_get_option" => crate::kcl_list_get_option as *const () as u64, + "kcl_list_insert" => crate::kcl_list_insert as *const () as u64, + "kcl_list_len" => crate::kcl_list_len as *const () as u64, + "kcl_list_pop" => crate::kcl_list_pop as *const () as u64, + "kcl_list_pop_first" => crate::kcl_list_pop_first as *const () as u64, + "kcl_list_remove_at" => crate::kcl_list_remove_at as *const () as u64, + "kcl_list_resize" => crate::kcl_list_resize as *const () as u64, + "kcl_list_set" => crate::kcl_list_set as *const () as u64, + "kcl_manifests_yaml_stream" => crate::kcl_manifests_yaml_stream as *const () as u64, + "kcl_math_ceil" => crate::kcl_math_ceil as *const () as u64, + "kcl_math_exp" => crate::kcl_math_exp as *const () as u64, + "kcl_math_expm1" => crate::kcl_math_expm1 as *const () as u64, + "kcl_math_factorial" => crate::kcl_math_factorial as *const () as u64, + "kcl_math_floor" => crate::kcl_math_floor as *const () as u64, + "kcl_math_gcd" => crate::kcl_math_gcd as *const () as u64, + "kcl_math_isfinite" => crate::kcl_math_isfinite as *const () as u64, + "kcl_math_isinf" => crate::kcl_math_isinf as *const () as u64, + "kcl_math_isnan" => crate::kcl_math_isnan as *const () as u64, + "kcl_math_log" => crate::kcl_math_log as *const () as u64, + "kcl_math_log10" => crate::kcl_math_log10 as *const () as u64, + "kcl_math_log1p" => crate::kcl_math_log1p as *const () as u64, + "kcl_math_log2" => crate::kcl_math_log2 as *const () as u64, + "kcl_math_modf" => crate::kcl_math_modf as *const () as u64, + "kcl_math_pow" => crate::kcl_math_pow as *const () as u64, + "kcl_math_sqrt" => crate::kcl_math_sqrt as *const () as u64, + "kcl_net_CIDR_host" => crate::kcl_net_CIDR_host as *const () as u64, + "kcl_net_CIDR_netmask" => crate::kcl_net_CIDR_netmask as *const () as u64, + "kcl_net_CIDR_subnet" => crate::kcl_net_CIDR_subnet as *const () as u64, + "kcl_net_CIDR_subnets" => crate::kcl_net_CIDR_subnets as *const () as u64, + "kcl_net_IP_string" => crate::kcl_net_IP_string as *const () as u64, + "kcl_net_fqdn" => crate::kcl_net_fqdn as *const () as u64, + "kcl_net_is_IP" => crate::kcl_net_is_IP as *const () as u64, + "kcl_net_is_IP_in_CIDR" => crate::kcl_net_is_IP_in_CIDR as *const () as u64, + "kcl_net_is_IPv4" => crate::kcl_net_is_IPv4 as *const () as u64, + "kcl_net_is_global_unicast_IP" => crate::kcl_net_is_global_unicast_IP as *const () as u64, + "kcl_net_is_interface_local_multicast_IP" => { + crate::kcl_net_is_interface_local_multicast_IP as *const () as u64 + } + "kcl_net_is_link_local_multicast_IP" => { + crate::kcl_net_is_link_local_multicast_IP as *const () as u64 + } + "kcl_net_is_link_local_unicast_IP" => { + crate::kcl_net_is_link_local_unicast_IP as *const () as u64 + } + "kcl_net_is_loopback_IP" => crate::kcl_net_is_loopback_IP as *const () as u64, + "kcl_net_is_multicast_IP" => crate::kcl_net_is_multicast_IP as *const () as u64, + "kcl_net_is_unspecified_IP" => crate::kcl_net_is_unspecified_IP as *const () as u64, + "kcl_net_join_host_port" => crate::kcl_net_join_host_port as *const () as u64, + "kcl_net_parse_CIDR" => crate::kcl_net_parse_CIDR as *const () as u64, + "kcl_net_parse_IP" => crate::kcl_net_parse_IP as *const () as u64, + "kcl_net_split_host_port" => crate::kcl_net_split_host_port as *const () as u64, + "kcl_net_to_IP4" => crate::kcl_net_to_IP4 as *const () as u64, + "kcl_net_to_IP6" => crate::kcl_net_to_IP6 as *const () as u64, + "kcl_plugin_init" => crate::kcl_plugin_init as *const () as u64, + "kcl_plugin_invoke" => crate::kcl_plugin_invoke as *const () as u64, + "kcl_plugin_invoke_json" => crate::kcl_plugin_invoke_json as *const () as u64, + "kcl_regex_compile" => crate::kcl_regex_compile as *const () as u64, + "kcl_regex_findall" => crate::kcl_regex_findall as *const () as u64, + "kcl_regex_match" => crate::kcl_regex_match as *const () as u64, + "kcl_regex_replace" => crate::kcl_regex_replace as *const () as u64, + "kcl_regex_search" => crate::kcl_regex_search as *const () as u64, + "kcl_regex_split" => crate::kcl_regex_split as *const () as u64, + "kcl_runtime_catch" => crate::kcl_runtime_catch as *const () as u64, + "kcl_schema_assert" => crate::kcl_schema_assert as *const () as u64, + "kcl_schema_backtrack_cache" => crate::kcl_schema_backtrack_cache as *const () as u64, + "kcl_schema_default_settings" => crate::kcl_schema_default_settings as *const () as u64, + "kcl_schema_do_check_with_index_sign_attr" => { + crate::kcl_schema_do_check_with_index_sign_attr as *const () as u64 + } + "kcl_schema_get_value" => crate::kcl_schema_get_value as *const () as u64, + "kcl_schema_instances" => crate::kcl_schema_instances as *const () as u64, + "kcl_schema_optional_check" => crate::kcl_schema_optional_check as *const () as u64, + "kcl_schema_value_check" => crate::kcl_schema_value_check as *const () as u64, + "kcl_schema_value_new" => crate::kcl_schema_value_new as *const () as u64, + "kcl_scope_add_setter" => crate::kcl_scope_add_setter as *const () as u64, + "kcl_scope_delete" => crate::kcl_scope_delete as *const () as u64, + "kcl_scope_get" => crate::kcl_scope_get as *const () as u64, + "kcl_scope_new" => crate::kcl_scope_new as *const () as u64, + "kcl_scope_set" => crate::kcl_scope_set as *const () as u64, + "kcl_template_execute" => crate::kcl_template_execute as *const () as u64, + "kcl_template_html_escape" => crate::kcl_template_html_escape as *const () as u64, + "kcl_units_to_G" => crate::kcl_units_to_G as *const () as u64, + "kcl_units_to_Gi" => crate::kcl_units_to_Gi as *const () as u64, + "kcl_units_to_K" => crate::kcl_units_to_K as *const () as u64, + "kcl_units_to_Ki" => crate::kcl_units_to_Ki as *const () as u64, + "kcl_units_to_M" => crate::kcl_units_to_M as *const () as u64, + "kcl_units_to_Mi" => crate::kcl_units_to_Mi as *const () as u64, + "kcl_units_to_P" => crate::kcl_units_to_P as *const () as u64, + "kcl_units_to_Pi" => crate::kcl_units_to_Pi as *const () as u64, + "kcl_units_to_T" => crate::kcl_units_to_T as *const () as u64, + "kcl_units_to_Ti" => crate::kcl_units_to_Ti as *const () as u64, + "kcl_units_to_m" => crate::kcl_units_to_m as *const () as u64, + "kcl_units_to_n" => crate::kcl_units_to_n as *const () as u64, + "kcl_units_to_u" => crate::kcl_units_to_u as *const () as u64, + "kcl_value_Bool" => crate::kcl_value_Bool as *const () as u64, + "kcl_value_Decorator" => crate::kcl_value_Decorator as *const () as u64, + "kcl_value_Dict" => crate::kcl_value_Dict as *const () as u64, + "kcl_value_False" => crate::kcl_value_False as *const () as u64, + "kcl_value_Float" => crate::kcl_value_Float as *const () as u64, + "kcl_value_Function" => crate::kcl_value_Function as *const () as u64, + "kcl_value_Function_using_ptr" => crate::kcl_value_Function_using_ptr as *const () as u64, + "kcl_value_Int" => crate::kcl_value_Int as *const () as u64, + "kcl_value_List" => crate::kcl_value_List as *const () as u64, + "kcl_value_List10" => crate::kcl_value_List10 as *const () as u64, + "kcl_value_List6" => crate::kcl_value_List6 as *const () as u64, + "kcl_value_None" => crate::kcl_value_None as *const () as u64, + "kcl_value_Schema" => crate::kcl_value_Schema as *const () as u64, + "kcl_value_Str" => crate::kcl_value_Str as *const () as u64, + "kcl_value_Str_ptr" => crate::kcl_value_Str_ptr as *const () as u64, + "kcl_value_True" => crate::kcl_value_True as *const () as u64, + "kcl_value_Undefined" => crate::kcl_value_Undefined as *const () as u64, + "kcl_value_Unit" => crate::kcl_value_Unit as *const () as u64, + "kcl_value_as" => crate::kcl_value_as as *const () as u64, + "kcl_value_check_function_ptr" => crate::kcl_value_check_function_ptr as *const () as u64, + "kcl_value_cmp_equal_to" => crate::kcl_value_cmp_equal_to as *const () as u64, + "kcl_value_cmp_greater_than" => crate::kcl_value_cmp_greater_than as *const () as u64, + "kcl_value_cmp_greater_than_or_equal" => { + crate::kcl_value_cmp_greater_than_or_equal as *const () as u64 + } + "kcl_value_cmp_less_than" => crate::kcl_value_cmp_less_than as *const () as u64, + "kcl_value_cmp_less_than_or_equal" => { + crate::kcl_value_cmp_less_than_or_equal as *const () as u64 + } + "kcl_value_cmp_not_equal_to" => crate::kcl_value_cmp_not_equal_to as *const () as u64, + "kcl_value_deep_copy" => crate::kcl_value_deep_copy as *const () as u64, + "kcl_value_delete" => crate::kcl_value_delete as *const () as u64, + "kcl_value_from_json" => crate::kcl_value_from_json as *const () as u64, + "kcl_value_function_invoke" => crate::kcl_value_function_invoke as *const () as u64, + "kcl_value_function_ptr" => crate::kcl_value_function_ptr as *const () as u64, + "kcl_value_in" => crate::kcl_value_in as *const () as u64, + "kcl_value_is" => crate::kcl_value_is as *const () as u64, + "kcl_value_is_not" => crate::kcl_value_is_not as *const () as u64, + "kcl_value_is_truthy" => crate::kcl_value_is_truthy as *const () as u64, + "kcl_value_iter" => crate::kcl_value_iter as *const () as u64, + "kcl_value_len" => crate::kcl_value_len as *const () as u64, + "kcl_value_load_attr" => crate::kcl_value_load_attr as *const () as u64, + "kcl_value_load_attr_option" => crate::kcl_value_load_attr_option as *const () as u64, + "kcl_value_logic_and" => crate::kcl_value_logic_and as *const () as u64, + "kcl_value_logic_or" => crate::kcl_value_logic_or as *const () as u64, + "kcl_value_not_in" => crate::kcl_value_not_in as *const () as u64, + "kcl_value_op_add" => crate::kcl_value_op_add as *const () as u64, + "kcl_value_op_aug_add" => crate::kcl_value_op_aug_add as *const () as u64, + "kcl_value_op_aug_bit_and" => crate::kcl_value_op_aug_bit_and as *const () as u64, + "kcl_value_op_aug_bit_lshift" => crate::kcl_value_op_aug_bit_lshift as *const () as u64, + "kcl_value_op_aug_bit_or" => crate::kcl_value_op_aug_bit_or as *const () as u64, + "kcl_value_op_aug_bit_rshift" => crate::kcl_value_op_aug_bit_rshift as *const () as u64, + "kcl_value_op_aug_bit_xor" => crate::kcl_value_op_aug_bit_xor as *const () as u64, + "kcl_value_op_aug_div" => crate::kcl_value_op_aug_div as *const () as u64, + "kcl_value_op_aug_floor_div" => crate::kcl_value_op_aug_floor_div as *const () as u64, + "kcl_value_op_aug_mod" => crate::kcl_value_op_aug_mod as *const () as u64, + "kcl_value_op_aug_mul" => crate::kcl_value_op_aug_mul as *const () as u64, + "kcl_value_op_aug_pow" => crate::kcl_value_op_aug_pow as *const () as u64, + "kcl_value_op_aug_sub" => crate::kcl_value_op_aug_sub as *const () as u64, + "kcl_value_op_bit_and" => crate::kcl_value_op_bit_and as *const () as u64, + "kcl_value_op_bit_lshift" => crate::kcl_value_op_bit_lshift as *const () as u64, + "kcl_value_op_bit_or" => crate::kcl_value_op_bit_or as *const () as u64, + "kcl_value_op_bit_rshift" => crate::kcl_value_op_bit_rshift as *const () as u64, + "kcl_value_op_bit_xor" => crate::kcl_value_op_bit_xor as *const () as u64, + "kcl_value_op_div" => crate::kcl_value_op_div as *const () as u64, + "kcl_value_op_floor_div" => crate::kcl_value_op_floor_div as *const () as u64, + "kcl_value_op_mod" => crate::kcl_value_op_mod as *const () as u64, + "kcl_value_op_mul" => crate::kcl_value_op_mul as *const () as u64, + "kcl_value_op_pow" => crate::kcl_value_op_pow as *const () as u64, + "kcl_value_op_sub" => crate::kcl_value_op_sub as *const () as u64, + "kcl_value_plan_to_json" => crate::kcl_value_plan_to_json as *const () as u64, + "kcl_value_plan_to_yaml" => crate::kcl_value_plan_to_yaml as *const () as u64, + "kcl_value_remove_item" => crate::kcl_value_remove_item as *const () as u64, + "kcl_value_schema_function" => crate::kcl_value_schema_function as *const () as u64, + "kcl_value_schema_with_config" => crate::kcl_value_schema_with_config as *const () as u64, + "kcl_value_slice" => crate::kcl_value_slice as *const () as u64, + "kcl_value_slice_option" => crate::kcl_value_slice_option as *const () as u64, + "kcl_value_subscr" => crate::kcl_value_subscr as *const () as u64, + "kcl_value_subscr_option" => crate::kcl_value_subscr_option as *const () as u64, + "kcl_value_subscr_set" => crate::kcl_value_subscr_set as *const () as u64, + "kcl_value_to_json_value" => crate::kcl_value_to_json_value as *const () as u64, + "kcl_value_to_json_value_with_null" => { + crate::kcl_value_to_json_value_with_null as *const () as u64 + } + "kcl_value_to_str_value" => crate::kcl_value_to_str_value as *const () as u64, + "kcl_value_to_yaml_value" => crate::kcl_value_to_yaml_value as *const () as u64, + "kcl_value_unary_l_not" => crate::kcl_value_unary_l_not as *const () as u64, + "kcl_value_unary_minus" => crate::kcl_value_unary_minus as *const () as u64, + "kcl_value_unary_not" => crate::kcl_value_unary_not as *const () as u64, + "kcl_value_unary_plus" => crate::kcl_value_unary_plus as *const () as u64, + "kcl_value_union" => crate::kcl_value_union as *const () as u64, + "kcl_value_union_all" => crate::kcl_value_union_all as *const () as u64, + "kcl_yaml_decode" => crate::kcl_yaml_decode as *const () as u64, + "kcl_yaml_decode_all" => crate::kcl_yaml_decode_all as *const () as u64, + "kcl_yaml_dump_all_to_file" => crate::kcl_yaml_dump_all_to_file as *const () as u64, + "kcl_yaml_dump_to_file" => crate::kcl_yaml_dump_to_file as *const () as u64, + "kcl_yaml_encode" => crate::kcl_yaml_encode as *const () as u64, + "kcl_yaml_encode_all" => crate::kcl_yaml_encode_all as *const () as u64, + "kcl_yaml_validate" => crate::kcl_yaml_validate as *const () as u64, + _ => panic!("unknown {name}"), + } +} diff --git a/crates/runtime/src/_kcl_api_spec.rs b/crates/runtime/src/_kcl_api_spec.rs new file mode 100644 index 000000000..c6c132361 --- /dev/null +++ b/crates/runtime/src/_kcl_api_spec.rs @@ -0,0 +1,1332 @@ +// Copyright The KCL Authors. All rights reserved. + +// Auto generated by command, DONOT EDIT!!! + +// api-spec: kcl_context_new +// api-spec(c): kcl_context_t* kcl_context_new(); +// api-spec(llvm): declare %kcl_context_t* @kcl_context_new(); + +// api-spec: kcl_context_delete +// api-spec(c): void kcl_context_delete(kcl_context_t* p); +// api-spec(llvm): declare void @kcl_context_delete(%kcl_context_t* %p); + +// api-spec: kcl_context_set_kcl_location +// api-spec(c): void kcl_context_set_kcl_location(kcl_context_t* p, char* filename, int32_t line, int32_t col); +// api-spec(llvm): declare void @kcl_context_set_kcl_location(%kcl_context_t* %p, i8* %filename, i32 %line, i32 %col); + +// api-spec: kcl_context_set_kcl_pkgpath +// api-spec(c): void kcl_context_set_kcl_pkgpath(kcl_context_t* p, char* pkgpath); +// api-spec(llvm): declare void @kcl_context_set_kcl_pkgpath(%kcl_context_t* %p, i8* %pkgpath); + +// api-spec: kcl_context_set_kcl_modpath +// api-spec(c): void kcl_context_set_kcl_modpath(kcl_context_t* p, char* module_path); +// api-spec(llvm): declare void @kcl_context_set_kcl_modpath(%kcl_context_t* %p, i8* %module_path); + +// api-spec: kcl_context_set_kcl_workdir +// api-spec(c): void kcl_context_set_kcl_workdir(kcl_context_t* p, char* workdir); +// api-spec(llvm): declare void @kcl_context_set_kcl_workdir(%kcl_context_t* %p, i8* %workdir); + +// api-spec: kcl_context_set_kcl_filename +// api-spec(c): void kcl_context_set_kcl_filename(kcl_context_t* ctx, char* filename); +// api-spec(llvm): declare void @kcl_context_set_kcl_filename(%kcl_context_t* %ctx, i8* %filename); + +// api-spec: kcl_context_set_kcl_line_col +// api-spec(c): void kcl_context_set_kcl_line_col(kcl_context_t* ctx, int32_t line, int32_t col); +// api-spec(llvm): declare void @kcl_context_set_kcl_line_col(%kcl_context_t* %ctx, i32 %line, i32 %col); + +// api-spec: kcl_scope_new +// api-spec(c): kcl_eval_scope_t* kcl_scope_new(); +// api-spec(llvm): declare %kcl_eval_scope_t* @kcl_scope_new(); + +// api-spec: kcl_scope_delete +// api-spec(c): void kcl_scope_delete(kcl_eval_scope_t* scope); +// api-spec(llvm): declare void @kcl_scope_delete(%kcl_eval_scope_t* %scope); + +// api-spec: kcl_scope_add_setter +// api-spec(c): void kcl_scope_add_setter(kcl_context_t* _ctx, kcl_eval_scope_t* scope, char* pkg, char* name, uint64_t* setter); +// api-spec(llvm): declare void @kcl_scope_add_setter(%kcl_context_t* %_ctx, %kcl_eval_scope_t* %scope, i8* %pkg, i8* %name, i64* %setter); + +// api-spec: kcl_scope_set +// api-spec(c): void kcl_scope_set(kcl_context_t* _ctx, kcl_eval_scope_t* scope, char* pkg, char* name, kcl_value_ref_t* value); +// api-spec(llvm): declare void @kcl_scope_set(%kcl_context_t* %_ctx, %kcl_eval_scope_t* %scope, i8* %pkg, i8* %name, %kcl_value_ref_t* %value); + +// api-spec: kcl_scope_get +// api-spec(c): kcl_value_ref_t* kcl_scope_get(kcl_context_t* ctx, kcl_eval_scope_t* scope, char* pkg, char* name, char* target, kcl_value_ref_t* default); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_scope_get(%kcl_context_t* %ctx, %kcl_eval_scope_t* %scope, i8* %pkg, i8* %name, i8* %target, %kcl_value_ref_t* %default); + +// api-spec: kcl_context_set_debug_mode +// api-spec(c): void kcl_context_set_debug_mode(kcl_context_t* p, kcl_bool_t v); +// api-spec(llvm): declare void @kcl_context_set_debug_mode(%kcl_context_t* %p, %kcl_bool_t %v); + +// api-spec: kcl_context_set_strict_range_check +// api-spec(c): void kcl_context_set_strict_range_check(kcl_context_t* p, kcl_bool_t v); +// api-spec(llvm): declare void @kcl_context_set_strict_range_check(%kcl_context_t* %p, %kcl_bool_t %v); + +// api-spec: kcl_context_set_disable_none +// api-spec(c): void kcl_context_set_disable_none(kcl_context_t* p, kcl_bool_t v); +// api-spec(llvm): declare void @kcl_context_set_disable_none(%kcl_context_t* %p, %kcl_bool_t %v); + +// api-spec: kcl_context_set_disable_schema_check +// api-spec(c): void kcl_context_set_disable_schema_check(kcl_context_t* p, kcl_bool_t v); +// api-spec(llvm): declare void @kcl_context_set_disable_schema_check(%kcl_context_t* %p, %kcl_bool_t %v); + +// api-spec: kcl_context_invoke +// api-spec(c): char* kcl_context_invoke(kcl_context_t* p, char* method, char* args, char* kwargs); +// api-spec(llvm): declare i8* @kcl_context_invoke(%kcl_context_t* %p, i8* %method, i8* %args, i8* %kwargs); + +// api-spec: kcl_context_pkgpath_is_imported +// api-spec(c): kcl_bool_t kcl_context_pkgpath_is_imported(kcl_context_t* ctx, kcl_char_t* pkgpath); +// api-spec(llvm): declare %kcl_bool_t @kcl_context_pkgpath_is_imported(%kcl_context_t* %ctx, %kcl_char_t* %pkgpath); + +// api-spec: kcl_context_set_import_names +// api-spec(c): void kcl_context_set_import_names(kcl_context_t* p, kcl_value_ref_t* import_names); +// api-spec(llvm): declare void @kcl_context_set_import_names(%kcl_context_t* %p, %kcl_value_ref_t* %import_names); + +// api-spec: kcl_value_Undefined +// api-spec(c): kcl_value_ref_t* kcl_value_Undefined(kcl_context_t* ctx); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_Undefined(%kcl_context_t* %ctx); + +// api-spec: kcl_value_None +// api-spec(c): kcl_value_ref_t* kcl_value_None(kcl_context_t* ctx); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_None(%kcl_context_t* %ctx); + +// api-spec: kcl_value_True +// api-spec(c): kcl_value_ref_t* kcl_value_True(kcl_context_t* ctx); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_True(%kcl_context_t* %ctx); + +// api-spec: kcl_value_False +// api-spec(c): kcl_value_ref_t* kcl_value_False(kcl_context_t* ctx); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_False(%kcl_context_t* %ctx); + +// api-spec: kcl_value_Bool +// api-spec(c): kcl_value_ref_t* kcl_value_Bool(kcl_context_t* ctx, kcl_bool_t v); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_Bool(%kcl_context_t* %ctx, %kcl_bool_t %v); + +// api-spec: kcl_value_Int +// api-spec(c): kcl_value_ref_t* kcl_value_Int(kcl_context_t* ctx, kcl_int_t v); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_Int(%kcl_context_t* %ctx, %kcl_int_t %v); + +// api-spec: kcl_value_Float +// api-spec(c): kcl_value_ref_t* kcl_value_Float(kcl_context_t* ctx, kcl_float_t v); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_Float(%kcl_context_t* %ctx, %kcl_float_t %v); + +// api-spec: kcl_value_Unit +// api-spec(c): kcl_value_ref_t* kcl_value_Unit(kcl_context_t* ctx, kcl_float_t v, kcl_int_t raw, kcl_char_t* unit); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_Unit(%kcl_context_t* %ctx, %kcl_float_t %v, %kcl_int_t %raw, %kcl_char_t* %unit); + +// api-spec: kcl_value_Str +// api-spec(c): kcl_value_ref_t* kcl_value_Str(kcl_context_t* ctx, kcl_char_t* v); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_Str(%kcl_context_t* %ctx, %kcl_char_t* %v); + +// api-spec: kcl_value_List +// api-spec(c): kcl_value_ref_t* kcl_value_List(kcl_context_t* ctx); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_List(%kcl_context_t* %ctx); + +// api-spec: kcl_value_List6 +// api-spec(c): kcl_value_ref_t* kcl_value_List6(kcl_context_t* ctx, kcl_value_ref_t* v1, kcl_value_ref_t* v2, kcl_value_ref_t* v3, kcl_value_ref_t* v4, kcl_value_ref_t* v5, kcl_value_ref_t* v6); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_List6(%kcl_context_t* %ctx, %kcl_value_ref_t* %v1, %kcl_value_ref_t* %v2, %kcl_value_ref_t* %v3, %kcl_value_ref_t* %v4, %kcl_value_ref_t* %v5, %kcl_value_ref_t* %v6); + +// api-spec: kcl_value_List10 +// api-spec(c): kcl_value_ref_t* kcl_value_List10(kcl_context_t* ctx, kcl_value_ref_t* v1, kcl_value_ref_t* v2, kcl_value_ref_t* v3, kcl_value_ref_t* v4, kcl_value_ref_t* v5, kcl_value_ref_t* v6, kcl_value_ref_t* v7, kcl_value_ref_t* v8, kcl_value_ref_t* v9, kcl_value_ref_t* v10); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_List10(%kcl_context_t* %ctx, %kcl_value_ref_t* %v1, %kcl_value_ref_t* %v2, %kcl_value_ref_t* %v3, %kcl_value_ref_t* %v4, %kcl_value_ref_t* %v5, %kcl_value_ref_t* %v6, %kcl_value_ref_t* %v7, %kcl_value_ref_t* %v8, %kcl_value_ref_t* %v9, %kcl_value_ref_t* %v10); + +// api-spec: kcl_value_Dict +// api-spec(c): kcl_value_ref_t* kcl_value_Dict(kcl_context_t* ctx); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_Dict(%kcl_context_t* %ctx); + +// api-spec: kcl_value_Schema +// api-spec(c): kcl_value_ref_t* kcl_value_Schema(kcl_context_t* ctx); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_Schema(%kcl_context_t* %ctx); + +// api-spec: kcl_value_schema_with_config +// api-spec(c): kcl_value_ref_t* kcl_value_schema_with_config(kcl_context_t* ctx, kcl_value_ref_t* schema_dict, kcl_value_ref_t* config, kcl_value_ref_t* config_meta, kcl_char_t* name, kcl_char_t* pkgpath, kcl_value_ref_t* is_sub_schema, kcl_value_ref_t* record_instance, kcl_value_ref_t* instance_pkgpath, kcl_value_ref_t* optional_mapping, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_schema_with_config(%kcl_context_t* %ctx, %kcl_value_ref_t* %schema_dict, %kcl_value_ref_t* %config, %kcl_value_ref_t* %config_meta, %kcl_char_t* %name, %kcl_char_t* %pkgpath, %kcl_value_ref_t* %is_sub_schema, %kcl_value_ref_t* %record_instance, %kcl_value_ref_t* %instance_pkgpath, %kcl_value_ref_t* %optional_mapping, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_value_Function +// api-spec(c): kcl_value_ref_t* kcl_value_Function(kcl_context_t* ctx, uint64_t* fn_ptr, kcl_value_ref_t* closure, kcl_char_t* name, kcl_bool_t is_external); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_Function(%kcl_context_t* %ctx, i64* %fn_ptr, %kcl_value_ref_t* %closure, %kcl_char_t* %name, %kcl_bool_t %is_external); + +// api-spec: kcl_value_Function_using_ptr +// api-spec(c): kcl_value_ref_t* kcl_value_Function_using_ptr(kcl_context_t* ctx, uint64_t* fn_ptr, kcl_char_t* name); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_Function_using_ptr(%kcl_context_t* %ctx, i64* %fn_ptr, %kcl_char_t* %name); + +// api-spec: kcl_value_schema_function +// api-spec(c): kcl_value_ref_t* kcl_value_schema_function(kcl_context_t* ctx, uint64_t* fn_ptr, uint64_t* check_fn_ptr, kcl_value_ref_t* attr_map, kcl_char_t* tpe); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_schema_function(%kcl_context_t* %ctx, i64* %fn_ptr, i64* %check_fn_ptr, %kcl_value_ref_t* %attr_map, %kcl_char_t* %tpe); + +// api-spec: kcl_value_from_json +// api-spec(c): kcl_value_ref_t* kcl_value_from_json(kcl_context_t* ctx, kcl_char_t* s); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_from_json(%kcl_context_t* %ctx, %kcl_char_t* %s); + +// api-spec: kcl_value_to_json_value +// api-spec(c): kcl_value_ref_t* kcl_value_to_json_value(kcl_context_t* ctx, kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_to_json_value(%kcl_context_t* %ctx, %kcl_value_ref_t* %p); + +// api-spec: kcl_value_to_json_value_with_null +// api-spec(c): kcl_value_ref_t* kcl_value_to_json_value_with_null(kcl_context_t* ctx, kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_to_json_value_with_null(%kcl_context_t* %ctx, %kcl_value_ref_t* %p); + +// api-spec: kcl_value_plan_to_json +// api-spec(c): kcl_value_ref_t* kcl_value_plan_to_json(kcl_context_t* ctx, kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_plan_to_json(%kcl_context_t* %ctx, %kcl_value_ref_t* %p); + +// api-spec: kcl_value_plan_to_yaml +// api-spec(c): kcl_value_ref_t* kcl_value_plan_to_yaml(kcl_context_t* ctx, kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_plan_to_yaml(%kcl_context_t* %ctx, %kcl_value_ref_t* %p); + +// api-spec: kcl_value_to_yaml_value +// api-spec(c): kcl_value_ref_t* kcl_value_to_yaml_value(kcl_context_t* ctx, kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_to_yaml_value(%kcl_context_t* %ctx, %kcl_value_ref_t* %p); + +// api-spec: kcl_value_to_str_value +// api-spec(c): kcl_value_ref_t* kcl_value_to_str_value(kcl_context_t* ctx, kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_to_str_value(%kcl_context_t* %ctx, %kcl_value_ref_t* %p); + +// api-spec: kcl_value_Str_ptr +// api-spec(c): kcl_char_t* kcl_value_Str_ptr(kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_char_t* @kcl_value_Str_ptr(%kcl_value_ref_t* %p); + +// api-spec: kcl_value_function_ptr +// api-spec(c): uint64_t* kcl_value_function_ptr(kcl_value_ref_t* p); +// api-spec(llvm): declare i64* @kcl_value_function_ptr(%kcl_value_ref_t* %p); + +// api-spec: kcl_value_check_function_ptr +// api-spec(c): uint64_t* kcl_value_check_function_ptr(kcl_value_ref_t* p); +// api-spec(llvm): declare i64* @kcl_value_check_function_ptr(%kcl_value_ref_t* %p); + +// api-spec: kcl_value_function_invoke +// api-spec(c): kcl_value_ref_t* kcl_value_function_invoke(kcl_value_ref_t* p, kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs, kcl_char_t* pkgpath, kcl_value_ref_t* is_in_schema); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_function_invoke(%kcl_value_ref_t* %p, %kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs, %kcl_char_t* %pkgpath, %kcl_value_ref_t* %is_in_schema); + +// api-spec: kcl_value_deep_copy +// api-spec(c): kcl_value_ref_t* kcl_value_deep_copy(kcl_context_t* ctx, kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_deep_copy(%kcl_context_t* %ctx, %kcl_value_ref_t* %p); + +// api-spec: kcl_value_delete +// api-spec(c): void kcl_value_delete(kcl_value_ref_t* p); +// api-spec(llvm): declare void @kcl_value_delete(%kcl_value_ref_t* %p); + +// api-spec: kcl_value_iter +// api-spec(c): kcl_iterator_t* kcl_value_iter(kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_iterator_t* @kcl_value_iter(%kcl_value_ref_t* %p); + +// api-spec: kcl_iterator_delete +// api-spec(c): void kcl_iterator_delete(kcl_iterator_t* p); +// api-spec(llvm): declare void @kcl_iterator_delete(%kcl_iterator_t* %p); + +// api-spec: kcl_iterator_is_end +// api-spec(c): kcl_bool_t kcl_iterator_is_end(kcl_iterator_t* p); +// api-spec(llvm): declare %kcl_bool_t @kcl_iterator_is_end(%kcl_iterator_t* %p); + +// api-spec: kcl_iterator_cur_key +// api-spec(c): kcl_value_ref_t* kcl_iterator_cur_key(kcl_iterator_t* p); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_iterator_cur_key(%kcl_iterator_t* %p); + +// api-spec: kcl_iterator_cur_value +// api-spec(c): kcl_value_ref_t* kcl_iterator_cur_value(kcl_iterator_t* p); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_iterator_cur_value(%kcl_iterator_t* %p); + +// api-spec: kcl_iterator_next_value +// api-spec(c): kcl_value_ref_t* kcl_iterator_next_value(kcl_iterator_t* p, kcl_value_ref_t* host); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_iterator_next_value(%kcl_iterator_t* %p, %kcl_value_ref_t* %host); + +// api-spec: kcl_list_len +// api-spec(c): kcl_size_t kcl_list_len(kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_size_t @kcl_list_len(%kcl_value_ref_t* %p); + +// api-spec: kcl_list_resize +// api-spec(c): void kcl_list_resize(kcl_value_ref_t* p, kcl_size_t newsize); +// api-spec(llvm): declare void @kcl_list_resize(%kcl_value_ref_t* %p, %kcl_size_t %newsize); + +// api-spec: kcl_list_clear +// api-spec(c): void kcl_list_clear(kcl_value_ref_t* p); +// api-spec(llvm): declare void @kcl_list_clear(%kcl_value_ref_t* %p); + +// api-spec: kcl_list_count +// api-spec(c): kcl_value_ref_t* kcl_list_count(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_value_ref_t* item); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_list_count(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_value_ref_t* %item); + +// api-spec: kcl_list_find +// api-spec(c): kcl_value_ref_t* kcl_list_find(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_value_ref_t* item); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_list_find(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_value_ref_t* %item); + +// api-spec: kcl_list_insert +// api-spec(c): void kcl_list_insert(kcl_value_ref_t* p, kcl_value_ref_t* index, kcl_value_ref_t* value); +// api-spec(llvm): declare void @kcl_list_insert(%kcl_value_ref_t* %p, %kcl_value_ref_t* %index, %kcl_value_ref_t* %value); + +// api-spec: kcl_list_get +// api-spec(c): kcl_value_ref_t* kcl_list_get(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_size_t i); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_list_get(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_size_t %i); + +// api-spec: kcl_list_get_option +// api-spec(c): kcl_value_ref_t* kcl_list_get_option(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_size_t i); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_list_get_option(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_size_t %i); + +// api-spec: kcl_list_set +// api-spec(c): void kcl_list_set(kcl_value_ref_t* p, kcl_size_t i, kcl_value_ref_t* v); +// api-spec(llvm): declare void @kcl_list_set(%kcl_value_ref_t* %p, %kcl_size_t %i, %kcl_value_ref_t* %v); + +// api-spec: kcl_list_pop +// api-spec(c): kcl_value_ref_t* kcl_list_pop(kcl_context_t* ctx, kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_list_pop(%kcl_context_t* %ctx, %kcl_value_ref_t* %p); + +// api-spec: kcl_list_pop_first +// api-spec(c): kcl_value_ref_t* kcl_list_pop_first(kcl_context_t* ctx, kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_list_pop_first(%kcl_context_t* %ctx, %kcl_value_ref_t* %p); + +// api-spec: kcl_list_append +// api-spec(c): void kcl_list_append(kcl_value_ref_t* p, kcl_value_ref_t* v); +// api-spec(llvm): declare void @kcl_list_append(%kcl_value_ref_t* %p, %kcl_value_ref_t* %v); + +// api-spec: kcl_list_append_bool +// api-spec(c): void kcl_list_append_bool(kcl_value_ref_t* p, kcl_bool_t v); +// api-spec(llvm): declare void @kcl_list_append_bool(%kcl_value_ref_t* %p, %kcl_bool_t %v); + +// api-spec: kcl_list_append_int +// api-spec(c): void kcl_list_append_int(kcl_value_ref_t* p, kcl_int_t v); +// api-spec(llvm): declare void @kcl_list_append_int(%kcl_value_ref_t* %p, %kcl_int_t %v); + +// api-spec: kcl_list_append_float +// api-spec(c): void kcl_list_append_float(kcl_value_ref_t* p, kcl_float_t v); +// api-spec(llvm): declare void @kcl_list_append_float(%kcl_value_ref_t* %p, %kcl_float_t %v); + +// api-spec: kcl_list_append_str +// api-spec(c): void kcl_list_append_str(kcl_value_ref_t* p, kcl_char_t* v); +// api-spec(llvm): declare void @kcl_list_append_str(%kcl_value_ref_t* %p, %kcl_char_t* %v); + +// api-spec: kcl_list_append_unpack +// api-spec(c): void kcl_list_append_unpack(kcl_value_ref_t* p, kcl_value_ref_t* v); +// api-spec(llvm): declare void @kcl_list_append_unpack(%kcl_value_ref_t* %p, %kcl_value_ref_t* %v); + +// api-spec: kcl_list_remove_at +// api-spec(c): void kcl_list_remove_at(kcl_value_ref_t* p, kcl_size_t i); +// api-spec(llvm): declare void @kcl_list_remove_at(%kcl_value_ref_t* %p, %kcl_size_t %i); + +// api-spec: kcl_dict_len +// api-spec(c): kcl_size_t kcl_dict_len(kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_size_t @kcl_dict_len(%kcl_value_ref_t* %p); + +// api-spec: kcl_dict_clear +// api-spec(c): void kcl_dict_clear(kcl_value_ref_t* p); +// api-spec(llvm): declare void @kcl_dict_clear(%kcl_value_ref_t* %p); + +// api-spec: kcl_dict_is_override_attr +// api-spec(c): kcl_bool_t kcl_dict_is_override_attr(kcl_value_ref_t* p, kcl_char_t* key); +// api-spec(llvm): declare %kcl_bool_t @kcl_dict_is_override_attr(%kcl_value_ref_t* %p, %kcl_char_t* %key); + +// api-spec: kcl_dict_get +// api-spec(c): kcl_value_ref_t* kcl_dict_get(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_value_ref_t* key); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_dict_get(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_value_ref_t* %key); + +// api-spec: kcl_dict_has_value +// api-spec(c): kcl_bool_t kcl_dict_has_value(kcl_value_ref_t* p, kcl_char_t* key); +// api-spec(llvm): declare %kcl_bool_t @kcl_dict_has_value(%kcl_value_ref_t* %p, %kcl_char_t* %key); + +// api-spec: kcl_dict_get_value +// api-spec(c): kcl_value_ref_t* kcl_dict_get_value(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_dict_get_value(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_char_t* %key); + +// api-spec: kcl_dict_get_entry +// api-spec(c): kcl_value_ref_t* kcl_dict_get_entry(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_dict_get_entry(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_char_t* %key); + +// api-spec: kcl_dict_get_value_by_path +// api-spec(c): kcl_value_ref_t* kcl_dict_get_value_by_path(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* path); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_dict_get_value_by_path(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_char_t* %path); + +// api-spec: kcl_dict_set_value +// api-spec(c): void kcl_dict_set_value(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key, kcl_value_ref_t* val); +// api-spec(llvm): declare void @kcl_dict_set_value(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_char_t* %key, %kcl_value_ref_t* %val); + +// api-spec: kcl_dict_keys +// api-spec(c): kcl_value_ref_t* kcl_dict_keys(kcl_context_t* ctx, kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_dict_keys(%kcl_context_t* %ctx, %kcl_value_ref_t* %p); + +// api-spec: kcl_dict_values +// api-spec(c): kcl_value_ref_t* kcl_dict_values(kcl_context_t* ctx, kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_dict_values(%kcl_context_t* %ctx, %kcl_value_ref_t* %p); + +// api-spec: kcl_dict_insert +// api-spec(c): void kcl_dict_insert(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key, kcl_value_ref_t* v, kcl_size_t op, kcl_size_t insert_index, kcl_bool_t has_insert_index); +// api-spec(llvm): declare void @kcl_dict_insert(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_char_t* %key, %kcl_value_ref_t* %v, %kcl_size_t %op, %kcl_size_t %insert_index, %kcl_bool_t %has_insert_index); + +// api-spec: kcl_dict_merge +// api-spec(c): void kcl_dict_merge(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key, kcl_value_ref_t* v, kcl_size_t op, kcl_size_t insert_index, kcl_bool_t has_insert_index); +// api-spec(llvm): declare void @kcl_dict_merge(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_char_t* %key, %kcl_value_ref_t* %v, %kcl_size_t %op, %kcl_size_t %insert_index, %kcl_bool_t %has_insert_index); + +// api-spec: kcl_dict_insert_value +// api-spec(c): void kcl_dict_insert_value(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_value_ref_t* key, kcl_value_ref_t* v, kcl_size_t op, kcl_size_t insert_index, kcl_bool_t has_insert_index); +// api-spec(llvm): declare void @kcl_dict_insert_value(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_value_ref_t* %key, %kcl_value_ref_t* %v, %kcl_size_t %op, %kcl_size_t %insert_index, %kcl_bool_t %has_insert_index); + +// api-spec: kcl_dict_update_key_value +// api-spec(c): void kcl_dict_update_key_value(kcl_value_ref_t* p, kcl_value_ref_t* key, kcl_value_ref_t* v); +// api-spec(llvm): declare void @kcl_dict_update_key_value(%kcl_value_ref_t* %p, %kcl_value_ref_t* %key, %kcl_value_ref_t* %v); + +// api-spec: kcl_dict_safe_insert +// api-spec(c): void kcl_dict_safe_insert(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key, kcl_value_ref_t* v, kcl_size_t op, kcl_size_t insert_index, kcl_bool_t has_insert_index); +// api-spec(llvm): declare void @kcl_dict_safe_insert(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_char_t* %key, %kcl_value_ref_t* %v, %kcl_size_t %op, %kcl_size_t %insert_index, %kcl_bool_t %has_insert_index); + +// api-spec: kcl_dict_insert_unpack +// api-spec(c): void kcl_dict_insert_unpack(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_value_ref_t* v); +// api-spec(llvm): declare void @kcl_dict_insert_unpack(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_value_ref_t* %v); + +// api-spec: kcl_default_collection_insert_int_pointer +// api-spec(c): void kcl_default_collection_insert_int_pointer(kcl_value_ref_t* p, kcl_char_t* key, uint64_t* ptr); +// api-spec(llvm): declare void @kcl_default_collection_insert_int_pointer(%kcl_value_ref_t* %p, %kcl_char_t* %key, i64* %ptr); + +// api-spec: kcl_default_collection_insert_value +// api-spec(c): void kcl_default_collection_insert_value(kcl_value_ref_t* p, kcl_char_t* key, kcl_value_ref_t* value); +// api-spec(llvm): declare void @kcl_default_collection_insert_value(%kcl_value_ref_t* %p, %kcl_char_t* %key, %kcl_value_ref_t* %value); + +// api-spec: kcl_dict_remove +// api-spec(c): void kcl_dict_remove(kcl_value_ref_t* p, kcl_char_t* key); +// api-spec(llvm): declare void @kcl_dict_remove(%kcl_value_ref_t* %p, %kcl_char_t* %key); + +// api-spec: kcl_dict_update +// api-spec(c): void kcl_dict_update(kcl_value_ref_t* p, kcl_value_ref_t* v); +// api-spec(llvm): declare void @kcl_dict_update(%kcl_value_ref_t* %p, %kcl_value_ref_t* %v); + +// api-spec: kcl_value_is_truthy +// api-spec(c): kcl_bool_t kcl_value_is_truthy(kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_bool_t @kcl_value_is_truthy(%kcl_value_ref_t* %p); + +// api-spec: kcl_value_len +// api-spec(c): kcl_size_t kcl_value_len(kcl_value_ref_t* p); +// api-spec(llvm): declare %kcl_size_t @kcl_value_len(%kcl_value_ref_t* %p); + +// api-spec: kcl_value_cmp_equal_to +// api-spec(c): kcl_value_ref_t* kcl_value_cmp_equal_to(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_cmp_equal_to(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_cmp_not_equal_to +// api-spec(c): kcl_value_ref_t* kcl_value_cmp_not_equal_to(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_cmp_not_equal_to(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_cmp_less_than +// api-spec(c): kcl_value_ref_t* kcl_value_cmp_less_than(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_cmp_less_than(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_cmp_less_than_or_equal +// api-spec(c): kcl_value_ref_t* kcl_value_cmp_less_than_or_equal(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_cmp_less_than_or_equal(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_cmp_greater_than +// api-spec(c): kcl_value_ref_t* kcl_value_cmp_greater_than(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_cmp_greater_than(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_cmp_greater_than_or_equal +// api-spec(c): kcl_value_ref_t* kcl_value_cmp_greater_than_or_equal(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_cmp_greater_than_or_equal(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_is +// api-spec(c): kcl_value_ref_t* kcl_value_is(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_is(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_is_not +// api-spec(c): kcl_value_ref_t* kcl_value_is_not(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_is_not(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_in +// api-spec(c): kcl_value_ref_t* kcl_value_in(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_in(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_not_in +// api-spec(c): kcl_value_ref_t* kcl_value_not_in(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_not_in(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_as +// api-spec(c): kcl_value_ref_t* kcl_value_as(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_as(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_unary_plus +// api-spec(c): kcl_value_ref_t* kcl_value_unary_plus(kcl_context_t* ctx, kcl_value_ref_t* a); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_unary_plus(%kcl_context_t* %ctx, %kcl_value_ref_t* %a); + +// api-spec: kcl_value_unary_minus +// api-spec(c): kcl_value_ref_t* kcl_value_unary_minus(kcl_context_t* ctx, kcl_value_ref_t* a); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_unary_minus(%kcl_context_t* %ctx, %kcl_value_ref_t* %a); + +// api-spec: kcl_value_unary_not +// api-spec(c): kcl_value_ref_t* kcl_value_unary_not(kcl_context_t* ctx, kcl_value_ref_t* a); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_unary_not(%kcl_context_t* %ctx, %kcl_value_ref_t* %a); + +// api-spec: kcl_value_unary_l_not +// api-spec(c): kcl_value_ref_t* kcl_value_unary_l_not(kcl_context_t* ctx, kcl_value_ref_t* a); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_unary_l_not(%kcl_context_t* %ctx, %kcl_value_ref_t* %a); + +// api-spec: kcl_value_op_add +// api-spec(c): kcl_value_ref_t* kcl_value_op_add(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_add(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_sub +// api-spec(c): kcl_value_ref_t* kcl_value_op_sub(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_sub(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_mul +// api-spec(c): kcl_value_ref_t* kcl_value_op_mul(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_mul(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_div +// api-spec(c): kcl_value_ref_t* kcl_value_op_div(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_div(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_mod +// api-spec(c): kcl_value_ref_t* kcl_value_op_mod(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_mod(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_pow +// api-spec(c): kcl_value_ref_t* kcl_value_op_pow(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_pow(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_floor_div +// api-spec(c): kcl_value_ref_t* kcl_value_op_floor_div(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_floor_div(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_bit_lshift +// api-spec(c): kcl_value_ref_t* kcl_value_op_bit_lshift(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_bit_lshift(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_bit_rshift +// api-spec(c): kcl_value_ref_t* kcl_value_op_bit_rshift(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_bit_rshift(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_bit_and +// api-spec(c): kcl_value_ref_t* kcl_value_op_bit_and(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_bit_and(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_bit_xor +// api-spec(c): kcl_value_ref_t* kcl_value_op_bit_xor(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_bit_xor(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_bit_or +// api-spec(c): kcl_value_ref_t* kcl_value_op_bit_or(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_bit_or(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_aug_add +// api-spec(c): kcl_value_ref_t* kcl_value_op_aug_add(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_aug_add(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_aug_sub +// api-spec(c): kcl_value_ref_t* kcl_value_op_aug_sub(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_aug_sub(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_aug_mul +// api-spec(c): kcl_value_ref_t* kcl_value_op_aug_mul(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_aug_mul(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_aug_div +// api-spec(c): kcl_value_ref_t* kcl_value_op_aug_div(kcl_context_t* _ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_aug_div(%kcl_context_t* %_ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_aug_mod +// api-spec(c): kcl_value_ref_t* kcl_value_op_aug_mod(kcl_context_t* _ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_aug_mod(%kcl_context_t* %_ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_aug_pow +// api-spec(c): kcl_value_ref_t* kcl_value_op_aug_pow(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_aug_pow(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_aug_floor_div +// api-spec(c): kcl_value_ref_t* kcl_value_op_aug_floor_div(kcl_context_t* _ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_aug_floor_div(%kcl_context_t* %_ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_aug_bit_lshift +// api-spec(c): kcl_value_ref_t* kcl_value_op_aug_bit_lshift(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_aug_bit_lshift(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_aug_bit_rshift +// api-spec(c): kcl_value_ref_t* kcl_value_op_aug_bit_rshift(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_aug_bit_rshift(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_aug_bit_and +// api-spec(c): kcl_value_ref_t* kcl_value_op_aug_bit_and(kcl_context_t* _ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_aug_bit_and(%kcl_context_t* %_ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_aug_bit_xor +// api-spec(c): kcl_value_ref_t* kcl_value_op_aug_bit_xor(kcl_context_t* _ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_aug_bit_xor(%kcl_context_t* %_ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_op_aug_bit_or +// api-spec(c): kcl_value_ref_t* kcl_value_op_aug_bit_or(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_op_aug_bit_or(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_union +// api-spec(c): kcl_value_ref_t* kcl_value_union(kcl_context_t* ctx, kcl_value_ref_t* schema, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_union(%kcl_context_t* %ctx, %kcl_value_ref_t* %schema, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_logic_and +// api-spec(c): kcl_value_ref_t* kcl_value_logic_and(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_logic_and(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_logic_or +// api-spec(c): kcl_value_ref_t* kcl_value_logic_or(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_logic_or(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_subscr +// api-spec(c): kcl_value_ref_t* kcl_value_subscr(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_subscr(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_subscr_set +// api-spec(c): void kcl_value_subscr_set(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_value_ref_t* index, kcl_value_ref_t* val); +// api-spec(llvm): declare void @kcl_value_subscr_set(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_value_ref_t* %index, %kcl_value_ref_t* %val); + +// api-spec: kcl_value_subscr_option +// api-spec(c): kcl_value_ref_t* kcl_value_subscr_option(kcl_context_t* ctx, kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_subscr_option(%kcl_context_t* %ctx, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_load_attr +// api-spec(c): kcl_value_ref_t* kcl_value_load_attr(kcl_context_t* ctx, kcl_value_ref_t* obj, kcl_char_t* key); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_load_attr(%kcl_context_t* %ctx, %kcl_value_ref_t* %obj, %kcl_char_t* %key); + +// api-spec: kcl_value_load_attr_option +// api-spec(c): kcl_value_ref_t* kcl_value_load_attr_option(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_load_attr_option(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_char_t* %key); + +// api-spec: kcl_value_remove_item +// api-spec(c): void kcl_value_remove_item(kcl_value_ref_t* a, kcl_value_ref_t* b); +// api-spec(llvm): declare void @kcl_value_remove_item(%kcl_value_ref_t* %a, %kcl_value_ref_t* %b); + +// api-spec: kcl_value_slice +// api-spec(c): kcl_value_ref_t* kcl_value_slice(kcl_context_t* ctx, kcl_value_ref_t* x, kcl_value_ref_t* a, kcl_value_ref_t* b, kcl_value_ref_t* step); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_slice(%kcl_context_t* %ctx, %kcl_value_ref_t* %x, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b, %kcl_value_ref_t* %step); + +// api-spec: kcl_value_slice_option +// api-spec(c): kcl_value_ref_t* kcl_value_slice_option(kcl_context_t* ctx, kcl_value_ref_t* x, kcl_value_ref_t* a, kcl_value_ref_t* b, kcl_value_ref_t* step); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_slice_option(%kcl_context_t* %ctx, %kcl_value_ref_t* %x, %kcl_value_ref_t* %a, %kcl_value_ref_t* %b, %kcl_value_ref_t* %step); + +// api-spec: kcl_schema_backtrack_cache +// api-spec(c): void kcl_schema_backtrack_cache(kcl_context_t* ctx, kcl_value_ref_t* schema, kcl_value_ref_t* cache, kcl_value_ref_t* cal_map, kcl_char_t* name, kcl_value_ref_t* runtime_type); +// api-spec(llvm): declare void @kcl_schema_backtrack_cache(%kcl_context_t* %ctx, %kcl_value_ref_t* %schema, %kcl_value_ref_t* %cache, %kcl_value_ref_t* %cal_map, %kcl_char_t* %name, %kcl_value_ref_t* %runtime_type); + +// api-spec: kcl_schema_instances +// api-spec(c): kcl_value_ref_t* kcl_schema_instances(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_schema_instances(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_schema_value_check +// api-spec(c): void kcl_schema_value_check(kcl_context_t* ctx, kcl_value_ref_t* schema_value, kcl_value_ref_t* schema_config, kcl_value_ref_t* _config_meta, kcl_char_t* schema_name, kcl_value_ref_t* index_sign_value, kcl_char_t* key_name, kcl_char_t* key_type, kcl_char_t* value_type, kcl_bool_t _any_other); +// api-spec(llvm): declare void @kcl_schema_value_check(%kcl_context_t* %ctx, %kcl_value_ref_t* %schema_value, %kcl_value_ref_t* %schema_config, %kcl_value_ref_t* %_config_meta, %kcl_char_t* %schema_name, %kcl_value_ref_t* %index_sign_value, %kcl_char_t* %key_name, %kcl_char_t* %key_type, %kcl_char_t* %value_type, %kcl_bool_t %_any_other); + +// api-spec: kcl_schema_do_check_with_index_sign_attr +// api-spec(c): void kcl_schema_do_check_with_index_sign_attr(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs, uint64_t* check_fn_ptr, kcl_char_t* attr_name); +// api-spec(llvm): declare void @kcl_schema_do_check_with_index_sign_attr(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs, i64* %check_fn_ptr, %kcl_char_t* %attr_name); + +// api-spec: kcl_schema_optional_check +// api-spec(c): void kcl_schema_optional_check(kcl_context_t* ctx, kcl_value_ref_t* p); +// api-spec(llvm): declare void @kcl_schema_optional_check(%kcl_context_t* %ctx, %kcl_value_ref_t* %p); + +// api-spec: kcl_schema_default_settings +// api-spec(c): void kcl_schema_default_settings(kcl_value_ref_t* schema_value, kcl_value_ref_t* _config_value, kcl_value_ref_t* args, kcl_value_ref_t* kwargs, kcl_char_t* runtime_type); +// api-spec(llvm): declare void @kcl_schema_default_settings(%kcl_value_ref_t* %schema_value, %kcl_value_ref_t* %_config_value, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs, %kcl_char_t* %runtime_type); + +// api-spec: kcl_schema_assert +// api-spec(c): void kcl_schema_assert(kcl_context_t* ctx, kcl_value_ref_t* value, kcl_value_ref_t* msg, kcl_value_ref_t* config_meta); +// api-spec(llvm): declare void @kcl_schema_assert(%kcl_context_t* %ctx, %kcl_value_ref_t* %value, %kcl_value_ref_t* %msg, %kcl_value_ref_t* %config_meta); + +// api-spec: kcl_schema_value_new +// api-spec(c): kcl_value_ref_t* kcl_schema_value_new(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs, kcl_value_ref_t* schema_value_or_func, kcl_value_ref_t* config, kcl_value_ref_t* config_meta, kcl_char_t* pkgpath); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_schema_value_new(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs, %kcl_value_ref_t* %schema_value_or_func, %kcl_value_ref_t* %config, %kcl_value_ref_t* %config_meta, %kcl_char_t* %pkgpath); + +// api-spec: kcl_convert_collection_value +// api-spec(c): kcl_value_ref_t* kcl_convert_collection_value(kcl_context_t* ctx, kcl_value_ref_t* value, kcl_char_t* tpe, kcl_value_ref_t* is_in_schema); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_convert_collection_value(%kcl_context_t* %ctx, %kcl_value_ref_t* %value, %kcl_char_t* %tpe, %kcl_value_ref_t* %is_in_schema); + +// api-spec: kcl_schema_get_value +// api-spec(c): kcl_value_ref_t* kcl_schema_get_value(kcl_context_t* ctx, kcl_value_ref_t* p, kcl_char_t* key, kcl_value_ref_t* config, kcl_value_ref_t* config_meta, kcl_value_ref_t* cal_map, kcl_char_t* target_attr, kcl_value_ref_t* backtrack_level_map, kcl_value_ref_t* backtrack_cache, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_schema_get_value(%kcl_context_t* %ctx, %kcl_value_ref_t* %p, %kcl_char_t* %key, %kcl_value_ref_t* %config, %kcl_value_ref_t* %config_meta, %kcl_value_ref_t* %cal_map, %kcl_char_t* %target_attr, %kcl_value_ref_t* %backtrack_level_map, %kcl_value_ref_t* %backtrack_cache, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_config_attr_map +// api-spec(c): void kcl_config_attr_map(kcl_value_ref_t* value, kcl_char_t* name, kcl_char_t* type_str); +// api-spec(llvm): declare void @kcl_config_attr_map(%kcl_value_ref_t* %value, %kcl_char_t* %name, %kcl_char_t* %type_str); + +// api-spec: kcl_value_Decorator +// api-spec(c): kcl_decorator_value_t* kcl_value_Decorator(kcl_context_t* ctx, kcl_char_t* name, kcl_value_ref_t* args, kcl_value_ref_t* kwargs, kcl_value_ref_t* config_meta, kcl_char_t* attr_name, kcl_value_ref_t* config_value, kcl_value_ref_t* is_schema_target); +// api-spec(llvm): declare %kcl_decorator_value_t* @kcl_value_Decorator(%kcl_context_t* %ctx, %kcl_char_t* %name, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs, %kcl_value_ref_t* %config_meta, %kcl_char_t* %attr_name, %kcl_value_ref_t* %config_value, %kcl_value_ref_t* %is_schema_target); + +// api-spec: kcl_builtin_str_lower +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_lower(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_lower(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_upper +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_upper(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_upper(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_capitalize +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_capitalize(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_capitalize(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_chars +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_chars(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_chars(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_count +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_count(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_count(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_endswith +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_endswith(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_endswith(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_find +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_find(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_find(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_format +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_format(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_format(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_str_index +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_index(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_index(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_isalnum +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_isalnum(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_isalnum(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_isalpha +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_isalpha(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_isalpha(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_isdigit +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_isdigit(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_isdigit(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_islower +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_islower(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_islower(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_isspace +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_isspace(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_isspace(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_istitle +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_istitle(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_istitle(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_isupper +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_isupper(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_isupper(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_join +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_join(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_join(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_lstrip +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_lstrip(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_lstrip(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_rstrip +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_rstrip(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_rstrip(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_replace +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_replace(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_replace(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_removeprefix +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_removeprefix(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_removeprefix(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_removesuffix +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_removesuffix(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_removesuffix(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_rfind +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_rfind(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_rfind(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_rindex +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_rindex(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_rindex(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_rsplit +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_rsplit(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_rsplit(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_str_split +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_split(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_split(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_str_splitlines +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_splitlines(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_splitlines(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_str_startswith +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_startswith(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_startswith(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_strip +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_strip(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_strip(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_str_title +// api-spec(c): kcl_value_ref_t* kcl_builtin_str_title(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str_title(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_base32_encode +// api-spec(c): kcl_value_ref_t* kcl_base32_encode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_base32_encode(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_base32_decode +// api-spec(c): kcl_value_ref_t* kcl_base32_decode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_base32_decode(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_base64_encode +// api-spec(c): kcl_value_ref_t* kcl_base64_encode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_base64_encode(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_base64_decode +// api-spec(c): kcl_value_ref_t* kcl_base64_decode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_base64_decode(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_value_union_all +// api-spec(c): kcl_value_ref_t* kcl_value_union_all(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_value_union_all(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_crypto_md5 +// api-spec(c): kcl_value_ref_t* kcl_crypto_md5(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_crypto_md5(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_crypto_sha1 +// api-spec(c): kcl_value_ref_t* kcl_crypto_sha1(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_crypto_sha1(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_crypto_sha224 +// api-spec(c): kcl_value_ref_t* kcl_crypto_sha224(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_crypto_sha224(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_crypto_sha256 +// api-spec(c): kcl_value_ref_t* kcl_crypto_sha256(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_crypto_sha256(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_crypto_sha384 +// api-spec(c): kcl_value_ref_t* kcl_crypto_sha384(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_crypto_sha384(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_crypto_sha512 +// api-spec(c): kcl_value_ref_t* kcl_crypto_sha512(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_crypto_sha512(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_crypto_blake3 +// api-spec(c): kcl_value_ref_t* kcl_crypto_blake3(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_crypto_blake3(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_crypto_uuid +// api-spec(c): kcl_value_ref_t* kcl_crypto_uuid(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_crypto_uuid(%kcl_context_t* %ctx, %kcl_value_ref_t* %_args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_crypto_filesha256 +// api-spec(c): kcl_value_ref_t* kcl_crypto_filesha256(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_crypto_filesha256(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_crypto_filesha512 +// api-spec(c): kcl_value_ref_t* kcl_crypto_filesha512(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_crypto_filesha512(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_crypto_fileblake3 +// api-spec(c): kcl_value_ref_t* kcl_crypto_fileblake3(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_crypto_fileblake3(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_datetime_today +// api-spec(c): kcl_value_ref_t* kcl_datetime_today(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_datetime_today(%kcl_context_t* %ctx, %kcl_value_ref_t* %_args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_datetime_now +// api-spec(c): kcl_value_ref_t* kcl_datetime_now(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_datetime_now(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_datetime_ticks +// api-spec(c): kcl_value_ref_t* kcl_datetime_ticks(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_datetime_ticks(%kcl_context_t* %ctx, %kcl_value_ref_t* %_args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_datetime_date +// api-spec(c): kcl_value_ref_t* kcl_datetime_date(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_datetime_date(%kcl_context_t* %ctx, %kcl_value_ref_t* %_args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_datetime_validate +// api-spec(c): kcl_value_ref_t* kcl_datetime_validate(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_datetime_validate(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_json_encode +// api-spec(c): kcl_value_ref_t* kcl_json_encode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_json_encode(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_json_decode +// api-spec(c): kcl_value_ref_t* kcl_json_decode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_json_decode(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_json_validate +// api-spec(c): kcl_value_ref_t* kcl_json_validate(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_json_validate(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_json_dump_to_file +// api-spec(c): kcl_value_ref_t* kcl_json_dump_to_file(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_json_dump_to_file(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_manifests_yaml_stream +// api-spec(c): kcl_value_ref_t* kcl_manifests_yaml_stream(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_manifests_yaml_stream(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_ceil +// api-spec(c): kcl_value_ref_t* kcl_math_ceil(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_ceil(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_factorial +// api-spec(c): kcl_value_ref_t* kcl_math_factorial(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_factorial(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_floor +// api-spec(c): kcl_value_ref_t* kcl_math_floor(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_floor(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_gcd +// api-spec(c): kcl_value_ref_t* kcl_math_gcd(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_gcd(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_isfinite +// api-spec(c): kcl_value_ref_t* kcl_math_isfinite(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_isfinite(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_isinf +// api-spec(c): kcl_value_ref_t* kcl_math_isinf(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_isinf(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_isnan +// api-spec(c): kcl_value_ref_t* kcl_math_isnan(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_isnan(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_modf +// api-spec(c): kcl_value_ref_t* kcl_math_modf(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_modf(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_exp +// api-spec(c): kcl_value_ref_t* kcl_math_exp(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_exp(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_expm1 +// api-spec(c): kcl_value_ref_t* kcl_math_expm1(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_expm1(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_log +// api-spec(c): kcl_value_ref_t* kcl_math_log(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_log(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_log1p +// api-spec(c): kcl_value_ref_t* kcl_math_log1p(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_log1p(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_log2 +// api-spec(c): kcl_value_ref_t* kcl_math_log2(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_log2(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_log10 +// api-spec(c): kcl_value_ref_t* kcl_math_log10(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_log10(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_pow +// api-spec(c): kcl_value_ref_t* kcl_math_pow(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_pow(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_math_sqrt +// api-spec(c): kcl_value_ref_t* kcl_math_sqrt(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_math_sqrt(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_split_host_port +// api-spec(c): kcl_value_ref_t* kcl_net_split_host_port(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_split_host_port(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_join_host_port +// api-spec(c): kcl_value_ref_t* kcl_net_join_host_port(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_join_host_port(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_fqdn +// api-spec(c): kcl_value_ref_t* kcl_net_fqdn(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_fqdn(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_parse_IP +// api-spec(c): kcl_value_ref_t* kcl_net_parse_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_parse_IP(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_to_IP4 +// api-spec(c): kcl_value_ref_t* kcl_net_to_IP4(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_to_IP4(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_to_IP6 +// api-spec(c): kcl_value_ref_t* kcl_net_to_IP6(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_to_IP6(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_IP_string +// api-spec(c): kcl_value_ref_t* kcl_net_IP_string(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_IP_string(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_is_IPv4 +// api-spec(c): kcl_value_ref_t* kcl_net_is_IPv4(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_is_IPv4(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_is_IP +// api-spec(c): kcl_value_ref_t* kcl_net_is_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_is_IP(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_is_loopback_IP +// api-spec(c): kcl_value_ref_t* kcl_net_is_loopback_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_is_loopback_IP(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_is_multicast_IP +// api-spec(c): kcl_value_ref_t* kcl_net_is_multicast_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_is_multicast_IP(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_is_interface_local_multicast_IP +// api-spec(c): kcl_value_ref_t* kcl_net_is_interface_local_multicast_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_is_interface_local_multicast_IP(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_is_link_local_multicast_IP +// api-spec(c): kcl_value_ref_t* kcl_net_is_link_local_multicast_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_is_link_local_multicast_IP(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_is_link_local_unicast_IP +// api-spec(c): kcl_value_ref_t* kcl_net_is_link_local_unicast_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_is_link_local_unicast_IP(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_is_global_unicast_IP +// api-spec(c): kcl_value_ref_t* kcl_net_is_global_unicast_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_is_global_unicast_IP(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_parse_CIDR +// api-spec(c): kcl_value_ref_t* kcl_net_parse_CIDR(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_parse_CIDR(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_is_IP_in_CIDR +// api-spec(c): kcl_value_ref_t* kcl_net_is_IP_in_CIDR(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_is_IP_in_CIDR(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_is_unspecified_IP +// api-spec(c): kcl_value_ref_t* kcl_net_is_unspecified_IP(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_is_unspecified_IP(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_CIDR_subnet +// api-spec(c): kcl_value_ref_t* kcl_net_CIDR_subnet(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_CIDR_subnet(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_CIDR_subnets +// api-spec(c): kcl_value_ref_t* kcl_net_CIDR_subnets(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_CIDR_subnets(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_CIDR_host +// api-spec(c): kcl_value_ref_t* kcl_net_CIDR_host(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_CIDR_host(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_net_CIDR_netmask +// api-spec(c): kcl_value_ref_t* kcl_net_CIDR_netmask(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_net_CIDR_netmask(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_regex_match +// api-spec(c): kcl_value_ref_t* kcl_regex_match(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_regex_match(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_regex_replace +// api-spec(c): kcl_value_ref_t* kcl_regex_replace(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_regex_replace(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_regex_compile +// api-spec(c): kcl_value_ref_t* kcl_regex_compile(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_regex_compile(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_regex_findall +// api-spec(c): kcl_value_ref_t* kcl_regex_findall(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_regex_findall(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_regex_search +// api-spec(c): kcl_value_ref_t* kcl_regex_search(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_regex_search(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_regex_split +// api-spec(c): kcl_value_ref_t* kcl_regex_split(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_regex_split(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_assert +// api-spec(c): void kcl_assert(kcl_context_t* ctx, kcl_value_ref_t* value, kcl_value_ref_t* msg); +// api-spec(llvm): declare void @kcl_assert(%kcl_context_t* %ctx, %kcl_value_ref_t* %value, %kcl_value_ref_t* %msg); + +// api-spec: kcl_builtin_option_init +// api-spec(c): void kcl_builtin_option_init(kcl_context_t* ctx, char* key, char* value); +// api-spec(llvm): declare void @kcl_builtin_option_init(%kcl_context_t* %ctx, i8* %key, i8* %value); + +// api-spec: kcl_builtin_option_reset +// api-spec(c): kcl_value_ref_t* kcl_builtin_option_reset(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_option_reset(%kcl_context_t* %ctx, %kcl_value_ref_t* %_args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_option +// api-spec(c): kcl_value_ref_t* kcl_builtin_option(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_option(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_print +// api-spec(c): kcl_value_ref_t* kcl_builtin_print(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_print(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_len +// api-spec(c): kcl_value_ref_t* kcl_builtin_len(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_len(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_any_true +// api-spec(c): kcl_value_ref_t* kcl_builtin_any_true(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_any_true(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_isunique +// api-spec(c): kcl_value_ref_t* kcl_builtin_isunique(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_isunique(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_sorted +// api-spec(c): kcl_value_ref_t* kcl_builtin_sorted(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_sorted(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_int +// api-spec(c): kcl_value_ref_t* kcl_builtin_int(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_int(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_float +// api-spec(c): kcl_value_ref_t* kcl_builtin_float(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_float(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_bool +// api-spec(c): kcl_value_ref_t* kcl_builtin_bool(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_bool(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_str +// api-spec(c): kcl_value_ref_t* kcl_builtin_str(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_str(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_max +// api-spec(c): kcl_value_ref_t* kcl_builtin_max(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_max(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_min +// api-spec(c): kcl_value_ref_t* kcl_builtin_min(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_min(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_multiplyof +// api-spec(c): kcl_value_ref_t* kcl_builtin_multiplyof(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_multiplyof(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_abs +// api-spec(c): kcl_value_ref_t* kcl_builtin_abs(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_abs(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_all_true +// api-spec(c): kcl_value_ref_t* kcl_builtin_all_true(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_all_true(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_hex +// api-spec(c): kcl_value_ref_t* kcl_builtin_hex(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_hex(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_sum +// api-spec(c): kcl_value_ref_t* kcl_builtin_sum(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_sum(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_pow +// api-spec(c): kcl_value_ref_t* kcl_builtin_pow(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_pow(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_round +// api-spec(c): kcl_value_ref_t* kcl_builtin_round(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_round(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_zip +// api-spec(c): kcl_value_ref_t* kcl_builtin_zip(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_zip(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_builtin_list +// api-spec(c): kcl_value_ref_t* kcl_builtin_list(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_list(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_dict +// api-spec(c): kcl_value_ref_t* kcl_builtin_dict(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_dict(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_typeof +// api-spec(c): kcl_value_ref_t* kcl_builtin_typeof(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_typeof(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_bin +// api-spec(c): kcl_value_ref_t* kcl_builtin_bin(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_bin(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_oct +// api-spec(c): kcl_value_ref_t* kcl_builtin_oct(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_oct(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_ord +// api-spec(c): kcl_value_ref_t* kcl_builtin_ord(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_ord(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_range +// api-spec(c): kcl_value_ref_t* kcl_builtin_range(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_range(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_builtin_isnullish +// api-spec(c): kcl_value_ref_t* kcl_builtin_isnullish(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_builtin_isnullish(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_plugin_init +// api-spec(c): void kcl_plugin_init(void* fn_ptr); +// api-spec(llvm): declare void @kcl_plugin_init(i8* %fn_ptr); + +// api-spec: kcl_plugin_invoke +// api-spec(c): kcl_value_ref_t* kcl_plugin_invoke(kcl_context_t* ctx, char* method, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_plugin_invoke(%kcl_context_t* %ctx, i8* %method, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_plugin_invoke_json +// api-spec(c): char* kcl_plugin_invoke_json(char* method, char* args, char* kwargs); +// api-spec(llvm): declare i8* @kcl_plugin_invoke_json(i8* %method, i8* %args, i8* %kwargs); + +// api-spec: kcl_units_to_n +// api-spec(c): kcl_value_ref_t* kcl_units_to_n(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_units_to_n(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_units_to_u +// api-spec(c): kcl_value_ref_t* kcl_units_to_u(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_units_to_u(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_units_to_m +// api-spec(c): kcl_value_ref_t* kcl_units_to_m(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_units_to_m(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_units_to_K +// api-spec(c): kcl_value_ref_t* kcl_units_to_K(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_units_to_K(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_units_to_M +// api-spec(c): kcl_value_ref_t* kcl_units_to_M(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_units_to_M(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_units_to_G +// api-spec(c): kcl_value_ref_t* kcl_units_to_G(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_units_to_G(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_units_to_T +// api-spec(c): kcl_value_ref_t* kcl_units_to_T(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_units_to_T(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_units_to_P +// api-spec(c): kcl_value_ref_t* kcl_units_to_P(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_units_to_P(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_units_to_Ki +// api-spec(c): kcl_value_ref_t* kcl_units_to_Ki(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_units_to_Ki(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_units_to_Mi +// api-spec(c): kcl_value_ref_t* kcl_units_to_Mi(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_units_to_Mi(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_units_to_Gi +// api-spec(c): kcl_value_ref_t* kcl_units_to_Gi(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_units_to_Gi(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_units_to_Ti +// api-spec(c): kcl_value_ref_t* kcl_units_to_Ti(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_units_to_Ti(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_units_to_Pi +// api-spec(c): kcl_value_ref_t* kcl_units_to_Pi(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_units_to_Pi(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_yaml_encode +// api-spec(c): kcl_value_ref_t* kcl_yaml_encode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_yaml_encode(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_yaml_encode_all +// api-spec(c): kcl_value_ref_t* kcl_yaml_encode_all(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_yaml_encode_all(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_yaml_decode +// api-spec(c): kcl_value_ref_t* kcl_yaml_decode(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_yaml_decode(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_yaml_decode_all +// api-spec(c): kcl_value_ref_t* kcl_yaml_decode_all(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_yaml_decode_all(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_yaml_dump_to_file +// api-spec(c): kcl_value_ref_t* kcl_yaml_dump_to_file(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_yaml_dump_to_file(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_yaml_dump_all_to_file +// api-spec(c): kcl_value_ref_t* kcl_yaml_dump_all_to_file(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_yaml_dump_all_to_file(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_yaml_validate +// api-spec(c): kcl_value_ref_t* kcl_yaml_validate(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_yaml_validate(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_file_read +// api-spec(c): kcl_value_ref_t* kcl_file_read(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_read(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_file_glob +// api-spec(c): kcl_value_ref_t* kcl_file_glob(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_glob(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_file_modpath +// api-spec(c): kcl_value_ref_t* kcl_file_modpath(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_modpath(%kcl_context_t* %ctx, %kcl_value_ref_t* %_args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_file_workdir +// api-spec(c): kcl_value_ref_t* kcl_file_workdir(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_workdir(%kcl_context_t* %ctx, %kcl_value_ref_t* %_args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_file_current +// api-spec(c): kcl_value_ref_t* kcl_file_current(kcl_context_t* ctx, kcl_value_ref_t* _args, kcl_value_ref_t* _kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_current(%kcl_context_t* %ctx, %kcl_value_ref_t* %_args, %kcl_value_ref_t* %_kwargs); + +// api-spec: kcl_file_exists +// api-spec(c): kcl_value_ref_t* kcl_file_exists(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_exists(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_file_abs +// api-spec(c): kcl_value_ref_t* kcl_file_abs(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_abs(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_file_mkdir +// api-spec(c): kcl_value_ref_t* kcl_file_mkdir(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_mkdir(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_file_delete +// api-spec(c): kcl_value_ref_t* kcl_file_delete(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_delete(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_file_cp +// api-spec(c): kcl_value_ref_t* kcl_file_cp(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_cp(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_file_mv +// api-spec(c): kcl_value_ref_t* kcl_file_mv(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_mv(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_file_size +// api-spec(c): kcl_value_ref_t* kcl_file_size(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_size(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_file_write +// api-spec(c): kcl_value_ref_t* kcl_file_write(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_write(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_file_append +// api-spec(c): kcl_value_ref_t* kcl_file_append(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_append(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_file_read_env +// api-spec(c): kcl_value_ref_t* kcl_file_read_env(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_file_read_env(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_template_execute +// api-spec(c): kcl_value_ref_t* kcl_template_execute(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_template_execute(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_template_html_escape +// api-spec(c): kcl_value_ref_t* kcl_template_html_escape(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_template_html_escape(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + +// api-spec: kcl_runtime_catch +// api-spec(c): kcl_value_ref_t* kcl_runtime_catch(kcl_context_t* ctx, kcl_value_ref_t* args, kcl_value_ref_t* kwargs); +// api-spec(llvm): declare %kcl_value_ref_t* @kcl_runtime_catch(%kcl_context_t* %ctx, %kcl_value_ref_t* %args, %kcl_value_ref_t* %kwargs); + diff --git a/crates/runtime/src/_kcl_run.rs b/crates/runtime/src/_kcl_run.rs new file mode 100644 index 000000000..947c951ea --- /dev/null +++ b/crates/runtime/src/_kcl_run.rs @@ -0,0 +1,188 @@ +//! Copyright The KCL Authors. All rights reserved. +#![allow(clippy::missing_safety_doc)] + +use std::os::raw::c_char; + +use crate::*; + +use self::eval::LazyEvalScope; + +#[allow(dead_code, non_camel_case_types)] +type kcl_context_t = Context; + +#[allow(dead_code, non_camel_case_types)] +type kcl_eval_scope_t = LazyEvalScope; + +#[allow(dead_code, non_camel_case_types)] +type kcl_kind_t = Kind; + +#[allow(dead_code, non_camel_case_types)] +type kcl_type_t = Type; + +#[allow(dead_code, non_camel_case_types)] +type kcl_value_ref_t = ValueRef; + +#[allow(dead_code, non_camel_case_types)] +type kcl_iterator_t = ValueIterator; + +#[allow(dead_code, non_camel_case_types)] +type kcl_char_t = c_char; + +#[allow(dead_code, non_camel_case_types)] +type kcl_size_t = i32; + +#[allow(dead_code, non_camel_case_types)] +type kcl_bool_t = i8; + +#[allow(dead_code, non_camel_case_types)] +type kcl_int_t = i64; + +#[allow(dead_code, non_camel_case_types)] +type kcl_float_t = f64; + +#[derive(Debug, Default, Clone)] +pub struct RuntimePanicRecord { + pub kcl_panic_info: bool, + pub message: String, + pub rust_file: String, + pub rust_line: i32, + pub rust_col: i32, +} + +#[derive(Debug, Default, Clone, Copy)] +#[repr(C)] +pub struct FFIRunOptions { + pub strict_range_check: i32, + pub disable_none: i32, + pub disable_schema_check: i32, + pub debug_mode: i32, + pub show_hidden: i32, + pub sort_keys: i32, + pub include_schema_type_path: i32, + pub disable_empty_list: i32, +} + +thread_local! { + static KCL_RUNTIME_PANIC_RECORD: std::cell::RefCell = std::cell::RefCell::new(RuntimePanicRecord::default()) +} + +fn new_ctx_with_opts(opts: FFIRunOptions, path_selector: &[String]) -> Context { + let mut ctx = Context::new(); + // Config + ctx.cfg.strict_range_check = opts.strict_range_check != 0; + ctx.cfg.disable_schema_check = opts.disable_schema_check != 0; + ctx.cfg.debug_mode = opts.debug_mode != 0; + // Plan options + ctx.plan_opts.disable_none = opts.disable_none != 0; + ctx.plan_opts.show_hidden = opts.show_hidden != 0; + ctx.plan_opts.sort_keys = opts.sort_keys != 0; + ctx.plan_opts.include_schema_type_path = opts.include_schema_type_path != 0; + ctx.plan_opts.disable_empty_list = opts.disable_empty_list != 0; + ctx.plan_opts.query_paths = path_selector.to_vec(); + ctx +} + +#[unsafe(no_mangle)] +#[allow(clippy::too_many_arguments)] +pub unsafe extern "C-unwind" fn _kcl_run( + kcl_main_ptr: u64, // main.k => kcl_main + option_len: kcl_size_t, + option_keys: *const *const kcl_char_t, + option_values: *const *const kcl_char_t, + opts: FFIRunOptions, + path_selector: *const *const kcl_char_t, + json_result_buffer_len: *mut kcl_size_t, + json_result_buffer: *mut kcl_char_t, + yaml_result_buffer_len: *mut kcl_size_t, + yaml_result_buffer: *mut kcl_char_t, + err_buffer_len: *mut kcl_size_t, + err_buffer: *mut kcl_char_t, + log_buffer_len: *mut kcl_size_t, + log_buffer: *mut kcl_char_t, +) -> kcl_size_t { + // Init runtime context with options + let ctx = Box::new(new_ctx_with_opts(opts, &c2str_vec(path_selector))).into_raw(); + let scope = unsafe { kcl_scope_new() }; + let option_keys = unsafe { std::slice::from_raw_parts(option_keys, option_len as usize) }; + let option_values = unsafe { std::slice::from_raw_parts(option_values, option_len as usize) }; + for i in 0..(option_len as usize) { + unsafe { kcl_builtin_option_init(ctx, option_keys[i], option_values[i]) }; + } + let prev_hook = std::panic::take_hook(); + std::panic::set_hook(Box::new(|info: &std::panic::PanicHookInfo| { + KCL_RUNTIME_PANIC_RECORD.with(|record| { + let mut record = record.borrow_mut(); + record.kcl_panic_info = true; + + record.message = if let Some(s) = info.payload().downcast_ref::<&str>() { + s.to_string() + } else if let Some(s) = info.payload().downcast_ref::<&String>() { + (*s).clone() + } else if let Some(s) = info.payload().downcast_ref::() { + (*s).clone() + } else { + "".to_string() + }; + if let Some(location) = info.location() { + record.rust_file = location.file().to_string(); + record.rust_line = location.line() as i32; + record.rust_col = location.column() as i32; + } + }) + })); + let result = + unsafe { std::panic::catch_unwind(|| _kcl_run_in_closure(ctx, scope, kcl_main_ptr)) }; + std::panic::set_hook(prev_hook); + KCL_RUNTIME_PANIC_RECORD.with(|record| { + let record = record.borrow(); + let ctx = mut_ptr_as_ref(ctx); + ctx.set_panic_info(&record); + }); + // Get the runtime context. + let ctx_ref = ptr_as_ref(ctx); + // Copy planned result and log message + copy_str_to( + &ctx_ref.json_result, + json_result_buffer, + json_result_buffer_len, + ); + copy_str_to( + &ctx_ref.yaml_result, + yaml_result_buffer, + yaml_result_buffer_len, + ); + copy_str_to(&ctx_ref.log_message, log_buffer, log_buffer_len); + // Copy JSON panic info message pointer + let json_panic_info = if result.is_err() { + ctx_ref.get_panic_info_json_string().unwrap_or_default() + } else { + "".to_string() + }; + copy_str_to(&json_panic_info, err_buffer, err_buffer_len); + unsafe { + // Delete the context + kcl_context_delete(ctx); + // Delete the scope + kcl_scope_delete(scope); + } + result.is_err() as kcl_size_t +} + +unsafe fn _kcl_run_in_closure( + ctx: *mut Context, + scope: *mut LazyEvalScope, + kcl_main_ptr: u64, // main.k => kcl_main +) { + let kcl_main = (&kcl_main_ptr as *const u64) as *const () + as *const extern "C-unwind" fn( + ctx: *mut kcl_context_t, + scope: *mut kcl_eval_scope_t, + ) -> *mut kcl_value_ref_t; + + unsafe { + if kcl_main.is_null() { + panic!("kcl program main function not found"); + } + (*kcl_main)(ctx, scope); + } +} diff --git a/crates/runtime/src/_kcl_undefined_wasm.txt b/crates/runtime/src/_kcl_undefined_wasm.txt new file mode 100644 index 000000000..25b69bb40 --- /dev/null +++ b/crates/runtime/src/_kcl_undefined_wasm.txt @@ -0,0 +1 @@ +kcl_plugin_invoke_json_wasm \ No newline at end of file diff --git a/kclvm/runtime/src/api/error.rs b/crates/runtime/src/api/error.rs similarity index 100% rename from kclvm/runtime/src/api/error.rs rename to crates/runtime/src/api/error.rs diff --git a/crates/runtime/src/api/kcl.rs b/crates/runtime/src/api/kcl.rs new file mode 100644 index 000000000..0f8431626 --- /dev/null +++ b/crates/runtime/src/api/kcl.rs @@ -0,0 +1,464 @@ +//! Copyright The KCL Authors. All rights reserved. + +use crate::{new_mut_ptr, val_plan::PlanOptions}; +use generational_arena::Index; +use kcl_primitives::{IndexMap, IndexSet}; +use serde::{Deserialize, Serialize}; +use std::collections::{HashMap, HashSet}; +use std::panic::{RefUnwindSafe, UnwindSafe}; +use std::rc::Rc; +use std::sync::Arc; +use std::{ + cell::RefCell, + cmp::Ordering, + hash::{Hash, Hasher}, +}; + +/* + * Single instance name constants Undefined, None, True, False + */ +#[allow(non_upper_case_globals)] +pub const UNDEFINED: Value = Value::undefined; +#[allow(non_upper_case_globals)] +pub const NONE: Value = Value::none; +#[allow(non_upper_case_globals)] +pub const TRUE: Value = Value::bool_value(true); +#[allow(non_upper_case_globals)] +pub const FALSE: Value = Value::bool_value(false); + +/* + * Runtime types + */ + +#[derive(Clone, PartialEq, Debug, Default)] +pub enum Type { + #[default] + Any, + Bool, + BoolLit(bool), + Int, + IntLit(i64), + Float, + FloatLit(f64), + Str, + StrLit(String), + List(ListType), + Dict(DictType), + Union(UnionType), + Schema(SchemaType), + Func(FuncType), +} + +#[derive(PartialEq, Clone, Default, Debug)] +pub struct ListType { + pub elem_type: Box, +} + +#[derive(PartialEq, Clone, Default, Debug)] +pub struct DictType { + pub key_type: Box, + pub elem_type: Box, +} + +#[derive(PartialEq, Clone, Default, Debug)] +pub struct UnionType { + pub elem_types: Vec, +} + +/// The runtime schema type. +#[derive(PartialEq, Clone, Default, Debug)] +pub struct SchemaType { + /// The schema runtime type name. + pub name: String, + /// Schema attributes. + pub attrs: IndexMap, + /// Schema index signature. + pub has_index_signature: bool, + /// Schema runtime function value. + pub func: ValueRef, +} + +#[derive(PartialEq, Clone, Default, Debug)] +pub struct FuncType { + pub args_types: Vec, + pub return_type: Box, +} + +#[repr(C)] +#[allow(non_camel_case_types)] +#[derive(Clone, Debug)] +pub struct ValueRef { + pub rc: Rc>, +} + +impl Eq for ValueRef {} + +impl PartialEq for ValueRef { + fn eq(&self, other: &Self) -> bool { + self.cmp_equal(other) + } +} + +impl Ord for ValueRef { + fn cmp(&self, other: &ValueRef) -> Ordering { + let ord = match &*self.rc.borrow() { + Value::int_value(a) => match *other.rc.borrow() { + Value::int_value(b) => a.partial_cmp(&b), + Value::float_value(b) => (*a as f64).partial_cmp(&b), + _ => None, + }, + Value::float_value(a) => match *other.rc.borrow() { + Value::int_value(b) => a.partial_cmp(&(b as f64)), + Value::float_value(b) => a.partial_cmp(&b), + _ => None, + }, + Value::str_value(a) => match &*other.rc.borrow() { + Value::str_value(b) => a.partial_cmp(b), + _ => None, + }, + _ => None, + }; + match ord { + Some(ord) => ord, + _ => panic!( + "cannot compare {} and {}", + self.type_str(), + other.type_str() + ), + } + } +} + +impl PartialOrd for ValueRef { + fn partial_cmp(&self, other: &ValueRef) -> Option { + Some(self.cmp(other)) + } +} + +impl Hash for ValueRef { + fn hash(&self, state: &mut H) { + match &*self.rc.borrow() { + Value::undefined => 0.hash(state), + Value::none => 0.hash(state), + Value::int_value(v) => (*v as f64).to_bits().hash(state), + Value::unit_value(_real, raw, unit) => { + raw.hash(state); + unit.hash(state); + } + Value::float_value(v) => v.to_bits().hash(state), + Value::bool_value(v) => v.hash(state), + Value::str_value(v) => (*v).hash(state), + Value::list_value(v) => { + for i in 0..v.values.len() { + v.values[i].hash(state); + } + } + Value::dict_value(v) => { + for (k, v) in v.values.iter() { + (*k).hash(state); + v.hash(state); + } + } + Value::schema_value(v) => { + for (k, v) in v.config.values.iter() { + (*k).hash(state); + v.hash(state); + } + } + Value::func_value(v) => { + v.fn_ptr.hash(state); + } + } + } +} + +impl Default for ValueRef { + fn default() -> Self { + Self { + rc: Rc::new(RefCell::new(Value::undefined)), + } + } +} + +impl ValueRef { + // Returns whether self and x refer to the same Value + pub fn is_same_ref(&self, x: &Self) -> bool { + std::ptr::eq(&*self.rc.borrow(), &*x.rc.borrow()) + } + + pub fn into_raw(self, ctx: &mut Context) -> *mut Self { + new_mut_ptr(ctx, self) + } + + pub fn from_raw(&self) { + // If value is a func, clear the captured ValueRef to break circular reference. + if let Value::func_value(val) = &mut *self.rc.borrow_mut() { + val.closure = ValueRef::none(); + } + } +} + +#[allow(non_camel_case_types)] +#[derive(Clone, PartialEq, Debug)] +pub enum Value { + undefined, + none, + bool_value(bool), + int_value(i64), + float_value(f64), + str_value(String), + list_value(Box), + dict_value(Box), + schema_value(Box), + func_value(Box), + unit_value(f64, i64, String), // (Real value, raw value, unit string) +} + +impl Default for Value { + fn default() -> Self { + Self::undefined + } +} + +#[derive(PartialEq, Eq, Clone, Default, Debug)] +pub struct ListValue { + pub values: Vec, +} + +#[derive(PartialEq, Eq, Clone, Default, Debug)] +pub struct DictValue { + pub values: IndexMap, + pub ops: IndexMap, + pub insert_indexs: IndexMap, + /// Attribute type annotation string mapping. + pub attr_map: IndexMap, + /// The runtime dict to schema reflect type string. + pub potential_schema: Option, +} + +#[derive(PartialEq, Clone, Default, Debug)] +pub struct SchemaValue { + /// Schema name without the package path prefix. + pub name: String, + /// Schema instance package path, note is it not the schema definition package path. + pub pkgpath: String, + /// Schema values. + pub config: Box, + /// Schema instance config keys e.g., "a" in `MySchema {a = "foo"}` + pub config_keys: Vec, + /// schema config meta information including filename, line and column. + pub config_meta: ValueRef, + /// This map stores which attributes of the schema are optional and which are required. + pub optional_mapping: ValueRef, + /// Schema instance argument values + pub args: ValueRef, + /// Schema instance keyword argument values + pub kwargs: ValueRef, +} + +#[derive(PartialEq, Eq, Clone, Default, Debug)] +pub struct DecoratorValue { + pub name: String, + pub args: ValueRef, + pub kwargs: ValueRef, +} + +#[derive(PartialEq, Eq, Clone, Default, Debug)] +pub struct FuncValue { + pub fn_ptr: u64, + pub check_fn_ptr: u64, + pub closure: ValueRef, + pub name: String, + pub runtime_type: String, + pub is_external: bool, + /// Proxy functions represent the saved functions of the runtime itself, + /// rather than executing KCL defined functions or plugin functions. + pub proxy: Option, +} + +#[allow(non_snake_case)] +#[derive(PartialEq, Eq, Clone, Default, Debug, Serialize, Deserialize)] +pub struct PanicInfo { + // Used to distinguish whether it is an error + // message JSON or a program run result. + #[serde(rename = "__kcl_PanicInfo__")] + pub __kcl_PanicInfo__: bool, + pub backtrace: Vec, + + pub rust_file: String, + pub rust_line: i32, + pub rust_col: i32, + + pub kcl_pkgpath: String, + pub kcl_file: String, + pub kcl_func: String, + pub kcl_line: i32, + pub kcl_col: i32, + pub kcl_arg_msg: String, + + // Only for schema check failed error message + pub kcl_config_meta_file: String, + pub kcl_config_meta_line: i32, + pub kcl_config_meta_col: i32, + pub kcl_config_meta_arg_msg: String, + + pub message: String, + pub err_type_code: i32, + pub is_warning: bool, +} + +#[derive(PartialEq, Eq, Clone, Default, Debug)] +pub struct ContextConfig { + pub debug_mode: bool, + pub strict_range_check: bool, + pub disable_schema_check: bool, +} + +#[derive(PartialEq, Eq, Clone, Debug)] +pub struct ContextBuffer { + pub kcl_context_invoke_result: String, + /// Custom manifest output string. + pub custom_manifests_output: Option, +} + +impl Default for ContextBuffer { + fn default() -> Self { + Self { + kcl_context_invoke_result: "\0".to_string(), + custom_manifests_output: None, + } + } +} + +/// Plugin functions +pub type PluginFunction = + Arc anyhow::Result + Send + Sync>; + +#[derive(Clone, Default)] +pub struct Context { + /// Runtime evaluation config. + pub cfg: ContextConfig, + /// kcl.mod path or the pwd path + pub module_path: String, + /// Program work directory + pub workdir: String, + /// Runtime backtrace frame for the debugger. + pub backtrace: Vec, + /// Imported package path to check the cyclic import process. + pub imported_pkgpath: HashSet, + /// Runtime arguments for the option function. + pub option_values: HashMap, + /// All schema instances, the first key is the schema runtime type and + /// the second key is the schema instance package path + pub instances: IndexMap>>, + /// All schema types + pub all_schemas: HashMap, + /// Import graph + pub import_names: IndexMap>, + /// A buffer to store plugin or hooks function calling results. + pub buffer: ContextBuffer, + /// Objects is to store all KCL object pointers at runtime for GC. + pub objects: IndexSet, + /// Log message used to store print results. + pub log_message: String, + /// Planned JSON result + pub json_result: String, + /// Planned YAML result + pub yaml_result: String, + /// Panic information at runtime + pub panic_info: PanicInfo, + /// Planning options + pub plan_opts: PlanOptions, + /// Builtin plugin functions, the key of the map is the form . e.g., `hello.say_hello` + pub plugin_functions: IndexMap, +} + +impl UnwindSafe for Context {} +impl RefUnwindSafe for Context {} + +#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)] +pub struct BacktraceFrame { + pub file: String, + pub func: String, + pub col: i32, + pub line: i32, +} +impl Default for BacktraceFrame { + fn default() -> Self { + Self { + file: Default::default(), + func: "_kcl_main".to_string(), + col: Default::default(), + line: Default::default(), + } + } +} + +impl BacktraceFrame { + pub fn from_panic_info(info: &PanicInfo) -> Self { + Self { + file: info.kcl_file.clone(), + func: info.kcl_func.clone(), + col: info.kcl_col, + line: info.kcl_line, + } + } +} + +impl Context { + pub fn new() -> Self { + Context { + instances: IndexMap::default(), + panic_info: PanicInfo { + kcl_func: "kcl_main".to_string(), + ..Default::default() + }, + ..Default::default() + } + } +} + +#[repr(C)] +#[derive(Clone, PartialEq, Eq, Debug, Hash)] +pub enum Kind { + Invalid = 0, + Undefined = 1, + None = 2, + Bool = 3, + Int = 4, + Float = 5, + Str = 6, + List = 7, + Dict = 8, + Schema = 9, + Error = 10, + Any = 11, + Union = 12, + BoolLit = 13, + IntLit = 14, + FloatLit = 15, + StrLit = 16, + Unit = 17, + Func = 18, +} + +#[derive(Clone, PartialEq, Eq, Debug, Hash, Default)] +pub enum ConfigEntryOperationKind { + #[default] + Union = 0, + Override = 1, + Insert = 2, +} + +impl ConfigEntryOperationKind { + pub fn from_i32(v: i32) -> Self { + match v { + x if x == ConfigEntryOperationKind::Union as i32 => ConfigEntryOperationKind::Union, + x if x == ConfigEntryOperationKind::Override as i32 => { + ConfigEntryOperationKind::Override + } + x if x == ConfigEntryOperationKind::Insert as i32 => ConfigEntryOperationKind::Insert, + _ => panic!("Invalid AttrOpKind integer {v}, expected 0, 1 or 2"), + } + } +} diff --git a/crates/runtime/src/api/mod.rs b/crates/runtime/src/api/mod.rs new file mode 100644 index 000000000..886682bca --- /dev/null +++ b/crates/runtime/src/api/mod.rs @@ -0,0 +1,10 @@ +//! Copyright The KCL Authors. All rights reserved. + +pub mod kcl; +pub use self::kcl::*; + +pub mod utils; +pub use self::utils::*; + +pub mod error; +pub use self::error::*; diff --git a/crates/runtime/src/api/utils.rs b/crates/runtime/src/api/utils.rs new file mode 100644 index 000000000..48db8b29e --- /dev/null +++ b/crates/runtime/src/api/utils.rs @@ -0,0 +1,108 @@ +//! Copyright The KCL Authors. All rights reserved. + +use std::os::raw::c_char; + +use crate::{Context, ValueRef, kcl_size_t}; + +/// New a mutable raw pointer. +/// Safety: The caller must ensure that `ctx` lives longer than the returned pointer +/// and that the pointer is properly deallocated by calling `free_mut_ptr`. +pub fn new_mut_ptr(ctx: &mut Context, x: ValueRef) -> *mut ValueRef { + let ptr = Box::into_raw(Box::new(x)); + // Store the object pointer address to + // drop it it after execution is complete + ctx.objects.insert(ptr as usize); + ptr +} + +/// Free a mutable raw pointer. +/// Safety: The caller must ensure `p` is a valid pointer obtained from `new_mut_ptr`. +pub fn free_mut_ptr(p: *mut T) { + if !p.is_null() { + unsafe { + drop(Box::from_raw(p)); + } + } +} + +/// Convert a const raw pointer to a immutable borrow. +/// Safety: The caller must ensure that `p` is valid for the lifetime `'a`. +pub fn ptr_as_ref<'a, T>(p: *const T) -> &'a T { + assert!(!p.is_null()); + unsafe { &*p } +} + +/// Convert a mutable raw pointer to a mutable borrow. +/// Safety: The caller must ensure that `p` is valid for the lifetime `'a`. +pub fn mut_ptr_as_ref<'a, T>(p: *mut T) -> &'a mut T { + assert!(!p.is_null()); + + unsafe { &mut *p } +} + +/// Copy str to mutable pointer with length +pub(crate) fn copy_str_to(v: &str, p: *mut c_char, size: *mut kcl_size_t) { + assert!(!p.is_null() || !size.is_null()); + + unsafe { + let c_str_ptr = v.as_ptr() as *const c_char; + let c_str_len = v.len() as i32; + if c_str_len <= *size { + std::ptr::copy(c_str_ptr, p, c_str_len as usize); + *size = c_str_len + } + } +} + +/// Convert a C str pointer to a Rust &str. +/// Safety: The caller must ensure that `s` is a valid null-terminated C string. +pub fn c2str<'a>(p: *const c_char) -> &'a str { + assert!(!p.is_null()); + + let s = unsafe { std::ffi::CStr::from_ptr(p) }.to_str().unwrap(); + s +} + +/// Convert a C str pointer pointer to a Rust Vec. +pub fn c2str_vec(ptr_array: *const *const c_char) -> Vec { + assert!(!ptr_array.is_null()); + + let mut result = Vec::new(); + let mut index = 0; + + unsafe { + loop { + let current_ptr = *ptr_array.offset(index); + if current_ptr.is_null() { + break; + } + let c_str = std::ffi::CStr::from_ptr(current_ptr); + let rust_string = c_str.to_string_lossy().to_string(); + result.push(rust_string); + index += 1; + } + } + + result +} + +pub fn assert_panic(msg: &str, func: F) { + match std::panic::catch_unwind(func) { + Ok(_v) => { + panic!("not panic, expect={msg}"); + } + Err(e) => match e.downcast::() { + Ok(v) => { + let got = v.to_string(); + assert!(got.contains(msg), "expect={msg}, got={got}"); + } + Err(e) => match e.downcast::<&str>() { + Ok(v) => { + let got = v.to_string(); + assert!(got.contains(msg), "expect={msg}, got={got}"); + } + _ => unreachable!(), + }, + }, + }; +} diff --git a/crates/runtime/src/base32/mod.rs b/crates/runtime/src/base32/mod.rs new file mode 100644 index 000000000..81ef46ff7 --- /dev/null +++ b/crates/runtime/src/base32/mod.rs @@ -0,0 +1,44 @@ +//! Copyright The KCL Authors. All rights reserved. + +extern crate base32; +use crate::*; +use base32::{Alphabet, decode, encode}; + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_base32_encode( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { + let s = encode(Alphabet::RFC4648 { padding: true }, s.as_bytes()); + return ValueRef::str(s.as_str()).into_raw(ctx); + } + panic!("encode() missing 1 required positional argument: 'value'"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_base32_decode( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { + if let Some(de_str) = decode(Alphabet::RFC4648 { padding: true }, &s) { + if let Ok(s) = std::str::from_utf8(&de_str) { + return ValueRef::str(s).into_raw(ctx); + } + } + // Handle decoding errors + return ValueRef::none().into_raw(ctx); + } + panic!("decode() missing 1 required positional argument: 'value'"); +} diff --git a/crates/runtime/src/base64/mod.rs b/crates/runtime/src/base64/mod.rs new file mode 100644 index 000000000..e8294ec0a --- /dev/null +++ b/crates/runtime/src/base64/mod.rs @@ -0,0 +1,40 @@ +//! Copyright The KCL Authors. All rights reserved. + +extern crate base64; +use base64::{decode, encode}; + +use crate::*; + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_base64_encode( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { + let s = encode(s); + return ValueRef::str(s.as_str()).into_raw(ctx); + } + panic!("encode() missing 1 required positional argument: 'value'"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_base64_decode( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { + let de_str = decode(s).unwrap(); + return ValueRef::str(std::str::from_utf8(&de_str).unwrap()).into_raw(ctx); + } + panic!("decode() missing 1 required positional argument: 'value'"); +} diff --git a/crates/runtime/src/collection/mod.rs b/crates/runtime/src/collection/mod.rs new file mode 100644 index 000000000..241ca7d20 --- /dev/null +++ b/crates/runtime/src/collection/mod.rs @@ -0,0 +1,31 @@ +//! Copyright The KCL Authors. All rights reserved. + +use crate::*; + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_value_union_all( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let ctx = mut_ptr_as_ref(ctx); + if let Some(arg) = args.arg_0() { + if !arg.is_truthy() || !arg.is_list() { + return ValueRef::dict(None).into_raw(ctx); + } + let value = arg.as_list_ref(); + if value.values.is_empty() { + return ValueRef::dict(None).into_raw(ctx); + } + let mut result = value.values[0].deep_copy(); + for (i, v) in value.values.iter().enumerate() { + if i > 0 { + result.bin_aug_union_with(ctx, v); + } + } + return result.into_raw(ctx); + } + panic!("union_all() takes at least 1 argument (0 given)") +} diff --git a/crates/runtime/src/context/api.rs b/crates/runtime/src/context/api.rs new file mode 100644 index 000000000..0c19d9f52 --- /dev/null +++ b/crates/runtime/src/context/api.rs @@ -0,0 +1,322 @@ +//! Copyright The KCL Authors. All rights reserved. +#![allow(clippy::missing_safety_doc)] + +use crate::*; +use std::os::raw::c_char; + +use self::eval::LazyEvalScope; + +#[allow(dead_code, non_camel_case_types)] +type kcl_context_t = Context; + +#[allow(dead_code, non_camel_case_types)] +type kcl_eval_scope_t = LazyEvalScope; + +#[allow(dead_code, non_camel_case_types)] +type kcl_kind_t = Kind; + +#[allow(dead_code, non_camel_case_types)] +type kcl_type_t = Type; + +#[allow(dead_code, non_camel_case_types)] +type kcl_value_t = Value; + +#[allow(dead_code, non_camel_case_types)] +type kcl_char_t = c_char; + +#[allow(dead_code, non_camel_case_types)] +type kcl_size_t = i32; + +#[allow(dead_code, non_camel_case_types)] +type kcl_bool_t = i8; + +#[allow(dead_code, non_camel_case_types)] +type kcl_int_t = i64; + +#[allow(dead_code, non_camel_case_types)] +type kcl_float_t = f64; + +// ---------------------------------------------------------------------------- +// new/delete +// ---------------------------------------------------------------------------- + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_new() -> *mut kcl_context_t { + Box::into_raw(Box::new(Context::new())) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_delete(p: *mut kcl_context_t) { + let ctx = mut_ptr_as_ref(p); + for o in &ctx.objects { + let ptr = (*o) as *mut kcl_value_ref_t; + unsafe { kcl_value_delete(ptr) }; + } + free_mut_ptr(p); +} + +// ---------------------------------------------------------------------------- +// panic_info +// ---------------------------------------------------------------------------- + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_set_kcl_location( + p: *mut kcl_context_t, + filename: *const c_char, + line: i32, + col: i32, +) { + let p = mut_ptr_as_ref(p); + if !filename.is_null() { + p.set_kcl_location_info(None, Some(c2str(filename)), Some(line), Some(col)); + } else { + p.set_kcl_location_info(None, None, Some(line), Some(col)); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_set_kcl_pkgpath( + p: *mut kcl_context_t, + pkgpath: *const c_char, +) { + let p = mut_ptr_as_ref(p); + if !pkgpath.is_null() { + p.set_kcl_pkgpath(c2str(pkgpath)); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_set_kcl_modpath( + p: *mut kcl_context_t, + module_path: *const c_char, +) { + let p = mut_ptr_as_ref(p); + if !module_path.is_null() { + p.set_kcl_module_path(c2str(module_path)); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_set_kcl_workdir( + p: *mut kcl_context_t, + workdir: *const c_char, +) { + let p = mut_ptr_as_ref(p); + if !workdir.is_null() { + p.set_kcl_workdir(c2str(workdir)); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_set_kcl_filename( + ctx: *mut kcl_context_t, + filename: *const c_char, +) { + let ctx = mut_ptr_as_ref(ctx); + if !filename.is_null() { + ctx.set_kcl_filename(c2str(filename)); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_set_kcl_line_col( + ctx: *mut kcl_context_t, + line: i32, + col: i32, +) { + let ctx = mut_ptr_as_ref(ctx); + ctx.set_kcl_line_col(line, col); +} + +// ---------------------------------------------------------------------------- +// Global values and evaluation scope. +// ---------------------------------------------------------------------------- + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_scope_new() -> *mut kcl_eval_scope_t { + Box::into_raw(Box::default()) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_scope_delete(scope: *mut kcl_eval_scope_t) { + drop(unsafe { Box::from_raw(scope) }); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_scope_add_setter( + _ctx: *mut kcl_context_t, + scope: *mut kcl_eval_scope_t, + pkg: *const c_char, + name: *const c_char, + setter: *const u64, +) { + let scope = mut_ptr_as_ref(scope); + let pkg = c2str(pkg); + let name = c2str(name); + let key = format!("{}.{}", pkg, name); + if !scope.setters.contains_key(&key) { + scope.setters.insert(key.clone(), vec![]); + } + if let Some(setters) = scope.setters.get_mut(&key) { + setters.push(setter as u64); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_scope_set( + _ctx: *mut kcl_context_t, + scope: *mut kcl_eval_scope_t, + pkg: *const c_char, + name: *const c_char, + value: *const kcl_value_ref_t, +) { + let scope = mut_ptr_as_ref(scope); + let value = ptr_as_ref(value); + let pkg = c2str(pkg); + let name = c2str(name); + let key = format!("{}.{}", pkg, name); + scope.set_value(&key, value); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_scope_get( + ctx: *mut kcl_context_t, + scope: *mut kcl_eval_scope_t, + pkg: *const c_char, + name: *const c_char, + target: *const c_char, + default: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let scope = mut_ptr_as_ref(scope); + let pkg = c2str(pkg); + let name = c2str(name); + let target = format!("{}.{}", pkg, c2str(target)); + let key = format!("{}.{}", pkg, name); + // Existing values or existing but not yet calculated values. + if scope.contains_key(&key) || scope.setters.contains_key(&key) { + scope.get_value(ctx, &key, &target).into_raw(ctx) + } else { + default + } +} + +// ---------------------------------------------------------------------------- +// CLI config +// ---------------------------------------------------------------------------- + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_set_debug_mode(p: *mut kcl_context_t, v: kcl_bool_t) { + let p = mut_ptr_as_ref(p); + p.cfg.debug_mode = v != 0; +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_set_strict_range_check( + p: *mut kcl_context_t, + v: kcl_bool_t, +) { + let p = mut_ptr_as_ref(p); + p.cfg.strict_range_check = v != 0; +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_set_disable_none(p: *mut kcl_context_t, v: kcl_bool_t) { + let p = mut_ptr_as_ref(p); + p.plan_opts.disable_none = v != 0; +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_set_disable_schema_check( + p: *mut kcl_context_t, + v: kcl_bool_t, +) { + let p = mut_ptr_as_ref(p); + p.cfg.disable_schema_check = v != 0; +} + +// ---------------------------------------------------------------------------- +// invoke +// ---------------------------------------------------------------------------- + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_invoke( + p: *mut kcl_context_t, + method: *const c_char, + args: *const c_char, + kwargs: *const c_char, +) -> *const c_char { + let p = mut_ptr_as_ref(p); + let method = c2str(method); + + let args = unsafe { kcl_value_from_json(p, args) }; + let kwargs = unsafe { kcl_value_from_json(p, kwargs) }; + let result = unsafe { _kcl_context_invoke(p, method, args, kwargs) }; + + p.buffer.kcl_context_invoke_result = ptr_as_ref(result).to_json_string_with_null(); + let result_json = p.buffer.kcl_context_invoke_result.as_ptr() as *const c_char; + + unsafe { kcl_value_delete(args) }; + unsafe { kcl_value_delete(kwargs) }; + unsafe { kcl_value_delete(result) }; + + result_json +} + +unsafe fn _kcl_context_invoke( + ctx: *mut kcl_context_t, + method: &str, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + + let fn_addr = _kcl_get_fn_ptr_by_name(method); + if fn_addr == 0 { + panic!("null fn ptr"); + } + + let ptr = (&fn_addr as *const u64) as *const () + as *const extern "C-unwind" fn( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, + ) -> *mut kcl_value_ref_t; + + unsafe { (*ptr)(ctx, args, kwargs) } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_pkgpath_is_imported( + ctx: *mut kcl_context_t, + pkgpath: *const kcl_char_t, +) -> kcl_bool_t { + let pkgpath = c2str(pkgpath); + let ctx = mut_ptr_as_ref(ctx); + let result = ctx.imported_pkgpath.contains(pkgpath); + ctx.imported_pkgpath.insert(pkgpath.to_string()); + result as kcl_bool_t +} + +// ---------------------------------------------------------------------------- +// END +// ---------------------------------------------------------------------------- diff --git a/crates/runtime/src/context/mod.rs b/crates/runtime/src/context/mod.rs new file mode 100644 index 000000000..a2e696729 --- /dev/null +++ b/crates/runtime/src/context/mod.rs @@ -0,0 +1,191 @@ +//! Copyright The KCL Authors. All rights reserved. + +pub mod api; +pub use api::*; +use std::fmt; + +use crate::{BacktraceFrame, PanicInfo, RuntimePanicRecord, kcl_value_delete, kcl_value_ref_t}; + +impl fmt::Display for PanicInfo { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{self:?}") + } +} + +impl PanicInfo { + pub fn to_json_string(&self) -> String { + let result = serde_json::to_string(&self); + match result { + Ok(res) => res, + _ => { + panic!("PanicInfo Deserialize Failed") + } + } + } + + /// Parse a json string to a PanicInfo. + pub fn from_json_string(s: &str) -> Self { + let result = serde_json::from_str(s); + match result { + Ok(res) => res, + _ => { + panic!("PanicInfo Deserialize Failed") + } + } + } + + /// Parse a string or json string to a PanicInfo. + pub fn from_string(s: &str) -> Self { + let result = serde_json::from_str(s); + match result { + Ok(res) => res, + Err(_) => PanicInfo { + __kcl_PanicInfo__: true, + message: s.to_string(), + err_type_code: crate::RuntimeErrorType::EvaluationError as i32, + ..Default::default() + }, + } + } +} + +impl From for PanicInfo { + fn from(value: String) -> Self { + Self::from_string(&value) + } +} + +impl PanicInfo { + /// New a [`PanicInfo`] from error message [`value`] and the position that error occur. + pub fn from_ast_pos(value: String, pos: (String, u64, u64, u64, u64)) -> Self { + let mut panic_info = Self::from_string(&value); + panic_info.kcl_file = pos.0; + panic_info.kcl_line = pos.1 as i32; + panic_info.kcl_col = pos.2 as i32; + panic_info + } +} + +impl From<&str> for PanicInfo { + fn from(value: &str) -> Self { + Self::from_string(value) + } +} + +impl crate::Context { + pub fn into_raw(self) -> *mut Self { + Box::into_raw(Box::new(self)) + } + + pub fn get_panic_info_json_string(&self) -> Option { + if self.panic_info.__kcl_PanicInfo__ { + Some(self.panic_info.to_json_string()) + } else { + None + } + } + + pub fn set_kcl_pkgpath(&mut self, pkgpath: &str) { + self.panic_info.kcl_pkgpath = pkgpath.to_string(); + } + + pub fn set_kcl_module_path(&mut self, module_path: &str) { + self.module_path = module_path.to_string(); + } + + pub fn set_kcl_workdir(&mut self, workdir: &str) { + self.workdir = workdir.to_string(); + } + + pub fn set_kcl_filename(&mut self, file: &str) { + if !file.is_empty() { + self.panic_info.kcl_file = file.to_string(); + } + } + + pub fn set_kcl_line_col(&mut self, line: i32, col: i32) { + self.panic_info.kcl_line = line; + self.panic_info.kcl_col = col; + } + + pub fn set_kcl_location_info( + &mut self, + arg_msg: Option<&str>, + file: Option<&str>, + line: Option, + col: Option, + ) { + if let Some(s) = arg_msg { + self.panic_info.kcl_arg_msg = s.to_string(); + } + if let Some(s) = file { + self.panic_info.kcl_file = s.to_string(); + } + if let Some(line) = line { + self.panic_info.kcl_line = line; + } + if let Some(col) = col { + self.panic_info.kcl_col = col; + } + } + + pub fn set_kcl_config_meta_location_info( + &mut self, + arg_msg: Option<&str>, + file: Option<&str>, + line: Option, + col: Option, + ) { + if let Some(s) = arg_msg { + self.panic_info.kcl_config_meta_arg_msg = s.to_string(); + } + if let Some(s) = file { + self.panic_info.kcl_config_meta_file = s.to_string(); + } + if let Some(line) = line { + self.panic_info.kcl_config_meta_line = line; + } + if let Some(col) = col { + self.panic_info.kcl_config_meta_col = col; + } + } + + pub fn set_err_type(&mut self, err_type: &crate::RuntimeErrorType) { + self.panic_info.__kcl_PanicInfo__ = true; + self.panic_info.err_type_code = *err_type as i32; + } + + pub fn set_warning_message(&mut self, msg: &str) { + self.panic_info.__kcl_PanicInfo__ = true; + self.panic_info.message = msg.to_string(); + self.panic_info.is_warning = true; + } + + pub fn set_panic_info(&mut self, record: &RuntimePanicRecord) { + self.panic_info.__kcl_PanicInfo__ = true; + + self.panic_info.message = record.message.clone(); + if self.cfg.debug_mode { + self.panic_info.backtrace = self.backtrace.clone(); + self.panic_info.backtrace.push(BacktraceFrame { + file: self.panic_info.kcl_file.clone(), + func: self.panic_info.kcl_func.clone(), + col: self.panic_info.kcl_col, + line: self.panic_info.kcl_line, + }); + } + + self.panic_info.rust_file = record.rust_file.clone(); + self.panic_info.rust_line = record.rust_line; + self.panic_info.rust_col = record.rust_col; + } + + pub fn gc(&self) { + unsafe { + for o in &self.objects { + let ptr = (*o) as *mut kcl_value_ref_t; + kcl_value_delete(ptr); + } + } + } +} diff --git a/crates/runtime/src/crypto/mod.rs b/crates/runtime/src/crypto/mod.rs new file mode 100644 index 000000000..cf4a05ad4 --- /dev/null +++ b/crates/runtime/src/crypto/mod.rs @@ -0,0 +1,342 @@ +//! Copyright The KCL Authors. All rights reserved. + +extern crate blake3; +extern crate md5; +extern crate sha1; +extern crate sha2; + +use core::panic; +use std::{fs::File, io::Read}; + +use crate::encoding::encode_text; +use sha2::{Digest, Sha224, Sha256, Sha384, Sha512}; + +use crate::*; +use uuid::Uuid; + +#[allow(non_camel_case_types)] +type kcl_value_ref_t = ValueRef; + +// md5(value: str, encoding: str = "utf-8") -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_crypto_md5( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { + let encoding = get_call_arg_str(args, kwargs, 1, Some("encoding")); + let bytes = encode_text(&s, encoding).unwrap(); + let hex = format!("{:x}", md5::compute(bytes)); + return ValueRef::str(hex.as_ref()).into_raw(ctx); + } + panic!("md5() missing 1 required positional argument: 'value'"); +} + +// sha1(value: str, encoding: str = "utf-8") -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_crypto_sha1( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { + let encoding = get_call_arg_str(args, kwargs, 1, Some("encoding")); + let bytes = encode_text(&s, encoding).unwrap(); + let hex = sha1::Sha1::from(bytes).digest().to_string(); + return ValueRef::str(hex.as_ref()).into_raw(ctx); + } + panic!("sha1() missing 1 required positional argument: 'value'"); +} + +// sha224(value: str, encoding: str = "utf-8") -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_crypto_sha224( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { + let encoding = get_call_arg_str(args, kwargs, 1, Some("encoding")); + let bytes = encode_text(&s, encoding).unwrap(); + let mut hasher = Sha224::new(); + hasher.update(bytes); + let result = hasher.finalize(); + + let mut hex = String::with_capacity(2 * Sha256::output_size()); + use std::fmt::Write; + + for byte in result { + let _ = write!(&mut hex, "{byte:02x}"); + } + + return ValueRef::str(hex.as_ref()).into_raw(ctx); + } + panic!("sha224() missing 1 required positional argument: 'value'"); +} + +// sha256(value: str, encoding: str = "utf-8") -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_crypto_sha256( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { + let encoding = get_call_arg_str(args, kwargs, 1, Some("encoding")); + let bytes = encode_text(&s, encoding).unwrap(); + let mut hasher = Sha256::new(); + hasher.update(bytes); + let result = hasher.finalize(); + + let mut hex = String::with_capacity(2 * Sha256::output_size()); + use std::fmt::Write; + + for byte in result { + let _ = write!(&mut hex, "{byte:02x}"); + } + + return ValueRef::str(hex.as_ref()).into_raw(ctx); + } + panic!("sha256() missing 1 required positional argument: 'value'"); +} + +// sha384(value: str, encoding: str = "utf-8") -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_crypto_sha384( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { + let encoding = get_call_arg_str(args, kwargs, 1, Some("encoding")); + let bytes = encode_text(&s, encoding).unwrap(); + let mut hasher = Sha384::new(); + hasher.update(bytes); + let result = hasher.finalize(); + + let mut hex = String::with_capacity(2 * Sha256::output_size()); + use std::fmt::Write; + + for byte in result { + let _ = write!(&mut hex, "{byte:02x}"); + } + + return ValueRef::str(hex.as_ref()).into_raw(ctx); + } + panic!("sha384() missing 1 required positional argument: 'value'"); +} + +// sha512(value: str, encoding: str = "utf-8") -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_crypto_sha512( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { + let encoding = get_call_arg_str(args, kwargs, 1, Some("encoding")); + let bytes = encode_text(&s, encoding).unwrap(); + let mut hasher = Sha512::new(); + hasher.update(bytes); + let result = hasher.finalize(); + + let mut hex = String::with_capacity(2 * Sha256::output_size()); + use std::fmt::Write; + + for byte in result { + let _ = write!(&mut hex, "{byte:02x}"); + } + + return ValueRef::str(hex.as_ref()).into_raw(ctx); + } + panic!("sha512() missing 1 required positional argument: 'value'"); +} + +// blake3(value: str, encoding: str = "utf-8") -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_crypto_blake3( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { + let encoding = get_call_arg_str(args, kwargs, 1, Some("encoding")); + let bytes = encode_text(&s, encoding).unwrap(); + let hasher = blake3::hash(&bytes); + + let mut hex = String::with_capacity(2 * blake3::OUT_LEN); + use std::fmt::Write; + + for byte in hasher.as_bytes() { + let _ = write!(&mut hex, "{byte:02x}"); + } + + return ValueRef::str(hex.as_ref()).into_raw(ctx); + } + panic!("blake3() missing 1 required positional argument: 'value'"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_crypto_uuid( + ctx: *mut kcl_context_t, + _args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + return ValueRef::str(Uuid::new_v4().to_string().as_ref()).into_raw(ctx); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_crypto_filesha256( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(filepath) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { + // Open the file + let mut file = File::open(&filepath) + .unwrap_or_else(|e| panic!("failed to access file '{}': {}", filepath, e)); + + // Create a SHA256 hasher instance + let mut hasher = Sha256::new(); + + // Read the file content and update the hasher + let mut buffer = Vec::new(); + file.read_to_end(&mut buffer) + .unwrap_or_else(|e| panic!("failed to read file '{}': {}", filepath, e)); + hasher.update(&buffer); + + // Compute the SHA256 hash + let hash_result = hasher.finalize(); + + let mut hex = String::with_capacity(2 * Sha256::output_size()); + use std::fmt::Write; + + for byte in hash_result { + let _ = write!(&mut hex, "{byte:02x}"); + } + + return ValueRef::str(hex.as_str()).into_raw(ctx); + } + panic!("filesha256() missing 1 required positional argument: 'filepath'"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_crypto_filesha512( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(filepath) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { + let mut file = File::open(&filepath) + .unwrap_or_else(|e| panic!("failed to access file '{}': {}", filepath, e)); + + let mut hasher = Sha512::new(); + + let mut buffer = [0; 4096]; + while let Ok(bytes_read) = file.read(&mut buffer) { + if bytes_read == 0 { + break; // End of file + } + hasher.update(&buffer[..bytes_read]); + } + + let hash_result = hasher.finalize(); + + let hex = hash_result + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + + return ValueRef::str(&hex).into_raw(ctx); + } + panic!("filesha512() missing 1 required positional argument: 'filepath'"); +} + +// fileblake3 +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_crypto_fileblake3( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(filepath) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { + let mut file = File::open(&filepath) + .unwrap_or_else(|e| panic!("failed to access file '{}': {}", filepath, e)); + + let mut buffer = Vec::new(); + file.read_to_end(&mut buffer) + .unwrap_or_else(|e| panic!("failed to read file '{}': {}", filepath, e)); + + let hasher = blake3::hash(&buffer); + + let mut hex = String::with_capacity(2 * blake3::OUT_LEN); + use std::fmt::Write; + + for byte in hasher.as_bytes() { + let _ = write!(&mut hex, "{byte:02x}"); + } + + return ValueRef::str(hex.as_str()).into_raw(ctx); + } + panic!("fileblake3() missing 1 required positional argument: 'filepath'"); +} diff --git a/crates/runtime/src/datetime/mod.rs b/crates/runtime/src/datetime/mod.rs new file mode 100644 index 000000000..f603655fd --- /dev/null +++ b/crates/runtime/src/datetime/mod.rs @@ -0,0 +1,109 @@ +//! Copyright The KCL Authors. All rights reserved. + +extern crate chrono; + +use chrono::{NaiveDate, NaiveDateTime, NaiveTime, prelude::Local}; + +use crate::*; + +/// Return the "%Y-%m-%d %H:%M:%S.%{ticks}" format date. +/// `today() -> str` +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_datetime_today( + ctx: *mut kcl_context_t, + _args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let s = Local::now(); + let ctx = mut_ptr_as_ref(ctx); + ValueRef::str(&(s.format("%Y-%m-%d %H:%M:%S").to_string() + "." + &s.timestamp().to_string())) + .into_raw(ctx) +} + +/// Return the local time format. e.g. 'Sat Jun 06 16:26:11 1998' or format the combined date and time per the specified format string, +/// and the default date format is "%a %b %d %H:%M:%S %Y". +/// `now() -> str` +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_datetime_now( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let s = Local::now(); + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let format = get_call_arg_str(args, kwargs, 0, Some("format")) + .unwrap_or_else(|| "%a %b %d %H:%M:%S %Y".to_string()); + ValueRef::str(&s.format(&format).to_string()).into_raw(ctx) +} + +/// Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. +/// `ticks() -> float` +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_datetime_ticks( + ctx: *mut kcl_context_t, + _args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let x = Local::now().timestamp(); + ValueRef::float(x as f64).into_raw(ctx) +} + +/// Return the %Y-%m-%d %H:%M:%S format date. +/// `date() -> str` +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_datetime_date( + ctx: *mut kcl_context_t, + _args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let s = Local::now(); + let ctx = mut_ptr_as_ref(ctx); + ValueRef::str(&s.format("%Y-%m-%d %H:%M:%S").to_string()).into_raw(ctx) +} + +/// Validates whether the provided date string matches the specified format. +/// `validate(str, str) -> bool` +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_datetime_validate( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + if let Some(date) = get_call_arg_str(args, kwargs, 0, Some("date")) { + if let Some(format) = get_call_arg_str(args, kwargs, 1, Some("format")) { + let result = validate_date(&date, &format); + return ValueRef::bool(result).into_raw(ctx); + } + panic!("validate() takes 2 positional arguments (1 given)"); + } + panic!("validate() takes 2 positional arguments (0 given)"); +} + +/// Validates whether the provided date string matches the specified format. +/// +/// # Parameters +/// - `date`: A string slice representing the date to be validated. +/// - `format`: A string slice representing the expected format for the date. +/// +/// # Returns +/// - Returns `true` if the date string successfully parses according to the specified format, +/// otherwise, returns `false`. +#[inline] +fn validate_date(date: &str, format: &str) -> bool { + NaiveDateTime::parse_from_str(date, format) + .map(|_| true) + .or_else(|_| NaiveDate::parse_from_str(date, format).map(|_| true)) + .or_else(|_| NaiveTime::parse_from_str(date, format).map(|_| true)) + .is_ok() +} diff --git a/crates/runtime/src/encoding/mod.rs b/crates/runtime/src/encoding/mod.rs new file mode 100644 index 000000000..346201e92 --- /dev/null +++ b/crates/runtime/src/encoding/mod.rs @@ -0,0 +1,44 @@ +use anyhow::{Result, bail}; +use encoding_rs::Encoding; + +/// Encoding string value to bytes with specific encoding format. +pub fn encode_text(value: &str, encoding: Option) -> Result> { + if let Some(encoding_name) = encoding { + let encoding_name = normalize_encoding_name(&encoding_name)?; + + // Look up the encoding by label + if let Some(encoding) = Encoding::for_label(encoding_name.as_bytes()) { + // Encode the string + let (cow, _, had_errors) = encoding.encode(value); + + if had_errors { + bail!( + "encoding errors occurred while encoding to {}", + encoding_name + ); + } + + Ok(cow.into_owned()) + } else { + bail!("unknown encoding {}", encoding_name) + } + } else { + Ok(value.as_bytes().to_vec()) + } +} + +fn normalize_encoding_name(encoding: &str) -> Result { + if let Some(i) = encoding.find(|c: char| c == ' ' || c.is_ascii_uppercase()) { + let mut out = encoding.as_bytes().to_owned(); + for byte in &mut out[i..] { + if *byte == b' ' { + *byte = b'-'; + } else { + byte.make_ascii_lowercase(); + } + } + String::from_utf8(out).map_err(|e| anyhow::anyhow!(e)) + } else { + Ok(encoding.into()) + } +} diff --git a/crates/runtime/src/eval/mod.rs b/crates/runtime/src/eval/mod.rs new file mode 100644 index 000000000..2e0895524 --- /dev/null +++ b/crates/runtime/src/eval/mod.rs @@ -0,0 +1,122 @@ +use std::{ + mem::transmute_copy, + panic::{RefUnwindSafe, UnwindSafe}, +}; + +use crate::{Context, ValueRef, kcl_context_t, kcl_eval_scope_t, kcl_value_ref_t, mut_ptr_as_ref}; +use kcl_primitives::IndexMap; + +/// Variable setter function type. fn(ctx: &mut Context, scope: &mut ScopeEval, args: ValueRef, kwargs: ValueRef) -> ValueRef. +pub type SetterFuncType = unsafe extern "C-unwind" fn( + *mut kcl_context_t, + *mut kcl_eval_scope_t, +) -> *const kcl_value_ref_t; + +/// LazyEvalScope represents a scope of sequentially independent calculations, where +/// the calculation of values is lazy and only recursively performed through +/// backtracking when needed. +#[derive(PartialEq, Clone, Default, Debug)] +pub struct LazyEvalScope { + /// Temp variable values. + pub vars: IndexMap, + /// Variable value cache. + pub cache: IndexMap, + /// Backtrack levels. + pub levels: IndexMap, + /// Variable setter function pointers. + pub setters: IndexMap>, + /// Calculate times without backtracking. + pub cal_times: IndexMap, +} + +impl LazyEvalScope { + #[inline] + pub fn is_backtracking(&self, key: &str) -> bool { + let level = self.levels.get(key).unwrap_or(&0); + *level > 0 + } + + #[inline] + pub fn setter_len(&self, key: &str) -> usize { + self.setters.get(key).unwrap_or(&vec![]).len() + } + + #[inline] + pub fn cal_increment(&mut self, key: &str) -> bool { + if self.is_backtracking(key) { + false + } else { + let cal_time = *self.cal_times.get(key).unwrap_or(&0); + let next_cal_time = cal_time + 1; + self.cal_times.insert(key.to_string(), next_cal_time); + next_cal_time >= self.setter_len(key) + } + } + + #[inline] + pub fn contains_key(&self, key: &str) -> bool { + self.vars.contains_key(key) + } + + /// Get the value from the context. + pub fn get_value(&mut self, ctx: &mut Context, key: &str, target: &str) -> ValueRef { + let value = match self.vars.get(key) { + Some(value) => value.clone(), + None => ValueRef::undefined(), + }; + // Deal in-place modify and return it self immediately. + if key == target && (!self.is_backtracking(key) || self.setter_len(key) <= 1) { + value + } else { + match self.cache.get(key) { + Some(value) => value.clone(), + None => { + match &self.setters.get(key) { + Some(setters) if !setters.is_empty() => { + // Call all setters function to calculate the value recursively. + let level = *self.levels.get(key).unwrap_or(&0); + let next_level = level + 1; + self.levels.insert(key.to_string(), next_level); + let n = setters.len(); + let index = n - next_level; + if index >= n { + value + } else { + let fn_ptr = setters[index]; + unsafe { + let ctx_ref = mut_ptr_as_ref(ctx); + let panic_info = ctx_ref.panic_info.clone(); + let setter_fn: SetterFuncType = transmute_copy(&fn_ptr); + // Restore the panic info of current schema attribute. + ctx_ref.panic_info = panic_info; + // Call setter functions + setter_fn(ctx, self) + }; + self.levels.insert(key.to_string(), level); + let value = match self.vars.get(key) { + Some(value) => value.clone(), + None => ValueRef::undefined(), + }; + self.cache.insert(key.to_string(), value.clone()); + value + } + } + _ => value, + } + } + } + } + } + + /// Set value to the context. + #[inline] + pub fn set_value(&mut self, key: &str, value: &ValueRef) { + self.vars.insert(key.to_string(), value.clone()); + if self.cal_increment(key) && self.cache.get(key).is_none() { + self.cache.insert(key.to_string(), value.clone()); + } + } +} + +impl UnwindSafe for LazyEvalScope {} +impl RefUnwindSafe for LazyEvalScope {} diff --git a/crates/runtime/src/file/mod.rs b/crates/runtime/src/file/mod.rs new file mode 100644 index 000000000..773dc312e --- /dev/null +++ b/crates/runtime/src/file/mod.rs @@ -0,0 +1,369 @@ +mod utils; + +use std::{fs, io::ErrorKind}; + +use crate::*; +use glob::glob; +use std::io::Write; +use std::path::Path; + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_read( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(x) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { + let contents = fs::read_to_string(&x) + .unwrap_or_else(|e| panic!("failed to access the file '{}': {}", x, e)); + + let s = ValueRef::str(contents.as_ref()); + return s.into_raw(ctx); + } + + panic!("read() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_glob( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + let pattern = get_call_arg_str(args, kwargs, 0, Some("pattern")) + .expect("glob() takes exactly one argument (0 given)"); + + let mut matched_paths = vec![]; + for entry in glob(&pattern).unwrap_or_else(|e| panic!("Failed to read glob pattern: {}", e)) { + match entry { + Ok(path) => matched_paths.push(path.display().to_string()), + Err(e) => panic!("failed to access the file matching '{}': {}", pattern, e), + } + } + + ValueRef::list_str(matched_paths.as_slice()).into_raw(ctx) +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_modpath( + ctx: *mut kcl_context_t, + _args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let s = ValueRef::str(ctx.module_path.as_ref()); + s.into_raw(ctx) +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_workdir( + ctx: *mut kcl_context_t, + _args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let s = ValueRef::str(ctx.workdir.as_ref()); + s.into_raw(ctx) +} + +/// Read the path of the current script or module that is being executed +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_current( + ctx: *mut kcl_context_t, + _args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let s = ValueRef::str(ctx.panic_info.kcl_file.as_ref()); + s.into_raw(ctx) +} + +/// Whether this file path exists. Returns true if the path points at +/// an existing entity. This function will traverse symbolic links to +/// query information about the destination file. +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_exists( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(path) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { + let exist = Path::new(&path).exists(); + return ValueRef::bool(exist).into_raw(ctx); + } + + panic!("read() takes exactly one argument (0 given)"); +} + +/// Returns the canonical, absolute form of the path with all intermediate +/// components normalized and symbolic links resolved. +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_abs( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(path) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { + if let Ok(abs_path) = Path::new(&path).canonicalize() { + return ValueRef::str(abs_path.to_str().unwrap()).into_raw(ctx); + } else { + panic!("Could not get the absolute path of {path}"); + } + } + + panic!("read() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_mkdir( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(path) = get_call_arg_str(args, kwargs, 0, Some("directory")) { + let exists = get_call_arg_bool(args, kwargs, 1, Some("exists")).unwrap_or_default(); + if let Err(e) = fs::create_dir_all(&path) { + // Ignore the file exists error. + if exists && matches!(e.kind(), ErrorKind::AlreadyExists) { + return ValueRef::none().into_raw(ctx); + } + panic!("Failed to create directory '{}': {}", path, e); + } + return ValueRef::none().into_raw(ctx); + } + + panic!("mkdir() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_delete( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(path) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { + if let Err(e) = fs::remove_file(&path) { + match e.kind() { + std::io::ErrorKind::NotFound => { + // if file not found, try to remove it as a directory + if let Err(e) = fs::remove_dir(&path) { + panic!("failed to delete '{}': {}", path, e); + } + } + _ => { + panic!("failed to delete '{}': {}", path, e); + } + } + } + return ValueRef::none().into_raw(ctx); + } + + panic!("delete() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_cp( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(src_path) = get_call_arg_str(args, kwargs, 0, Some("src")) { + if let Some(dest_path) = get_call_arg_str(args, kwargs, 1, Some("dest")) { + let src_path = Path::new(&src_path); + let dest_path = Path::new(&dest_path); + let result = if src_path.is_dir() { + utils::copy_directory(&src_path, &dest_path) + } else { + fs::copy(&src_path, &dest_path).map(|_| ()) + }; + if let Err(e) = result { + panic!( + "Failed to copy from '{}' to '{}': {}", + src_path.display(), + dest_path.display(), + e + ); + } + return ValueRef::none().into_raw(ctx); + } else { + panic!("cp() missing 'dest_path' argument"); + } + } else { + panic!("cp() missing 'src_path' argument"); + } +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_mv( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(src_path) = get_call_arg_str(args, kwargs, 0, Some("src")) { + if let Some(dest_path) = get_call_arg_str(args, kwargs, 1, Some("dest")) { + if let Err(e) = fs::rename(&src_path, &dest_path) { + panic!("Failed to move '{}' to '{}': {}", src_path, dest_path, e); + } + return ValueRef::none().into_raw(ctx); + } else { + panic!("mv() missing 'dest_path' argument"); + } + } else { + panic!("mv() missing 'src_path' argument"); + } +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_size( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(path) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { + let metadata = fs::metadata(&path); + match metadata { + Ok(metadata) => { + let size = metadata.len(); + let value = kcl::ValueRef::int(size as i64); + return value.into_raw(ctx); + } + Err(e) => { + panic!("failed to get size of '{}': {}", path, e); + } + } + } + + panic!("size() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_write( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(path) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { + if let Some(content) = get_call_arg_str(args, kwargs, 1, Some("content")) { + match fs::File::create(&path) { + Ok(mut file) => { + if let Err(e) = file.write_all(content.as_bytes()) { + panic!("Failed to write to '{}': {}", path, e); + } + return ValueRef::none().into_raw(ctx); + } + Err(e) => panic!("Failed to create file '{}': {}", path, e), + } + } else { + panic!("write() missing 'content' argument"); + } + } else { + panic!("write() missing 'filepath' argument"); + } +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_append( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(path) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { + if let Some(content) = get_call_arg_str(args, kwargs, 1, Some("content")) { + // Open the file in append mode, creating it if it doesn't exist + match fs::OpenOptions::new().append(true).create(true).open(&path) { + Ok(mut file) => { + if let Err(e) = file.write_all(content.as_bytes()) { + panic!("Failed to append to file '{}': {}", path, e); + } + return ValueRef::none().into_raw(ctx); + } + Err(e) => { + panic!("Failed to open or create file '{}': {}", path, e); + } + } + } else { + panic!("append() requires 'content' argument"); + } + } else { + panic!("append() requires 'filepath' argument"); + } +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_file_read_env( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(key) = get_call_arg_str(args, kwargs, 0, Some("key")) { + match std::env::var(key) { + Ok(v) => ValueRef::str(&v).into_raw(ctx), + Err(_) => ValueRef::undefined().into_raw(ctx), + } + } else { + panic!("read_env() requires 'key' argument"); + } +} diff --git a/kclvm/runtime/src/file/utils.rs b/crates/runtime/src/file/utils.rs similarity index 100% rename from kclvm/runtime/src/file/utils.rs rename to crates/runtime/src/file/utils.rs diff --git a/crates/runtime/src/json/mod.rs b/crates/runtime/src/json/mod.rs new file mode 100644 index 000000000..7d7555e49 --- /dev/null +++ b/crates/runtime/src/json/mod.rs @@ -0,0 +1,109 @@ +//! Copyright The KCL Authors. All rights reserved. + +use crate::*; + +// data, sort_keys=False, indent=None, ignore_private=False, ignore_none=False + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_json_encode( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let ctx = mut_ptr_as_ref(ctx); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("data")) { + let s = ValueRef::str( + arg0.to_json_string_with_options(&args_to_opts(args, kwargs, 1)) + .as_ref(), + ); + return s.into_raw(ctx); + } + panic!("encode() missing 1 required positional argument: 'value'") +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_json_decode( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("value")) { + match ValueRef::from_json(ctx, arg0.as_str().as_ref()) { + Ok(x) => return x.into_raw(ctx), + Err(err) => panic!("{}", err), + } + } + panic!("decode() missing 1 required positional argument: 'value'") +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_json_validate( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("value")) { + match ValueRef::from_json(ctx, arg0.as_str().as_ref()) { + Ok(_) => return kcl_value_True(ctx), + Err(_) => return kcl_value_False(ctx), + } + } + panic!("validate() missing 1 required positional argument: 'value'") +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_json_dump_to_file( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let data = args.arg_i(0).or(kwargs.get_by_key("data")); + let filename = args.arg_i(1).or(kwargs.get_by_key("filename")); + match (data, filename) { + (Some(data), Some(filename)) => { + let filename = filename.as_str(); + let json = data.to_json_string_with_options(&args_to_opts(args, kwargs, 2)); + std::fs::write(&filename, json) + .unwrap_or_else(|e| panic!("Unable to write file '{}': {}", filename, e)); + kcl_value_Undefined(ctx) + } + _ => { + panic!("dump_to_file() missing 2 required positional arguments: 'data' and 'filename'") + } + } +} + +fn args_to_opts(args: &ValueRef, kwargs: &ValueRef, index: usize) -> JsonEncodeOptions { + let mut opts = JsonEncodeOptions::default(); + if let Some(sort_keys) = get_call_arg_bool(args, kwargs, index, Some("sort_keys")) { + opts.sort_keys = sort_keys; + } + if let Some(indent) = get_call_arg_int(args, kwargs, index + 1, Some("indent")) { + opts.indent = indent; + } + if let Some(ignore_private) = get_call_arg_bool(args, kwargs, index + 2, Some("ignore_private")) + { + opts.ignore_private = ignore_private; + } + if let Some(ignore_none) = get_call_arg_bool(args, kwargs, index + 3, Some("ignore_none")) { + opts.ignore_none = ignore_none; + } + opts +} diff --git a/crates/runtime/src/lib.rs b/crates/runtime/src/lib.rs new file mode 100644 index 000000000..7f72a1bc2 --- /dev/null +++ b/crates/runtime/src/lib.rs @@ -0,0 +1,132 @@ +//! Copyright The KCL Authors. All rights reserved. + +// api-spec: kcl_context_t +// api-spec(c): typedef struct kcl_context_t kcl_context_t; +// api-spec(llvm): %"kcl_context_t" = type { i8* } + +// api-spec: kcl_eval_scope_t +// api-spec(c): typedef struct kcl_eval_scope_t kcl_eval_scope_t; +// api-spec(llvm): %"kcl_eval_scope_t" = type { i8* } + +// api-spec: kcl_type_t +// api-spec(c): typedef struct kcl_type_t kcl_type_t; +// api-spec(llvm): %"kcl_type_t" = type { i8* } + +// api-spec: kcl_value_t +// api-spec(c): typedef struct kcl_value_t kcl_value_t; +// api-spec(llvm): %"kcl_value_t" = type { i8* } + +// api-spec: kcl_value_ref_t +// api-spec(c): typedef struct kcl_value_ref_t kcl_value_ref_t; +// api-spec(llvm): %"kcl_value_ref_t" = type { i8* } + +// api-spec: kcl_iterator_t +// api-spec(c): typedef struct kcl_iterator_t kcl_iterator_t; +// api-spec(llvm): %"kcl_iterator_t" = type { i8* } + +// api-spec: kcl_buffer_t +// api-spec(c): typedef struct kcl_buffer_t kcl_buffer_t; +// api-spec(llvm): %"kcl_buffer_t" = type { i8* } + +// api-spec: kcl_kind_t +// api-spec(c): typedef enum kcl_kind_t kcl_kind_t; +// api-spec(llvm): %"kcl_kind_t" = type i32 + +// api-spec: kcl_size_t +// api-spec(c): typedef int32_t kcl_size_t; +// api-spec(llvm): %"kcl_size_t" = type i32 + +// api-spec: kcl_char_t +// api-spec(c): typedef char kcl_char_t; +// api-spec(llvm): %"kcl_char_t" = type i8 + +// api-spec: kcl_bool_t +// api-spec(c): typedef int8_t kcl_bool_t; +// api-spec(llvm): %"kcl_bool_t" = type i8 + +// api-spec: kcl_int_t +// api-spec(c): typedef int64_t kcl_int_t; +// api-spec(llvm): %"kcl_int_t" = type i64 + +// api-spec: kcl_float_t +// api-spec(c): typedef double kcl_float_t; +// api-spec(llvm): %"kcl_float_t" = type double + +// api-spec: kcl_decorator_value_t +// api-spec(c): typedef struct kcl_decorator_value_t kcl_decorator_value_t; +// api-spec(llvm): %"kcl_decorator_value_t" = type opaque + +pub mod api; +pub use self::api::*; + +pub mod context; +pub use self::context::*; + +pub mod types; +pub use self::types::*; + +pub mod unification; + +pub mod value; +pub use self::value::*; + +pub mod base32; +pub use self::base32::*; + +pub mod base64; +pub use self::base64::*; + +pub mod collection; +pub use self::collection::*; + +pub mod crypto; +pub use self::crypto::*; + +mod eval; + +pub mod datetime; +pub use self::datetime::*; + +pub mod encoding; + +pub mod json; +pub use self::json::*; + +pub mod manifests; +pub use self::manifests::*; + +pub mod math; +pub use self::math::*; + +pub mod net; +pub use self::net::*; + +pub mod regex; +pub use self::regex::*; + +pub mod stdlib; +pub use self::stdlib::*; + +pub mod units; +pub use self::units::*; + +pub mod yaml; +pub use self::yaml::*; + +pub mod file; +pub use self::file::*; + +pub mod template; +pub use self::template::*; + +pub mod panic; +pub use self::panic::*; + +pub mod _kcl_run; +pub use self::_kcl_run::*; + +pub mod _kcl; +pub use self::_kcl::*; + +pub mod _kcl_addr; +pub use self::_kcl_addr::*; diff --git a/crates/runtime/src/manifests/mod.rs b/crates/runtime/src/manifests/mod.rs new file mode 100644 index 000000000..33896ea31 --- /dev/null +++ b/crates/runtime/src/manifests/mod.rs @@ -0,0 +1,102 @@ +//! KCL manifests system module +//! +//! Copyright The KCL Authors. All rights reserved. + +use crate::*; + +#[cfg(test)] +mod tests; +mod yaml; + +#[allow(non_camel_case_types)] +type kcl_value_ref_t = ValueRef; + +/// The function is to serialize a list of KCL objects to YAML and output using the style with +/// the `---\n` separator, and put it to the custom manifest output in the context. +/// +/// ManifestsYamlStreamOptions contain these options +/// - sort_keys: Sort the encode result by keys (defaults to false). +/// - ignore_private: Whether to ignore the attribute whose name starts with +/// a character `_` (defaults to false). +/// - ignore_none: Whether to ignore the attribute whose value is `None` (defaults to false). +/// - sep: Which separator to use between YAML documents (defaults to "---"). +/// More information: https://github.com/kcl-lang/kcl/issues/94 +/// +/// - Function signature. +/// +/// ```kcl, no run +/// schema ManifestsYamlStreamOptions: +/// sort_keys: bool = False +/// ignore_private: bool = True +/// ignore_none: bool = False +/// separator: str = "---\n" +/// +/// manifests.yaml_stream(values: [any], * , opts: ManifestsYamlStreamOptions = ManifestsYamlStreamOptions {}) +/// ``` +/// +/// - Usage +/// +/// ```kcl, no run +/// import manifests +/// +/// config1 = {k1 = "v1"} +/// config2 = {k2 = "v2"} +/// +/// manifests.yaml_stream([config1, config2]) +/// manifests.yaml_stream([config1, config2], opts = { +/// sort_keys = True +/// ignore_none = True +/// }) +/// ``` +/// TODO: more options on the function `yaml_stream`. +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_manifests_yaml_stream( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + // Get the YAML encode options from the second keyword argument `opts`. + let opts = match kwargs.kwarg("opts").or_else(|| args.arg_i(1)) { + Some(opts) => { + if opts.is_config() { + // Get options or default. + YamlEncodeOptions { + sort_keys: opts + .get_by_key("sort_keys") + .unwrap_or_else(|| ValueRef::bool(false)) + .as_bool(), + ignore_private: opts + .get_by_key("ignore_private") + .unwrap_or_else(|| ValueRef::bool(true)) + .as_bool(), + ignore_none: opts + .get_by_key("ignore_none") + .unwrap_or_else(|| ValueRef::bool(false)) + .as_bool(), + sep: opts + .get_by_key("sep") + .unwrap_or_else(|| ValueRef::str("---")) + .as_str(), + } + } else { + panic!( + "Invalid options arguments in yaml_stream(): expect config, got {}", + opts.type_str() + ) + } + } + None => YamlEncodeOptions::default(), + }; + + if let Some(value) = get_call_arg(args, kwargs, 0, Some("values")) { + self::yaml::encode_yaml_stream_to_manifests(ctx, &value, opts); + } else { + panic!("yaml_stream() missing 1 required positional argument: 'values'"); + } + ValueRef::undefined().into_raw(ctx) +} diff --git a/crates/runtime/src/manifests/tests.rs b/crates/runtime/src/manifests/tests.rs new file mode 100644 index 000000000..7670b6703 --- /dev/null +++ b/crates/runtime/src/manifests/tests.rs @@ -0,0 +1,121 @@ +use crate::*; + +#[test] +fn test_kcl_manifests_yaml_stream() { + let cases = [ + ( + "a: 1\n", + ValueRef::list(Some(&[&ValueRef::dict(Some(&[("a", &ValueRef::int(1))]))])), + YamlEncodeOptions::default(), + ), + ( + "a: 1\nb: 2\n", + ValueRef::list(Some(&[&ValueRef::dict(Some(&[ + ("a", &ValueRef::int(1)), + ("b", &ValueRef::int(2)), + ]))])), + YamlEncodeOptions::default(), + ), + ( + "a:\n- 1\n- 2\n- 3\nb: s\n", + ValueRef::list(Some(&[&ValueRef::dict(Some(&[ + ("a", &ValueRef::list_int(&[1, 2, 3])), + ("b", &ValueRef::str("s")), + ]))])), + YamlEncodeOptions::default(), + ), + ( + "a: 1\n", + ValueRef::list(Some(&[&ValueRef::dict(Some(&[ + ("a", &ValueRef::int(1)), + ("_b", &ValueRef::none()), + ]))])), + YamlEncodeOptions { + ignore_private: true, + ..Default::default() + }, + ), + ( + "a: 1\nb: null\n", + ValueRef::list(Some(&[&ValueRef::dict(Some(&[ + ("a", &ValueRef::int(1)), + ("b", &ValueRef::none()), + ]))])), + YamlEncodeOptions::default(), + ), + ( + "a: 1\n", + ValueRef::list(Some(&[&ValueRef::dict(Some(&[ + ("a", &ValueRef::int(1)), + ("_b", &ValueRef::int(2)), + ("c", &ValueRef::none()), + ("d", &ValueRef::undefined()), + ]))])), + YamlEncodeOptions { + ignore_private: true, + ignore_none: true, + ..Default::default() + }, + ), + ]; + for (yaml_str, value, opts) in cases { + let mut ctx = Context::default(); + let opts = ValueRef::dict(Some(&[ + ("sort_keys", &ValueRef::bool(opts.sort_keys)), + ("ignore_private", &ValueRef::bool(opts.ignore_private)), + ("ignore_none", &ValueRef::bool(opts.ignore_none)), + ("sep", &ValueRef::str(&opts.sep)), + ])); + let mut args = ValueRef::list(None); + args.list_append(&value); + let mut kwargs = ValueRef::dict(None); + kwargs.dict_insert( + &mut ctx, + "opts", + &opts, + ConfigEntryOperationKind::Override, + None, + ); + kcl_manifests_yaml_stream(&mut ctx, &args, &kwargs); + assert_eq!( + Some(yaml_str.to_string()), + ctx.buffer.custom_manifests_output + ); + } +} + +#[test] +fn test_kcl_manifests_yaml_stream_invalid() { + let prev_hook = std::panic::take_hook(); + // Disable print panic info in stderr. + std::panic::set_hook(Box::new(|_| {})); + assert_panic( + "yaml_stream() missing 1 required positional argument: 'values'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_manifests_yaml_stream(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "Invalid options arguments in yaml_stream(): expect config, got str", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(Some(&[("opts", &ValueRef::str("invalid_kwarg"))])) + .into_raw(&mut ctx); + kcl_manifests_yaml_stream(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "Invalid options arguments in yaml_stream(): expect config, got NoneType", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(Some(&[("opts", &ValueRef::none())])).into_raw(&mut ctx); + kcl_manifests_yaml_stream(ctx.into_raw(), args, kwargs); + }, + ); + std::panic::set_hook(prev_hook); +} diff --git a/kclvm/runtime/src/manifests/yaml.rs b/crates/runtime/src/manifests/yaml.rs similarity index 100% rename from kclvm/runtime/src/manifests/yaml.rs rename to crates/runtime/src/manifests/yaml.rs diff --git a/crates/runtime/src/math/mod.rs b/crates/runtime/src/math/mod.rs new file mode 100644 index 000000000..1e73d34e1 --- /dev/null +++ b/crates/runtime/src/math/mod.rs @@ -0,0 +1,394 @@ +//! Copyright The KCL Authors. All rights reserved. + +extern crate num_integer; + +use crate::*; + +// https://docs.python.org/3/library/math.html +// https://doc.rust-lang.org/std/primitive.f64.html +// https://github.com/RustPython/RustPython/blob/main/stdlib/src/math.rs + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_ceil( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { + return kcl_value_Int(ctx, x); + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + return kcl_value_Int(ctx, x.ceil() as i64); + } + + panic!("ceil() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_factorial( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + fn factorial(num: i64) -> i64 { + if num >= 21 { + // overflow: 21! = 51090942171709440000 + // MaxInt64: 9223372036854775807 + panic!("factorial() result overflow"); + } + match num { + 0 => 1, + 1 => 1, + _ => factorial(num - 1) * num, + } + } + + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { + if x >= 0 { + return kcl_value_Int(ctx, factorial(x)); + } + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + if x >= 0.0 && (x as i64 as f64) == x { + return kcl_value_Float(ctx, factorial(x as i64) as f64); + } + } + + if args.args_len() > 0 { + panic!("factorial() only accepts integral values") + } + panic!("factorial() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_floor( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { + return kcl_value_Int(ctx, x); + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + return kcl_value_Int(ctx, x.floor() as i64); + } + + panic!("floor() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_gcd( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(a) = args.arg_i_int(0, None).or(kwargs.kwarg_int("a", None)) { + if let Some(b) = args.arg_i_int(1, None).or(kwargs.kwarg_int("b", None)) { + return kcl_value_Int(ctx, num_integer::gcd(a, b)); + } + } + + panic!( + "gcd() takes exactly two arguments ({} given)", + args.args_len() + ); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_isfinite( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if args + .arg_i_int(0, None) + .or(kwargs.kwarg_int("x", None)) + .is_some() + { + return kcl_value_Bool(ctx, true as i8); + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + return kcl_value_Bool(ctx, x.is_finite() as i8); + } + + panic!("isfinite() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_isinf( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if args + .arg_i_int(0, None) + .or(kwargs.kwarg_int("x", None)) + .is_some() + { + return kcl_value_Bool(ctx, false as i8); + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + return kcl_value_Bool(ctx, x.is_infinite() as i8); + } + if args.arg_i_bool(0, None).is_some() { + return kcl_value_Bool(ctx, false as i8); + } + + panic!("isinf() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_isnan( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if args + .arg_i_int(0, None) + .or(kwargs.kwarg_int("x", None)) + .is_some() + { + return kcl_value_Bool(ctx, false as i8); + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + return kcl_value_Bool(ctx, x.is_nan() as i8); + } + + panic!("isnan() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_modf( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let ctx = mut_ptr_as_ref(ctx); + let kwargs = ptr_as_ref(kwargs); + + if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { + let list = ValueRef::list_float(&[0.0, x as f64]); + return list.into_raw(ctx); + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + if !x.is_finite() { + if x.is_infinite() { + let list = ValueRef::list_float(&[0.0_f64.copysign(x), x]); + return list.into_raw(ctx); + } else if x.is_nan() { + let list = ValueRef::list_float(&[x, x]); + return list.into_raw(ctx); + } + } + let list = ValueRef::list_float(&[x.fract(), x.trunc()]); + return list.into_raw(ctx); + } + + panic!("modf() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_exp( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { + return kcl_value_Float(ctx, (x as f64).exp()); + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + return kcl_value_Float(ctx, x.exp()); + } + panic!("exp() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_expm1( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { + return kcl_value_Float(ctx, (x as f64).exp_m1()); + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + return kcl_value_Float(ctx, x.exp_m1()); + } + panic!("expm1() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_log( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { + if let Some(base) = args + .arg_i_float(1, Some(std::f64::consts::E)) + .or_else(|| kwargs.kwarg_float("e", Some(std::f64::consts::E))) + { + return kcl_value_Int(ctx, (x as f64).log(base) as i64); + } + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + if let Some(base) = args + .arg_i_float(1, Some(std::f64::consts::E)) + .or_else(|| kwargs.kwarg_float("e", Some(std::f64::consts::E))) + { + return kcl_value_Float(ctx, x.log(base)); + } + } + panic!("log() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_log1p( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { + return kcl_value_Float(ctx, ((x + 1) as f64).ln_1p()); + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + return kcl_value_Float(ctx, (x + 1.0).ln_1p()); + } + panic!("log1p() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_log2( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { + return kcl_value_Int(ctx, (x as f64).log2() as i64); + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + return kcl_value_Float(ctx, x.log2()); + } + panic!("log2() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_log10( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { + return kcl_value_Float(ctx, (x as f64).log10()); + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + return kcl_value_Float(ctx, x.log10()); + } + panic!("log10() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_pow( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { + if let Some(n) = args.arg_i_int(1, None).or(kwargs.kwarg_int("n", None)) { + if n < 0 { + return kcl_value_Float(ctx, (x as f64).powf(n as f64)); + } else { + return kcl_value_Int(ctx, x.pow(n as u32)); + } + } + if let Some(n) = args.arg_i_float(1, None).or(kwargs.kwarg_float("n", None)) { + return kcl_value_Float(ctx, (x as f64).powf(n)); + } + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + if let Some(n) = args.arg_i_int(1, None).or(kwargs.kwarg_int("n", None)) { + return kcl_value_Float(ctx, x.powi(n as i32)); + } + if let Some(n) = args.arg_i_float(1, None).or(kwargs.kwarg_float("n", None)) { + return kcl_value_Float(ctx, x.powf(n)); + } + } + panic!("pow() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_math_sqrt( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { + return kcl_value_Float(ctx, (x as f64).sqrt()); + } + if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { + return kcl_value_Float(ctx, x.sqrt()); + } + panic!("sqrt() takes exactly one argument (0 given)"); +} diff --git a/crates/runtime/src/net/mod.rs b/crates/runtime/src/net/mod.rs new file mode 100644 index 000000000..f1d5788af --- /dev/null +++ b/crates/runtime/src/net/mod.rs @@ -0,0 +1,2680 @@ +//! Copyright The KCL Authors. All rights reserved. + +use crate::*; +use cidr::{IpCidr, Ipv4Cidr, Ipv6Cidr}; +use itertools::Itertools; +use std::net::IpAddr; +use std::net::IpAddr::V4; +use std::net::IpAddr::V6; +use std::net::Ipv4Addr; +use std::net::Ipv6Addr; +use std::str::FromStr; + +// split_host_port(ip_end_point: str) -> List[str] + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_split_host_port( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(ip_end_point) = get_call_arg(args, kwargs, 0, Some("ip_end_point")) { + let ip_end_point_str = ip_end_point.as_str(); + match ip_end_point_str.rsplit_once(':') { + None => panic!( + "ip_end_point \"{}\" missing port", + ip_end_point_str.escape_default() + ), + Some((host, port)) => { + if host.starts_with('[') { + match ip_end_point_str.find(']') { + None => panic!( + "ip_end_point \"{}\" missing ']'", + ip_end_point_str.escape_default() + ), + Some(end) => { + if end > host.len() || !ip_end_point_str[end + 1..].starts_with(':') { + panic!( + "ip_end_point \"{}\" missing port", + ip_end_point_str.escape_default() + ); + } + if end < host.len() - 1 { + panic!( + "ip_end_point \"{}\" too many colons", + ip_end_point_str.escape_default() + ); + } + if ip_end_point_str[1..].contains('[') { + panic!( + "ip_end_point \"{}\" unexpected '['", + ip_end_point_str.escape_default() + ); + } + if port.contains(']') { + panic!( + "ip_end_point \"{}\" unexpected ']'", + ip_end_point_str.escape_default() + ); + } + return ValueRef::list(Some(&[ + &ValueRef::str(&host[1..end]), + &ValueRef::str(port), + ])) + .into_raw(ctx); + } + } + } + if host.contains(':') { + panic!( + "ip_end_point \"{}\" too many colons", + ip_end_point_str.escape_default() + ); + } + if ip_end_point_str[1..].contains('[') { + panic!( + "ip_end_point \"{}\" unexpected '['", + ip_end_point_str.escape_default() + ); + } + if ip_end_point_str.contains(']') { + panic!( + "ip_end_point \"{}\" unexpected ']'", + ip_end_point_str.escape_default() + ); + } + return ValueRef::list(Some(&[&ValueRef::str(host), &ValueRef::str(port)])) + .into_raw(ctx); + } + } + } + + panic!("split_host_port() missing 1 required positional argument: 'ip_end_point'"); +} + +// join_host_port(host, port) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_join_host_port( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(host) = get_call_arg(args, kwargs, 0, Some("host")) { + if let Some(port) = get_call_arg(args, kwargs, 1, Some("port")) { + if host.as_str().contains(':') { + return ValueRef::str(format!("[{host}]:{port}").as_ref()).into_raw(ctx); + } + return ValueRef::str(format!("{host}:{port}").as_ref()).into_raw(ctx); + } + } + panic!("join_host_port() missing 2 required positional arguments: 'host' and 'port'"); +} + +// fqdn(name: str = '') -> str + +#[cfg(not(target_arch = "wasm32"))] +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_fqdn( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + use std::net::ToSocketAddrs; + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let name = get_call_arg_str(args, kwargs, 0, Some("name")).unwrap_or_default(); + let hostname = if name.is_empty() { + match hostname::get() { + Ok(name) => name.to_string_lossy().into_owned(), + Err(_) => return ValueRef::str("").into_raw(ctx), + } + } else { + name + }; + match (hostname.as_str(), 0).to_socket_addrs() { + Ok(mut addrs) => { + if let Some(addr) = addrs.next() { + match dns_lookup::lookup_addr(&addr.ip()) { + Ok(fqdn) => ValueRef::str(&fqdn), + Err(_) => ValueRef::str(&hostname), + } + } else { + ValueRef::str(&hostname) + } + } + Err(_) => ValueRef::str(&hostname), + } + .into_raw(ctx) +} + +#[cfg(target_arch = "wasm32")] +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_fqdn( + _ctx: *mut kcl_context_t, + _args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + panic!("fqdn() do not support the WASM target"); +} + +// parse_IP(ip) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_parse_IP( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + kcl_net_IP_string(ctx, args, kwargs) +} + +// to_IP4(ip) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_to_IP4( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { + match Ipv4Addr::from_str(ip.as_ref()) { + Ok(addr) => { + let s = format!("{addr}"); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + Err(_e) => match Ipv6Addr::from_str(ip.as_ref()) { + Ok(addr) => { + if let Some(v4) = addr.to_ipv4() { + let s = format!("{v4}"); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + let s = format!("can not parse {} ipv6 to ipv4!", ip); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + Err(e) => { + let s = format!("can not both parse {} to ipv6 and ipv4,err:{}", ip, e); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + }, + } + } + panic!("IP_string() missing 1 required positional argument: 'ip'"); +} + +// to_IP6(ip) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_to_IP6( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { + match Ipv6Addr::from_str(ip.as_ref()) { + Ok(addr) => { + let s = format!("{addr}"); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + Err(_) => { + match Ipv4Addr::from_str(ip.as_ref()) { + Ok(addr) => { + // Convert IPv4 to IPv6-mapped address (::ffff:0:0/96) + let v6 = addr.to_ipv6_mapped(); + let s = format!("{v6}"); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + Err(e) => { + let s = format!("can not both parse {} to ipv6 and ipv4,err:{}", ip, e); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + } + } + } + } + panic!("IP_string() missing 1 required positional argument: 'ip'"); +} + +// IP_string(ip: str) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_IP_string( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { + if let Ok(addr) = Ipv4Addr::from_str(ip.as_ref()) { + let s = format!("{addr}"); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { + let s = format!("{addr}"); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + + return ValueRef::str("").into_raw(ctx); + } + + panic!("IP_string() missing 1 required positional argument: 'ip'"); +} + +// is_IPv4(ip: str) -> bool + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_is_IPv4( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { + if let Ok(_addr) = Ipv4Addr::from_str(ip.as_ref()) { + return kcl_value_True(ctx); + } + if let Ok(_addr) = Ipv6Addr::from_str(ip.as_ref()) { + return kcl_value_False(ctx); + } + + return kcl_value_False(ctx); + } + + panic!("is_IPv4() missing 1 required positional argument: 'ip'"); +} + +// is_IP(ip: str) -> bool + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_is_IP( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { + if Ipv4Addr::from_str(ip.as_ref()).is_ok() || Ipv6Addr::from_str(ip.as_ref()).is_ok() { + kcl_value_True(ctx) + } else { + kcl_value_False(ctx) + } + } else { + panic!("is_IP() missing 1 required positional argument: 'ip'"); + } +} + +// is_loopback_IP(ip: str) -> bool + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_is_loopback_IP( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { + if let Ok(addr) = Ipv4Addr::from_str(ip.as_ref()) { + let x = addr.is_loopback(); + return kcl_value_Bool(ctx, x as i8); + } + if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { + let x = addr.is_loopback(); + return kcl_value_Bool(ctx, x as i8); + } + + return kcl_value_False(ctx); + } + + panic!("is_loopback_IP() missing 1 required positional argument: 'ip'"); +} + +// is_multicast_IP(ip: str) -> bool + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_is_multicast_IP( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { + if let Ok(addr) = Ipv4Addr::from_str(ip.as_ref()) { + let x = addr.is_multicast(); + return kcl_value_Bool(ctx, x as i8); + } + if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { + let x = addr.is_multicast(); + return kcl_value_Bool(ctx, x as i8); + } + + return kcl_value_False(ctx); + } + + panic!("kcl_net_is_multicast_IP() missing 1 required positional argument: 'ip'"); +} + +// is_interface_local_multicast_IP(ip: str) -> bool + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_is_interface_local_multicast_IP( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { + if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { + // For IPv6, interface-local multicast addresses start with ffx1::/16 + let is_interface_local = (addr.segments()[0] & 0xff0f) == 0xff01; + let x = is_interface_local && addr.is_multicast(); + return kcl_value_Bool(ctx, x as i8); + } + return kcl_value_Bool(ctx, 0); // False for IPv4 and invalid IP addresses + } + panic!("is_interface_local_multicast_IP() missing 1 required positional argument: 'ip'"); +} + +// is_link_local_multicast_IP(ip: str) -> bool + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_is_link_local_multicast_IP( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { + if let Ok(addr) = Ipv4Addr::from_str(ip.as_ref()) { + // For IPv4, link-local multicast addresses are in the range 224.0.0.0/24 + let is_link_local_multicast = + addr.octets()[0] == 224 && addr.octets()[1] == 0 && addr.octets()[2] == 0; + let x = is_link_local_multicast && addr.is_multicast(); + return kcl_value_Bool(ctx, x as i8); + } + if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { + // For IPv6, link-local multicast addresses start with ffx2::/16 + let is_link_local_multicast = (addr.segments()[0] & 0xff0f) == 0xff02; + let x = is_link_local_multicast && addr.is_multicast(); + return kcl_value_Bool(ctx, x as i8); + } + return kcl_value_Bool(ctx, 0); // False for invalid IP addresses + } + + panic!("is_link_local_multicast_IP() missing 1 required positional argument: 'ip'"); +} + +// is_link_local_unicast_IP(ip: str) -> bool + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_is_link_local_unicast_IP( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { + if let Ok(addr) = Ipv4Addr::from_str(ip.as_ref()) { + let x = addr.is_link_local() && (!addr.is_multicast()); + return kcl_value_Bool(ctx, x as i8); + } + if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { + let x = Ipv6Addr_is_unicast_link_local(&addr) && (!addr.is_multicast()); + return kcl_value_Bool(ctx, x as i8); + } + return kcl_value_False(ctx); + } + + panic!("is_link_local_unicast_IP() missing 1 required positional argument: 'ip'"); +} + +#[allow(non_camel_case_types, non_snake_case)] +fn Ipv6Addr_is_global(_self: &std::net::Ipv6Addr) -> bool { + let segments = _self.segments(); + // 2000::/3 global unicast + if (segments[0] & 0xe000) == 0x2000 { + // 2001:db8::/32 documentation + if segments[0] == 0x2001 && segments[1] == 0xdb8 { + return false; + } + // 2001:2::/48 benchmarking + if segments[0] == 0x2001 && segments[1] == 2 && segments[2] == 0 { + return false; + } + return true; + } + // 64:ff9b::/96 NAT64 + if segments[0] == 0x64 + && segments[1] == 0xff9b + && segments[2] == 0 + && segments[3] == 0 + && segments[4] == 0 + && segments[5] == 0 + { + let ipv4 = Ipv4Addr::from(((segments[6] as u32) << 16) + segments[7] as u32); + return Ipv4Addr_is_global(&ipv4) && (!ipv4.is_multicast()); + } + return false; +} + +#[allow(non_camel_case_types, non_snake_case)] +pub const fn Ipv6Addr_is_unicast_link_local(_self: &Ipv6Addr) -> bool { + (_self.segments()[0] & 0xffc0) == 0xfe80 +} + +// is_global_unicast_IP(ip: str) -> bool + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_is_global_unicast_IP( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { + if let Ok(addr) = Ipv4Addr::from_str(ip.as_ref()) { + let x = Ipv4Addr_is_global(&addr) && (!addr.is_multicast()); + return kcl_value_Bool(ctx, x as i8); + } + if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { + return kcl_value_Bool(ctx, Ipv6Addr_is_global(&addr) as i8); + } + + return kcl_value_False(ctx); + } + + panic!("is_global_unicast_IP() missing 1 required positional argument: 'ip'"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_parse_CIDR( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(cidr) = get_call_arg(args, kwargs, 0, Some("cidr")) { + if let Ok(cidr) = IpCidr::from_str(&cidr.as_str()) { + let ip = ValueRef::str(&cidr.first_address().to_string()); + let mask = ValueRef::int(cidr.network_length().into()); + return ValueRef::dict(Some(&[("ip", &ip), ("mask", &mask)])).into_raw(ctx); + } + return ValueRef::dict(None).into_raw(ctx); + } + + panic!("parse_CIDR() missing 1 required positional argument: 'cidr'"); +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_is_IP_in_CIDR( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + let ip = match get_call_arg_str(args, kwargs, 0, Some("ip")) { + None => { + panic!("is_IP_in_CIDR() missing 2 required positional arguments: 'ip' and 'cidr'"); + } + Some(ip) => match IpAddr::from_str(ip.as_str()) { + Err(err) => panic!("is_IP_in_CIDR() invalid ip: {}", err), + Ok(ip) => ip, + }, + }; + let cidr = match get_call_arg_str(args, kwargs, 1, Some("cidr")) { + None => { + panic!("is_IP_in_CIDR() missing 2 required positional arguments: 'ip' and 'cidr'"); + } + Some(cidr) => match IpCidr::from_str(&cidr.as_str()) { + Err(err) => panic!("is_IP_in_CIDR() invalid cidr: {}", err), + Ok(cidr) => cidr, + }, + }; + + if cidr.is_ipv6() { + match ip { + IpAddr::V4(ip) => { + return kcl_value_Bool(ctx, cidr.contains(&IpAddr::V6(ip.to_ipv6_mapped())) as i8); + } + IpAddr::V6(_ip) => {} + } + } + return kcl_value_Bool(ctx, cidr.contains(&ip) as i8); +} + +#[allow(non_camel_case_types, non_snake_case)] +fn Ipv4Addr_is_global(_self: &std::net::Ipv4Addr) -> bool { + // check if this address is 192.0.0.9 or 192.0.0.10. These addresses are the only two + // globally routable addresses in the 192.0.0.0/24 range. + if u32::from_be_bytes(_self.octets()) == 0xc0000009 + || u32::from_be_bytes(_self.octets()) == 0xc000000a + { + return true; + } + !_self.is_private() + && !_self.is_loopback() + && !_self.is_link_local() + && !_self.is_broadcast() + && !_self.is_documentation() + && !Ipv4Addr_is_shared(_self) // _self.is_shared() + && !Ipv4Addr_is_ietf_protocol_assignment(_self) // _self.is_ietf_protocol_assignment() + && !Ipv4Addr_is_reserved(_self) // _self.is_reserved() + && !Ipv4Addr_is_benchmarking(_self) // _self.is_benchmarking() + // Make sure the address is not in 0.0.0.0/8 + && _self.octets()[0] != 0 +} + +#[allow(non_camel_case_types, non_snake_case)] +const fn Ipv4Addr_is_shared(_self: &std::net::Ipv4Addr) -> bool { + _self.octets()[0] == 100 && (_self.octets()[1] & 0b1100_0000 == 0b0100_0000) +} +#[allow(non_camel_case_types, non_snake_case)] +const fn Ipv4Addr_is_ietf_protocol_assignment(_self: &std::net::Ipv4Addr) -> bool { + _self.octets()[0] == 192 && _self.octets()[1] == 0 && _self.octets()[2] == 0 +} +#[allow(non_camel_case_types, non_snake_case)] +const fn Ipv4Addr_is_reserved(_self: &std::net::Ipv4Addr) -> bool { + _self.octets()[0] & 240 == 240 && !_self.is_broadcast() +} +#[allow(non_camel_case_types, non_snake_case)] +const fn Ipv4Addr_is_benchmarking(_self: &std::net::Ipv4Addr) -> bool { + _self.octets()[0] == 198 && (_self.octets()[1] & 0xfe) == 18 +} + +// is_unspecified_IP(ip: str) -> bool + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_is_unspecified_IP( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { + if let Ok(addr) = Ipv4Addr::from_str(ip.as_ref()) { + return kcl_value_Bool(ctx, addr.is_unspecified() as i8); + } + if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { + return kcl_value_Bool(ctx, addr.is_unspecified() as i8); + } + return kcl_value_False(ctx); + } + panic!("is_unspecified_IP() missing 1 required positional argument: 'ip'"); +} + +// CIDR_subnet(cidr: str, additional_bits: int, net_num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_CIDR_subnet( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + let cidr = match get_call_arg(args, kwargs, 0, Some("cidr")) { + None => { + panic!( + "CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'" + ); + } + Some(cidr) => match IpCidr::from_str(&cidr.as_str()) { + Err(err) => { + panic!("CIDR_subnet() invalid cidr: {}", err) + } + Ok(cidr) => cidr, + }, + }; + + let additional_bits = match get_call_arg(args, kwargs, 1, Some("additional_bits")) { + None => { + panic!( + "CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'" + ); + } + Some(additional_bits) => additional_bits.must_as_strict_int(), + }; + if additional_bits < 0 { + panic!("CIDR_subnet() invalid additional_bits: cannot be negative"); + } + + let net_num = match get_call_arg(args, kwargs, 2, Some("net_num")) { + None => { + panic!( + "CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'" + ); + } + Some(net_num) => net_num.must_as_strict_int(), + }; + if net_num < 0 { + panic!("CIDR_subnet() invalid net_num: cannot be negative"); + } + + match CIDR_allocate(cidr, additional_bits, net_num) { + Ok(value) => return value.into_raw(ctx), + Err(message) => panic!("CIDR_subnet() {}", message), + }; +} + +#[allow(non_camel_case_types, non_snake_case)] +fn CIDR_allocate(cidr: IpCidr, additional_bits: i64, net_num: i64) -> Result { + let len = cidr.network_length() as i64 + additional_bits; + let new_cidr = match cidr.first_address() { + V4(ipv4) => { + if len > 32 { + return Err(format!( + "invalid additional_bits: would extend network length to {} bits, which is too long for IPv4", + len + )); + } + if net_num >= (1 << additional_bits) { + return Err(format!( + "additional_bits of {} does not accommodate a net_num of {}", + additional_bits, net_num + )); + } + match Ipv4Cidr::new( + Ipv4Addr::from_bits(ipv4.to_bits() + (net_num << (32 - len)) as u32), + len as u8, + ) { + Err(_e) => unreachable!(), + Ok(cidr) => format!("{}/{}", cidr.first_address(), cidr.network_length()), + } + } + V6(ipv6) => { + if len > 128 { + return Err(format!( + "invalid additional_bits: would extend network length to {} bits, which is too long for IPv6", + len + )); + } + if additional_bits < 64 && net_num as u64 >= (1u64 << additional_bits) { + return Err(format!( + "additional_bits of {} does not accommodate a net_num of {}", + additional_bits, net_num + )); + } + if len == 0 { + return Ok(ValueRef::str("::/0")); + } + match Ipv6Cidr::new( + Ipv6Addr::from_bits(ipv6.to_bits() + ((net_num as u128) << (128 - len))), + len as u8, + ) { + Err(_e) => unreachable!(), + Ok(cidr) => format!("{}/{}", cidr.first_address(), cidr.network_length()), + } + } + }; + Ok(ValueRef::str(new_cidr.as_str())) +} + +// CIDR_subnets(cidr: str, additional_bits: [int]) -> [str] + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_CIDR_subnets( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + let cidr = match get_call_arg(args, kwargs, 0, Some("cidr")) { + None => { + panic!( + "CIDR_subnets() missing 2 required positional arguments: 'cidr' and 'additional_bits'" + ); + } + Some(cidr) => match IpCidr::from_str(&cidr.as_str()) { + Err(err) => { + panic!("CIDR_subnets() invalid cidr: {}", err) + } + Ok(cidr) => cidr, + }, + }; + + let additional_bits_valueref = match get_call_arg(args, kwargs, 1, Some("additional_bits")) { + None => { + panic!( + "CIDR_subnets() missing 2 required positional arguments: 'cidr' and 'additional_bits'" + ); + } + Some(additional_bits) => additional_bits, + }; + let additional_bits = additional_bits_valueref.as_list_ref(); + + let mut net_num: Vec = Vec::with_capacity(additional_bits.values.len()); + for new_additional in additional_bits.values.iter() { + let mut num = 0i64; + let bits = new_additional.must_as_strict_int(); + + if bits < 0 { + panic!("CIDR_subnets() invalid additional_bits: cannot be negative"); + } + let new_bits = cidr.network_length() as i64 + bits; + if cidr.is_ipv4() && new_bits > 32 { + panic!( + "CIDR_subnets() invalid additional_bits: would extend network length to {} bits, which is too long for IPv4", + new_bits + ); + } + if cidr.is_ipv6() { + if bits > 63 { + panic!("CIDR_subnets() invalid additional_bits: cannot extend more than 63 bits") + } + if new_bits > 128 { + panic!( + "CIDR_subnets() invalid additional_bits: would extend network length to {} bits, which is too long for IPv6", + new_bits + ); + } + } + + let mut try_again = true; + while try_again { + try_again = false; + for i in 0..net_num.len() { + let mut allocated_num = net_num[i]; + let mut allocated_bits = additional_bits.values[i].must_as_strict_int(); + if allocated_bits > bits { + allocated_num >>= allocated_bits - bits; + allocated_bits = bits + } + if allocated_bits < bits { + allocated_num <<= bits - allocated_bits; + } + if allocated_num == num { + num += 1 << (bits - allocated_bits); + try_again = true; + } + } + } + net_num.push(num); + } + + let mut subnets = Vec::with_capacity(net_num.len()); + for (additional, num) in additional_bits.values.iter().zip_eq(net_num.iter()) { + if *num as u64 >= (1u64 << additional.must_as_strict_int()) { + match subnets.pop() { + None => unreachable!(), + Some(last) => panic!( + "CIDR_subnets() not enough remaining address space for a subnet with a prefix of {} bits after {}", + cidr.network_length() as i64 + additional.must_as_strict_int(), + last + ), + } + } + let subnet = match CIDR_allocate(cidr, additional.must_as_strict_int(), *num) { + Ok(value) => value, + Err(message) => panic!("CIDR_subnets {}", message), + }; + subnets.push(subnet); + } + ValueRef::list(Some(subnets.iter().collect_vec().as_slice())).into_raw(ctx) +} + +// CIDR_host(cidr: str, host_num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_CIDR_host( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + let cidr = match get_call_arg(args, kwargs, 0, Some("cidr")) { + None => { + panic!("CIDR_host() missing 2 required positional arguments: 'cidr' and 'host_num'"); + } + Some(cidr) => match IpCidr::from_str(&cidr.as_str()) { + Err(err) => { + panic!("CIDR_host() invalid cidr: {}", err) + } + Ok(cidr) => cidr, + }, + }; + + let host_num = match get_call_arg(args, kwargs, 1, Some("host_num")) { + None => { + panic!("CIDR_host() missing 2 required positional arguments: 'cidr' and 'host_num'"); + } + Some(net_num) => net_num.must_as_strict_int(), + }; + + let host_len = cidr.family().len() - cidr.network_length(); + let abs_host_num = match host_num < 0 { + true => -(host_num + 1), + false => host_num, + } as u64; + if host_len < 64 && (1u64 << host_len) <= abs_host_num { + panic!( + "CIDR_host() prefix of {} does not accommodate a host numbered {}", + cidr.network_length(), + host_num + ); + } + + let addr = match cidr.first_address() { + V4(ipv4) => { + let mut bits = ipv4.to_bits() as i64; + if host_num < 0 { + bits += 1i64 << host_len + } + bits += host_num; + Ipv4Addr::from_bits(bits as u32).to_string() + } + V6(ipv6) => { + let mut bits = ipv6.to_bits(); + if host_len == 128 { + bits = host_num as u128; + } else { + let host_bits = match host_num < 0 { + true => (1u128 << host_len) - (-(host_num as i128)) as u128, + false => host_num as u128, + }; + bits += host_bits; + } + Ipv6Addr::from_bits(bits).to_string() + } + }; + return ValueRef::str(addr.as_str()).into_raw(ctx); +} + +// CIDR_netmask(cidr: str) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_net_CIDR_netmask( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + let cidr = match get_call_arg(args, kwargs, 0, Some("cidr")) { + None => { + panic!("CIDR_netmask() missing 1 required positional argument: 'cidr'"); + } + Some(cidr) => match IpCidr::from_str(&cidr.as_str()) { + Err(err) => { + panic!("CIDR_netmask() invalid cidr: {}", err) + } + Ok(cidr) => cidr, + }, + }; + + if cidr.is_ipv6() { + panic!("CIDR_netmask() IPv6 addresses cannot have a netmask") + } + + let bits = -1i64 << (32 - cidr.network_length()); + return ValueRef::str(Ipv4Addr::from_bits(bits as u32).to_string().as_str()).into_raw(ctx); +} + +#[cfg(test)] +mod test_net { + use super::*; + + #[test] + #[allow(non_snake_case)] + fn test_to_ip4() { + let cases = [ + ("::FFFF:192.168.1.10", "192.168.1.10"), + ( + "::FFFF:192.168.x.10", + "can not both parse ::FFFF:192.168.x.10 to ipv6 and ipv4,err:invalid IPv6 address syntax", + ), + ("::FFFF:10.0.0.1", "10.0.0.1"), + ("::FFFF:172.16.0.1", "172.16.0.1"), + ("::FFFF:127.0.0.1", "127.0.0.1"), + ("0000:0000:0000:0000:0000:FFFF:0A00:0001", "10.0.0.1"), + ("::FFFF:224.0.0.1", "224.0.0.1"), + ( + "::FFFF:invalid.ip", + "can not both parse ::FFFF:invalid.ip to ipv6 and ipv4,err:invalid IPv6 address syntax", + ), + // IPv4-mapped IPv6 addresses + ("::FFFF:0A00:0001", "10.0.0.1"), + ("0:0:0:0:0:FFFF:AC10:0001", "172.16.0.1"), + ]; + let mut ctx = Context::default(); + for (ip6, expected) in cases.iter() { + unsafe { + let actual = &*kcl_net_to_IP4( + &mut ctx, + &ValueRef::list(Some(&[&ValueRef::str(ip6)])), + &ValueRef::dict(None), + ); + assert_eq!(&ValueRef::str(expected), actual, "{} positional", ip6,); + } + } + } + + #[test] + #[allow(non_snake_case)] + fn test_to_ip6() { + let cases = [ + ("192.168.1.10", "::ffff:192.168.1.10"), + ( + "192.168.x.10", + "can not both parse 192.168.x.10 to ipv6 and ipv4,err:invalid IPv4 address syntax", + ), + ("10.0.0.1", "::ffff:10.0.0.1"), + ("172.16.0.1", "::ffff:172.16.0.1"), + ("127.0.0.1", "::ffff:127.0.0.1"), + ("224.0.0.1", "::ffff:224.0.0.1"), + ( + "invalid.ip", + "can not both parse invalid.ip to ipv6 and ipv4,err:invalid IPv4 address syntax", + ), + // IPv6 addresses + ("2001:db8::1", "2001:db8::1"), + ("::1", "::1"), + ( + "2001:db8:::1", + "can not both parse 2001:db8:::1 to ipv6 and ipv4,err:invalid IPv4 address syntax", + ), + ]; + let mut ctx = Context::default(); + for (ip4, expected) in cases.iter() { + unsafe { + let actual = &*kcl_net_to_IP6( + &mut ctx, + &ValueRef::list(Some(&[&ValueRef::str(ip4)])), + &ValueRef::dict(None), + ); + assert_eq!(&ValueRef::str(expected), actual, "{} positional", ip4,); + } + } + } + + #[test] + fn test_split_host_port() { + let cases = [ + ( + ValueRef::str("invalid.invalid:21"), + ValueRef::list(Some(&[ + &ValueRef::str("invalid.invalid"), + &ValueRef::str("21"), + ])), + ), + ( + ValueRef::str("192.0.2.1:14"), + ValueRef::list(Some(&[&ValueRef::str("192.0.2.1"), &ValueRef::str("14")])), + ), + ( + ValueRef::str("[2001:db8::]:80"), + ValueRef::list(Some(&[&ValueRef::str("2001:db8::"), &ValueRef::str("80")])), + ), + ]; + let mut ctx = Context::default(); + for (ip_end_point, expected) in cases.iter() { + unsafe { + let actual = &*kcl_net_split_host_port( + &mut ctx, + &ValueRef::list(Some(&[&ip_end_point])), + &ValueRef::dict(None), + ); + assert_eq!(expected, actual); + } + unsafe { + let actual = &*kcl_net_split_host_port( + &mut ctx, + &ValueRef::list(None), + &ValueRef::dict(Some(&[("ip_end_point", ip_end_point)])), + ); + assert_eq!(expected, actual); + } + } + } + #[test] + fn test_split_host_port_invalid() { + let prev_hook = std::panic::take_hook(); + // Disable print panic info in stderr. + std::panic::set_hook(Box::new(|_| {})); + assert_panic( + "split_host_port() missing 1 required positional argument: 'ip_end_point'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_split_host_port(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic("ip_end_point \"test-host\" missing port", || { + let ctx = Context::new(); + let args = &ValueRef::list(Some(&[&ValueRef::str("test-host")])); + kcl_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); + }); + assert_panic("ip_end_point \"test-host:7:80\" too many colons", || { + let ctx = Context::new(); + let args = &ValueRef::list(Some(&[&ValueRef::str("test-host:7:80")])); + kcl_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); + }); + assert_panic("ip_end_point \"[2001:db8::]\" missing port", || { + let ctx = Context::new(); + let args = &ValueRef::list(Some(&[&ValueRef::str("[2001:db8::]")])); + kcl_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); + }); + assert_panic("ip_end_point \"[2001:db8::]80\" missing port", || { + let ctx = Context::new(); + let args = &ValueRef::list(Some(&[&ValueRef::str("[2001:db8::]80")])); + kcl_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); + }); + assert_panic("ip_end_point \"[2001:db8::]9:80\" missing port", || { + let ctx = Context::new(); + let args = &ValueRef::list(Some(&[&ValueRef::str("[2001:db8::]9:80")])); + kcl_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); + }); + assert_panic("ip_end_point \"[2001:db8::]:9:80\" too many colons", || { + let ctx = Context::new(); + let args = &ValueRef::list(Some(&[&ValueRef::str("[2001:db8::]:9:80")])); + kcl_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); + }); + assert_panic("ip_end_point \"[2001:db8:::80\" missing ']'", || { + let ctx = Context::new(); + let args = &ValueRef::list(Some(&[&ValueRef::str("[2001:db8:::80")])); + kcl_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); + }); + assert_panic("ip_end_point \"t[est-host:80\" unexpected '['", || { + let ctx = Context::new(); + let args = &ValueRef::list(Some(&[&ValueRef::str("t[est-host:80")])); + kcl_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); + }); + assert_panic("ip_end_point \"]test-host:80\" unexpected ']'", || { + let ctx = Context::new(); + let args = &ValueRef::list(Some(&[&ValueRef::str("]test-host:80")])); + kcl_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); + }); + assert_panic("ip_end_point \"[[2001:db8::]:80\" unexpected '['", || { + let ctx = Context::new(); + let args = &ValueRef::list(Some(&[&ValueRef::str("[[2001:db8::]:80")])); + kcl_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); + }); + assert_panic("ip_end_point \"[2001:db8::]:]80\" unexpected ']'", || { + let ctx = Context::new(); + let args = &ValueRef::list(Some(&[&ValueRef::str("[2001:db8::]:]80")])); + kcl_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); + }); + std::panic::set_hook(prev_hook); + } + + #[test] + fn test_join_host_port() { + let cases = [ + ( + ValueRef::str("invalid.invalid"), + ValueRef::int(21), + ValueRef::str("invalid.invalid:21"), + ), + ( + ValueRef::str("invalid.invalid"), + ValueRef::str("21"), + ValueRef::str("invalid.invalid:21"), + ), + ( + ValueRef::str("192.0.2.1"), + ValueRef::int(14), + ValueRef::str("192.0.2.1:14"), + ), + ( + ValueRef::str("192.0.2.1"), + ValueRef::str("14"), + ValueRef::str("192.0.2.1:14"), + ), + ( + ValueRef::str("2001:db8::"), + ValueRef::int(14), + ValueRef::str("[2001:db8::]:14"), + ), + ( + ValueRef::str("2001:db8::"), + ValueRef::str("14"), + ValueRef::str("[2001:db8::]:14"), + ), + ]; + let mut ctx = Context::default(); + for (host, port, expected) in cases.iter() { + unsafe { + let actual = &*kcl_net_join_host_port( + &mut ctx, + &ValueRef::list(Some(&[&host, &port])), + &ValueRef::dict(None), + ); + assert_eq!(expected, actual); + } + unsafe { + let actual = &*kcl_net_join_host_port( + &mut ctx, + &ValueRef::list(None), + &ValueRef::dict(Some(&[("host", host), ("port", port)])), + ); + assert_eq!(expected, actual); + } + } + } + + #[test] + fn test_join_host_port_invalid() { + let prev_hook = std::panic::take_hook(); + // Disable print panic info in stderr. + std::panic::set_hook(Box::new(|_| {})); + assert_panic( + "join_host_port() missing 2 required positional arguments: 'host' and 'port'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_join_host_port(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "join_host_port() missing 2 required positional arguments: 'host' and 'port'", + || { + let mut ctx = Context::new(); + let args = + ValueRef::list(Some(&[&ValueRef::str("invalid.invalid")])).into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_join_host_port(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "join_host_port() missing 2 required positional arguments: 'host' and 'port'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(Some(&[("host", &ValueRef::str("invalid.invalid"))])) + .into_raw(&mut ctx); + kcl_net_join_host_port(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "join_host_port() missing 2 required positional arguments: 'host' and 'port'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = + ValueRef::dict(Some(&[("port", &ValueRef::str("80"))])).into_raw(&mut ctx); + kcl_net_join_host_port(ctx.into_raw(), args, kwargs); + }, + ); + std::panic::set_hook(prev_hook); + } + + #[test] + #[allow(non_snake_case)] + fn test_parse_CIDR() { + let cases = [ + ( + ValueRef::str("0.0.0.0/0"), + ValueRef::dict(Some(&[ + ("ip", &ValueRef::str("0.0.0.0")), + ("mask", &ValueRef::int(0)), + ])), + ), + ( + ValueRef::str("::/0"), + ValueRef::dict(Some(&[ + ("ip", &ValueRef::str("::")), + ("mask", &ValueRef::int(0)), + ])), + ), + ( + ValueRef::str("10.0.0.0/8"), + ValueRef::dict(Some(&[ + ("ip", &ValueRef::str("10.0.0.0")), + ("mask", &ValueRef::int(8)), + ])), + ), + ( + ValueRef::str("2001:db8::/56"), + ValueRef::dict(Some(&[ + ("ip", &ValueRef::str("2001:db8::")), + ("mask", &ValueRef::int(56)), + ])), + ), + ( + ValueRef::str("10.1.2.3/32"), + ValueRef::dict(Some(&[ + ("ip", &ValueRef::str("10.1.2.3")), + ("mask", &ValueRef::int(32)), + ])), + ), + ( + ValueRef::str("2001:db8:1:2:3:4:5:7/128"), + ValueRef::dict(Some(&[ + ("ip", &ValueRef::str("2001:db8:1:2:3:4:5:7")), + ("mask", &ValueRef::int(128)), + ])), + ), + ( + ValueRef::str("10.1.2.3"), + ValueRef::dict(Some(&[ + ("ip", &ValueRef::str("10.1.2.3")), + ("mask", &ValueRef::int(32)), + ])), + ), + ( + ValueRef::str("2001:db8:1:2:3:4:5:7"), + ValueRef::dict(Some(&[ + ("ip", &ValueRef::str("2001:db8:1:2:3:4:5:7")), + ("mask", &ValueRef::int(128)), + ])), + ), + (ValueRef::str("10.0.0/8"), ValueRef::dict(None)), + (ValueRef::str("10.0.0.0/33"), ValueRef::dict(None)), + ( + ValueRef::str("2001:db8:1:2:3:4:5:7/129"), + ValueRef::dict(None), + ), + (ValueRef::str("0.0.0.0/256"), ValueRef::dict(None)), + (ValueRef::str("::/256"), ValueRef::dict(None)), + (ValueRef::str("10.0.0.0/8/8"), ValueRef::dict(None)), + (ValueRef::str("2001:db8::/56/56"), ValueRef::dict(None)), + (ValueRef::str("0.0.0.0/-1"), ValueRef::dict(None)), + (ValueRef::str("::/-1"), ValueRef::dict(None)), + (ValueRef::str("10.128.0.0/8"), ValueRef::dict(None)), + (ValueRef::str("2001:db8::/16"), ValueRef::dict(None)), + (ValueRef::str("10.1.2.3/31"), ValueRef::dict(None)), + ( + ValueRef::str("2001:db8:1:2:3:4:5:7/127"), + ValueRef::dict(None), + ), + ]; + let mut ctx = Context::default(); + for (cidr, expected) in cases.iter() { + unsafe { + let actual = &*kcl_net_parse_CIDR( + &mut ctx, + &ValueRef::list(Some(&[&cidr])), + &ValueRef::dict(None), + ); + assert_eq!(expected, actual, "{} positional", cidr); + } + unsafe { + let actual = &*kcl_net_parse_CIDR( + &mut ctx, + &ValueRef::list(None), + &ValueRef::dict(Some(&[("cidr", cidr)])), + ); + assert_eq!(expected, actual, "{} named", cidr); + } + } + } + + #[test] + #[allow(non_snake_case)] + fn test_parse_CIDR_invalid() { + let prev_hook = std::panic::take_hook(); + // Disable print panic info in stderr. + std::panic::set_hook(Box::new(|_| {})); + assert_panic( + "parse_CIDR() missing 1 required positional argument: 'cidr'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_parse_CIDR(ctx.into_raw(), args, kwargs); + }, + ); + std::panic::set_hook(prev_hook); + } + + #[test] + #[allow(non_snake_case)] + fn test_is_IP_in_CIDR() { + let cases = [ + ( + "0.0.0.0/0", + vec!["0.0.0.0", "255.255.255.255"], + vec!["::", "2001:db8::"], + ), + ( + "::/0", + vec![ + "::", + "2001:db8::", + "10.1.2.3", + "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", + ], + vec![], + ), + ( + "10.0.0.0/8", + vec!["10.0.0.0", "10.1.2.3", "10.255.255.255"], + vec!["9.255.255.255", "11.0.0.0", "a000::"], + ), + ( + "2001:db8::/56", + vec!["2001:db8::", "2001:db8:0000:ff:ffff:ffff:ffff:ffff"], + vec![ + "2001:db7:ffff:ffff:ffff:ffff:ffff:ffff", + "2001:db8:0:100::", + "10.1.2.3", + ], + ), + ( + "10.1.2.3/32", + vec!["10.1.2.3"], + vec!["10.1.2.2", "10.1.2.4", "0a01:0203::"], + ), + ( + "2001:db8:1:2:3:4:5:7/128", + vec!["2001:db8:1:2:3:4:5:7"], + vec!["2001:db8:1:2:3:4:5:6", "2001:db8:1:2:3:4:5:8", "10.1.2.3"], + ), + ( + "10.1.2.3", + vec!["10.1.2.3"], + vec!["10.1.2.2", "10.1.2.4", "0a01:0203::"], + ), + ( + "2001:db8:1:2:3:4:5:7", + vec!["2001:db8:1:2:3:4:5:7"], + vec!["2001:db8:1:2:3:4:5:6", "2001:db8:1:2:3:4:5:8", "10.1.2.3"], + ), + ]; + let mut ctx = Context::default(); + for (cidr, expect_in, expect_not_in) in cases.iter() { + for ip in expect_in.iter() { + unsafe { + let actual = &*kcl_net_is_IP_in_CIDR( + &mut ctx, + &ValueRef::list(Some(&[&ValueRef::str(ip), &ValueRef::str(cidr)])), + &ValueRef::dict(None), + ); + assert_eq!( + &ValueRef::bool(true), + actual, + "{} in {} positional", + ip, + cidr + ); + } + unsafe { + let actual = &*kcl_net_is_IP_in_CIDR( + &mut ctx, + &ValueRef::list(None), + &ValueRef::dict(Some(&[ + ("cidr", &ValueRef::str(cidr)), + ("ip", &ValueRef::str(ip)), + ])), + ); + assert_eq!(&ValueRef::bool(true), actual, "{} in {} named", ip, cidr); + } + } + for ip in expect_not_in.iter() { + unsafe { + let actual = &*kcl_net_is_IP_in_CIDR( + &mut ctx, + &ValueRef::list(Some(&[&ValueRef::str(ip), &ValueRef::str(cidr)])), + &ValueRef::dict(None), + ); + assert_eq!( + &ValueRef::bool(false), + actual, + "{} not in {} positional", + ip, + cidr + ); + } + unsafe { + let actual = &*kcl_net_is_IP_in_CIDR( + &mut ctx, + &ValueRef::list(None), + &ValueRef::dict(Some(&[ + ("cidr", &ValueRef::str(cidr)), + ("ip", &ValueRef::str(ip)), + ])), + ); + assert_eq!( + &ValueRef::bool(false), + actual, + "{} not in {} named", + ip, + cidr + ); + } + } + } + } + + #[test] + #[allow(non_snake_case)] + fn test_is_IP_in_CIDR_invalid() { + let prev_hook = std::panic::take_hook(); + // Disable print panic info in stderr. + std::panic::set_hook(Box::new(|_| {})); + assert_panic( + "is_IP_in_CIDR() missing 2 required positional arguments: 'ip' and 'cidr'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_is_IP_in_CIDR(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "is_IP_in_CIDR() missing 2 required positional arguments: 'ip' and 'cidr'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(Some(&[&ValueRef::str("10.1.2.3")])).into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_is_IP_in_CIDR(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "is_IP_in_CIDR() missing 2 required positional arguments: 'ip' and 'cidr'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = + ValueRef::dict(Some(&[("ip", &ValueRef::str("10.1.2.3"))])).into_raw(&mut ctx); + kcl_net_is_IP_in_CIDR(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "is_IP_in_CIDR() missing 2 required positional arguments: 'ip' and 'cidr'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(Some(&[("cidr", &ValueRef::str("10.0.0.0/8"))])) + .into_raw(&mut ctx); + kcl_net_is_IP_in_CIDR(ctx.into_raw(), args, kwargs); + }, + ); + let cases = [ + ( + "10.0.0/8", + "10.0.0.1", + "is_IP_in_CIDR() invalid cidr: couldn't parse address in network: invalid IP address syntax", + ), + ( + "10.0.0.0/33", + "10.0.0.1", + "is_IP_in_CIDR() invalid cidr: invalid length for network: Network length 33 is too long for Ipv4 (maximum: 32)", + ), + ( + "2001:db8:1:2:3:4:5:7/129", + "2001:db8::", + "is_IP_in_CIDR() invalid cidr: invalid length for network: Network length 129 is too long for Ipv6 (maximum: 128)", + ), + ( + "0.0.0.0/256", + "10.0.0.1", + "is_IP_in_CIDR() invalid cidr: couldn't parse length in network: number too large to fit in target type", + ), + ( + "::/256", + "2001:db8::", + "is_IP_in_CIDR() invalid cidr: couldn't parse length in network: number too large to fit in target type", + ), + ( + "10.0.0.0/8/8", + "10.0.0.1", + "is_IP_in_CIDR() invalid cidr: couldn't parse address in network: invalid IP address syntax", + ), + ( + "2001:db8::/56/56", + "2001:db8::", + "is_IP_in_CIDR() invalid cidr: couldn't parse address in network: invalid IP address syntax", + ), + ( + "0.0.0.0/-1", + "10.0.0.1", + "is_IP_in_CIDR() invalid cidr: couldn't parse length in network: invalid digit found in string", + ), + ( + "::/-1", + "2001:db8::", + "is_IP_in_CIDR() invalid cidr: couldn't parse length in network: invalid digit found in string", + ), + ( + "10.128.0.0/8", + "10.0.0.1", + "is_IP_in_CIDR() invalid cidr: host part of address was not zero", + ), + ( + "2001:db8::/16", + "2001:db8::", + "is_IP_in_CIDR() invalid cidr: host part of address was not zero", + ), + ( + "10.1.2.3/31", + "10.0.0.1", + "is_IP_in_CIDR() invalid cidr: host part of address was not zero", + ), + ( + "2001:db8:1:2:3:4:5:7/127", + "2001:db8::", + "is_IP_in_CIDR() invalid cidr: host part of address was not zero", + ), + ( + "10.0.0.0/8", + "10.0.0", + "is_IP_in_CIDR() invalid ip: invalid IP address syntax", + ), + ( + "2001:db8::/56", + "2001:db8:::", + "is_IP_in_CIDR() invalid ip: invalid IP address syntax", + ), + ]; + for (cidr, ip, expect_error) in cases.iter() { + assert_panic(expect_error, || { + let mut ctx = Context::new(); + let args = ValueRef::list(Some(&[&ValueRef::str(ip), &ValueRef::str(cidr)])) + .into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_is_IP_in_CIDR(ctx.into_raw(), args, kwargs); + }); + } + std::panic::set_hook(prev_hook); + } + + #[test] + #[allow(non_snake_case)] + fn test_CIDR_subnet() { + let cases = [ + ("0.0.0.0/0", 0i64, 0i64, "0.0.0.0/0"), + ("0.0.0.0/0", 1, 1, "128.0.0.0/1"), + ("0.0.0.0/0", 8, 10, "10.0.0.0/8"), + ("0.0.0.0/0", 9, 11, "5.128.0.0/9"), + ("0.0.0.0/0", 32, 4294967295, "255.255.255.255/32"), + ("10.0.0.0/8", 9, 11, "10.5.128.0/17"), + ("10.0.0.0/8", 24, 16777215, "10.255.255.255/32"), + ("255.1.2.254/31", 1, 1, "255.1.2.255/32"), + ("255.255.255.254/31", 1, 1, "255.255.255.255/32"), + ("255.255.255.255/32", 0, 0, "255.255.255.255/32"), + ("::/0", 0, 0, "::/0"), + ("::/0", 1, 1, "8000::/1"), + ("::/0", 16, 10, "a::/16"), + ("::/0", 17, 11, "5:8000::/17"), + ("::/0", 63, 9223372036854775807, "ffff:ffff:ffff:fffe::/63"), + ("::/0", 64, 9223372036854775807, "7fff:ffff:ffff:ffff::/64"), + ( + "ffff:ffff:ffff:ffff:8000::/65", + 63, + 9223372036854775807, + "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128", + ), + ("2001:db8::/56", 8, 5, "2001:db8:0:5::/64"), + ( + "2001:db8:1:2:3:4:5:fffe/127", + 1, + 1, + "2001:db8:1:2:3:4:5:ffff/128", + ), + ("2001:db8:1:2:3:4:5:7/128", 0, 0, "2001:db8:1:2:3:4:5:7/128"), + ]; + let mut ctx = Context::default(); + for (cidr, additional_bits, net_num, expected) in cases.iter() { + unsafe { + let actual = &*kcl_net_CIDR_subnet( + &mut ctx, + &ValueRef::list(Some(&[ + &ValueRef::str(cidr), + &ValueRef::int(*additional_bits), + &ValueRef::int(*net_num), + ])), + &ValueRef::dict(None), + ); + assert_eq!( + &ValueRef::str(expected), + actual, + "{} {} {} positional", + cidr, + additional_bits, + net_num + ); + } + unsafe { + let actual = &*kcl_net_CIDR_subnet( + &mut ctx, + &ValueRef::list(None), + &ValueRef::dict(Some(&[ + ("cidr", &ValueRef::str(cidr)), + ("additional_bits", &ValueRef::int(*additional_bits)), + ("net_num", &ValueRef::int(*net_num)), + ])), + ); + assert_eq!( + &ValueRef::str(expected), + actual, + "{} {} {} named", + cidr, + additional_bits, + net_num + ); + } + } + } + + #[test] + #[allow(non_snake_case)] + fn test_CIDR_subnet_invalid() { + let prev_hook = std::panic::take_hook(); + // Disable print panic info in stderr. + std::panic::set_hook(Box::new(|_| {})); + assert_panic( + "CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_CIDR_subnet(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(Some(&[&ValueRef::str("10.1.2.3"), &ValueRef::int(1)])) + .into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_CIDR_subnet(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(Some(&[ + ("cidr", &ValueRef::str("10.1.2.3")), + ("additional_bits", &ValueRef::int(1)), + ])) + .into_raw(&mut ctx); + kcl_net_CIDR_subnet(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(Some(&[ + ("cidr", &ValueRef::str("10.1.2.3")), + ("net_num", &ValueRef::int(1)), + ])) + .into_raw(&mut ctx); + kcl_net_CIDR_subnet(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(Some(&[ + ("additional_bits", &ValueRef::int(1)), + ("net_num", &ValueRef::int(1)), + ])) + .into_raw(&mut ctx); + kcl_net_CIDR_subnet(ctx.into_raw(), args, kwargs); + }, + ); + let cases = [ + ( + "10.0.0/8", + 1i64, + 0i64, + "CIDR_subnet() invalid cidr: couldn't parse address in network: invalid IP address syntax", + ), + ( + "10.0.0.0/33", + 1, + 0, + "CIDR_subnet() invalid cidr: invalid length for network: Network length 33 is too long for Ipv4 (maximum: 32)", + ), + ( + "2001:db8:1:2:3:4:5:7/129", + 1, + 0, + "CIDR_subnet() invalid cidr: invalid length for network: Network length 129 is too long for Ipv6 (maximum: 128)", + ), + ( + "0.0.0.0/256", + 1, + 0, + "CIDR_subnet() invalid cidr: couldn't parse length in network: number too large to fit in target type", + ), + ( + "::/256", + 1, + 0, + "CIDR_subnet() invalid cidr: couldn't parse length in network: number too large to fit in target type", + ), + ( + "10.0.0.0/8/8", + 1, + 0, + "CIDR_subnet() invalid cidr: couldn't parse address in network: invalid IP address syntax", + ), + ( + "2001:db8::/56/56", + 1, + 0, + "CIDR_subnet() invalid cidr: couldn't parse address in network: invalid IP address syntax", + ), + ( + "0.0.0.0/-1", + 1, + 0, + "CIDR_subnet() invalid cidr: couldn't parse length in network: invalid digit found in string", + ), + ( + "::/-1", + 1, + 0, + "CIDR_subnet() invalid cidr: couldn't parse length in network: invalid digit found in string", + ), + ( + "10.128.0.0/8", + 1, + 0, + "CIDR_subnet() invalid cidr: host part of address was not zero", + ), + ( + "2001:db8::/16", + 1, + 0, + "CIDR_subnet() invalid cidr: host part of address was not zero", + ), + ( + "10.1.2.3/31", + 1, + 0, + "CIDR_subnet() invalid cidr: host part of address was not zero", + ), + ( + "2001:db8:1:2:3:4:5:7/127", + 1, + 0, + "CIDR_subnet() invalid cidr: host part of address was not zero", + ), + ( + "10.0.0.0/8", + -1, + 0, + "CIDR_subnet() invalid additional_bits: cannot be negative", + ), + ( + "2001:db8::/64", + 1, + -1, + "CIDR_subnet() invalid net_num: cannot be negative", + ), + ( + "10.0.0.0/8", + 25, + 0, + "CIDR_subnet() invalid additional_bits: would extend network length to 33 bits, which is too long for IPv4", + ), + ( + "2001:db8::/65", + 64, + 0, + "CIDR_subnet() invalid additional_bits: would extend network length to 129 bits, which is too long for IPv6", + ), + ( + "10.0.0.0/8", + 8, + 256, + "CIDR_subnet() additional_bits of 8 does not accommodate a net_num of 256", + ), + ( + "2001:db8::/64", + 8, + 256, + "CIDR_subnet() additional_bits of 8 does not accommodate a net_num of 256", + ), + ]; + for (cidr, additional_bits, net_num, expect_error) in cases.iter() { + assert_panic(expect_error, || { + let mut ctx = Context::new(); + let args = ValueRef::list(Some(&[ + &ValueRef::str(cidr), + &ValueRef::int(*additional_bits), + &ValueRef::int(*net_num), + ])) + .into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_CIDR_subnet(ctx.into_raw(), args, kwargs); + }); + } + std::panic::set_hook(prev_hook); + } + + #[test] + #[allow(non_snake_case)] + fn test_CIDR_subnets() { + let cases = [ + ("0.0.0.0/0", vec![0i64], vec!["0.0.0.0/0"]), + ("0.0.0.0/0", vec![], vec![]), + ("0.0.0.0/0", vec![1, 1], vec!["0.0.0.0/1", "128.0.0.0/1"]), + ( + "0.0.0.0/0", + vec![8, 9, 9, 32, 32], + vec![ + "0.0.0.0/8", + "1.0.0.0/9", + "1.128.0.0/9", + "2.0.0.0/32", + "2.0.0.1/32", + ], + ), + ( + "0.0.0.0/0", + vec![8, 32, 32, 9], + vec!["0.0.0.0/8", "1.0.0.0/32", "1.0.0.1/32", "1.128.0.0/9"], + ), + ( + "10.0.0.0/8", + vec![8, 9, 9, 9, 8], + vec![ + "10.0.0.0/16", + "10.1.0.0/17", + "10.1.128.0/17", + "10.2.0.0/17", + "10.3.0.0/16", + ], + ), + ( + "10.0.0.0/8", + vec![8, 10, 8, 9, 10, 10], + vec![ + "10.0.0.0/16", + "10.1.0.0/18", + "10.2.0.0/16", + "10.1.128.0/17", + "10.1.64.0/18", + "10.3.0.0/18", + ], + ), + ( + "255.1.2.254/31", + vec![1, 1], + vec!["255.1.2.254/32", "255.1.2.255/32"], + ), + ("255.255.255.255/32", vec![0], vec!["255.255.255.255/32"]), + ("::/0", vec![0], vec!["::/0"]), + ("::/0", vec![], vec![]), + ("::/0", vec![1, 1], vec!["::/1", "8000::/1"]), + ( + "::/0", + vec![8, 9, 9, 63, 63], + vec!["::/8", "100::/9", "180::/9", "200::/63", "200:0:0:2::/63"], + ), + ( + "::/0", + vec![8, 63, 63, 9], + vec!["::/8", "100::/63", "100:0:0:2::/63", "180::/9"], + ), + ( + "2001:db8::/65", + vec![8, 63, 63, 63, 8], + vec![ + "2001:db8::/73", + "2001:db8:0:0:80::/128", + "2001:db8::80:0:0:1/128", + "2001:db8::80:0:0:2/128", + "2001:db8:0:0:100::/73", + ], + ), + ( + "2001:db8::/65", + vec![8, 10, 8, 9, 10, 10], + vec![ + "2001:db8::/73", + "2001:db8:0:0:80::/75", + "2001:db8:0:0:100::/73", + "2001:db8:0:0:c0::/74", + "2001:db8:0:0:a0::/75", + "2001:db8:0:0:180::/75", + ], + ), + ]; + let mut ctx = Context::default(); + for (cidr, additional_bits, expected) in cases.iter() { + let additional_bits_valueref = additional_bits + .iter() + .map(|x| ValueRef::int(*x)) + .collect::>(); + let expected_valueref = expected + .iter() + .map(|x| ValueRef::str(*x)) + .collect::>(); + unsafe { + let actual = &*kcl_net_CIDR_subnets( + &mut ctx, + &ValueRef::list(Some(&[ + &ValueRef::str(cidr), + &ValueRef::list(Some(&additional_bits_valueref.iter().collect::>())), + ])), + &ValueRef::dict(None), + ); + assert_eq!( + &ValueRef::list(Some(&expected_valueref.iter().collect::>())), + actual, + "{} {:?} positional", + cidr, + additional_bits, + ); + } + unsafe { + let actual = &*kcl_net_CIDR_subnets( + &mut ctx, + &ValueRef::list(None), + &ValueRef::dict(Some(&[ + ("cidr", &ValueRef::str(cidr)), + ( + "additional_bits", + &ValueRef::list(Some( + &additional_bits_valueref.iter().collect::>(), + )), + ), + ])), + ); + assert_eq!( + &ValueRef::list(Some(&expected_valueref.iter().collect::>())), + actual, + "{} {:?} named", + cidr, + additional_bits, + ); + } + } + } + + #[test] + #[allow(non_snake_case)] + fn test_CIDR_subnets_invalid() { + let prev_hook = std::panic::take_hook(); + // Disable print panic info in stderr. + std::panic::set_hook(Box::new(|_| {})); + assert_panic( + "CIDR_subnets() missing 2 required positional arguments: 'cidr' and 'additional_bits'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_CIDR_subnets(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "CIDR_subnets() missing 2 required positional arguments: 'cidr' and 'additional_bits'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(Some(&[&ValueRef::str("10.1.2.3")])).into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_CIDR_subnets(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "CIDR_subnets() missing 2 required positional arguments: 'cidr' and 'additional_bits'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(Some(&[("cidr", &ValueRef::str("10.1.2.3"))])) + .into_raw(&mut ctx); + kcl_net_CIDR_subnets(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "CIDR_subnets() missing 2 required positional arguments: 'cidr' and 'additional_bits'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(Some(&[("additional_bits", &ValueRef::int(1))])) + .into_raw(&mut ctx); + kcl_net_CIDR_subnets(ctx.into_raw(), args, kwargs); + }, + ); + let cases = [ + ( + "10.0.0/8", + vec![1i64], + "CIDR_subnets() invalid cidr: couldn't parse address in network: invalid IP address syntax", + ), + ( + "10.0.0.0/33", + vec![1], + "CIDR_subnets() invalid cidr: invalid length for network: Network length 33 is too long for Ipv4 (maximum: 32)", + ), + ( + "2001:db8:1:2:3:4:5:7/129", + vec![1], + "CIDR_subnets() invalid cidr: invalid length for network: Network length 129 is too long for Ipv6 (maximum: 128)", + ), + ( + "0.0.0.0/256", + vec![1], + "CIDR_subnets() invalid cidr: couldn't parse length in network: number too large to fit in target type", + ), + ( + "::/256", + vec![1], + "CIDR_subnets() invalid cidr: couldn't parse length in network: number too large to fit in target type", + ), + ( + "10.0.0.0/8/8", + vec![1], + "CIDR_subnets() invalid cidr: couldn't parse address in network: invalid IP address syntax", + ), + ( + "2001:db8::/56/56", + vec![1], + "CIDR_subnets() invalid cidr: couldn't parse address in network: invalid IP address syntax", + ), + ( + "0.0.0.0/-1", + vec![1], + "CIDR_subnets() invalid cidr: couldn't parse length in network: invalid digit found in string", + ), + ( + "::/-1", + vec![1], + "CIDR_subnets() invalid cidr: couldn't parse length in network: invalid digit found in string", + ), + ( + "10.128.0.0/8", + vec![1], + "CIDR_subnets() invalid cidr: host part of address was not zero", + ), + ( + "2001:db8::/16", + vec![1], + "CIDR_subnets() invalid cidr: host part of address was not zero", + ), + ( + "10.1.2.3/31", + vec![1], + "CIDR_subnets() invalid cidr: host part of address was not zero", + ), + ( + "2001:db8:1:2:3:4:5:7/127", + vec![1], + "CIDR_subnets() invalid cidr: host part of address was not zero", + ), + ( + "10.0.0.0/8", + vec![3, 2, -1], + "CIDR_subnets() invalid additional_bits: cannot be negative", + ), + ( + "10.0.0.0/8", + vec![3, 2, 25], + "CIDR_subnets() invalid additional_bits: would extend network length to 33 bits, which is too long for IPv4", + ), + ( + "2001:db8::/32", + vec![3, 2, 64], + "CIDR_subnets() invalid additional_bits: cannot extend more than 63 bits", + ), + ( + "2001:db8::/66", + vec![3, 2, 63], + "CIDR_subnets() invalid additional_bits: would extend network length to 129 bits, which is too long for IPv6", + ), + ( + "10.0.0.0/8", + vec![1, 1, 1], + "CIDR_subnets() not enough remaining address space for a subnet with a prefix of 9 bits after 10.128.0.0/9", + ), + ( + "2001:db8::/126", + vec![1, 1, 1], + "CIDR_subnets() not enough remaining address space for a subnet with a prefix of 127 bits after 2001:db8::2/127", + ), + ]; + for (cidr, additional_bits, expect_error) in cases.iter() { + assert_panic(expect_error, || { + let additional_bits_valueref = additional_bits + .iter() + .map(|x| ValueRef::int(*x)) + .collect::>(); + let mut ctx = Context::new(); + let args = ValueRef::list(Some(&[ + &ValueRef::str(cidr), + &ValueRef::list(Some(&additional_bits_valueref.iter().collect::>())), + ])) + .into_raw(&mut ctx); + + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_CIDR_subnets(ctx.into_raw(), args, kwargs); + }); + } + std::panic::set_hook(prev_hook); + } + + #[test] + #[allow(non_snake_case)] + fn test_CIDR_host() { + let cases = [ + ("0.0.0.0/0", 0i64, "0.0.0.0"), + ("0.0.0.0/0", 1, "0.0.0.1"), + ("0.0.0.0/0", -1, "255.255.255.255"), + ("0.0.0.0/0", 256, "0.0.1.0"), + ("0.0.0.0/0", -256, "255.255.255.0"), + ("0.0.0.0/0", 4294967295, "255.255.255.255"), + ("0.0.0.0/0", -4294967296, "0.0.0.0"), + ("10.0.0.0/8", 11, "10.0.0.11"), + ("10.0.0.0/8", 16777215, "10.255.255.255"), + ("10.0.0.0/8", -1, "10.255.255.255"), + ("255.1.2.254/31", 1, "255.1.2.255"), + ("255.255.255.254/31", 1, "255.255.255.255"), + ("255.255.255.255/32", 0, "255.255.255.255"), + ("255.255.255.255/32", -1, "255.255.255.255"), + ("::/0", 0, "::"), + ("::/0", 1, "::1"), + ("::/0", 16, "::10"), + ("::/0", -1, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), + ("::/0", 9223372036854775807, "::7fff:ffff:ffff:ffff"), + ("::/0", -9223372036854775808, "ffff:ffff:ffff:ffff:8000::"), + ( + "2001:db8:0:2:8000::/65", + 9223372036854775807, + "2001:db8:0:2:ffff:ffff:ffff:ffff", + ), + ( + "2001:db8:0:2:8000::/65", + -9223372036854775808, + "2001:db8:0:2:8000::", + ), + ( + "ffff:ffff:ffff:ffff:8000::/65", + 9223372036854775807, + "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", + ), + ("2001:db8::/56", 5, "2001:db8::5"), + ("2001:db8:1:2:3:4:5:fffe/127", 1, "2001:db8:1:2:3:4:5:ffff"), + ("2001:db8:1:2:3:4:5:fffe/127", -1, "2001:db8:1:2:3:4:5:ffff"), + ("2001:db8:1:2:3:4:5:7/128", 0, "2001:db8:1:2:3:4:5:7"), + ("2001:db8:1:2:3:4:5:7/128", -1, "2001:db8:1:2:3:4:5:7"), + ]; + let mut ctx = Context::default(); + for (cidr, host_num, expected) in cases.iter() { + unsafe { + let actual = &*kcl_net_CIDR_host( + &mut ctx, + &ValueRef::list(Some(&[&ValueRef::str(cidr), &ValueRef::int(*host_num)])), + &ValueRef::dict(None), + ); + assert_eq!( + &ValueRef::str(expected), + actual, + "{} {} positional", + cidr, + host_num + ); + } + unsafe { + let actual = &*kcl_net_CIDR_host( + &mut ctx, + &ValueRef::list(None), + &ValueRef::dict(Some(&[ + ("cidr", &ValueRef::str(cidr)), + ("host_num", &ValueRef::int(*host_num)), + ])), + ); + assert_eq!( + &ValueRef::str(expected), + actual, + "{} {} named", + cidr, + host_num + ); + } + } + } + + #[test] + #[allow(non_snake_case)] + fn test_CIDR_host_invalid() { + let prev_hook = std::panic::take_hook(); + // Disable print panic info in stderr. + std::panic::set_hook(Box::new(|_| {})); + assert_panic( + "CIDR_host() missing 2 required positional arguments: 'cidr' and 'host_num'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_CIDR_host(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "CIDR_host() missing 2 required positional arguments: 'cidr' and 'host_num'", + || { + let mut ctx = Context::new(); + let args = + ValueRef::list(Some(&[&ValueRef::str("10.1.2.3/32")])).into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_CIDR_host(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "CIDR_host() missing 2 required positional arguments: 'cidr' and 'host_num'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = ValueRef::dict(Some(&[("cidr", &ValueRef::str("10.1.2.3/32"))])) + .into_raw(&mut ctx); + kcl_net_CIDR_host(ctx.into_raw(), args, kwargs); + }, + ); + assert_panic( + "CIDR_host() missing 2 required positional arguments: 'cidr' and 'host_num'", + || { + let mut ctx = Context::new(); + let args = ValueRef::list(None).into_raw(&mut ctx); + let kwargs = + ValueRef::dict(Some(&[("host_num", &ValueRef::int(1))])).into_raw(&mut ctx); + kcl_net_CIDR_host(ctx.into_raw(), args, kwargs); + }, + ); + let cases = [ + ( + "10.0.0/8", + 0i64, + "CIDR_host() invalid cidr: couldn't parse address in network: invalid IP address syntax", + ), + ( + "10.0.0.0/33", + 0, + "CIDR_host() invalid cidr: invalid length for network: Network length 33 is too long for Ipv4 (maximum: 32)", + ), + ( + "2001:db8:1:2:3:4:5:7/129", + 0, + "CIDR_host() invalid cidr: invalid length for network: Network length 129 is too long for Ipv6 (maximum: 128)", + ), + ( + "0.0.0.0/256", + 0, + "CIDR_host() invalid cidr: couldn't parse length in network: number too large to fit in target type", + ), + ( + "::/256", + 0, + "CIDR_host() invalid cidr: couldn't parse length in network: number too large to fit in target type", + ), + ( + "10.0.0.0/8/8", + 0, + "CIDR_host() invalid cidr: couldn't parse address in network: invalid IP address syntax", + ), + ( + "2001:db8::/56/56", + 0, + "CIDR_host() invalid cidr: couldn't parse address in network: invalid IP address syntax", + ), + ( + "0.0.0.0/-1", + 0, + "CIDR_host() invalid cidr: couldn't parse length in network: invalid digit found in string", + ), + ( + "::/-1", + 0, + "CIDR_host() invalid cidr: couldn't parse length in network: invalid digit found in string", + ), + ( + "10.128.0.0/8", + 0, + "CIDR_host() invalid cidr: host part of address was not zero", + ), + ( + "2001:db8::/16", + 0, + "CIDR_host() invalid cidr: host part of address was not zero", + ), + ( + "10.1.2.3/31", + 0, + "CIDR_host() invalid cidr: host part of address was not zero", + ), + ( + "2001:db8:1:2:3:4:5:7/127", + 0, + "CIDR_host() invalid cidr: host part of address was not zero", + ), + ( + "10.0.0.0/24", + 256, + "CIDR_host() prefix of 24 does not accommodate a host numbered 256", + ), + ( + "10.0.0.0/24", + -257, + "CIDR_host() prefix of 24 does not accommodate a host numbered -257", + ), + ( + "10.0.0.0/32", + 1, + "CIDR_host() prefix of 32 does not accommodate a host numbered 1", + ), + ( + "10.0.0.0/32", + -2, + "CIDR_host() prefix of 32 does not accommodate a host numbered -2", + ), + ( + "0.0.0.0/0", + 4294967296, + "CIDR_host() prefix of 0 does not accommodate a host numbered 4294967296", + ), + ( + "0.0.0.0/0", + -4294967297, + "CIDR_host() prefix of 0 does not accommodate a host numbered -4294967297", + ), + ( + "2001:db8::/120", + 256, + "CIDR_host() prefix of 120 does not accommodate a host numbered 256", + ), + ( + "2001:db8::/120", + -257, + "CIDR_host() prefix of 120 does not accommodate a host numbered -257", + ), + ( + "2001:db8::/66", + 9223372036854775807, + "CIDR_host() prefix of 66 does not accommodate a host numbered 9223372036854775807", + ), + ( + "2001:db8::/66", + -9223372036854775808, + "CIDR_host() prefix of 66 does not accommodate a host numbered -9223372036854775808", + ), + ]; + for (cidr, host_num, expect_error) in cases.iter() { + assert_panic(expect_error, || { + let mut ctx = Context::new(); + let args = ValueRef::list(Some(&[&ValueRef::str(cidr), &ValueRef::int(*host_num)])) + .into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_CIDR_host(ctx.into_raw(), args, kwargs); + }); + } + std::panic::set_hook(prev_hook); + } + + #[test] + #[allow(non_snake_case)] + fn test_CIDR_netmask() { + let cases = [ + ("0.0.0.0/0", "0.0.0.0"), + ("0.0.0.0/1", "128.0.0.0"), + ("0.0.0.0/24", "255.255.255.0"), + ("0.0.0.0/31", "255.255.255.254"), + ("0.0.0.0/32", "255.255.255.255"), + ("10.0.0.0/8", "255.0.0.0"), + ]; + let mut ctx = Context::default(); + for (cidr, expected) in cases.iter() { + unsafe { + let actual = &*kcl_net_CIDR_netmask( + &mut ctx, + &ValueRef::list(Some(&[&ValueRef::str(cidr)])), + &ValueRef::dict(None), + ); + assert_eq!(&ValueRef::str(expected), actual, "{} positional", cidr,); + } + unsafe { + let actual = &*kcl_net_CIDR_netmask( + &mut ctx, + &ValueRef::list(None), + &ValueRef::dict(Some(&[("cidr", &ValueRef::str(cidr))])), + ); + assert_eq!(&ValueRef::str(expected), actual, "{} named", cidr,); + } + } + } + + #[test] + #[allow(non_snake_case)] + fn test_CIDR_netmask_invalid() { + let prev_hook = std::panic::take_hook(); + // Disable print panic info in stderr. + std::panic::set_hook(Box::new(|_| {})); + let cases = [ + ( + "10.0.0/8", + "CIDR_netmask() invalid cidr: couldn't parse address in network: invalid IP address syntax", + ), + ( + "10.0.0.0/33", + "CIDR_netmask() invalid cidr: invalid length for network: Network length 33 is too long for Ipv4 (maximum: 32)", + ), + ( + "0.0.0.0/256", + "CIDR_netmask() invalid cidr: couldn't parse length in network: number too large to fit in target type", + ), + ( + "10.0.0.0/8/8", + "CIDR_netmask() invalid cidr: couldn't parse address in network: invalid IP address syntax", + ), + ( + "0.0.0.0/-1", + "CIDR_netmask() invalid cidr: couldn't parse length in network: invalid digit found in string", + ), + ( + "10.128.0.0/8", + "CIDR_netmask() invalid cidr: host part of address was not zero", + ), + ( + "10.1.2.3/31", + "CIDR_netmask() invalid cidr: host part of address was not zero", + ), + ( + "2001:db8::/64", + "CIDR_netmask() IPv6 addresses cannot have a netmask", + ), + ]; + for (cidr, expect_error) in cases.iter() { + assert_panic(expect_error, || { + let mut ctx = Context::new(); + let args = ValueRef::list(Some(&[&ValueRef::str(cidr)])).into_raw(&mut ctx); + let kwargs = ValueRef::dict(None).into_raw(&mut ctx); + kcl_net_CIDR_netmask(ctx.into_raw(), args, kwargs); + }); + } + std::panic::set_hook(prev_hook); + } + + #[test] + #[allow(non_snake_case)] + fn test_is_interface_local_multicast_IP() { + let cases = [("ff11::1", true), ("224.0.0.0", false)]; + let mut ctx = Context::default(); + for (ip, expect) in cases.iter() { + unsafe { + let actual = &*kcl_net_is_interface_local_multicast_IP( + &mut ctx, + &ValueRef::dict(None), + &ValueRef::dict(Some(&[("ip", &ValueRef::str(ip))])), + ); + assert_eq!(*expect, actual.as_bool(), "ip: {} ", ip); + } + } + } + + #[test] + #[allow(non_snake_case)] + fn test_is_link_local_multicast_IP() { + let cases = [("ff12::1", true)]; + let mut ctx = Context::default(); + for (ip, expect) in cases.iter() { + unsafe { + let actual = &*kcl_net_is_link_local_multicast_IP( + &mut ctx, + &ValueRef::dict(None), + &ValueRef::dict(Some(&[("ip", &ValueRef::str(ip))])), + ); + assert_eq!(*expect, actual.as_bool(), "ip: {} ", ip); + } + } + } + + #[test] + #[allow(non_snake_case)] + fn test_is_global_unicast_IP() { + let cases = [ + ("2607:f8b0:4005:802::200e", true), + ("64:ff9b::800:1", true), + ("220.181.108.89", true), + ]; + let mut ctx = Context::default(); + for (ip, expect) in cases.iter() { + unsafe { + let actual = &*kcl_net_is_global_unicast_IP( + &mut ctx, + &ValueRef::dict(None), + &ValueRef::dict(Some(&[("ip", &ValueRef::str(ip))])), + ); + assert_eq!(*expect, actual.as_bool(), "ip: {} ", ip); + } + } + } + + #[test] + #[allow(non_snake_case)] + fn test_is_multicast_IP() { + let cases = [("239.255.255.255", true)]; + let mut ctx = Context::default(); + for (ip, expect) in cases.iter() { + unsafe { + let actual = &*kcl_net_is_multicast_IP( + &mut ctx, + &ValueRef::dict(None), + &ValueRef::dict(Some(&[("ip", &ValueRef::str(ip))])), + ); + assert_eq!(*expect, actual.as_bool(), "ip: {} ", ip); + } + } + } + + #[test] + #[allow(non_snake_case)] + fn test_is_loopback_IP() { + let cases = [("127.0.0.1", true)]; + let mut ctx = Context::default(); + for (ip, expect) in cases.iter() { + unsafe { + let actual = &*kcl_net_is_loopback_IP( + &mut ctx, + &ValueRef::dict(None), + &ValueRef::dict(Some(&[("ip", &ValueRef::str(ip))])), + ); + assert_eq!(*expect, actual.as_bool(), "ip: {} ", ip); + } + } + } + + #[test] + #[allow(non_snake_case)] + fn test_is_link_local_unicast_IP() { + let cases = [("fe80::2012:1", true)]; + let mut ctx = Context::default(); + for (ip, expect) in cases.iter() { + unsafe { + let actual = &*kcl_net_is_link_local_unicast_IP( + &mut ctx, + &ValueRef::dict(None), + &ValueRef::dict(Some(&[("ip", &ValueRef::str(ip))])), + ); + assert_eq!(*expect, actual.as_bool(), "ip: {} ", ip); + } + } + } + + #[test] + #[allow(non_snake_case)] + fn test_is_unspecified_IP() { + let cases = [("0.0.0.0", true)]; + let mut ctx = Context::default(); + for (ip, expect) in cases.iter() { + unsafe { + let actual = &*kcl_net_is_unspecified_IP( + &mut ctx, + &ValueRef::dict(None), + &ValueRef::dict(Some(&[("ip", &ValueRef::str(ip))])), + ); + assert_eq!(*expect, actual.as_bool(), "ip: {}", ip); + } + } + } +} diff --git a/crates/runtime/src/panic/mod.rs b/crates/runtime/src/panic/mod.rs new file mode 100644 index 000000000..35342d7f1 --- /dev/null +++ b/crates/runtime/src/panic/mod.rs @@ -0,0 +1,123 @@ +use std::{any::Any, mem::transmute_copy, os::raw::c_char}; + +use std::cell::UnsafeCell; +use std::panic::AssertUnwindSafe; +use std::panic::RefUnwindSafe; +use std::panic::UnwindSafe; +use std::panic::catch_unwind; + +use crate::*; + +/// Executes the provided function and catches any potential runtime errors. +/// Returns undefined if execution is successful, otherwise returns an error +/// message in case of a runtime panic. +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_runtime_catch( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(func) = get_call_arg(args, kwargs, 0, Some("func")) { + let func = func.as_function(); + if ctx.cfg.debug_mode { + ctx.backtrace + .push(BacktraceFrame::from_panic_info(&ctx.panic_info)); + ctx.panic_info.kcl_func = func.name.clone(); + } + let now_meta_info = ctx.panic_info.clone(); + let fn_ptr = func.fn_ptr; + let wrapper = UnsafeWrapper::new(|| { + let args = ValueRef::list(None).into_raw(ctx); + let kwargs = ValueRef::dict(None).into_raw(ctx); + unsafe { + let call_fn: SchemaTypeFunc = transmute_copy(&fn_ptr); + // Call schema constructor twice + if func.is_external { + let name = format!("{}\0", func.name); + kcl_plugin_invoke(ctx, name.as_ptr() as *const c_char, args, kwargs) + } else { + call_fn(ctx, args, kwargs) + }; + }; + }); + let result = catch_unwind(AssertUnwindSafe(|| unsafe { + (wrapper.get())(); + })); + if ctx.cfg.debug_mode { + ctx.backtrace.pop(); + } + ctx.panic_info = now_meta_info; + return match result { + Ok(_) => ValueRef::undefined(), + Err(err) => ValueRef::str(&err_to_str(err)), + } + .into_raw(ctx); + } + panic!("catch() takes exactly one argument (0 given)"); +} + +#[inline] +pub fn is_runtime_catch_function(ptr: u64) -> bool { + ptr == kcl_runtime_catch as *const () as u64 +} + +/// Convert an error to string. +pub fn err_to_str(err: Box) -> String { + if let Some(s) = err.downcast_ref::<&str>() { + s.to_string() + } else if let Some(s) = err.downcast_ref::<&String>() { + (*s).clone() + } else if let Some(s) = err.downcast_ref::() { + (*s).clone() + } else { + "".to_string() + } +} + +/// A wrapper struct that holds a value of type T inside an UnsafeCell. +/// UnsafeCell is the core primitive for interior mutability in Rust. +pub struct UnsafeWrapper { + value: UnsafeCell, +} + +impl UnsafeWrapper { + /// Creates a new instance of UnsafeWrapper with the provided value. + /// + /// # Arguments + /// + /// * `value` - The value to be wrapped inside an UnsafeCell. + /// + /// # Returns + /// + /// A new instance of UnsafeWrapper containing the provided value. + pub fn new(value: T) -> Self { + UnsafeWrapper { + value: UnsafeCell::new(value), + } + } + + /// Provides a mutable reference to the inner value. + /// + /// # Safety + /// + /// This is an unsafe function because obtaining multiple mutable references + /// can lead to undefined behavior. The caller must ensure that the returned + /// reference does not violate Rust's borrowing rules. + /// + /// # Returns + /// + /// A mutable reference to the inner value of type T. + pub unsafe fn get(&self) -> &mut T { + unsafe { &mut *self.value.get() } + } +} + +// Implementing the UnwindSafe and RefUnwindSafe traits for UnsafeWrapper +// to ensure it can be safely used across panic boundaries. +impl UnwindSafe for UnsafeWrapper {} +impl RefUnwindSafe for UnsafeWrapper {} diff --git a/crates/runtime/src/regex/mod.rs b/crates/runtime/src/regex/mod.rs new file mode 100644 index 000000000..6e86cd06e --- /dev/null +++ b/crates/runtime/src/regex/mod.rs @@ -0,0 +1,197 @@ +//! Copyright The KCL Authors. All rights reserved. + +extern crate fancy_regex; + +use crate::*; + +// match(string: str, pattern: str) -> bool: + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_regex_match( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(string) = get_call_arg_str(args, kwargs, 0, Some("string")) { + if let Some(pattern) = get_call_arg_str(args, kwargs, 1, Some("pattern")) { + let re = fancy_regex::Regex::new(pattern.as_ref()).unwrap(); + match re.is_match(string.as_ref()) { + Ok(ok) => { + if ok { + return kcl_value_Bool(ctx, 1); + } else { + return kcl_value_Bool(ctx, 0); + } + } + _ => return kcl_value_Bool(ctx, 0), + } + } + } + + panic!("match() missing 2 required positional arguments: 'string' and 'pattern'") +} + +// replace(string: str, pattern: str, replace: str, count: int = 0): + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_regex_replace( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + if let Some(string) = get_call_arg_str(args, kwargs, 0, Some("string")) { + if let Some(pattern) = get_call_arg_str(args, kwargs, 1, Some("pattern")) { + if let Some(replace) = get_call_arg_str(args, kwargs, 2, Some("replace")) { + let count = get_call_arg_int(args, kwargs, 3, Some("count")).unwrap_or_else(|| 0); + let re = fancy_regex::Regex::new(pattern.as_ref()).unwrap(); + let s = re.replacen(string.as_ref(), count as usize, replace.as_ref() as &str); + return ValueRef::str(&s).into_raw(ctx); + } + panic!("replace() missing the required positional argument: 'replace'"); + } + panic!("replace() missing the required positional argument: 'pattern'"); + } + panic!("replace() missing 3 required positional arguments: 'string', 'pattern', and 'replace"); +} + +// compile(pattern: str) -> bool: + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_regex_compile( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(pattern) = get_call_arg_str(args, kwargs, 0, Some("pattern")) { + match fancy_regex::Regex::new(pattern.as_ref()) { + Ok(_) => return kcl_value_Bool(ctx, 1), + _ => return kcl_value_Bool(ctx, 0), + } + } + panic!("compile() missing the required positional argument: 'pattern'") +} + +// findall(string: str, pattern: str) -> [str]: + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_regex_findall( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + if let Some(string) = get_call_arg_str(args, kwargs, 0, Some("string")) { + if let Some(pattern) = get_call_arg_str(args, kwargs, 1, Some("pattern")) { + let mut list = ValueRef::list(None); + + for x in fancy_regex::Regex::new(pattern.as_ref()) + .unwrap() + .captures_iter(string.as_ref()) + .flatten() + { + let len = x.len(); + if len < 3 { + list.list_append(&ValueRef::str(x.get(0).unwrap().as_str())); + } else { + let mut sub_list = ValueRef::list(None); + for i in 1..len { + sub_list.list_append(&ValueRef::str(x.get(i).unwrap().as_str())); + } + list.list_append(&sub_list) + } + } + + return list.into_raw(ctx); + } + panic!("findall() missing the required positional argument: 'pattern'") + } + panic!("findall() missing 2 required positional arguments: 'string' and 'pattern'") +} + +// search(string: str, pattern: str): + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_regex_search( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(string) = get_call_arg_str(args, kwargs, 0, Some("string")) { + if let Some(pattern) = get_call_arg_str(args, kwargs, 1, Some("pattern")) { + let re = fancy_regex::Regex::new(pattern.as_ref()).unwrap(); + + if let Ok(Some(..)) = re.find(string.as_ref()) { + return kcl_value_Bool(ctx, 1); + } + return kcl_value_Bool(ctx, 0); + } + panic!("search() missing the required positional argument: 'pattern'"); + } + panic!("search() missing 2 required positional arguments: 'string' and 'pattern'"); +} + +// split(string: str, pattern: str, maxsplit: int = 0): + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_regex_split( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + if let Some(string) = get_call_arg_str(args, kwargs, 0, Some("string")) { + if let Some(pattern) = get_call_arg_str(args, kwargs, 1, Some("pattern")) { + let maxsplit = get_call_arg_int(args, kwargs, 2, Some("maxsplit")).unwrap_or_else(|| 0); + let mut list = ValueRef::list(None); + + let re = fancy_regex::Regex::new(pattern.as_ref()).unwrap(); + + let mut fields: Vec = Vec::new(); + let mut current_pos = 0; + loop { + let capture = re + .captures_from_pos(string.as_ref(), current_pos) + .map_or(None, |c| c); + if let Some(Some(cap)) = capture.map(|c| c.get(0)) { + fields.push(string[current_pos..cap.start()].to_string()); + if maxsplit > 0 && fields.len() >= (maxsplit as usize) { + break; + } + current_pos = cap.end(); + } else { + fields.push(string[current_pos..].to_string()); + break; + } + } + + for s in fields { + list.list_append(&ValueRef::str(s.as_ref())); + } + return list.into_raw(ctx); + } + panic!("split() missing the required positional argument: 'pattern'"); + } + panic!("split() missing 2 required positional arguments: 'string' and 'pattern'"); +} diff --git a/crates/runtime/src/stdlib/assert_api.rs b/crates/runtime/src/stdlib/assert_api.rs new file mode 100644 index 000000000..069462522 --- /dev/null +++ b/crates/runtime/src/stdlib/assert_api.rs @@ -0,0 +1,25 @@ +//! Copyright The KCL Authors. All rights reserved. + +use crate::*; + +#[allow(non_camel_case_types)] +type kcl_value_ref_t = ValueRef; + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_assert( + ctx: *mut kcl_context_t, + value: *const kcl_value_ref_t, + msg: *const kcl_value_ref_t, +) { + let value = ptr_as_ref(value); + let msg = ptr_as_ref(msg); + + if !value.is_truthy() { + let ctx = mut_ptr_as_ref(ctx); + ctx.set_err_type(&RuntimeErrorType::AssertionError); + + let msg = msg.as_str(); + panic!("{}", msg); + } +} diff --git a/kclvm/runtime/src/stdlib/builtin.rs b/crates/runtime/src/stdlib/builtin.rs similarity index 95% rename from kclvm/runtime/src/stdlib/builtin.rs rename to crates/runtime/src/stdlib/builtin.rs index 8ecf6506e..24b557899 100644 --- a/kclvm/runtime/src/stdlib/builtin.rs +++ b/crates/runtime/src/stdlib/builtin.rs @@ -22,7 +22,7 @@ impl Context { impl ValueRef { pub fn any_true(&self) -> bool { match &*self.rc.borrow() { - Value::list_value(ref list) => { + Value::list_value(list) => { for x in list.values.iter() { if x.is_truthy() { return true; @@ -30,7 +30,7 @@ impl ValueRef { } false } - Value::dict_value(ref dict) => { + Value::dict_value(dict) => { for (_k, x) in dict.values.iter() { if x.is_truthy() { return true; @@ -38,7 +38,7 @@ impl ValueRef { } false } - Value::schema_value(ref schema) => { + Value::schema_value(schema) => { for (_k, x) in schema.config.values.iter() { if x.is_truthy() { return true; @@ -52,7 +52,7 @@ impl ValueRef { pub fn all_true(&self) -> bool { match &*self.rc.borrow() { - Value::list_value(ref list) => { + Value::list_value(list) => { for x in list.values.iter() { if !x.is_truthy() { return false; @@ -60,7 +60,7 @@ impl ValueRef { } true } - Value::dict_value(ref dict) => { + Value::dict_value(dict) => { for (_k, x) in dict.values.iter() { if !x.is_truthy() { return false; @@ -68,7 +68,7 @@ impl ValueRef { } true } - Value::schema_value(ref schema) => { + Value::schema_value(schema) => { for (_k, x) in schema.config.values.iter() { if x.is_truthy() { return false; @@ -82,7 +82,7 @@ impl ValueRef { pub fn isunique(&self) -> bool { match &*self.rc.borrow() { - Value::list_value(ref list) => { + Value::list_value(list) => { let mut set: HashSet<&ValueRef> = HashSet::new(); for x in list.values.iter() { if set.contains(x) { @@ -153,9 +153,9 @@ impl ValueRef { let strict_range_check_i64 = ctx.cfg.debug_mode || !ctx.cfg.strict_range_check; match &*self.rc.borrow() { - Value::int_value(ref v) => ValueRef::int(*v), - Value::float_value(ref v) => ValueRef::int(*v as i64), - Value::unit_value(ref v, raw, unit) => { + Value::int_value(v) => ValueRef::int(*v), + Value::float_value(v) => ValueRef::int(*v as i64), + Value::unit_value(v, raw, unit) => { let v_i128 = crate::real_uint_value(*raw, unit); let int_32_overflow = strict_range_check_i32 && v_i128 != ((v_i128 as i32) as i128); let int_64_overflow = strict_range_check_i64 && v_i128 != ((v_i128 as i64) as i128); @@ -175,8 +175,8 @@ impl ValueRef { ValueRef::int(*v as i64) } - Value::bool_value(ref v) => ValueRef::int(*v as i64), - Value::str_value(ref v) => { + Value::bool_value(v) => ValueRef::int(*v as i64), + Value::str_value(v) => { let base = if let Some(v) = base { v.as_int() } else { 10 }; let number_str = to_quantity(v.as_str()).to_string(); let v: i64 = @@ -197,8 +197,8 @@ impl ValueRef { let strict_range_check_i64 = ctx.cfg.debug_mode || !ctx.cfg.strict_range_check; match &*self.rc.borrow() { - Value::int_value(ref v) => ValueRef::float(*v as f64), - Value::float_value(ref v) => { + Value::int_value(v) => ValueRef::float(*v as f64), + Value::float_value(v) => { let float32_overflow = strict_range_check_i32 && (*v as f32).is_infinite(); let float64_overflow = strict_range_check_i64 && (*v).is_infinite(); @@ -214,9 +214,9 @@ impl ValueRef { } ValueRef::float(*v) } - Value::unit_value(ref v, _, _) => ValueRef::float(*v), - Value::bool_value(ref v) => ValueRef::float((*v as i64) as f64), - Value::str_value(ref v) => { + Value::unit_value(v, _, _) => ValueRef::float(*v), + Value::bool_value(v) => ValueRef::float((*v as i64) as f64), + Value::str_value(v) => { let v: f64 = v.parse().unwrap_or_else(|_| { panic!("invalid literal for float() with base 10: '{self}'") }); @@ -248,7 +248,7 @@ impl ValueRef { pub fn filter(&self, filter: fn(&ValueRef, &ValueRef) -> bool) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref s) => { + Value::str_value(s) => { if s.is_empty() { panic!("arg is an empty str"); } @@ -263,7 +263,7 @@ impl ValueRef { } ValueRef::str(&result.to_string()) } - Value::list_value(ref list) => { + Value::list_value(list) => { if list.values.is_empty() { panic!("arg is an empty list"); } @@ -275,7 +275,7 @@ impl ValueRef { } result.clone() } - Value::dict_value(ref dict) => { + Value::dict_value(dict) => { if dict.values.is_empty() { panic!("arg is an empty dict"); } @@ -288,7 +288,7 @@ impl ValueRef { } ValueRef::str(result) } - Value::schema_value(ref schema) => { + Value::schema_value(schema) => { if schema.config.values.is_empty() { panic!("arg is an empty dict"); } @@ -458,7 +458,11 @@ pub fn dict(ctx: &mut Context, iterable: Option<&ValueRef>) -> ValueRef { _ => { let mut elem_iter = elem.iter(); if elem_iter.len != 2 { - panic!("dictionary update sequence element #{} has length {}; 2 is required",iter.pos-1,elem_iter.len); + panic!( + "dictionary update sequence element #{} has length {}; 2 is required", + iter.pos - 1, + elem_iter.len + ); } let k = elem_iter.next(val).unwrap().to_string(); let v = elem_iter.next(val).unwrap(); @@ -782,10 +786,14 @@ mod test_builtin { #[test] fn test_multiplyof() { - assert!(builtin::multiplyof(&ValueRef::int(25), &ValueRef::int(5)) - .cmp_equal(&ValueRef::bool(true))); - assert!(builtin::multiplyof(&ValueRef::int(25), &ValueRef::int(7)) - .cmp_equal(&ValueRef::bool(false))); + assert!( + builtin::multiplyof(&ValueRef::int(25), &ValueRef::int(5)) + .cmp_equal(&ValueRef::bool(true)) + ); + assert!( + builtin::multiplyof(&ValueRef::int(25), &ValueRef::int(7)) + .cmp_equal(&ValueRef::bool(false)) + ); } #[test] diff --git a/crates/runtime/src/stdlib/builtin_api.rs b/crates/runtime/src/stdlib/builtin_api.rs new file mode 100644 index 000000000..eeb06b435 --- /dev/null +++ b/crates/runtime/src/stdlib/builtin_api.rs @@ -0,0 +1,690 @@ +//! Copyright The KCL Authors. All rights reserved. +#![allow(clippy::missing_safety_doc)] + +use std::os::raw::c_char; + +use crate::*; + +#[allow(non_camel_case_types)] +type kcl_value_ref_t = ValueRef; + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_option_init( + ctx: *mut kcl_context_t, + key: *const c_char, + value: *const c_char, +) { + let ctx = mut_ptr_as_ref(ctx); + ctx.builtin_option_init(c2str(key), c2str(value)); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_option_reset( + ctx: *mut kcl_context_t, + _args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let ctx_ref = mut_ptr_as_ref(ctx); + + ctx_ref.builtin_option_reset(); + kcl_value_Undefined(ctx) +} + +// def kcl_option(name: str, *, type="", required=False, default=None, help="", file="", line=0) -> typing.Any: + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_option( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + fn _value_to_type(this: &ValueRef, typ: String) -> ValueRef { + if typ.is_empty() { + return this.clone(); + } + if typ == "bool" { + match &*this.rc.borrow() { + Value::bool_value(v) => { + return ValueRef::bool(*v); + } + Value::int_value(v) => { + return ValueRef::bool(*v != 0); + } + Value::float_value(v) => { + return ValueRef::bool(*v != 0.0); + } + Value::str_value(v) => { + return ValueRef::bool(v == "True" || v == "true"); + } + _ => { + return ValueRef::undefined(); + } + } + } + if typ == "int" { + match &*this.rc.borrow() { + Value::bool_value(v) => { + if *v { + return ValueRef::int(1); + } else { + return ValueRef::int(0); + } + } + Value::int_value(v) => { + return ValueRef::int(*v); + } + Value::float_value(v) => { + return ValueRef::int(*v as i64); + } + Value::str_value(v) => { + match v.parse::() { + Ok(n) => return ValueRef::int(n), + _ => panic!("cannot use '{v}' as type '{typ}'"), + }; + } + _ => { + let err_msg = format!("cannot use '{this}' as type '{typ}'"); + panic!("{}", err_msg); + } + } + } + if typ == "float" { + match &*this.rc.borrow() { + Value::bool_value(v) => { + if *v { + return ValueRef::float(1.0); + } else { + return ValueRef::float(0.0); + } + } + Value::int_value(v) => { + return ValueRef::float(*v as f64); + } + Value::float_value(v) => { + return ValueRef::float(*v); + } + Value::str_value(v) => { + match v.parse::() { + Ok(n) => return ValueRef::float(n), + _ => return ValueRef::float(0.0), + }; + } + _ => { + let err_msg = format!("cannot use '{this}' as type '{typ}'"); + panic!("{}", err_msg); + } + } + } + if typ == "str" { + match &*this.rc.borrow() { + Value::bool_value(v) => { + let s = format!("{}", v); + return ValueRef::str(s.as_ref()); + } + Value::int_value(v) => { + let s = format!("{}", v); + return ValueRef::str(s.as_ref()); + } + Value::float_value(v) => { + let s = format!("{}", v); + return ValueRef::str(s.as_ref()); + } + Value::str_value(v) => { + return ValueRef::str(v.as_ref()); + } + _ => { + let err_msg = format!("cannot use '{this}' as type '{typ}'"); + panic!("{}", err_msg); + } + } + } + if typ == "list" { + match &*this.rc.borrow() { + Value::list_value(_) => { + return this.clone(); + } + _ => { + let err_msg = format!("cannot use '{this}' as type '{typ}'"); + panic!("{}", err_msg); + } + } + } + if typ == "dict" { + match &*this.rc.borrow() { + Value::dict_value(_) => { + return this.clone(); + } + _ => { + let err_msg = format!("cannot use '{this}' as type '{typ}'"); + panic!("{}", err_msg); + } + } + } + + panic!("unknown type '{typ}'"); + } + + if let Some(arg0) = get_call_arg_str(args, kwargs, 0, Some("key")) { + if let Some(x) = ctx.option_values.get(&arg0) { + if let Some(kwarg_type) = get_call_arg_str(args, kwargs, 1, Some("type")) { + return _value_to_type(x, kwarg_type).into_raw(ctx); + } + return x.clone().into_raw(ctx); + } else if let Some(kwarg_default) = get_call_arg(args, kwargs, 3, Some("default")) { + if let Some(kwarg_type) = get_call_arg_str(args, kwargs, 1, Some("type")) { + return _value_to_type(&kwarg_default, kwarg_type).into_raw(ctx); + } + return kwarg_default.into_raw(ctx); + } + } + let required = get_call_arg_bool(args, kwargs, 2, Some("required")).unwrap_or_default(); + if required { + let name = + get_call_arg_str(args, kwargs, 0, Some("key")).unwrap_or_else(|| "?".to_string()); + panic!("option('{name}') must be initialized, try '-D {name}=?' argument"); + } + ValueRef::none().into_raw(ctx) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_print( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx_ref = mut_ptr_as_ref(ctx); + // args + let list = args.as_list_ref(); + let values: Vec = list.values.iter().map(|v| v.to_string()).collect(); + ctx_ref.log_message.push_str(&values.join(" ")); + let dict = kwargs.as_dict_ref(); + // kwargs: end + if let Some(c) = dict.values.get("end") { + ctx_ref.log_message.push_str(&format!("{c}")); + } else { + ctx_ref.log_message.push('\n'); + } + kcl_value_None(ctx) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_len( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg) = get_call_arg(args, kwargs, 0, Some("inval")) { + return kcl_value_Int(ctx, arg.len() as i64); + } + panic!("len() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_any_true( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("inval")) { + return kcl_value_Bool(ctx, arg0.any_true() as i8); + } + kcl_value_Bool(ctx, 0) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_isunique( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("inval")) { + return kcl_value_Bool(ctx, arg0.isunique() as i8); + } + kcl_value_Bool(ctx, 0) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_sorted( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("inval")) { + let reverse = get_call_arg(args, kwargs, 1, Some("reverse")); + return arg0.sorted(reverse.as_ref()).into_raw(ctx); + } + panic!("sorted() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_int( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("number")) { + let base = get_call_arg(args, kwargs, 1, Some("base")); + return arg0.convert_to_int(ctx, base.as_ref()).into_raw(ctx); + } + panic!("int() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_float( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("number")) { + return arg0.convert_to_float(ctx).into_raw(ctx); + } + panic!("float() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_bool( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("x")) { + return ValueRef::bool(arg0.is_truthy()).into_raw(ctx); + } + panic!("bool() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("x")) { + return ValueRef::str(&arg0.to_string()).into_raw(ctx); + } + ValueRef::str("").into_raw(ctx) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_max( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + if args.args_len() > 1 { + return args.max_value().into_raw(ctx); + } + if let Some(arg0) = args.arg_0() { + return arg0.max_value().into_raw(ctx); + } + panic!("max() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_min( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + if args.args_len() > 1 { + return args.min_value().into_raw(ctx); + } + if let Some(arg0) = args.arg_0() { + return arg0.min_value().into_raw(ctx); + } + panic!("min() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_multiplyof( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let (Some(arg0), Some(arg1)) = ( + get_call_arg(args, kwargs, 0, Some("a")), + get_call_arg(args, kwargs, 1, Some("b")), + ) { + return builtin::multiplyof(&arg0, &arg1).into_raw(ctx); + } + panic!( + "multiplyof() takes exactly two argument ({} given)", + args.args_len() + ); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_abs( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("inval")) { + return arg0.abs().into_raw(ctx); + } + panic!("abs() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] +pub unsafe extern "C-unwind" fn kcl_builtin_all_true( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("inval")) { + return kcl_value_Bool(ctx, arg0.all_true() as i8); + } + kcl_value_Bool(ctx, 0) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_hex( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("number")) { + return arg0.hex().into_raw(ctx); + } + panic!("hex() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_sum( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx_ref = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + match get_call_arg(args, kwargs, 0, Some("iterable")) { + Some(arg0) => match get_call_arg(args, kwargs, 1, Some("start")) { + Some(arg1) => arg0.sum(ctx_ref, &arg1).into_raw(ctx_ref), + _ => arg0.sum(ctx_ref, &ValueRef::int(0)).into_raw(ctx_ref), + }, + _ => kcl_value_Undefined(ctx), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_pow( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx_ref = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + match ( + get_call_arg(args, kwargs, 0, Some("x")), + get_call_arg(args, kwargs, 1, Some("y")), + ) { + (Some(arg0), Some(arg1)) => match get_call_arg(args, kwargs, 2, Some("z")) { + Some(arg2) => builtin::pow(&arg0, &arg1, &arg2).into_raw(ctx_ref), + _ => builtin::pow(&arg0, &arg1, &ValueRef::none()).into_raw(ctx_ref), + }, + _ => kcl_value_Undefined(ctx), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_round( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx_ref = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + match get_call_arg(args, kwargs, 0, Some("number")) { + Some(arg0) => match get_call_arg(args, kwargs, 1, Some("ndigits")) { + Some(arg1) => builtin::round(&arg0, &arg1).into_raw(ctx_ref), + _ => builtin::round(&arg0, &ValueRef::none()).into_raw(ctx_ref), + }, + _ => kcl_value_Undefined(ctx), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_zip( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + args.zip().into_raw(ctx) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_list( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if args.args_len() > 0 { + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("x")) { + return builtin::list(Some(&arg0)).into_raw(ctx); + } + panic!("invalid arguments in list() function"); + } else { + builtin::list(None).into_raw(ctx) + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_dict( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let mut dict = ValueRef::dict(None); + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("x")) { + let v = builtin::dict(ctx, Some(&arg0)); + dict.dict_insert_unpack(ctx, &v); + } + let v = builtin::dict(ctx, Some(kwargs)); + dict.dict_insert_unpack(ctx, &v); + dict.into_raw(ctx) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_typeof( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("x")) { + if let Some(full_name) = get_call_arg(args, kwargs, 1, Some("full_name")) { + return builtin::type_of(&arg0, &full_name).into_raw(ctx); + } + return builtin::type_of(&arg0, &ValueRef::bool(false)).into_raw(ctx); + } + + panic!("typeof() missing 1 required positional argument: 'x'"); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_bin( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("number")) { + return arg0.bin().into_raw(ctx); + } + panic!("bin() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_oct( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("number")) { + return arg0.oct().into_raw(ctx); + } + panic!("oct() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_ord( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("c")) { + return arg0.ord().into_raw(ctx); + } + panic!("ord() takes exactly one argument (0 given)"); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_range( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let ctx_ref = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + match get_call_arg(args, kwargs, 0, Some("start")) { + Some(arg0) => match get_call_arg(args, kwargs, 1, Some("stop")) { + Some(arg1) => match get_call_arg(args, kwargs, 2, Some("step")) { + Some(arg2) => builtin::range(&arg0, &arg1, &arg2).into_raw(ctx_ref), + _ => builtin::range(&arg0, &arg1, &ValueRef::int(1)).into_raw(ctx_ref), + }, + _ => builtin::range(&ValueRef::int(0), &arg0, &ValueRef::int(1)).into_raw(ctx_ref), + }, + _ => kcl_value_Undefined(ctx), + } +} + +/// Return `True` if the input value is `None` or `Undefined`, and `False` otherwise. +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_isnullish( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("inval")) { + return ValueRef::bool(arg0.is_none_or_undefined()).into_raw(ctx); + } + panic!("is_nullable() takes exactly one argument (0 given)"); +} diff --git a/kclvm/runtime/src/stdlib/mod.rs b/crates/runtime/src/stdlib/mod.rs similarity index 100% rename from kclvm/runtime/src/stdlib/mod.rs rename to crates/runtime/src/stdlib/mod.rs diff --git a/crates/runtime/src/stdlib/plugin.rs b/crates/runtime/src/stdlib/plugin.rs new file mode 100644 index 000000000..af785b009 --- /dev/null +++ b/crates/runtime/src/stdlib/plugin.rs @@ -0,0 +1,125 @@ +//! Copyright The KCL Authors. All rights reserved. + +#![allow(clippy::missing_safety_doc)] + +use crate::*; + +use lazy_static::lazy_static; +use std::os::raw::c_char; +use std::sync::Mutex; + +lazy_static! { + static ref PLUGIN_HANDLER_FN_PTR: Mutex< + Option< + extern "C-unwind" fn( + method: *const c_char, + args_json: *const c_char, + kwargs_json: *const c_char, + ) -> *const c_char, + >, + > = Mutex::new(None); +} + +/// KCL plugin module prefix +pub const PLUGIN_MODULE_PREFIX: &str = "kcl_plugin."; + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_plugin_init( + fn_ptr: extern "C-unwind" fn( + method: *const c_char, + args_json: *const c_char, + kwargs_json: *const c_char, + ) -> *const c_char, +) { + let mut fn_ptr_guard = PLUGIN_HANDLER_FN_PTR.lock().unwrap(); + *fn_ptr_guard = Some(fn_ptr); +} + +// import kcl_plugin.hello +// hello.say_hello() +// +// => return kcl_plugin_invoke("kcl_plugin.hello.say_hello", args, kwargs) + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_plugin_invoke( + ctx: *mut kcl_context_t, + method: *const c_char, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx_ref = mut_ptr_as_ref(ctx); + let method_ref = c2str(method); + let plugin_short_method = match method_ref.strip_prefix(PLUGIN_MODULE_PREFIX) { + Some(s) => s, + None => method_ref, + }; + if let Some(func) = ctx_ref.plugin_functions.get(plugin_short_method) { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let result = func(ctx_ref, args, kwargs); + return result.unwrap().into_raw(ctx_ref); + } + let args_s = unsafe { kcl_value_to_json_value_with_null(ctx, args) }; + let kwargs_s = unsafe { kcl_value_to_json_value_with_null(ctx, kwargs) }; + + let args_json = unsafe { kcl_value_Str_ptr(args_s) }; + let kwargs_json = unsafe { kcl_value_Str_ptr(kwargs_s) }; + + let result_json = kcl_plugin_invoke_json(method, args_json, kwargs_json); + + // Value delete by context. + // kcl_value_delete(args_s); + // kcl_value_delete(kwargs_s); + + let ptr = unsafe { kcl_value_from_json(ctx, result_json) }; + { + if let Some(msg) = ptr_as_ref(ptr).dict_get_value("__kcl_PanicInfo__") { + let ctx = mut_ptr_as_ref(ctx); + ctx.set_err_type(&RuntimeErrorType::EvaluationError); + + panic!("{}", msg.as_str()); + } + } + + ptr +} + +#[cfg(not(target_arch = "wasm32"))] +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_plugin_invoke_json( + method: *const c_char, + args: *const c_char, + kwargs: *const c_char, +) -> *const c_char { + let fn_ptr_guard = PLUGIN_HANDLER_FN_PTR.lock().unwrap(); + if let Some(fn_ptr) = *fn_ptr_guard { + fn_ptr(method, args, kwargs) + } else { + panic!("plugin handler is nil, should call kcl_plugin_init at first"); + } +} + +#[cfg(target_arch = "wasm32")] +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_plugin_invoke_json( + method: *const c_char, + args: *const c_char, + kwargs: *const c_char, +) -> *const c_char { + unsafe { + return kcl_plugin_invoke_json_wasm(method, args, kwargs); + } +} + +#[cfg(target_arch = "wasm32")] +unsafe extern "C-unwind" { + pub fn kcl_plugin_invoke_json_wasm( + method: *const c_char, + args: *const c_char, + kwargs: *const c_char, + ) -> *const c_char; +} diff --git a/crates/runtime/src/template/mod.rs b/crates/runtime/src/template/mod.rs new file mode 100644 index 000000000..ac0df75c5 --- /dev/null +++ b/crates/runtime/src/template/mod.rs @@ -0,0 +1,55 @@ +use std::collections::HashMap; + +use crate::*; +use handlebars::{Handlebars, html_escape}; + +/// Applies a parsed template to the specified data object and +/// returns the string output. +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_template_execute( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(template) = get_call_arg_str(args, kwargs, 0, Some("template")) { + let mut handlebars = Handlebars::new(); + handlebars + .register_template_string("template", template) + .expect("register template failed"); + let data = get_call_arg(args, kwargs, 1, Some("data")).unwrap_or(ValueRef::dict(None)); + let data: HashMap = HashMap::from_iter( + data.as_dict_ref() + .values + .iter() + .map(|(k, v)| (k.to_string(), v.build_json(&Default::default()))), + ); + let result = handlebars + .render("template", &data) + .expect("render template failed"); + return ValueRef::str(&result).into_raw(ctx); + } + panic!("execute() takes exactly one argument (0 given)"); +} + +/// Replaces the characters `&"<>` with the equivalent html / xml entities. +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_template_html_escape( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(data) = get_call_arg_str(args, kwargs, 0, Some("data")) { + return ValueRef::str(&html_escape(&data)).into_raw(ctx); + } + panic!("html_escape() takes exactly one argument (0 given)"); +} diff --git a/kclvm/runtime/src/types/constructor.rs b/crates/runtime/src/types/constructor.rs similarity index 98% rename from kclvm/runtime/src/types/constructor.rs rename to crates/runtime/src/types/constructor.rs index 4b703a43f..a664dcd8f 100644 --- a/kclvm/runtime/src/types/constructor.rs +++ b/crates/runtime/src/types/constructor.rs @@ -1,6 +1,6 @@ //! Copyright The KCL Authors. All rights reserved. -use kclvm_primitives::IndexMap; +use kcl_primitives::IndexMap; use crate::*; diff --git a/kclvm/runtime/src/types/kind.rs b/crates/runtime/src/types/kind.rs similarity index 100% rename from kclvm/runtime/src/types/kind.rs rename to crates/runtime/src/types/kind.rs diff --git a/kclvm/runtime/src/types/mod.rs b/crates/runtime/src/types/mod.rs similarity index 100% rename from kclvm/runtime/src/types/mod.rs rename to crates/runtime/src/types/mod.rs diff --git a/crates/runtime/src/types/str.rs b/crates/runtime/src/types/str.rs new file mode 100644 index 000000000..2f42b776f --- /dev/null +++ b/crates/runtime/src/types/str.rs @@ -0,0 +1,34 @@ +//! Copyright The KCL Authors. All rights reserved. + +use crate::*; + +impl Type { + pub fn type_str(&self) -> String { + match self { + Type::Any => KCL_TYPE_ANY.to_string(), + Type::Bool => BUILTIN_TYPE_BOOL.to_string(), + Type::BoolLit(v) => format!("{BUILTIN_TYPE_BOOL}({v})"), + Type::Int => BUILTIN_TYPE_INT.to_string(), + Type::IntLit(v) => format!("{BUILTIN_TYPE_INT}({v})"), + Type::Float => BUILTIN_TYPE_FLOAT.to_string(), + Type::FloatLit(v) => format!("{BUILTIN_TYPE_FLOAT}({v})"), + Type::Str => BUILTIN_TYPE_STR.to_string(), + Type::StrLit(v) => format!("{BUILTIN_TYPE_STR}({v})"), + Type::List(v) => format!("[{}]", v.elem_type.type_str()), + Type::Dict(v) => { + format!("{{{}:{}}}", v.key_type.type_str(), v.elem_type.type_str()) + } + Type::Union(v) => match v.elem_types.len() { + 0 => String::new(), + 1 => v.elem_types[0].type_str(), + _ => { + let mut types = Vec::new(); + let _ = v.elem_types.iter().map(|e| types.push(e.type_str())); + types.join(" | ") + } + }, + Type::Schema(v) => v.name.to_string(), + Type::Func(_v) => "func".to_string(), + } + } +} diff --git a/kclvm/runtime/src/unification/mod.rs b/crates/runtime/src/unification/mod.rs similarity index 100% rename from kclvm/runtime/src/unification/mod.rs rename to crates/runtime/src/unification/mod.rs diff --git a/kclvm/runtime/src/unification/subsume.rs b/crates/runtime/src/unification/subsume.rs similarity index 100% rename from kclvm/runtime/src/unification/subsume.rs rename to crates/runtime/src/unification/subsume.rs diff --git a/crates/runtime/src/units/mod.rs b/crates/runtime/src/units/mod.rs new file mode 100644 index 000000000..d54ede360 --- /dev/null +++ b/crates/runtime/src/units/mod.rs @@ -0,0 +1,443 @@ +//! Copyright The KCL Authors. All rights reserved. + +use crate::*; + +#[derive(Debug)] +#[allow(non_camel_case_types, dead_code)] +enum to_unit_suffix { + n, + u, + m, + k, + K, + M, + G, + T, + P, + Ki, + Mi, + Gi, + Ti, + Pi, +} + +use phf::{Map, phf_map}; + +pub const IEC_SUFFIX: &str = "i"; +pub const EXPONENTS: Map<&str, i8> = phf_map! { + "n" => -3, + "u" => -2, + "m" => -1, + "k" => 1, + "K" => 1, + "M" => 2, + "G" => 3, + "T" => 4, + "P" => 5, +}; +pub const INVALID_UNITS: [&str; 4] = ["ni", "ui", "mi", "ki"]; + +// to_n(num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_units_to_n( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(num) = get_call_arg(args, kwargs, 0, Some("num")) { + let num = num.convert_to_float(ctx).as_float(); + let s = to_unit(num, to_unit_suffix::n); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + panic!("to_n() missing 1 required positional argument: 'num'"); +} + +// to_u(num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_units_to_u( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(num) = get_call_arg(args, kwargs, 0, Some("num")) { + let num = num.convert_to_float(ctx).as_float(); + let s = to_unit(num, to_unit_suffix::u); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + panic!("to_u() missing 1 required positional argument: 'num'"); +} + +// to_m(num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_units_to_m( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(num) = get_call_arg(args, kwargs, 0, Some("num")) { + let num = num.convert_to_float(ctx).as_float(); + let s = to_unit(num, to_unit_suffix::m); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + panic!("to_m() missing 1 required positional argument: 'num'"); +} + +// to_K(num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_units_to_K( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { + let s = to_unit(num, to_unit_suffix::K); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + panic!("to_K() missing 1 required positional argument: 'num'"); +} + +// to_M(num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_units_to_M( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { + let s = to_unit(num, to_unit_suffix::M); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + panic!("to_M() missing 1 required positional argument: 'num'"); +} + +// to_G(num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_units_to_G( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { + let s = to_unit(num, to_unit_suffix::G); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + panic!("to_G() missing 1 required positional argument: 'num'"); +} + +// to_T(num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_units_to_T( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { + let s = to_unit(num, to_unit_suffix::T); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + panic!("to_T() missing 1 required positional argument: 'num'"); +} + +// to_P(num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_units_to_P( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { + let s = to_unit(num, to_unit_suffix::P); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + panic!("to_P() missing 1 required positional argument: 'num'"); +} + +// to_Ki(num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_units_to_Ki( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { + let s = to_unit(num, to_unit_suffix::Ki); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + panic!("to_Ki() missing 1 required positional argument: 'num'"); +} + +// to_Mi(num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_units_to_Mi( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { + let s = to_unit(num, to_unit_suffix::Mi); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + panic!("to_Mi() missing 1 required positional argument: 'num'"); +} + +// to_Gi(num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_units_to_Gi( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { + let s = to_unit(num, to_unit_suffix::Gi); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + panic!("to_Gi() missing 1 required positional argument: 'num'"); +} + +// to_Ti(num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_units_to_Ti( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { + let s = to_unit(num, to_unit_suffix::Ti); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + panic!("to_Ti() missing 1 required positional argument: 'num'"); +} + +// to_Pi(num: int) -> str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_units_to_Pi( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { + let s = to_unit(num, to_unit_suffix::Pi); + return ValueRef::str(s.as_ref()).into_raw(ctx); + } + panic!("to_Pi() missing 1 required positional argument: 'num'"); +} + +fn to_unit(num: f64, suffix: to_unit_suffix) -> String { + match suffix { + to_unit_suffix::n => format!("{}{:?}", (num / 1e-09) as i64, suffix), + to_unit_suffix::u => format!("{}{:?}", (num / 1e-06) as i64, suffix), + to_unit_suffix::m => format!("{}{:?}", (num / 0.001) as i64, suffix), + to_unit_suffix::k => format!("{}{:?}", (num / 1_000.0) as i64, suffix), + to_unit_suffix::K => format!("{}{:?}", (num / 1_000.0) as i64, suffix), + to_unit_suffix::M => format!("{}{:?}", (num / 1_000_000.0) as i64, suffix), + to_unit_suffix::G => format!("{}{:?}", (num / 1_000_000_000.0) as i64, suffix), + to_unit_suffix::T => format!("{}{:?}", (num / 1_000_000_000_000.0) as i64, suffix), + to_unit_suffix::P => format!("{}{:?}", (num / 1_000_000_000_000_000.0) as i64, suffix), + to_unit_suffix::Ki => format!("{}{:?}", (num / 1024.0) as i64, suffix), + to_unit_suffix::Mi => format!("{}{:?}", (num / (1024.0 * 1024.0)) as i64, suffix), + to_unit_suffix::Gi => format!("{}{:?}", (num / (1024.0 * 1024.0 * 1024.0)) as i64, suffix), + to_unit_suffix::Ti => format!( + "{}{:?}", + (num / (1024.0 * 1024.0 * 1024.0 * 1024.0)) as i64, + suffix + ), + to_unit_suffix::Pi => format!( + "{}{:?}", + (num / (1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0)) as i64, + suffix + ), + } +} + +/// Parse and return number based on input quantity. +/// +/// Supported suffixes: +/// SI: n | u | m | k | K | M | G | T | P +/// IEC: Ki | Mi | Gi | Ti | Pi +/// +/// Input: +/// quantity: &str. +/// +/// Returns: +/// result: i64 +pub fn to_quantity(quantity: &str) -> i64 { + let quantity_len = quantity.len(); + let mut number = quantity; + let mut suffix: Option<&str> = None; + if quantity_len >= 2 && &quantity[quantity_len - 1..] == IEC_SUFFIX { + if EXPONENTS.contains_key(&quantity[quantity_len - 2..quantity_len - 1]) { + number = &quantity[..quantity_len - 2]; + suffix = Some(&quantity[quantity_len - 2..]); + } + } else if quantity_len >= 1 && EXPONENTS.contains_key(&quantity[quantity_len - 1..]) { + number = &quantity[..quantity_len - 1]; + suffix = Some(&quantity[quantity_len - 1..]); + } + if number.is_empty() { + panic!("number can't be empty") + } + let number: i64 = number.parse().unwrap(); + if suffix.is_none() { + return number; + } + let suffix = suffix.unwrap(); + validate_unit(&suffix[0..1]); + let base: i64 = if suffix.ends_with(IEC_SUFFIX) { + 1024 + } else { + 1000 + }; + let exponent = EXPONENTS.get(&suffix[0..1]).unwrap(); + number * (base.pow(*exponent as u32)) +} + +/// Calculate number based on value and binary suffix. +/// +/// Supported suffixes: +/// SI: n | u | m | k | K | M | G | T | P +/// IEC: Ki | Mi | Gi | Ti | Pi +/// +/// Input: +/// value: int. +/// suffix: str. +/// +/// Returns: +/// int +/// +/// Raises: +/// ValueError on invalid or unknown suffix +pub fn cal_num(value: i64, unit: &str) -> f64 { + validate_unit(unit); + let mut base: f64 = 1000.0; + let mut unit = unit; + if unit.len() > 1 && &unit[1..2] == IEC_SUFFIX { + base = 1024.0; + unit = &unit[0..1]; + } + let exponent = EXPONENTS + .get(unit) + .unwrap_or_else(|| panic!("invalid unit {unit}")); + value as f64 * base.powf(*exponent as f64) +} + +#[inline] +pub fn real_uint_value(raw: i64, unit: &str) -> i128 { + (raw as i128) * (u64_unit_value(unit) as i128) +} + +/// Validate the unit is valid +pub fn validate_unit(unit: &str) { + if unit.is_empty() || unit.len() > 2 { + panic!("Invalid suffix {unit}"); + } + if INVALID_UNITS.contains(&unit) { + panic!("Invalid suffix {unit}"); + } + if !EXPONENTS.contains_key(&unit[..1]) { + panic!("Invalid suffix {unit}"); + } +} + +pub fn f64_unit_value(unit: &str) -> f64 { + match unit { + "n" => 1e-09, + "u" => 1e-06, + "m" => 0.001, + _ => 1_f64, + } +} + +pub fn u64_unit_value(unit: &str) -> u64 { + match unit { + "k" => 1_000, + "K" => 1_000, + "M" => 1_000_000, + "G" => 1_000_000_000, + "T" => 1_000_000_000_000, + "P" => 1_000_000_000_000_000, + "Ki" => 1024, + "Mi" => 1048576, + "Gi" => 1073741824, + "Ti" => 1099511627776, + "Pi" => 1125899906842624, + _ => 1_u64, + } +} diff --git a/crates/runtime/src/value/api.rs b/crates/runtime/src/value/api.rs new file mode 100644 index 000000000..c9487ba57 --- /dev/null +++ b/crates/runtime/src/value/api.rs @@ -0,0 +1,3123 @@ +//! Copyright The KCL Authors. All rights reserved. +#![allow(clippy::missing_safety_doc)] + +use std::{mem::transmute_copy, os::raw::c_char}; + +use kcl_primitives::IndexMap; + +use crate::*; + +use self::{eval::LazyEvalScope, walker::walk_value_mut}; + +#[allow(non_camel_case_types)] +pub type kcl_context_t = Context; + +#[allow(non_camel_case_types)] +pub type kcl_eval_scope_t = LazyEvalScope; + +#[allow(non_camel_case_types)] +pub type kcl_decorator_value_t = DecoratorValue; + +#[allow(non_camel_case_types)] +pub type kcl_kind_t = Kind; + +#[allow(non_camel_case_types)] +pub type kcl_type_t = Type; + +#[allow(non_camel_case_types)] +pub type kcl_value_ref_t = ValueRef; + +#[allow(non_camel_case_types)] +pub type kcl_iterator_t = ValueIterator; + +#[allow(non_camel_case_types)] +pub type kcl_char_t = c_char; + +#[allow(non_camel_case_types)] +pub type kcl_size_t = i32; + +#[allow(non_camel_case_types)] +type kcl_bool_t = i8; + +#[allow(non_camel_case_types)] +pub type kcl_int_t = i64; + +#[allow(non_camel_case_types)] +pub type kcl_float_t = f64; + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_context_set_import_names( + p: *mut kcl_context_t, + import_names: *const kcl_value_ref_t, +) { + let p = mut_ptr_as_ref(p); + let import_names = ptr_as_ref(import_names); + + let import_names_dict = import_names.as_dict_ref(); + for (k, v) in &import_names_dict.values { + let mut map = IndexMap::default(); + let v_dict = v.as_dict_ref(); + for (pkgname, pkgpath) in &v_dict.values { + map.insert(pkgname.to_string(), pkgpath.as_str()); + } + p.import_names.insert(k.to_string(), map); + } +} + +// ---------------------------------------------------------------------------- +// values: new +// ---------------------------------------------------------------------------- + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_value_Undefined(ctx: *mut kcl_context_t) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + new_mut_ptr(ctx, ValueRef::undefined()) +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_value_None(ctx: *mut kcl_context_t) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + new_mut_ptr(ctx, ValueRef::none()) +} + +// bool/int/float/str + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_value_True(ctx: *mut kcl_context_t) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + kcl_value_Bool(ctx, 1) +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_value_False(ctx: *mut kcl_context_t) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + kcl_value_Bool(ctx, 0) +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_value_Bool( + ctx: *mut kcl_context_t, + v: kcl_bool_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + if v != 0 { + ValueRef::bool(true).into_raw(ctx) + } else { + ValueRef::bool(false).into_raw(ctx) + } +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_value_Int( + ctx: *mut kcl_context_t, + v: kcl_int_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + new_mut_ptr(ctx, ValueRef::int(v)) +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_value_Float( + ctx: *mut kcl_context_t, + v: kcl_float_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + new_mut_ptr(ctx, ValueRef::float(v)) +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_value_Unit( + ctx: *mut kcl_context_t, + v: kcl_float_t, + raw: kcl_int_t, + unit: *const kcl_char_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let unit = c2str(unit); + new_mut_ptr(ctx, ValueRef::unit(v, raw, unit)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_Str( + ctx: *mut kcl_context_t, + v: *const kcl_char_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + unsafe { + if v.is_null() || *v == '\0' as c_char { + return new_mut_ptr(ctx, ValueRef::str("")); + } + } + return new_mut_ptr(ctx, ValueRef::str(c2str(v))); +} + +// list/dict/schema + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_value_List(ctx: *mut kcl_context_t) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + new_mut_ptr(ctx, ValueRef::list(None)) +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_value_List6( + ctx: *mut kcl_context_t, + v1: *const kcl_value_ref_t, + v2: *const kcl_value_ref_t, + v3: *const kcl_value_ref_t, + v4: *const kcl_value_ref_t, + v5: *const kcl_value_ref_t, + v6: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let values: Vec<&ValueRef> = vec![v1, v2, v3, v4, v5, v6] + .into_iter() + .map(ptr_as_ref) + .collect(); + new_mut_ptr(ctx, ValueRef::list(Some(values.as_slice()))) +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_value_List10( + ctx: *mut kcl_context_t, + v1: *const kcl_value_ref_t, + v2: *const kcl_value_ref_t, + v3: *const kcl_value_ref_t, + v4: *const kcl_value_ref_t, + v5: *const kcl_value_ref_t, + v6: *const kcl_value_ref_t, + v7: *const kcl_value_ref_t, + v8: *const kcl_value_ref_t, + v9: *const kcl_value_ref_t, + v10: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let values: Vec<&ValueRef> = vec![v1, v2, v3, v4, v5, v6, v7, v8, v9, v10] + .into_iter() + .map(ptr_as_ref) + .collect(); + new_mut_ptr(ctx, ValueRef::list(Some(values.as_slice()))) +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_value_Dict(ctx: *mut kcl_context_t) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + new_mut_ptr(ctx, ValueRef::dict(None)) +} + +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_value_Schema(ctx: *mut kcl_context_t) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + new_mut_ptr(ctx, ValueRef::schema()) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_schema_with_config( + ctx: *mut kcl_context_t, + schema_dict: *const kcl_value_ref_t, + config: *const kcl_value_ref_t, + config_meta: *const kcl_value_ref_t, + name: *const kcl_char_t, + pkgpath: *const kcl_char_t, + is_sub_schema: *const kcl_value_ref_t, + record_instance: *const kcl_value_ref_t, + instance_pkgpath: *const kcl_value_ref_t, + optional_mapping: *const kcl_value_ref_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let schema_dict = ptr_as_ref(schema_dict); + // Config dict + let config = ptr_as_ref(config); + let config_meta = ptr_as_ref(config_meta); + let config_keys: Vec = config.as_dict_ref().values.keys().cloned().collect(); + // Schema meta + let name = c2str(name); + let pkgpath = c2str(pkgpath); + let runtime_type = schema_runtime_type(name, pkgpath); + let is_sub_schema = ptr_as_ref(is_sub_schema); + let record_instance = ptr_as_ref(record_instance); + let instance_pkgpath = ptr_as_ref(instance_pkgpath); + let instance_pkgpath = instance_pkgpath.as_str(); + let optional_mapping = ptr_as_ref(optional_mapping); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + if record_instance.is_truthy() { + // Record schema instance in the context + if !ctx.instances.contains_key(&runtime_type) { + ctx.instances + .insert(runtime_type.clone(), IndexMap::default()); + } + let pkg_instance_map = ctx.instances.get_mut(&runtime_type).unwrap(); + if !pkg_instance_map.contains_key(&instance_pkgpath) { + pkg_instance_map.insert(instance_pkgpath.clone(), vec![]); + } + pkg_instance_map + .get_mut(&instance_pkgpath) + .unwrap() + .push(schema_dict.clone()); + } + // Dict to schema + if is_sub_schema.is_truthy() { + let schema = schema_dict.dict_to_schema( + name, + pkgpath, + &config_keys, + config_meta, + optional_mapping, + Some(args.clone()), + Some(kwargs.clone()), + ); + schema.into_raw(ctx) + } else { + schema_dict.clone().into_raw(ctx) + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_Function( + ctx: *mut kcl_context_t, + fn_ptr: *const u64, + closure: *const kcl_value_ref_t, + name: *const kcl_char_t, + is_external: kcl_bool_t, +) -> *mut kcl_value_ref_t { + let ctx = mut_ptr_as_ref(ctx); + let closure = ptr_as_ref(closure); + let name = c2str(name); + new_mut_ptr( + ctx, + ValueRef::func( + fn_ptr as u64, + 0, + closure.clone(), + name, + "", + is_external != 0, + ), + ) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_Function_using_ptr( + ctx: *mut kcl_context_t, + fn_ptr: *const u64, + name: *const kcl_char_t, +) -> *mut kcl_value_ref_t { + let name = c2str(name); + let ctx = mut_ptr_as_ref(ctx); + new_mut_ptr( + ctx, + ValueRef::func(fn_ptr as u64, 0, ValueRef::none(), name, "", false), + ) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_schema_function( + ctx: *mut kcl_context_t, + fn_ptr: *const u64, + check_fn_ptr: *const u64, + attr_map: *const kcl_value_ref_t, + tpe: *const kcl_char_t, +) -> *mut kcl_value_ref_t { + // Schema function closures + let ctx = mut_ptr_as_ref(ctx); + let is_sub_schema = ValueRef::bool(false); + let config_meta = ValueRef::dict(None); + let config = ValueRef::dict(None); + let schema = ValueRef::dict(None); + let optional_mapping = ValueRef::dict(None); + let cal_map = ValueRef::dict(None); + let backtrack_level_map = ValueRef::dict(None); + let backtrack_cache = ValueRef::dict(None); + let record_instance = ValueRef::bool(false); + let instance_pkgpath = ValueRef::str(MAIN_PKG_PATH); + + let mut schema_args = ValueRef::list(None); + { + let mut schema_args_ref = schema_args.as_list_mut_ref(); + schema_args_ref.values.push(is_sub_schema); + schema_args_ref.values.push(config_meta); + schema_args_ref.values.push(config); + schema_args_ref.values.push(schema); + schema_args_ref.values.push(optional_mapping); + schema_args_ref.values.push(cal_map); + schema_args_ref.values.push(backtrack_level_map); + schema_args_ref.values.push(backtrack_cache); + schema_args_ref.values.push(record_instance); + schema_args_ref.values.push(instance_pkgpath); + } + let runtime_type = c2str(tpe); + let schema_func = ValueRef::func( + fn_ptr as u64, + check_fn_ptr as u64, + schema_args, + "", + runtime_type, + false, + ); + let attr_map = ptr_as_ref(attr_map); + let attr_dict = attr_map.as_dict_ref(); + let schema_ty = SchemaType { + name: runtime_type.to_string(), + attrs: attr_dict + .values + .iter() + .map(|(k, _)| (k.to_string(), Type::any())) // TODO: store schema attr type in the runtime. + .collect(), + has_index_signature: attr_dict.attr_map.contains_key(CAL_MAP_INDEX_SIGNATURE), + func: schema_func.clone(), + }; + ctx.all_schemas.insert(runtime_type.to_string(), schema_ty); + new_mut_ptr(ctx, schema_func) +} + +// ---------------------------------------------------------------------------- +// values: json +// ---------------------------------------------------------------------------- + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_from_json( + ctx: *mut kcl_context_t, + s: *const kcl_char_t, +) -> *mut kcl_value_ref_t { + let ctx_ref = mut_ptr_as_ref(ctx); + if s.is_null() { + return kcl_value_Undefined(ctx); + } + match ValueRef::from_json(ctx_ref, c2str(s)) { + Ok(x) => x.into_raw(ctx_ref), + _ => kcl_value_Undefined(ctx), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_to_json_value( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + if p.is_null() { + return unsafe { kcl_value_Str(ctx, std::ptr::null()) }; + } + + let p = ptr_as_ref(p); + let s = p.to_json_string(); + let ctx = mut_ptr_as_ref(ctx); + new_mut_ptr(ctx, ValueRef::str(s.as_ref())) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_to_json_value_with_null( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + if p.is_null() { + return unsafe { kcl_value_Str(ctx, std::ptr::null()) }; + } + + let p = ptr_as_ref(p); + let s = p.to_json_string_with_null(); + let ctx = mut_ptr_as_ref(ctx); + new_mut_ptr(ctx, ValueRef::str(s.as_ref())) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_plan_to_json( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let p = ptr_as_ref(p); + let ctx: &mut Context = mut_ptr_as_ref(ctx); + let value = match ctx.buffer.custom_manifests_output.clone() { + Some(output) => ValueRef::from_yaml_stream(ctx, &output).unwrap(), + None => p.clone(), + }; + let (json_string, yaml_string) = value.plan(ctx); + ctx.json_result = json_string.clone(); + ctx.yaml_result = yaml_string.clone(); + new_mut_ptr(ctx, ValueRef::str(&json_string)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_plan_to_yaml( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let p = ptr_as_ref(p); + let ctx = mut_ptr_as_ref(ctx); + let value = match ctx.buffer.custom_manifests_output.clone() { + Some(output) => ValueRef::from_yaml_stream(ctx, &output).unwrap(), + None => p.clone(), + }; + let (json_string, yaml_string) = value.plan(ctx); + ctx.json_result = json_string.clone(); + ctx.yaml_result = yaml_string.clone(); + new_mut_ptr(ctx, ValueRef::str(&yaml_string)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_to_yaml_value( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + if p.is_null() { + return unsafe { kcl_value_Str(ctx, std::ptr::null()) }; + } + let ctx = mut_ptr_as_ref(ctx); + let p = ptr_as_ref(p); + let s = p.to_yaml_string(); + + new_mut_ptr(ctx, ValueRef::str(s.as_ref())) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_to_str_value( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + if p.is_null() { + return unsafe { kcl_value_Str(ctx, std::ptr::null()) }; + } + + let ctx = mut_ptr_as_ref(ctx); + let p = ptr_as_ref(p); + let s = p.to_string(); + + new_mut_ptr(ctx, ValueRef::str(s.as_ref())) +} + +// ---------------------------------------------------------------------------- +// values: value pointer +// ---------------------------------------------------------------------------- + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_Str_ptr(p: *const kcl_value_ref_t) -> *const kcl_char_t { + let p = ptr_as_ref(p); + match &*p.rc.borrow() { + Value::str_value(v) => v.as_ptr() as *const c_char, + _ => std::ptr::null(), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_function_ptr(p: *const kcl_value_ref_t) -> *const u64 { + let p = ptr_as_ref(p); + match &*p.rc.borrow() { + Value::func_value(v) => v.fn_ptr as *const u64, + _ => std::ptr::null::(), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_check_function_ptr( + p: *const kcl_value_ref_t, +) -> *const u64 { + let p = ptr_as_ref(p); + match &*p.rc.borrow() { + Value::func_value(v) => v.check_fn_ptr as *const u64, + _ => std::ptr::null::(), + } +} + +#[unsafe(no_mangle)] +pub unsafe fn kcl_value_function_invoke( + p: *const kcl_value_ref_t, + ctx: *mut kcl_context_t, + args: *mut kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, + pkgpath: *const kcl_char_t, + is_in_schema: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let func = ptr_as_ref(p); + let args_ref = mut_ptr_as_ref(args); + if func.is_func() { + let func = func.as_function(); + let fn_ptr = func.fn_ptr; + let closure = &func.closure; + let is_schema = !func.runtime_type.is_empty(); + let ctx_ref = mut_ptr_as_ref(ctx); + if ctx_ref.cfg.debug_mode { + ctx_ref + .backtrace + .push(BacktraceFrame::from_panic_info(&ctx_ref.panic_info)); + ctx_ref.panic_info.kcl_func = func.name.clone(); + } + let now_meta_info = ctx_ref.panic_info.clone(); + unsafe { + let call_fn: SchemaTypeFunc = transmute_copy(&fn_ptr); + // Call schema constructor twice + let value = if is_schema { + let pkgpath = c2str(pkgpath); + // Schema function closure + let mut args_new = args_ref.deep_copy(); + let mut closure_new = closure.deep_copy(); + let config_meta_index: isize = 1; + let cal_map_index: isize = 5; + let record_instance_index = closure.len() - 2; + let instance_pkgpath_index = closure.len() - 1; + args_ref.list_append_unpack(closure); + let args = args_ref.clone().into_raw(ctx_ref); + call_fn(ctx, args, kwargs); + let cal_map = closure.list_get(cal_map_index).unwrap(); + // is sub schema + closure_new.list_set(0, &ValueRef::bool(true)); + // record instance + closure_new.list_set(record_instance_index, &ValueRef::bool(true)); + // instance pkgpath + closure_new.list_set(instance_pkgpath_index, &ValueRef::str(pkgpath)); + // cal map + closure_new.list_set(cal_map_index as usize, &cal_map); + // config meta + let config_meta = schema_config_meta( + &ctx_ref.panic_info.kcl_file, + ctx_ref.panic_info.kcl_line as u64, + ctx_ref.panic_info.kcl_col as u64, + ); + closure_new.list_set(config_meta_index as usize, &config_meta); + args_new.list_append_unpack(&closure_new); + call_fn(ctx, args_new.into_raw(ctx_ref), kwargs) + // Normal kcl function, call directly + } else if func.is_external { + let name = format!("{}\0", func.name); + kcl_plugin_invoke(ctx, name.as_ptr() as *const c_char, args, kwargs) + } else { + args_ref.list_append_unpack_first(closure); + let args = args_ref.clone().into_raw(ctx_ref); + call_fn(ctx, args, kwargs) + }; + let is_in_schema = ptr_as_ref(is_in_schema); + if is_schema && !is_in_schema.is_truthy() { + let schema_value = ptr_as_ref(value); + schema_value.schema_check_attr_optional(ctx_ref, true); + } + if ctx_ref.cfg.debug_mode { + ctx_ref.backtrace.pop(); + } + ctx_ref.panic_info = now_meta_info; + return value; + }; + } + kcl_value_Undefined(ctx) +} + +// ---------------------------------------------------------------------------- +// values: method +// ---------------------------------------------------------------------------- + +// clone + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_deep_copy( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let p = ptr_as_ref(p); + let ctx = mut_ptr_as_ref(ctx); + p.deep_copy().into_raw(ctx) +} + +// delete + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_delete(p: *mut kcl_value_ref_t) { + if p.is_null() { + return; + } + let val = ptr_as_ref(p); + val.from_raw(); + free_mut_ptr(p); +} + +// ---------------------------------------------------------------------------- +// values: iterator +// ---------------------------------------------------------------------------- + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_iter(p: *const kcl_value_ref_t) -> *mut kcl_iterator_t { + let p = ptr_as_ref(p); + let iter = ValueIterator::from_value(p); + Box::into_raw(Box::new(iter)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_iterator_delete(p: *mut kcl_iterator_t) { + free_mut_ptr(p); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_iterator_is_end(p: *mut kcl_iterator_t) -> kcl_bool_t { + let p = ptr_as_ref(p); + p.is_end() as kcl_bool_t +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_iterator_cur_key( + p: *mut kcl_iterator_t, +) -> *const kcl_value_ref_t { + let p = ptr_as_ref(p); + match p.key() { + Some(x) => x, + None => std::ptr::null(), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_iterator_cur_value( + p: *mut kcl_iterator_t, +) -> *const kcl_value_ref_t { + let p = mut_ptr_as_ref(p); + match p.value() { + Some(x) => x, + None => std::ptr::null(), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_iterator_next_value( + p: *mut kcl_iterator_t, + host: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let p = mut_ptr_as_ref(p); + let host = ptr_as_ref(host); + + match p.next(host) { + Some(x) => x, + None => std::ptr::null(), + } +} + +// ---------------------------------------------------------------------------- +// values: list +// ---------------------------------------------------------------------------- + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_len(p: *const kcl_value_ref_t) -> kcl_size_t { + let p = ptr_as_ref(p); + p.len() as kcl_size_t +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_resize(p: *mut kcl_value_ref_t, newsize: kcl_size_t) { + let p = mut_ptr_as_ref(p); + p.list_resize(newsize as usize); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_clear(p: *mut kcl_value_ref_t) { + let p = mut_ptr_as_ref(p); + p.list_clear(); +} + +/// Return number of occurrences of the list value. +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_count( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, + item: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let p = ptr_as_ref(p); + let item = ptr_as_ref(item); + let count = p.list_count(item); + let ctx = mut_ptr_as_ref(ctx); + let count_value = ValueRef::int(count as i64); + count_value.into_raw(ctx) +} + +/// Return first index of the list value. Panic if the value is not present. +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_find( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, + item: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let p = ptr_as_ref(p); + let item = ptr_as_ref(item); + let index = p.list_find(item); + let index_value = ValueRef::int(index as i64); + let ctx = mut_ptr_as_ref(ctx); + index_value.into_raw(ctx) +} + +/// Insert object before index of the list value. +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_insert( + p: *mut kcl_value_ref_t, + index: *const kcl_value_ref_t, + value: *const kcl_value_ref_t, +) { + let p = mut_ptr_as_ref(p); + let index = ptr_as_ref(index); + let value = ptr_as_ref(value); + p.list_insert_at(index.as_int() as usize, value); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_get( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, + i: kcl_size_t, +) -> *const kcl_value_ref_t { + let p = ptr_as_ref(p); + let ctx = mut_ptr_as_ref(ctx); + match p.list_get(i as isize) { + Some(x) => x.into_raw(ctx), + _ => panic!("list index out of range"), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_get_option( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, + i: kcl_size_t, +) -> *const kcl_value_ref_t { + let p = ptr_as_ref(p); + + match p.list_get_option(i as isize) { + Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), + _ => kcl_value_Undefined(ctx), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_set( + p: *mut kcl_value_ref_t, + i: kcl_size_t, + v: *const kcl_value_ref_t, +) { + let p = mut_ptr_as_ref(p); + let v = ptr_as_ref(v); + p.list_set(i as usize, v); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_pop( + ctx: *mut kcl_context_t, + p: *mut kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let p = mut_ptr_as_ref(p); + + match p.list_pop() { + Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), + _ => kcl_value_Undefined(ctx), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_pop_first( + ctx: *mut kcl_context_t, + p: *mut kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let p = mut_ptr_as_ref(p); + match p.list_pop_first() { + Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), + _ => kcl_value_Undefined(ctx), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_append( + p: *mut kcl_value_ref_t, + v: *const kcl_value_ref_t, +) { + let p = mut_ptr_as_ref(p); + let v = ptr_as_ref(v); + p.list_append(v); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_append_bool(p: *mut kcl_value_ref_t, v: kcl_bool_t) { + let p = mut_ptr_as_ref(p); + p.list_append(&ValueRef::bool(v != 0)); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_append_int(p: *mut kcl_value_ref_t, v: kcl_int_t) { + let p = mut_ptr_as_ref(p); + p.list_append(&ValueRef::int(v)); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_append_float(p: *mut kcl_value_ref_t, v: kcl_float_t) { + let p = mut_ptr_as_ref(p); + p.list_append(&ValueRef::float(v)); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_append_str(p: *mut kcl_value_ref_t, v: *const kcl_char_t) { + let p = mut_ptr_as_ref(p); + p.list_append(&ValueRef::str(c2str(v))); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_append_unpack( + p: *mut kcl_value_ref_t, + v: *const kcl_value_ref_t, +) { + let p = mut_ptr_as_ref(p); + let v = ptr_as_ref(v); + + if p.is_list() { + p.list_append_unpack(v); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_list_remove_at(p: *mut kcl_value_ref_t, i: kcl_size_t) { + let p = mut_ptr_as_ref(p); + p.list_remove_at(i as usize); +} + +// ---------------------------------------------------------------------------- +// values: dict +// ---------------------------------------------------------------------------- + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_len(p: *const kcl_value_ref_t) -> kcl_size_t { + let p = ptr_as_ref(p); + match &*p.rc.borrow() { + Value::dict_value(dict) => dict.values.len() as kcl_size_t, + _ => 0, + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_clear(p: *mut kcl_value_ref_t) { + let p = mut_ptr_as_ref(p); + p.dict_clear(); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_is_override_attr( + p: *const kcl_value_ref_t, + key: *const kcl_char_t, +) -> kcl_bool_t { + let p = ptr_as_ref(p); + let key = c2str(key); + let is_override_op = matches!( + p.dict_get_attr_operator(key), + Some(ConfigEntryOperationKind::Override) + ); + let without_index = matches!(p.dict_get_insert_index(key), Some(-1) | None); + (is_override_op && without_index) as kcl_bool_t +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_get( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, + key: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let p = ptr_as_ref(p); + let key = ptr_as_ref(key); + + match p.dict_get(key) { + Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), + None => kcl_value_Undefined(ctx), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_has_value( + p: *const kcl_value_ref_t, + key: *const kcl_char_t, +) -> kcl_bool_t { + let p = ptr_as_ref(p); + let key = c2str(key); + match p.dict_get_value(key) { + Some(_) => true as kcl_bool_t, + None => false as kcl_bool_t, + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_get_value( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, + key: *const kcl_char_t, +) -> *const kcl_value_ref_t { + let p = ptr_as_ref(p); + let key = c2str(key); + match p.dict_get_value(key) { + Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), + None => kcl_value_Undefined(ctx), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_get_entry( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, + key: *const kcl_char_t, +) -> *const kcl_value_ref_t { + let p = ptr_as_ref(p); + let key = c2str(key); + match p.dict_get_entry(key) { + Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), + None => kcl_value_Undefined(ctx), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_get_value_by_path( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, + path: *const kcl_char_t, +) -> *const kcl_value_ref_t { + let p = ptr_as_ref(p); + let path = c2str(path); + match p.get_by_path(path) { + Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), + None => kcl_value_Undefined(ctx), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_set_value( + ctx: *mut kcl_context_t, + p: *mut kcl_value_ref_t, + key: *const kcl_char_t, + val: *const kcl_value_ref_t, +) { + let p = mut_ptr_as_ref(p); + let key = c2str(key); + let val = ptr_as_ref(val); + if p.is_config() { + p.dict_update_key_value(key, val.clone()); + if p.is_schema() { + let schema: ValueRef; + { + let schema_value = p.as_schema(); + let mut config_keys = schema_value.config_keys.clone(); + config_keys.push(key.to_string()); + schema = resolve_schema(mut_ptr_as_ref(ctx), p, &config_keys); + } + p.schema_update_with_schema(&schema); + } + } else { + panic!( + "failed to update the dict. An iterable of key-value pairs was expected, but got {}. Check if the syntax for updating the dictionary with the attribute '{}' is correct", + p.type_str(), + key + ); + } +} + +#[unsafe(no_mangle)] + +/// Return all dict keys. +pub unsafe extern "C-unwind" fn kcl_dict_keys( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let p = ptr_as_ref(p); + let r = p.dict_keys(); + r.into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +/// Return all dict values. +pub unsafe extern "C-unwind" fn kcl_dict_values( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let p = ptr_as_ref(p); + let r = p.dict_values(); + r.into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_insert( + ctx: *mut kcl_context_t, + p: *mut kcl_value_ref_t, + key: *const kcl_char_t, + v: *const kcl_value_ref_t, + op: kcl_size_t, + insert_index: kcl_size_t, + has_insert_index: kcl_bool_t, +) { + let p = mut_ptr_as_ref(p); + let v = ptr_as_ref(v); + p.dict_insert( + mut_ptr_as_ref(ctx), + c2str(key), + v, + ConfigEntryOperationKind::from_i32(op), + if has_insert_index != 0 { + Some(insert_index) + } else { + None + }, + ); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_merge( + ctx: *mut kcl_context_t, + p: *mut kcl_value_ref_t, + key: *const kcl_char_t, + v: *const kcl_value_ref_t, + op: kcl_size_t, + insert_index: kcl_size_t, + has_insert_index: kcl_bool_t, +) { + let p = mut_ptr_as_ref(p); + let v = ptr_as_ref(v); + let key = c2str(key); + let ctx = mut_ptr_as_ref(ctx); + let attr_map = { + match &*p.rc.borrow() { + Value::dict_value(dict) => dict.attr_map.clone(), + Value::schema_value(schema) => schema.config.attr_map.clone(), + _ => panic!("invalid object '{}' in attr_map", p.type_str()), + } + }; + if attr_map.contains_key(key) { + let v = type_pack_and_check(ctx, v, vec![attr_map.get(key).unwrap()], false); + p.dict_merge( + ctx, + key, + &v, + ConfigEntryOperationKind::from_i32(op), + if has_insert_index != 0 { + Some(insert_index) + } else { + None + }, + ); + } else { + p.dict_merge( + ctx, + key, + v, + ConfigEntryOperationKind::from_i32(op), + if has_insert_index != 0 { + Some(insert_index) + } else { + None + }, + ); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_insert_value( + ctx: *mut kcl_context_t, + p: *mut kcl_value_ref_t, + key: *const kcl_value_ref_t, + v: *const kcl_value_ref_t, + op: kcl_size_t, + insert_index: kcl_size_t, + has_insert_index: kcl_bool_t, +) { + let p = mut_ptr_as_ref(p); + let v = ptr_as_ref(v); + let key = ptr_as_ref(key); + let key = key.attr_str(); + p.dict_insert( + mut_ptr_as_ref(ctx), + key.as_str(), + v, + ConfigEntryOperationKind::from_i32(op), + if has_insert_index != 0 { + Some(insert_index) + } else { + None + }, + ); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_update_key_value( + p: *mut kcl_value_ref_t, + key: *const kcl_value_ref_t, + v: *const kcl_value_ref_t, +) { + let p = mut_ptr_as_ref(p); + let v = ptr_as_ref(v); + let key = ptr_as_ref(key); + let key = key.attr_str(); + p.dict_update_key_value(key.as_str(), v.clone()); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_safe_insert( + ctx: *mut kcl_context_t, + p: *mut kcl_value_ref_t, + key: *const kcl_char_t, + v: *const kcl_value_ref_t, + op: kcl_size_t, + insert_index: kcl_size_t, + has_insert_index: kcl_bool_t, +) { + if p.is_null() || key.is_null() || v.is_null() { + return; + } + unsafe { kcl_dict_insert(ctx, p, key, v, op, insert_index, has_insert_index) }; +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_insert_unpack( + ctx: *mut kcl_context_t, + p: *mut kcl_value_ref_t, + v: *const kcl_value_ref_t, +) { + let p = mut_ptr_as_ref(p); + let ctx = mut_ptr_as_ref(ctx); + let v = ptr_as_ref(v); + p.dict_insert_unpack(ctx, v); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_default_collection_insert_int_pointer( + p: *mut kcl_value_ref_t, + key: *const kcl_char_t, + ptr: *const u64, +) { + let p = mut_ptr_as_ref(p); + let key = c2str(key); + let ptr = ptr as i64; + if p.is_dict() { + let mut dict_ref_mut = p.as_dict_mut_ref(); + if !dict_ref_mut.values.contains_key(key) { + let value = ValueRef::list(None); + dict_ref_mut.values.insert(key.to_string(), value); + } + let values = dict_ref_mut.values.get_mut(key).unwrap(); + let value = ValueRef::int(ptr); + if !value.r#in(values) { + values.list_append(&value); + } + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_default_collection_insert_value( + p: *mut kcl_value_ref_t, + key: *const kcl_char_t, + value: *const kcl_value_ref_t, +) { + let p = mut_ptr_as_ref(p); + let key = c2str(key); + let value = ptr_as_ref(value); + if p.is_dict() { + let mut dict_ref_mut = p.as_dict_mut_ref(); + if !dict_ref_mut.values.contains_key(key) { + let value = ValueRef::list(None); + dict_ref_mut.values.insert(key.to_string(), value); + } + let values = dict_ref_mut.values.get_mut(key).unwrap(); + if !value.r#in(values) { + values.list_append(value); + } + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_remove(p: *mut kcl_value_ref_t, key: *const kcl_char_t) { + let p = mut_ptr_as_ref(p); + p.dict_remove(c2str(key)); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_dict_update( + p: *mut kcl_value_ref_t, + v: *const kcl_value_ref_t, +) { + let p = mut_ptr_as_ref(p); + let v = ptr_as_ref(v); + p.dict_update(v); +} + +// ---------------------------------------------------------------------------- +// values: arith +// ---------------------------------------------------------------------------- + +// is true + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_is_truthy(p: *const kcl_value_ref_t) -> kcl_bool_t { + let p = ptr_as_ref(p); + p.is_truthy() as kcl_bool_t +} + +// len + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_len(p: *const kcl_value_ref_t) -> kcl_size_t { + let p = ptr_as_ref(p); + p.len() as kcl_size_t +} + +// compare + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_cmp_equal_to( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + if a == b { + return kcl_value_Bool(ctx, 1); + } + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + ValueRef::bool(a.cmp_equal(b)).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_cmp_not_equal_to( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + if a == b { + return kcl_value_Bool(ctx, 0); + } + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + ValueRef::bool(!a.cmp_equal(b)).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_cmp_less_than( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + if a == b { + return kcl_value_Bool(ctx, 0); + } + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + ValueRef::bool(a.cmp_less_than(b)).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_cmp_less_than_or_equal( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + ValueRef::bool(a.cmp_less_than_or_equal(b)).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_cmp_greater_than( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + if a == b { + return kcl_value_Bool(ctx, 0); + } + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + ValueRef::bool(a.cmp_greater_than(b)).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_cmp_greater_than_or_equal( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + ValueRef::bool(a.cmp_greater_than_or_equal(b)).into_raw(mut_ptr_as_ref(ctx)) +} + +// is/in + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_is( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + if a == b { + return kcl_value_Bool(ctx, 1); + } + kcl_value_Bool(ctx, 0) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_is_not( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + if a == b { + return kcl_value_Bool(ctx, 0); + } + kcl_value_Bool(ctx, 1) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_in( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + ValueRef::bool(a.r#in(b)).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_not_in( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + ValueRef::bool(a.not_in(b)).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_as( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + let ty_str = b.as_str(); + let ctx = mut_ptr_as_ref(ctx); + let value = type_pack_and_check(ctx, a, vec![ty_str.as_str()], true); + value.into_raw(ctx) +} + +// unary-xxx + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_unary_plus( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + a.unary_plus().into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_unary_minus( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + a.unary_minus().into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_unary_not( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + a.unary_not().into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_unary_l_not( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + a.unary_l_not().into_raw(mut_ptr_as_ref(ctx)) +} + +// op-xxx + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_add( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + a.bin_add(ctx, b).into_raw(ctx) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_sub( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + a.bin_sub(ctx, b).into_raw(ctx) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_mul( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + a.bin_mul(ctx, b).into_raw(ctx) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_div( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + a.bin_div(b).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_mod( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + a.bin_mod(b).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_pow( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + a.bin_pow(ctx, b).into_raw(ctx) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_floor_div( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + a.bin_floor_div(b).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_bit_lshift( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + a.bin_bit_lshift(ctx, b).into_raw(ctx) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_bit_rshift( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + a.bin_bit_rshift(ctx, b).into_raw(ctx) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_bit_and( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + a.bin_bit_and(b).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_bit_xor( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + a.bin_bit_xor(b).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_bit_or( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + a.bin_bit_or(ctx, b).into_raw(ctx) +} + +// op-aug-xxx + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_aug_add( + ctx: *mut kcl_context_t, + a: *mut kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let a = mut_ptr_as_ref(a); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + return a.bin_aug_add(ctx, b) as *const kcl_value_ref_t; +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_aug_sub( + ctx: *mut kcl_context_t, + a: *mut kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let a = mut_ptr_as_ref(a); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + return a.bin_aug_sub(ctx, b) as *const kcl_value_ref_t; +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_aug_mul( + ctx: *mut kcl_context_t, + a: *mut kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let a = mut_ptr_as_ref(a); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + return a.bin_aug_mul(ctx, b); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_aug_div( + _ctx: *mut kcl_context_t, + a: *mut kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let a = mut_ptr_as_ref(a); + let b = ptr_as_ref(b); + return a.bin_aug_div(b) as *const kcl_value_ref_t; +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_aug_mod( + _ctx: *mut kcl_context_t, + a: *mut kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let a = mut_ptr_as_ref(a); + let b = ptr_as_ref(b); + return a.bin_aug_mod(b) as *const kcl_value_ref_t; +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_aug_pow( + ctx: *mut kcl_context_t, + a: *mut kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let a = mut_ptr_as_ref(a); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + return a.bin_aug_pow(ctx, b) as *const kcl_value_ref_t; +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_aug_floor_div( + _ctx: *mut kcl_context_t, + a: *mut kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let a = mut_ptr_as_ref(a); + let b = ptr_as_ref(b); + return a.bin_aug_floor_div(b) as *const kcl_value_ref_t; +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_aug_bit_lshift( + ctx: *mut kcl_context_t, + a: *mut kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let a = mut_ptr_as_ref(a); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + a.bin_aug_bit_lshift(ctx, b) as *const kcl_value_ref_t +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_aug_bit_rshift( + ctx: *mut kcl_context_t, + a: *mut kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let a = mut_ptr_as_ref(a); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + a.bin_aug_bit_rshift(ctx, b) as *const kcl_value_ref_t +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_aug_bit_and( + _ctx: *mut kcl_context_t, + a: *mut kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let a = mut_ptr_as_ref(a); + let b = ptr_as_ref(b); + a.bin_aug_bit_and(b) as *const kcl_value_ref_t +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_aug_bit_xor( + _ctx: *mut kcl_context_t, + a: *mut kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let a = mut_ptr_as_ref(a); + let b = ptr_as_ref(b); + a.bin_aug_bit_xor(b) as *const kcl_value_ref_t +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_op_aug_bit_or( + ctx: *mut kcl_context_t, + a: *mut kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let a = mut_ptr_as_ref(a); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + a.bin_aug_bit_or(ctx, b) as *const kcl_value_ref_t +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_union( + ctx: *mut kcl_context_t, + schema: *mut kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let a = mut_ptr_as_ref(schema); + let b = ptr_as_ref(b); + let ctx = mut_ptr_as_ref(ctx); + let attr_map = match &*a.rc.borrow() { + Value::dict_value(dict) => dict.attr_map.clone(), + Value::schema_value(schema) => schema.config.attr_map.clone(), + _ => panic!("invalid object '{}' in attr_map", a.type_str()), + }; + let opts = UnionOptions { + list_override: false, + idempotent_check: false, + config_resolve: true, + }; + if b.is_config() { + let dict = b.as_dict_ref(); + for k in dict.values.keys() { + let entry = b.dict_get_entry(k).unwrap(); + a.union_entry(ctx, &entry, true, &opts); + // Has type annotation + if let Some(ty) = attr_map.get(k) { + let value = a.dict_get_value(k).unwrap(); + a.dict_update_key_value(k, type_pack_and_check(ctx, &value, vec![ty], false)); + } + } + a.clone().into_raw(ctx) + } else { + a.union_entry(ctx, b, true, &opts).into_raw(ctx) + } +} + +// logic: && || + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_logic_and( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + ValueRef::bool(a.logic_and(b)).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_logic_or( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + ValueRef::bool(a.logic_or(b)).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_subscr( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + a.bin_subscr(b).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_subscr_set( + ctx: *mut kcl_context_t, + p: *mut kcl_value_ref_t, + index: *const kcl_value_ref_t, + val: *const kcl_value_ref_t, +) { + let ctx = mut_ptr_as_ref(ctx); + let p = mut_ptr_as_ref(p); + let index = ptr_as_ref(index); + let val = ptr_as_ref(val); + p.bin_subscr_set(ctx, index, val); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_subscr_option( + ctx: *mut kcl_context_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, +) -> *mut kcl_value_ref_t { + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + a.bin_subscr_option(b).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_load_attr( + ctx: *mut kcl_context_t, + obj: *const kcl_value_ref_t, + key: *const kcl_char_t, +) -> *const kcl_value_ref_t { + let p = ptr_as_ref(obj); + let key = c2str(key); + let ctx = mut_ptr_as_ref(ctx); + p.load_attr(key).into_raw(ctx) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_load_attr_option( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, + key: *const kcl_char_t, +) -> *const kcl_value_ref_t { + let p_ref = ptr_as_ref(p); + if p_ref.is_truthy() { + unsafe { kcl_value_load_attr(ctx, p, key) } + } else { + kcl_value_None(ctx) + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_remove_item( + a: *mut kcl_value_ref_t, + b: *const kcl_value_ref_t, +) { + let a = mut_ptr_as_ref(a); + let b = ptr_as_ref(b); + if a.is_dict() { + a.dict_remove(&b.as_str()); + } else if a.is_list() { + a.list_remove(b); + } else { + panic!("only list, dict and schema can be removed item"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_slice( + ctx: *mut kcl_context_t, + x: *const kcl_value_ref_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, + step: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let x = ptr_as_ref(x); + let a = ptr_as_ref(a); + let b = ptr_as_ref(b); + let step = ptr_as_ref(step); + x.list_slice(a, b, step).into_raw(mut_ptr_as_ref(ctx)) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_slice_option( + ctx: *mut kcl_context_t, + x: *const kcl_value_ref_t, + a: *const kcl_value_ref_t, + b: *const kcl_value_ref_t, + step: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let value = ptr_as_ref(x); + if value.is_truthy() { + unsafe { kcl_value_slice(ctx, x, a, b, step) } + } else { + kcl_value_None(ctx) + } +} + +// ---------------------------------------------------------------------------- +// values: schema +// ---------------------------------------------------------------------------- + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_schema_backtrack_cache( + ctx: *mut kcl_context_t, + schema: *const kcl_value_ref_t, + cache: *mut kcl_value_ref_t, + cal_map: *const kcl_value_ref_t, + name: *const kcl_char_t, + runtime_type: *const kcl_value_ref_t, +) { + let schema = ptr_as_ref(schema); + let cache = mut_ptr_as_ref(cache); + let cal_map = ptr_as_ref(cal_map); + let name = c2str(name); + if let Some(v) = cal_map.dict_get_value(name) { + if v.len() == 1 { + if let Some(value) = schema.dict_get_value(name) { + cache.dict_update_key_value(name, value); + } + } else if let (Some(cal_map_runtime_type_list), Some(cal_map_meta_line_list)) = ( + cal_map.dict_get_value(&format!("{name}_{CAL_MAP_RUNTIME_TYPE}")), + cal_map.dict_get_value(&format!("{name}_{CAL_MAP_META_LINE}")), + ) { + if let (Some(cal_map_runtime_type), Some(cal_map_meta_line)) = ( + cal_map_runtime_type_list.list_get(-1), + cal_map_meta_line_list.list_get(-1), + ) { + let runtime_type = ptr_as_ref(runtime_type); + let ctx = mut_ptr_as_ref(ctx); + let line = ctx.panic_info.kcl_line as i64; + let cal_map_meta_line = cal_map_meta_line.as_int(); + if runtime_type == &cal_map_runtime_type && line >= cal_map_meta_line { + if let Some(value) = schema.dict_get_value(name) { + cache.dict_update_key_value(name, value); + } + } + } + } + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_schema_instances( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let ctx_ref = mut_ptr_as_ref(ctx); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + if let Some(val) = args.pop_arg_first() { + let function = val.as_function(); + let full_pkg = args.arg_0().or_else(|| kwargs.kwarg("full_pkg")); + let full_pkg = if let Some(v) = full_pkg { + v.is_truthy() + } else { + false + }; + let runtime_type = &function.runtime_type; + if ctx_ref.instances.contains_key(runtime_type) { + let mut list = ValueRef::list(None); + let instance_map = ctx_ref.instances.get(runtime_type).unwrap(); + if full_pkg { + for (_, v_list) in instance_map { + collect_schema_instances(&mut list, &v_list, runtime_type) + } + } else { + // Get the schema instances only located at the main package. + if let Some(v_list) = instance_map.get(MAIN_PKG_PATH) { + collect_schema_instances(&mut list, &v_list, runtime_type) + } + if let Some(v_list) = instance_map.get("") { + collect_schema_instances(&mut list, &v_list, runtime_type) + } + }; + list.into_raw(ctx_ref) + } else { + kcl_value_List(ctx) + } + } else { + kcl_value_None(ctx) + } +} + +fn collect_schema_instances(list: &mut ValueRef, v_list: &[ValueRef], runtime_type: &str) { + for v in v_list { + if v.is_schema() { + list.list_append(v) + } else if v.is_dict() { + let runtime_type = v + .get_potential_schema_type() + .unwrap_or(runtime_type.to_string()); + let names: Vec<&str> = runtime_type.rsplit('.').collect(); + let name = names[0]; + let pkgpath = names[1]; + let v = v.dict_to_schema( + name, + pkgpath, + &[], + &ValueRef::dict(None), + &ValueRef::dict(None), + None, + None, + ); + list.list_append(&v); + } + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_schema_value_check( + ctx: *mut kcl_context_t, + schema_value: *mut kcl_value_ref_t, + schema_config: *const kcl_value_ref_t, + _config_meta: *const kcl_value_ref_t, + schema_name: *const kcl_char_t, + index_sign_value: *const kcl_value_ref_t, + key_name: *const kcl_char_t, + key_type: *const kcl_char_t, + value_type: *const kcl_char_t, + _any_other: kcl_bool_t, +) { + let schema_value = mut_ptr_as_ref(schema_value); + let schema_config = ptr_as_ref(schema_config); + let index_sign_value = ptr_as_ref(index_sign_value); + let key_type = c2str(key_type); + let value_type = c2str(value_type); + let index_key_name = c2str(key_name); + let has_index_signature = !key_type.is_empty(); + + let ctx = mut_ptr_as_ref(ctx); + if ctx.cfg.disable_schema_check { + return; + } + let config = schema_config.as_dict_ref(); + for (key, value) in &config.values { + let no_such_attr = schema_value.dict_get_value(key).is_none(); + if has_index_signature && no_such_attr { + // Allow index signature value has different values + // related to the index signature key name. + let should_update = + if let Some(index_key_value) = schema_value.dict_get_value(index_key_name) { + index_key_value.is_str() && key == &index_key_value.as_str() + } else { + true + }; + if should_update { + let op = config + .ops + .get(key) + .unwrap_or(&ConfigEntryOperationKind::Union); + schema_value.dict_update_entry( + key.as_str(), + &index_sign_value.deep_copy(), + &ConfigEntryOperationKind::Override, + None, + ); + schema_value.dict_insert(ctx, key.as_str(), value, op.clone(), None); + let value = schema_value.dict_get_value(key).unwrap(); + schema_value.dict_update_key_value( + key.as_str(), + type_pack_and_check(ctx, &value, vec![value_type], false), + ); + } + } else if !has_index_signature && no_such_attr { + let schema_name = c2str(schema_name); + panic!("No attribute named '{key}' in the schema '{schema_name}'"); + } + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_schema_do_check_with_index_sign_attr( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, + check_fn_ptr: *const u64, + attr_name: *const kcl_char_t, +) { + let check_fn_ptr = check_fn_ptr as u64; + let args_value = ptr_as_ref(args); + let attr_name = c2str(attr_name); + unsafe { + let check_fn: SchemaTypeFunc = transmute_copy(&check_fn_ptr); + // args_0: config_meta, args_1: config, args_2: schema, args_3: cal_map + // Schema check function closure + let config_meta = args_value.arg_i(0).unwrap(); + let config = args_value.arg_i(1).unwrap(); + let mut schema = args_value.arg_i(2).unwrap(); + let cal_map = args_value.arg_i(3).unwrap(); + let backtrack_level_map = args_value.arg_i(4).unwrap(); + let backtrack_cache = args_value.arg_i(5).unwrap(); + for (k, _) in &config.as_dict_ref().values { + // relaxed keys + if schema.attr_map_get(k).is_none() { + let value = ValueRef::str(k); + schema.dict_update_key_value(attr_name, value); + let args = &mut ValueRef::list(None); + // Schema check function closure + args.list_append(&config_meta); + args.list_append(&config); + args.list_append(&schema); + args.list_append(&cal_map); + args.list_append(&backtrack_level_map); + args.list_append(&backtrack_cache); + let args = args.clone().into_raw(mut_ptr_as_ref(ctx)); + check_fn(ctx, args, kwargs); + } + } + schema.dict_remove(attr_name); + }; +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_schema_optional_check( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, +) { + let p = ptr_as_ref(p); + let ctx = mut_ptr_as_ref(ctx); + if !ctx.cfg.disable_schema_check { + p.schema_check_attr_optional(ctx, true); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_schema_default_settings( + schema_value: *mut kcl_value_ref_t, + _config_value: *const kcl_value_ref_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, + runtime_type: *const kcl_char_t, +) { + let schema_value = mut_ptr_as_ref(schema_value); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let runtime_type = c2str(runtime_type); + schema_value.set_potential_schema_type(runtime_type); + schema_value.set_schema_args(args, kwargs); +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_schema_assert( + ctx: *mut kcl_context_t, + value: *const kcl_value_ref_t, + msg: *const kcl_value_ref_t, + config_meta: *const kcl_value_ref_t, +) { + let value = ptr_as_ref(value); + let msg = ptr_as_ref(msg); + let config_meta = ptr_as_ref(config_meta); + if !value.is_truthy() { + let ctx = mut_ptr_as_ref(ctx); + ctx.set_err_type(&RuntimeErrorType::SchemaCheckFailure); + if let Some(config_meta_file) = config_meta.get_by_key(CONFIG_META_FILENAME) { + let config_meta_line = config_meta.get_by_key(CONFIG_META_LINE).unwrap(); + let config_meta_column = config_meta.get_by_key(CONFIG_META_COLUMN).unwrap(); + ctx.set_kcl_config_meta_location_info( + Some("Instance check failed"), + Some(config_meta_file.as_str().as_str()), + Some(config_meta_line.as_int() as i32), + Some(config_meta_column.as_int() as i32), + ); + } + + let arg_msg = format!( + "Check failed on the condition{}", + if msg.is_empty() { + "".to_string() + } else { + format!(": {msg}") + } + ); + ctx.set_kcl_location_info(Some(arg_msg.as_str()), None, None, None); + + panic!("{}", msg.as_str()); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_schema_value_new( + ctx: *mut kcl_context_t, + args: *mut kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, + schema_value_or_func: *const kcl_value_ref_t, + config: *const kcl_value_ref_t, + config_meta: *const kcl_value_ref_t, + pkgpath: *const kcl_char_t, +) -> *const kcl_value_ref_t { + let schema_value_or_func = ptr_as_ref(schema_value_or_func); + if schema_value_or_func.is_func() { + let schema_func = schema_value_or_func.as_function(); + let schema_fn_ptr = schema_func.fn_ptr; + let ctx_ref = mut_ptr_as_ref(ctx); + let now_meta_info = ctx_ref.panic_info.clone(); + if ctx_ref.cfg.debug_mode { + ctx_ref + .backtrace + .push(BacktraceFrame::from_panic_info(&ctx_ref.panic_info)); + ctx_ref.panic_info.kcl_func = schema_func.runtime_type.clone(); + } + let value = unsafe { + let org_args = ptr_as_ref(args).deep_copy(); + let schema_fn: SchemaTypeFunc = transmute_copy(&schema_fn_ptr); + let cal_map = kcl_value_Dict(ctx); + let instance_pkgpath = kcl_value_Str(ctx, pkgpath); + // Schema function closures + let values = [ + // is_sub_schema + kcl_value_Bool(ctx, 0), + // Config meta + config_meta, + // Config value + config, + // Schema value + kcl_value_Dict(ctx), + // optional_mapping + kcl_value_Dict(ctx), + // cal order map + cal_map, + // backtrack level map + kcl_value_Dict(ctx), + // backtrack cache + kcl_value_Dict(ctx), + // record instance + kcl_value_Bool(ctx, 0), + // instance pkgpath + instance_pkgpath, + ]; + for value in values { + kcl_list_append(args, value); + } + schema_fn(ctx, args, kwargs); + // schema args + let args = org_args.into_raw(ctx_ref); + let values = [ + // is_sub_schema + kcl_value_Bool(ctx, 1), + // Config meta + config_meta, + // Config value + config, + // Schema value + kcl_value_Dict(ctx), + // optional_mapping + kcl_value_Dict(ctx), + // cal order map + cal_map, + // backtrack level map + kcl_value_Dict(ctx), + // backtrack cache + kcl_value_Dict(ctx), + // record instance + kcl_value_Bool(ctx, 1), + // instance pkgpath + instance_pkgpath, + ]; + for value in values { + kcl_list_append(args, value); + } + schema_fn(ctx, args, kwargs) + }; + ctx_ref.panic_info = now_meta_info; + if ctx_ref.cfg.debug_mode { + ctx_ref.backtrace.pop(); + } + value + } else { + let config = ptr_as_ref(config); + let result = schema_value_or_func.deep_copy().union_entry( + mut_ptr_as_ref(ctx), + config, + true, + &UnionOptions::default(), + ); + result.into_raw(mut_ptr_as_ref(ctx)) + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_convert_collection_value( + ctx: *mut kcl_context_t, + value: *const kcl_value_ref_t, + tpe: *const kcl_char_t, + is_in_schema: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let value = ptr_as_ref(value); + let ctx = mut_ptr_as_ref(ctx); + let tpe = c2str(tpe); + let value = type_pack_and_check(ctx, value, vec![tpe], false); + let is_in_schema = ptr_as_ref(is_in_schema); + // Schema required attribute validating. + if !is_in_schema.is_truthy() { + walk_value_mut(&value, &mut |value: &ValueRef| { + if value.is_schema() { + value.schema_check_attr_optional(ctx, true); + } + }) + } + value.into_raw(ctx) +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_schema_get_value( + ctx: *mut kcl_context_t, + p: *const kcl_value_ref_t, + key: *const kcl_char_t, + config: *const kcl_value_ref_t, + config_meta: *const kcl_value_ref_t, + cal_map: *const kcl_value_ref_t, + target_attr: *const kcl_char_t, + backtrack_level_map: *mut kcl_value_ref_t, + backtrack_cache: *mut kcl_value_ref_t, + args: *mut kcl_value_ref_t, + kwargs: *mut kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let schema = ptr_as_ref(p); + let key = c2str(key); + let cal_map = ptr_as_ref(cal_map); + let target_attr = c2str(target_attr); + let backtrack_level_map = mut_ptr_as_ref(backtrack_level_map); + let backtrack_cache = mut_ptr_as_ref(backtrack_cache); + let args_org = mut_ptr_as_ref(args); + let kwargs = mut_ptr_as_ref(kwargs); + let default_level = ValueRef::int(0); + let level = backtrack_level_map + .dict_get_value(key) + .unwrap_or(default_level); + let level = level.as_int(); + let is_backtracking = level > 0; + // Deal in-place modify and return it self immediately + if key == target_attr && !is_backtracking { + match schema.dict_get_value(key) { + Some(x) => return x.into_raw(mut_ptr_as_ref(ctx)), + None => return kcl_value_Undefined(ctx), + } + } + if let Some(v) = backtrack_cache.dict_get_value(key) { + return v.into_raw(mut_ptr_as_ref(ctx)); + } + if let Some(attr_code) = cal_map.dict_get_value(key) { + let now_level = level + 1; + backtrack_level_map.dict_update_key_value(key, ValueRef::int(now_level)); + let attr_code = attr_code.as_list_ref(); + let n = attr_code.values.len(); + let index = n - now_level as usize; + if index >= n { + let value = match schema.dict_get_value(key) { + Some(x) => x, + None => ValueRef::undefined(), + }; + return value.into_raw(mut_ptr_as_ref(ctx)); + } + let fn_ptr = &attr_code.values[index]; + let fn_ptr = fn_ptr.as_int(); + // When we calculate other schema attribute values, we retain + // the row and column number information of the current schema attribute. + let ctx_ref = mut_ptr_as_ref(ctx); + let panic_info = ctx_ref.panic_info.clone(); + unsafe { + let attr_fn: SchemaTypeFunc = transmute_copy(&fn_ptr); + // args_0: config_meta, args_1: config, args_2: schema, args_3: cal_map + let config_meta = ptr_as_ref(config_meta); + let config = ptr_as_ref(config); + let mut args = ValueRef::list(None); + let args_org = args_org.as_list_ref(); + for value in &args_org.values { + args.list_append(value); + } + // Schema attr function closure + args.list_append(config_meta); + args.list_append(config); + args.list_append(schema); + args.list_append(cal_map); + args.list_append(backtrack_level_map); + args.list_append(backtrack_cache); + let args = args.into_raw(ctx_ref); + let kwargs = kwargs.clone().into_raw(ctx_ref); + attr_fn(ctx, args, kwargs); + }; + // Restore the panic info of current schema attribute. + ctx_ref.panic_info = panic_info; + backtrack_level_map.dict_update_key_value(key, ValueRef::int(level)); + let value = match schema.dict_get_value(key) { + Some(x) => x, + None => ValueRef::undefined(), + }; + backtrack_cache.dict_update_key_value(key, value); + } + match schema.dict_get_value(key) { + Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), + None => kcl_value_Undefined(ctx), + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_config_attr_map( + value: *mut kcl_value_ref_t, + name: *const kcl_char_t, + type_str: *const kcl_char_t, +) { + let value = mut_ptr_as_ref(value); + let name = c2str(name); + let type_str = c2str(type_str); + value.update_attr_map(name, type_str); +} + +// ---------------------------------------------------------------------------- +// values: decorators +// ---------------------------------------------------------------------------- + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_value_Decorator( + ctx: *mut kcl_context_t, + name: *const kcl_char_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, + config_meta: *const kcl_value_ref_t, + attr_name: *const kcl_char_t, + config_value: *const kcl_value_ref_t, + is_schema_target: *const kcl_value_ref_t, +) -> *const kcl_decorator_value_t { + let name = c2str(name); + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let config_meta = ptr_as_ref(config_meta); + let attr_name = c2str(attr_name); + let config_value = ptr_as_ref(config_value); + let is_schema_target = ptr_as_ref(is_schema_target); + let decorator = DecoratorValue::new(name, args, kwargs); + decorator.run( + mut_ptr_as_ref(ctx), + attr_name, + is_schema_target.as_bool(), + config_value, + config_meta, + ); + decorator.into_raw() +} + +// ---------------------------------------------------------------------------- +// values: string member functions +// ---------------------------------------------------------------------------- + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_lower( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + val.str_lower().into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_lower"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_upper( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + val.str_upper().into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_upper"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_capitalize( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + val.str_capitalize().into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_capitalize"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_chars( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + val.str_chars().into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_chars"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_count( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + if let Some(sub) = args.arg_0() { + let start = args.arg_i(1); + let end = args.arg_i(2); + val.str_count(&sub, start.as_ref(), end.as_ref()) + .into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("count() takes at least 1 argument (0 given)"); + } + } else { + panic!("invalid self value in str_count"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_endswith( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + if let Some(suffix) = args.arg_0() { + let start = args.arg_i(1); + let end = args.arg_i(2); + val.str_endswith(&suffix, start.as_ref(), end.as_ref()) + .into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("endswith() takes at least 1 argument (0 given)"); + } + } else { + panic!("invalid self value in str_endswith"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_find( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + if let Some(sub) = args.arg_0() { + let start = args.arg_i(1); + let end = args.arg_i(2); + val.str_find(&sub, start.as_ref(), end.as_ref()) + .into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("find() takes at least 1 argument (0 given)"); + } + } else { + panic!("invalid self value in str_find"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_format( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + if let Some(val) = args.pop_arg_first() { + val.str_format(args, kwargs).into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_format"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_index( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + if let Some(sub) = args.arg_0() { + let start = args.arg_i(1); + let end = args.arg_i(2); + val.str_index(&sub, start.as_ref(), end.as_ref()) + .into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("index() takes at least 1 argument (0 given)"); + } + } else { + panic!("invalid self value in str_index"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_isalnum( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + val.str_isalnum().into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_isalnum"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_isalpha( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + val.str_isalpha().into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_isalpha"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_isdigit( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + val.str_isdigit().into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_isdigit"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_islower( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + val.str_islower().into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_islower"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_isspace( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + val.str_isspace().into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_isspace"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_istitle( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + val.str_istitle().into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_istitle"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_isupper( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + val.str_isupper().into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_isupper"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_join( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + let iter = args.arg_i(0).unwrap(); + val.str_join(&iter).into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_join"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_lstrip( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + let chars = args.arg_i(0); + val.str_lstrip(chars.as_ref()).into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_lstrip"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_rstrip( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + let chars = args.arg_i(0); + val.str_rstrip(chars.as_ref()).into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_rstrip"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_replace( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + let old = args.arg_i(0).expect("expect 1 argument, found 0"); + let new = args.arg_i(1).expect("expect 2 arguments, found 1"); + let count = args.arg_i(2); + val.str_replace(&old, &new, count.as_ref()) + .into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_replace"); + } +} + +/// If the string starts with the prefix string, return string[len(prefix):]. +/// Otherwise, return a copy of the original string. +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_removeprefix( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + let prefix = args.arg_i(0).expect("expect 1 argument, found 0"); + val.str_removeprefix(&prefix).into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_removeprefix"); + } +} + +/// If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. +/// Otherwise, return a copy of the original string. +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_removesuffix( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + let suffix = args.arg_i(0).expect("expect 1 argument, found 0"); + val.str_removesuffix(&suffix).into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_removesuffix"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_rfind( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + if let Some(sub) = args.arg_0() { + let start = args.arg_i(1); + let end = args.arg_i(2); + val.str_rfind(&sub, start.as_ref(), end.as_ref()) + .into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("rfind() takes at least 1 argument (0 given)"); + } + } else { + panic!("invalid self value in str_rfind"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_rindex( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + if let Some(sub) = args.arg_0() { + let start = args.arg_i(1); + let end = args.arg_i(2); + val.str_rindex(&sub, start.as_ref(), end.as_ref()) + .into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("rindex() takes at least 1 argument (0 given)"); + } + } else { + panic!("invalid self value in str_rindex"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_rsplit( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + if let Some(val) = args.pop_arg_first() { + let sep = if let Some(sep) = args.arg_i(0) { + Some(sep) + } else { + kwargs.kwarg("sep") + }; + let maxsplit = if let Some(maxsplit) = args.arg_i(1) { + Some(maxsplit) + } else { + kwargs.kwarg("maxsplit") + }; + val.str_rsplit(sep.as_ref(), maxsplit.as_ref()) + .into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_rsplit"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_split( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + if let Some(val) = args.pop_arg_first() { + let sep = if let Some(sep) = args.arg_i(0) { + Some(sep) + } else { + kwargs.kwarg("sep") + }; + let maxsplit = if let Some(maxsplit) = args.arg_i(1) { + Some(maxsplit) + } else { + kwargs.kwarg("maxsplit") + }; + let x = val.str_split(sep.as_ref(), maxsplit.as_ref()); + x.into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_split"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_splitlines( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + if let Some(val) = args.pop_arg_first() { + if let Some(keepends) = args.arg_i(0) { + val.str_splitlines(Some(&keepends)) + .into_raw(mut_ptr_as_ref(ctx)) + } else if let Some(keepends) = kwargs.kwarg("keepends") { + val.str_splitlines(Some(&keepends)) + .into_raw(mut_ptr_as_ref(ctx)) + } else { + val.str_splitlines(None).into_raw(mut_ptr_as_ref(ctx)) + } + } else { + panic!("invalid self value in str_splitlines"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_startswith( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + if let Some(suffix) = args.arg_0() { + let start = args.arg_i(1); + let end = args.arg_i(2); + val.str_startswith(&suffix, start.as_ref(), end.as_ref()) + .into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("startswith() takes at least 1 argument (0 given)"); + } + } else { + panic!("invalid self value in str_startswith"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_strip( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + let chars = args.arg_i(0); + val.str_strip(chars.as_ref()).into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_strip"); + } +} + +#[unsafe(no_mangle)] + +pub unsafe extern "C-unwind" fn kcl_builtin_str_title( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + _kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + if let Some(val) = args.pop_arg_first() { + val.str_title().into_raw(mut_ptr_as_ref(ctx)) + } else { + panic!("invalid self value in str_title"); + } +} + +// ---------------------------------------------------------------------------- +// END +// ---------------------------------------------------------------------------- diff --git a/kclvm/runtime/src/value/iter.rs b/crates/runtime/src/value/iter.rs similarity index 93% rename from kclvm/runtime/src/value/iter.rs rename to crates/runtime/src/value/iter.rs index 29acdd537..94f2f4cbb 100644 --- a/kclvm/runtime/src/value/iter.rs +++ b/crates/runtime/src/value/iter.rs @@ -32,22 +32,22 @@ impl ValueIterator { if p.is_empty() { return Default::default(); } - match *p.rc.borrow() { - Value::str_value(ref s) => ValueIterator { + match &*p.rc.borrow() { + Value::str_value(s) => ValueIterator { len: s.len(), cur_key: Default::default(), cur_val: Default::default(), keys: Vec::new(), pos: 0, }, - Value::list_value(ref list) => ValueIterator { + Value::list_value(list) => ValueIterator { len: list.values.len(), cur_key: Default::default(), cur_val: Default::default(), keys: Vec::new(), pos: 0, }, - Value::dict_value(ref dict) => { + Value::dict_value(dict) => { let keys: Vec = dict.values.keys().map(|s| (*s).clone()).collect(); ValueIterator { len: dict.values.len(), @@ -58,7 +58,7 @@ impl ValueIterator { } } - Value::schema_value(ref schema) => { + Value::schema_value(schema) => { let keys: Vec = schema.config.values.keys().map(|s| (*s).clone()).collect(); ValueIterator { len: schema.config.values.len(), @@ -111,8 +111,8 @@ impl ValueIterator { if self.pos >= host.len() as i32 { return None; } - match *host.rc.borrow() { - Value::str_value(ref s) => { + match &*host.rc.borrow() { + Value::str_value(s) => { if self.pos >= s.chars().count() as i32 { return None; } @@ -122,20 +122,20 @@ impl ValueIterator { self.pos += 1; Some(&self.cur_val) } - Value::list_value(ref list) => { + Value::list_value(list) => { self.cur_key = ValueRef::int(self.pos as i64); self.cur_val = list.values[self.pos as usize].clone(); self.pos += 1; Some(&self.cur_val) } - Value::dict_value(ref dict) => { + Value::dict_value(dict) => { let key = &self.keys[self.pos as usize]; self.cur_key = ValueRef::str(key); self.cur_val = dict.values[key].clone(); self.pos += 1; Some(&self.cur_key) } - Value::schema_value(ref schema) => { + Value::schema_value(schema) => { let key = &self.keys[self.pos as usize]; self.cur_key = ValueRef::str(key); self.cur_val = schema.config.values[key].clone(); diff --git a/kclvm/runtime/src/value/mod.rs b/crates/runtime/src/value/mod.rs similarity index 100% rename from kclvm/runtime/src/value/mod.rs rename to crates/runtime/src/value/mod.rs diff --git a/kclvm/runtime/src/value/val.rs b/crates/runtime/src/value/val.rs similarity index 100% rename from kclvm/runtime/src/value/val.rs rename to crates/runtime/src/value/val.rs diff --git a/kclvm/runtime/src/value/val_args.rs b/crates/runtime/src/value/val_args.rs similarity index 93% rename from kclvm/runtime/src/value/val_args.rs rename to crates/runtime/src/value/val_args.rs index c32810775..5b8a96bce 100644 --- a/kclvm/runtime/src/value/val_args.rs +++ b/crates/runtime/src/value/val_args.rs @@ -22,22 +22,22 @@ impl ValueRef { } pub fn arg_last(&self) -> Option { - match *self.rc.borrow() { - Value::list_value(ref list) => Some(list.values[list.values.len() - 1].clone()), + match &*self.rc.borrow() { + Value::list_value(list) => Some(list.values[list.values.len() - 1].clone()), _ => None, } } pub fn pop_arg_last(&self) -> Option { - match *self.rc.borrow_mut() { - Value::list_value(ref mut list) => list.values.pop(), + match &mut *self.rc.borrow_mut() { + Value::list_value(list) => list.values.pop(), _ => None, } } pub fn pop_arg_first(&self) -> Option { - match *self.rc.borrow_mut() { - Value::list_value(ref mut list) => { + match &mut *self.rc.borrow_mut() { + Value::list_value(list) => { if !list.values.is_empty() { Some(list.values.remove(0)) } else { @@ -49,15 +49,15 @@ impl ValueRef { } pub fn args_len(&self) -> usize { - match *self.rc.borrow() { - Value::list_value(ref list) => list.values.len(), + match &*self.rc.borrow() { + Value::list_value(list) => list.values.len(), _ => 1, } } pub fn arg_i(&self, i: usize) -> Option { - match *self.rc.borrow() { - Value::list_value(ref list) => { + match &*self.rc.borrow() { + Value::list_value(list) => { if i < list.values.len() { return Some(list.values[i].clone()); } @@ -150,8 +150,8 @@ impl ValueRef { } pub fn kwarg(&self, name: &str) -> Option { - match *self.rc.borrow() { - Value::dict_value(ref dict) => dict.values.get(&name.to_string()).cloned(), + match &*self.rc.borrow() { + Value::dict_value(dict) => dict.values.get(&name.to_string()).cloned(), _ => None, } } diff --git a/kclvm/runtime/src/value/val_as_val.rs b/crates/runtime/src/value/val_as_val.rs similarity index 79% rename from kclvm/runtime/src/value/val_as_val.rs rename to crates/runtime/src/value/val_as_val.rs index 7e79f566c..156414513 100644 --- a/kclvm/runtime/src/value/val_as_val.rs +++ b/crates/runtime/src/value/val_as_val.rs @@ -11,45 +11,45 @@ impl ValueRef { #[inline] pub fn as_int(&self) -> i64 { - match *self.rc.borrow() { - Value::int_value(ref v) => *v, - Value::float_value(ref v) => *v as i64, - Value::unit_value(ref v, _, _) => *v as i64, + match &*self.rc.borrow() { + Value::int_value(v) => *v, + Value::float_value(v) => *v as i64, + Value::unit_value(v, _, _) => *v as i64, _ => 0, } } #[inline] pub fn must_as_strict_int(&self) -> i64 { - match *self.rc.borrow() { - Value::int_value(ref v) => *v, + match &*self.rc.borrow() { + Value::int_value(v) => *v, _ => panic!("invalid int value"), } } #[inline] pub fn as_float(&self) -> f64 { - match *self.rc.borrow() { - Value::int_value(ref v) => *v as f64, - Value::float_value(ref v) => *v, - Value::unit_value(ref v, _, _) => *v, + match &*self.rc.borrow() { + Value::int_value(v) => *v as f64, + Value::float_value(v) => *v, + Value::unit_value(v, _, _) => *v, _ => 0.0, } } #[inline] pub fn as_num(&self) -> f64 { - match *self.rc.borrow() { - Value::float_value(v) => v, - Value::int_value(v) => v as f64, + match &*self.rc.borrow() { + Value::float_value(v) => *v, + Value::int_value(v) => *v as f64, _ => return 0.0, } } #[inline] pub fn as_str(&self) -> String { - match *self.rc.borrow() { - Value::str_value(ref v) => v.clone(), + match &*self.rc.borrow() { + Value::str_value(v) => v.clone(), _ => "".to_string(), } } @@ -57,7 +57,7 @@ impl ValueRef { #[inline] pub fn as_list_ref(&self) -> Ref { Ref::map(self.rc.borrow(), |val| match val { - Value::list_value(ref v) => v.as_ref(), + Value::list_value(v) => v.as_ref(), _ => panic!("invalid list value"), }) } @@ -65,7 +65,7 @@ impl ValueRef { #[inline] pub fn as_list_mut_ref(&mut self) -> RefMut { RefMut::map(self.rc.borrow_mut(), |val| match val { - Value::list_value(ref mut v) => v.as_mut(), + Value::list_value(v) => v.as_mut(), _ => panic!("invalid list value"), }) } @@ -73,8 +73,8 @@ impl ValueRef { #[inline] pub fn as_dict_ref(&self) -> Ref { Ref::map(self.rc.borrow(), |val| match val { - Value::dict_value(ref v) => v.as_ref(), - Value::schema_value(ref v) => v.config.as_ref(), + Value::dict_value(v) => v.as_ref(), + Value::schema_value(v) => v.config.as_ref(), _ => panic!("invalid dict value"), }) } @@ -82,8 +82,8 @@ impl ValueRef { #[inline] pub fn as_dict_mut_ref(&mut self) -> RefMut { RefMut::map(self.rc.borrow_mut(), |val| match val { - Value::dict_value(ref mut v) => v.as_mut(), - Value::schema_value(ref mut v) => v.config.as_mut(), + Value::dict_value(v) => v.as_mut(), + Value::schema_value(v) => v.config.as_mut(), _ => panic!("invalid dict value"), }) } @@ -91,7 +91,7 @@ impl ValueRef { #[inline] pub fn as_schema(&self) -> Ref { Ref::map(self.rc.borrow(), |val| match val { - Value::schema_value(ref v) => v.as_ref(), + Value::schema_value(v) => v.as_ref(), _ => panic!("invalid schema value"), }) } @@ -99,7 +99,7 @@ impl ValueRef { #[inline] pub fn as_function(&self) -> Ref { Ref::map(self.rc.borrow(), |val| match val { - Value::func_value(ref v) => v.as_ref(), + Value::func_value(v) => v.as_ref(), _ => panic!("invalid func value"), }) } diff --git a/crates/runtime/src/value/val_attr.rs b/crates/runtime/src/value/val_attr.rs new file mode 100644 index 000000000..7aedffe38 --- /dev/null +++ b/crates/runtime/src/value/val_attr.rs @@ -0,0 +1,75 @@ +//! Copyright The KCL Authors. All rights reserved. + +use crate::*; + +impl ValueRef { + /// Load attribute named `key` from the self value, the attribute maybe a + /// member function or a builtin value. + pub fn load_attr(&self, key: &str) -> Self { + let p: &ValueRef = self; + // load_attr including str/dict/schema. + if p.is_dict() { + match p.dict_get_value(key) { + Some(x) => x, + None => ValueRef::undefined(), + } + } else if p.is_schema() { + let dict = p.schema_to_dict(); + match dict.dict_get_value(key) { + Some(x) => x, + None => panic!("schema '{}' attribute '{}' not found", p.type_str(), key), + } + } else if p.is_str() { + let function = match key { + "lower" => kcl_builtin_str_lower, + "upper" => kcl_builtin_str_upper, + "capitalize" => kcl_builtin_str_capitalize, + "chars" => kcl_builtin_str_chars, + "count" => kcl_builtin_str_count, + "endswith" => kcl_builtin_str_endswith, + "find" => kcl_builtin_str_find, + "format" => kcl_builtin_str_format, + "index" => kcl_builtin_str_index, + "isalnum" => kcl_builtin_str_isalnum, + "isalpha" => kcl_builtin_str_isalpha, + "isdigit" => kcl_builtin_str_isdigit, + "islower" => kcl_builtin_str_islower, + "isspace" => kcl_builtin_str_isspace, + "istitle" => kcl_builtin_str_istitle, + "isupper" => kcl_builtin_str_isupper, + "join" => kcl_builtin_str_join, + "lstrip" => kcl_builtin_str_lstrip, + "rstrip" => kcl_builtin_str_rstrip, + "replace" => kcl_builtin_str_replace, + "removeprefix" => kcl_builtin_str_removeprefix, + "removesuffix" => kcl_builtin_str_removesuffix, + "rfind" => kcl_builtin_str_rfind, + "rindex" => kcl_builtin_str_rindex, + "rsplit" => kcl_builtin_str_rsplit, + "split" => kcl_builtin_str_split, + "splitlines" => kcl_builtin_str_splitlines, + "startswith" => kcl_builtin_str_startswith, + "strip" => kcl_builtin_str_strip, + "title" => kcl_builtin_str_title, + _ => panic!("str object attr '{key}' not found"), + }; + let closure = ValueRef::list(Some(&[p])); + ValueRef::func(function as usize as u64, 0, closure, "", "", false) + } + // schema instance + else if p.is_func() { + let function = match key { + "instances" => kcl_schema_instances, + _ => panic!("schema object attr '{key}' not found"), + }; + let closure = ValueRef::list(Some(&[p])); + ValueRef::func(function as usize as u64, 0, closure, "", "", false) + } else { + panic!( + "invalid value '{}' to load attribute '{}'", + p.type_str(), + key + ); + } + } +} diff --git a/kclvm/runtime/src/value/val_bin.rs b/crates/runtime/src/value/val_bin.rs similarity index 99% rename from kclvm/runtime/src/value/val_bin.rs rename to crates/runtime/src/value/val_bin.rs index 38fb862ad..1459d9cbd 100644 --- a/kclvm/runtime/src/value/val_bin.rs +++ b/crates/runtime/src/value/val_bin.rs @@ -186,7 +186,7 @@ impl ValueRef { let strict_range_check_64 = ctx.cfg.debug_mode || !ctx.cfg.strict_range_check; match (&*self.rc.borrow(), &*x.rc.borrow()) { - (Value::int_value(ref a), Value::int_value(b)) => { + (Value::int_value(a), Value::int_value(b)) => { if strict_range_check_32 && is_i32_overflow_pow(*a, *b) { panic_i32_overflow!(ctx, (*a as i128).pow(*b as u32)); } diff --git a/kclvm/runtime/src/value/val_bin_aug.rs b/crates/runtime/src/value/val_bin_aug.rs similarity index 99% rename from kclvm/runtime/src/value/val_bin_aug.rs rename to crates/runtime/src/value/val_bin_aug.rs index d5e2c4543..9836e3dfd 100644 --- a/kclvm/runtime/src/value/val_bin_aug.rs +++ b/crates/runtime/src/value/val_bin_aug.rs @@ -44,7 +44,7 @@ impl ValueRef { true } (Value::list_value(a), _) => match &*x.rc.borrow() { - Value::list_value(ref b) => { + Value::list_value(b) => { for x in b.values.iter() { a.values.push(x.clone()); } @@ -147,7 +147,7 @@ impl ValueRef { true } (Value::list_value(list), _) => match &*x.rc.borrow() { - Value::int_value(ref b) => { + Value::int_value(b) => { let n = list.values.len(); for _ in 1..(*b as usize) { for i in 0..n { diff --git a/kclvm/runtime/src/value/val_clone.rs b/crates/runtime/src/value/val_clone.rs similarity index 90% rename from kclvm/runtime/src/value/val_clone.rs rename to crates/runtime/src/value/val_clone.rs index 5ba0494b4..d166a59f8 100644 --- a/kclvm/runtime/src/value/val_clone.rs +++ b/crates/runtime/src/value/val_clone.rs @@ -15,7 +15,7 @@ impl ValueRef { Value::none => ValueRef { rc: Rc::new(RefCell::new(Value::none)), }, - Value::func_value(ref v) => ValueRef { + Value::func_value(v) => ValueRef { rc: Rc::new(RefCell::new(Value::func_value(Box::new(FuncValue { fn_ptr: v.fn_ptr, check_fn_ptr: v.check_fn_ptr, @@ -32,27 +32,27 @@ impl ValueRef { proxy: v.proxy, })))), }, - Value::bool_value(ref v) => ValueRef { + Value::bool_value(v) => ValueRef { rc: Rc::new(RefCell::new(Value::bool_value(*v))), }, - Value::int_value(ref v) => ValueRef { + Value::int_value(v) => ValueRef { rc: Rc::new(RefCell::new(Value::int_value(*v))), }, - Value::float_value(ref v) => ValueRef { + Value::float_value(v) => ValueRef { rc: Rc::new(RefCell::new(Value::float_value(*v))), }, - Value::unit_value(ref v, ref raw, ref unit) => ValueRef { + Value::unit_value(v, raw, unit) => ValueRef { rc: Rc::new(RefCell::new(Value::unit_value(*v, *raw, unit.clone()))), }, - Value::str_value(ref v) => ValueRef { + Value::str_value(v) => ValueRef { rc: Rc::new(RefCell::new(Value::str_value(v.to_string()))), }, - Value::list_value(ref v) => ValueRef { + Value::list_value(v) => ValueRef { rc: Rc::new(RefCell::new(Value::list_value(Box::new(ListValue { values: v.values.iter().map(|x| x.deep_copy()).collect(), })))), }, - Value::dict_value(ref v) => { + Value::dict_value(v) => { let mut dict = ValueRef::from(Value::dict_value(Box::new(DictValue::new(&[])))); for (key, val) in &v.values { let op = v.ops.get(key).unwrap_or(&ConfigEntryOperationKind::Union); @@ -62,7 +62,7 @@ impl ValueRef { dict.set_potential_schema_type(&v.potential_schema.clone().unwrap_or_default()); dict } - Value::schema_value(ref v) => { + Value::schema_value(v) => { let mut dict = ValueRef::from(Value::dict_value(Box::new(DictValue::new(&[])))); dict.set_potential_schema_type( &v.config.potential_schema.clone().unwrap_or_default(), diff --git a/kclvm/runtime/src/value/val_cmp.rs b/crates/runtime/src/value/val_cmp.rs similarity index 98% rename from kclvm/runtime/src/value/val_cmp.rs rename to crates/runtime/src/value/val_cmp.rs index b4126552d..90dbe9b9f 100644 --- a/kclvm/runtime/src/value/val_cmp.rs +++ b/crates/runtime/src/value/val_cmp.rs @@ -5,15 +5,15 @@ use crate::*; // cmp impl ValueRef { pub fn cmp_equal(&self, x: &Self) -> bool { - match *self.rc.borrow() { - Value::int_value(a) => match *x.rc.borrow() { + match &*self.rc.borrow() { + Value::int_value(a) => match &*x.rc.borrow() { Value::int_value(b) => a == b, - Value::float_value(b) => a as f64 == b, + Value::float_value(b) => *a as f64 == *b, _ => false, }, - Value::float_value(a) => match *x.rc.borrow() { - Value::int_value(b) => a == b as f64, - Value::float_value(b) => a == b, + Value::float_value(a) => match &*x.rc.borrow() { + Value::int_value(b) => *a == *b as f64, + Value::float_value(b) => *a == *b, _ => false, }, _ => match (&*self.rc.borrow(), &*x.rc.borrow()) { diff --git a/kclvm/runtime/src/value/val_decorator.rs b/crates/runtime/src/value/val_decorator.rs similarity index 100% rename from kclvm/runtime/src/value/val_decorator.rs rename to crates/runtime/src/value/val_decorator.rs diff --git a/kclvm/runtime/src/value/val_dict.rs b/crates/runtime/src/value/val_dict.rs similarity index 92% rename from kclvm/runtime/src/value/val_dict.rs rename to crates/runtime/src/value/val_dict.rs index 72bf019f5..6226f9940 100644 --- a/kclvm/runtime/src/value/val_dict.rs +++ b/crates/runtime/src/value/val_dict.rs @@ -13,19 +13,19 @@ impl DictValue { pub fn get(&self, key: &ValueRef) -> Option { match &*key.rc.borrow() { - Value::str_value(ref s) => self.values.get(s).cloned(), + Value::str_value(s) => self.values.get(s).cloned(), _ => None, } } pub fn insert(&mut self, key: &ValueRef, value: &ValueRef) { - if let Value::str_value(ref s) = &*key.rc.borrow() { + if let Value::str_value(s) = &*key.rc.borrow() { self.values.insert(s.to_string(), value.clone()); } } pub fn insert_unpack(&mut self, v: &ValueRef) { - if let Value::dict_value(ref b) = &*v.rc.borrow() { + if let Value::dict_value(b) = &*v.rc.borrow() { for (k, v) in b.values.iter() { self.values.insert(k.clone(), v.clone()); } @@ -36,8 +36,8 @@ impl DictValue { impl ValueRef { fn dict_config(&self) -> Ref { Ref::map(self.rc.borrow(), |val| match val { - Value::dict_value(ref dict) => dict.as_ref(), - Value::schema_value(ref schema) => schema.config.as_ref(), + Value::dict_value(dict) => dict.as_ref(), + Value::schema_value(schema) => schema.config.as_ref(), _ => panic!("invalid dict config value type {}", self.type_str()), }) } @@ -101,8 +101,8 @@ impl ValueRef { /// Dict get e.g., {k1: v1, k2, v2}.get(ValueRef::str(k1)) == v1 pub fn dict_get(&self, key: &ValueRef) -> Option { match &*self.rc.borrow() { - Value::dict_value(ref dict) => dict.get(key), - Value::schema_value(ref schema) => schema.config.get(key), + Value::dict_value(dict) => dict.get(key), + Value::schema_value(schema) => schema.config.get(key), _ => panic!("invalid config value in dict_get"), } } @@ -110,8 +110,8 @@ impl ValueRef { /// Dict get value e.g., {k1: v1, k2, v2}.get_value(k1) == v1 pub fn dict_get_value(&self, key: &str) -> Option { match &*self.rc.borrow() { - Value::dict_value(ref dict) => dict.values.get(key).cloned(), - Value::schema_value(ref schema) => schema.config.values.get(key).cloned(), + Value::dict_value(dict) => dict.values.get(key).cloned(), + Value::schema_value(schema) => schema.config.values.get(key).cloned(), _ => None, } } @@ -119,8 +119,8 @@ impl ValueRef { /// Dict get value e.g., {k1 = v1, k2 = v2}.get_attr_operator(k1) == Some(ConfigEntryOperationKind::Override) pub fn dict_get_attr_operator(&self, key: &str) -> Option { match &*self.rc.borrow() { - Value::dict_value(ref dict) => dict.ops.get(key).cloned(), - Value::schema_value(ref schema) => schema.config.ops.get(key).cloned(), + Value::dict_value(dict) => dict.ops.get(key).cloned(), + Value::schema_value(schema) => schema.config.ops.get(key).cloned(), _ => None, } } @@ -128,8 +128,8 @@ impl ValueRef { /// Dict get value e.g., {k1 = v1, k2 = v2}.get_attr_operator(k1) == Some(ConfigEntryOperationKind::Override) pub fn dict_get_insert_index(&self, key: &str) -> Option { match &*self.rc.borrow() { - Value::dict_value(ref dict) => dict.insert_indexs.get(key).cloned(), - Value::schema_value(ref schema) => schema.config.insert_indexs.get(key).cloned(), + Value::dict_value(dict) => dict.insert_indexs.get(key).cloned(), + Value::schema_value(schema) => schema.config.insert_indexs.get(key).cloned(), _ => None, } } @@ -137,7 +137,7 @@ impl ValueRef { /// Dict get entry e.g., {k1: v1, k2, v2}.get_entry(k1) == {k1: v1} pub fn dict_get_entry(&self, key: &str) -> Option { match &*self.rc.borrow() { - Value::dict_value(ref dict) => { + Value::dict_value(dict) => { if dict.values.contains_key(key) { let mut d = ValueRef::dict(None); let value = dict.values.get(key).unwrap(); @@ -154,7 +154,7 @@ impl ValueRef { None } } - Value::schema_value(ref schema) => { + Value::schema_value(schema) => { if schema.config.values.contains_key(key) { let mut d = ValueRef::dict(None); let value = schema.config.values.get(key).unwrap(); @@ -181,7 +181,7 @@ impl ValueRef { /// Dict get entries e.g., {k1: v1, k2, v2}.get_entries([k1, k2]) == {k1: v1, k1: v2} pub fn dict_get_entries(&self, keys: Vec<&str>) -> ValueRef { match &*self.rc.borrow() { - Value::dict_value(ref dict) => { + Value::dict_value(dict) => { let mut d = ValueRef::dict(None); for key in keys { if dict.values.contains_key(key) { @@ -197,7 +197,7 @@ impl ValueRef { d.set_potential_schema_type(&dict.potential_schema.clone().unwrap_or_default()); d } - Value::schema_value(ref schema) => { + Value::schema_value(schema) => { let mut d = ValueRef::dict(None); for key in keys { if schema.config.values.contains_key(key) { @@ -233,7 +233,7 @@ impl ValueRef { op: &ConfigEntryOperationKind, ) -> ValueRef { match &*self.rc.borrow() { - Value::dict_value(ref dict) => { + Value::dict_value(dict) => { let mut d = ValueRef::dict(None); for key in keys { if dict.values.contains_key(key) { @@ -245,7 +245,7 @@ impl ValueRef { d.set_potential_schema_type(&dict.potential_schema.clone().unwrap_or_default()); d } - Value::schema_value(ref schema) => { + Value::schema_value(schema) => { let mut d = ValueRef::dict(None); for key in keys { if schema.config.values.contains_key(key) { @@ -360,7 +360,7 @@ impl ValueRef { idempotent_check: bool, ) { if ctx.cfg.debug_mode { - if let Value::int_value(ref x) = *v.rc.borrow() { + if let Value::int_value(x) = &*v.rc.borrow() { let strict_range_check_i32 = ctx.cfg.strict_range_check; let strict_range_check_i64 = ctx.cfg.debug_mode || !ctx.cfg.strict_range_check; let v_i128 = *x as i128; @@ -415,7 +415,9 @@ impl ValueRef { } (Value::dict_value(_) | Value::schema_value(_), Value::undefined) => { /*Do nothing on unpacking None/Undefined*/ } - _ => panic!("only list, dict and schema object can be used with unpack operators * and **, got {v}"), + _ => panic!( + "only list, dict and schema object can be used with unpack operators * and **, got {v}" + ), } if union { self.bin_aug_bit_or(ctx, &v.schema_to_dict().deep_copy()); diff --git a/kclvm/runtime/src/value/val_fmt.rs b/crates/runtime/src/value/val_fmt.rs similarity index 98% rename from kclvm/runtime/src/value/val_fmt.rs rename to crates/runtime/src/value/val_fmt.rs index 30e3a1e1a..cec5d3095 100644 --- a/kclvm/runtime/src/value/val_fmt.rs +++ b/crates/runtime/src/value/val_fmt.rs @@ -882,7 +882,9 @@ impl FormatString { } FieldType::Index(index) => { if auto_argument_index != 0 { - panic!("cannot switch from automatic field numbering to manual field specification"); + panic!( + "cannot switch from automatic field numbering to manual field specification" + ); } args.arg_i(index) .expect("argument tuple index out of range") @@ -977,15 +979,15 @@ impl fmt::Display for ValueRef { match &*self.rc.borrow() { Value::undefined => write!(f, "Undefined"), Value::none => write!(f, "None"), - Value::bool_value(ref v) => { + Value::bool_value(v) => { if *v { write!(f, "True") } else { write!(f, "False") } } - Value::int_value(ref v) => write!(f, "{v}"), - Value::float_value(ref v) => { + Value::int_value(v) => write!(f, "{v}"), + Value::float_value(v) => { let mut float_str = v.to_string(); if !float_str.contains('.') { float_str.push_str(".0"); @@ -995,12 +997,12 @@ impl fmt::Display for ValueRef { Value::unit_value(_, raw, unit) => { write!(f, "{raw}{unit}") } - Value::str_value(ref v) => write!(f, "{v}"), - Value::list_value(ref v) => { + Value::str_value(v) => write!(f, "{v}"), + Value::list_value(v) => { let values: Vec = v.values.iter().map(|v| v.to_string()).collect(); write!(f, "[{}]", values.join(", ")) } - Value::dict_value(ref v) => { + Value::dict_value(v) => { let values: Vec = v .values .iter() @@ -1008,7 +1010,7 @@ impl fmt::Display for ValueRef { .collect(); write!(f, "{{{}}}", values.join(", ")) } - Value::schema_value(ref v) => { + Value::schema_value(v) => { let values: Vec = v .config .values @@ -1026,13 +1028,13 @@ impl ValueRef { /// to_string_with_spec e.g., "{:.0f}".format(1.0) pub fn to_string_with_spec(&self, spec: &str) -> String { match &*self.rc.borrow() { - Value::int_value(ref v) => { + Value::int_value(v) => { match FormatSpec::parse(spec).and_then(|format_spec| format_spec.format_int(v)) { Ok(string) => string, Err(err) => panic!("{}", err), } } - Value::float_value(ref v) => { + Value::float_value(v) => { match FormatSpec::parse(spec).and_then(|format_spec| format_spec.format_float(*v)) { Ok(string) => string, Err(err) => panic!("{}", err), diff --git a/kclvm/runtime/src/value/val_from.rs b/crates/runtime/src/value/val_from.rs similarity index 100% rename from kclvm/runtime/src/value/val_from.rs rename to crates/runtime/src/value/val_from.rs diff --git a/kclvm/runtime/src/value/val_func.rs b/crates/runtime/src/value/val_func.rs similarity index 100% rename from kclvm/runtime/src/value/val_func.rs rename to crates/runtime/src/value/val_func.rs diff --git a/kclvm/runtime/src/value/val_get_set.rs b/crates/runtime/src/value/val_get_set.rs similarity index 89% rename from kclvm/runtime/src/value/val_get_set.rs rename to crates/runtime/src/value/val_get_set.rs index ceecb7a75..e4fb5ea80 100644 --- a/kclvm/runtime/src/value/val_get_set.rs +++ b/crates/runtime/src/value/val_get_set.rs @@ -5,12 +5,12 @@ use crate::*; impl ValueRef { pub fn get_by_key(&self, key: &str) -> Option { match &*self.rc.borrow() { - Value::list_value(ref list) => match key.parse::() { + Value::list_value(list) => match key.parse::() { Ok(i) => list.values.as_slice().get(i).cloned(), Err(_) => None, }, - Value::dict_value(ref dict) => dict.values.get(key).cloned(), - Value::schema_value(ref schema) => schema.config.values.get(key).cloned(), + Value::dict_value(dict) => dict.values.get(key).cloned(), + Value::schema_value(schema) => schema.config.values.get(key).cloned(), _ => None, } } diff --git a/kclvm/runtime/src/value/val_is_in.rs b/crates/runtime/src/value/val_is_in.rs similarity index 91% rename from kclvm/runtime/src/value/val_is_in.rs rename to crates/runtime/src/value/val_is_in.rs index e93ee9d08..26abf138d 100644 --- a/kclvm/runtime/src/value/val_is_in.rs +++ b/crates/runtime/src/value/val_is_in.rs @@ -120,12 +120,12 @@ impl ValueRef { pub fn r#in(&self, x: &Self) -> bool { match &*x.rc.borrow() { // "a" in "abc" - Value::str_value(ref b) => match &*self.rc.borrow() { - Value::str_value(ref a) => b.contains(a), + Value::str_value(b) => match &*self.rc.borrow() { + Value::str_value(a) => b.contains(a), _ => false, }, // x in [1, 2, 3] - Value::list_value(ref list) => { + Value::list_value(list) => { for v in list.values.as_slice().iter() { if self.cmp_equal(v) { return true; @@ -134,12 +134,12 @@ impl ValueRef { false } // k in {k:v} - Value::dict_value(ref dict) => { + Value::dict_value(dict) => { let key = self.as_str(); dict.values.contains_key(&key) } // k in schema{} - Value::schema_value(ref schema) => { + Value::schema_value(schema) => { let key = self.as_str(); schema.config.values.contains_key(&key) } @@ -161,8 +161,8 @@ impl ValueRef { impl ValueRef { pub fn has_key(&self, key: &str) -> bool { match &*self.rc.borrow() { - Value::dict_value(ref dict) => dict.values.contains_key(key), - Value::schema_value(ref schema) => schema.config.values.contains_key(key), + Value::dict_value(dict) => dict.values.contains_key(key), + Value::schema_value(schema) => schema.config.values.contains_key(key), _ => false, } } diff --git a/kclvm/runtime/src/value/val_json.rs b/crates/runtime/src/value/val_json.rs similarity index 95% rename from kclvm/runtime/src/value/val_json.rs rename to crates/runtime/src/value/val_json.rs index 7118b5c4d..b5e3f0039 100644 --- a/kclvm/runtime/src/value/val_json.rs +++ b/crates/runtime/src/value/val_json.rs @@ -1,13 +1,13 @@ //! Copyright The KCL Authors. All rights reserved. use bstr::ByteSlice; -use kclvm_primitives::{DefaultHashBuilder, IndexMap}; +use kcl_primitives::{DefaultHashBuilder, IndexMap}; use serde::{ - de::{DeserializeSeed, MapAccess, SeqAccess, Visitor}, Deserialize, Serialize, + de::{DeserializeSeed, MapAccess, SeqAccess, Visitor}, }; -use crate::{val_plan::KCL_PRIVATE_VAR_PREFIX, ConfigEntryOperationKind, Context, ValueRef}; +use crate::{ConfigEntryOperationKind, Context, ValueRef, val_plan::KCL_PRIVATE_VAR_PREFIX}; macro_rules! tri { ($e:expr $(,)?) => { @@ -449,21 +449,21 @@ impl ValueRef { crate::Value::undefined => JsonValue::Null, crate::Value::none => JsonValue::Null, - crate::Value::bool_value(ref v) => JsonValue::Bool(*v), - crate::Value::int_value(ref v) => JsonValue::Number(serde_json::Number::from(*v)), - crate::Value::float_value(ref v) => match serde_json::Number::from_f64(*v) { + crate::Value::bool_value(v) => JsonValue::Bool(*v), + crate::Value::int_value(v) => JsonValue::Number(serde_json::Number::from(*v)), + crate::Value::float_value(v) => match serde_json::Number::from_f64(*v) { Some(n) => JsonValue::Number(n), None => JsonValue::Null, }, // The number_multiplier is still a number, if we want to get the string form, we can // use the `str` function e.g. `str(1Mi)` - crate::Value::unit_value(ref v, ..) => match serde_json::Number::from_f64(*v) { + crate::Value::unit_value(v, ..) => match serde_json::Number::from_f64(*v) { Some(n) => JsonValue::Number(n), None => JsonValue::Null, }, - crate::Value::str_value(ref v) => JsonValue::String(v.clone()), + crate::Value::str_value(v) => JsonValue::String(v.clone()), - crate::Value::list_value(ref v) => { + crate::Value::list_value(v) => { let mut val_array = Vec::new(); for x in v.values.iter() { match *x.rc.borrow() { @@ -485,7 +485,7 @@ impl ValueRef { } JsonValue::Array(val_array) } - crate::Value::dict_value(ref v) => { + crate::Value::dict_value(v) => { let mut val_map = IndexMap::with_hasher(DefaultHashBuilder::default()); let mut vals = v.values.clone(); if opts.sort_keys { @@ -515,7 +515,7 @@ impl ValueRef { JsonValue::Object(val_map) } - crate::Value::schema_value(ref v) => { + crate::Value::schema_value(v) => { let mut val_map = IndexMap::with_hasher(DefaultHashBuilder::default()); let mut vals = v.config.values.clone(); if opts.sort_keys { @@ -544,9 +544,7 @@ impl ValueRef { } JsonValue::Object(val_map) } - crate::Value::func_value(ref v) => { - JsonValue::Number(serde_json::Number::from(v.fn_ptr)) - } + crate::Value::func_value(v) => JsonValue::Number(serde_json::Number::from(v.fn_ptr)), } } } diff --git a/kclvm/runtime/src/value/val_kind.rs b/crates/runtime/src/value/val_kind.rs similarity index 95% rename from kclvm/runtime/src/value/val_kind.rs rename to crates/runtime/src/value/val_kind.rs index 3e36e83d6..9bb55dafd 100644 --- a/kclvm/runtime/src/value/val_kind.rs +++ b/crates/runtime/src/value/val_kind.rs @@ -5,7 +5,7 @@ use crate::*; // common impl ValueRef { pub fn kind(&self) -> Kind { - match *self.rc.borrow() { + match &*self.rc.borrow() { Value::undefined => Kind::Undefined, Value::none => Kind::None, Value::bool_value(_) => Kind::Bool, diff --git a/kclvm/runtime/src/value/val_len.rs b/crates/runtime/src/value/val_len.rs similarity index 84% rename from kclvm/runtime/src/value/val_len.rs rename to crates/runtime/src/value/val_len.rs index 602dc81a4..da1c0d2a8 100644 --- a/kclvm/runtime/src/value/val_len.rs +++ b/crates/runtime/src/value/val_len.rs @@ -4,11 +4,11 @@ use crate::*; impl ValueRef { pub fn len(&self) -> usize { - match *self.rc.borrow() { - Value::str_value(ref s) => s.len(), - Value::list_value(ref v) => v.values.len(), - Value::dict_value(ref v) => v.values.len(), - Value::schema_value(ref v) => v.config.values.len(), + match &*self.rc.borrow() { + Value::str_value(s) => s.len(), + Value::list_value(v) => v.values.len(), + Value::dict_value(v) => v.values.len(), + Value::schema_value(v) => v.config.values.len(), _ => panic!("object of type '{}' has no len()", self.type_str()), } } diff --git a/kclvm/runtime/src/value/val_list.rs b/crates/runtime/src/value/val_list.rs similarity index 95% rename from kclvm/runtime/src/value/val_list.rs rename to crates/runtime/src/value/val_list.rs index 9b9f11238..05b293f22 100644 --- a/kclvm/runtime/src/value/val_list.rs +++ b/crates/runtime/src/value/val_list.rs @@ -69,7 +69,7 @@ impl ValueRef { pub fn list_get(&self, i: isize) -> Option { match &*self.rc.borrow() { - Value::list_value(ref list) => { + Value::list_value(list) => { let index = if i < 0 { (i + list.values.len() as isize) as usize } else { @@ -87,7 +87,7 @@ impl ValueRef { pub fn list_get_option(&self, i: isize) -> Option { match &*self.rc.borrow() { - Value::list_value(ref list) => { + Value::list_value(list) => { let index = if i < 0 { (i + list.values.len() as isize) as usize } else { @@ -164,25 +164,27 @@ impl ValueRef { } pub fn list_append_unpack(&mut self, x_or_list: &Self) { - match &mut*self.rc.borrow_mut() { + match &mut *self.rc.borrow_mut() { Value::list_value(list) => match &*x_or_list.rc.borrow() { - Value::list_value(ref list_b) => { + Value::list_value(list_b) => { for x in list_b.values.iter() { list.values.push(x.clone()); } } - Value::dict_value(ref dict_b) => { + Value::dict_value(dict_b) => { for (x, _) in dict_b.values.iter() { list.values.push(Self::str(x.as_str())); } } - Value::schema_value(ref schema_b) => { + Value::schema_value(schema_b) => { for (x, _) in schema_b.config.values.iter() { list.values.push(Self::str(x.as_str())); } } Value::none | Value::undefined => { /*Do nothing on unpacking None/Undefined*/ } - _ => panic!("only list, dict and schema object can be used with unpack operators * and **, got {x_or_list}"), + _ => panic!( + "only list, dict and schema object can be used with unpack operators * and **, got {x_or_list}" + ), }, _ => panic!("Invalid list object in list_append_unpack"), } @@ -191,17 +193,17 @@ impl ValueRef { pub fn list_append_unpack_first(&mut self, x_or_list: &Self) { match &mut *self.rc.borrow_mut() { Value::list_value(list) => match &*x_or_list.rc.borrow() { - Value::list_value(ref list_b) => { + Value::list_value(list_b) => { for (i, x) in list_b.values.iter().enumerate() { list.values.insert(i, x.clone()); } } - Value::dict_value(ref dict_b) => { + Value::dict_value(dict_b) => { for (i, x) in dict_b.values.iter().enumerate() { list.values.insert(i, Self::str(x.0.as_str())); } } - Value::schema_value(ref schema_b) => { + Value::schema_value(schema_b) => { for (i, x) in schema_b.config.values.iter().enumerate() { list.values.insert(i, Self::str(x.0.as_str())); } @@ -219,7 +221,7 @@ impl ValueRef { pub fn list_count(&self, item: &Self) -> usize { let mut count: usize = 0; match &*self.rc.borrow() { - Value::list_value(ref list) => { + Value::list_value(list) => { for v in &list.values { if v == item { count += 1; @@ -233,7 +235,7 @@ impl ValueRef { pub fn list_find(&self, item: &Self) -> isize { match &*self.rc.borrow() { - Value::list_value(ref list) => { + Value::list_value(list) => { for (i, v) in list.values.iter().enumerate() { if v == item { return i as isize; @@ -285,7 +287,7 @@ impl ValueRef { let step_val; let stop_val; match &*step.rc.borrow() { - Value::int_value(ref step) => { + Value::int_value(step) => { step_val = *step; if step_val == 0 { panic!("slice step cannot be zero"); @@ -296,7 +298,7 @@ impl ValueRef { } } match &*start.rc.borrow() { - Value::int_value(ref start) => start_val = *start, + Value::int_value(start) => start_val = *start, _ => { if step_val < 0 { start_val = i64::MAX; @@ -306,7 +308,7 @@ impl ValueRef { } } match &*stop.rc.borrow() { - Value::int_value(ref stop) => stop_val = *stop, + Value::int_value(stop) => stop_val = *stop, _ => { if step_val < 0 { stop_val = i64::MIN; @@ -373,7 +375,7 @@ impl ValueRef { pub fn list_slice(&self, start: &ValueRef, stop: &ValueRef, step: &ValueRef) -> ValueRef { match &*self.rc.borrow() { - Value::list_value(ref list) => { + Value::list_value(list) => { let (start, stop, step) = ValueRef::slice_unpack(start, stop, step); let (start, _stop, slice_len) = ValueRef::slice_adjust_indices(list.values.len() as i64, start, stop, step); @@ -385,7 +387,7 @@ impl ValueRef { } slice } - Value::str_value(ref str) => { + Value::str_value(str) => { let (start, stop, step) = ValueRef::slice_unpack(start, stop, step); let (start, _stop, slice_len) = ValueRef::slice_adjust_indices(str.chars().count() as i64, start, stop, step); diff --git a/kclvm/runtime/src/value/val_logic.rs b/crates/runtime/src/value/val_logic.rs similarity index 83% rename from kclvm/runtime/src/value/val_logic.rs rename to crates/runtime/src/value/val_logic.rs index bb9a2179e..e89c99550 100644 --- a/kclvm/runtime/src/value/val_logic.rs +++ b/crates/runtime/src/value/val_logic.rs @@ -5,18 +5,18 @@ use crate::*; impl ValueRef { #[inline] pub fn is_truthy(&self) -> bool { - match *self.rc.borrow() { + match &*self.rc.borrow() { Value::undefined => false, Value::none => false, - Value::bool_value(ref v) => *v, - Value::int_value(ref v) => *v != 0, - Value::float_value(ref v) => *v != 0.0, - Value::str_value(ref v) => !v.is_empty(), - Value::list_value(ref v) => !v.values.is_empty(), - Value::dict_value(ref v) => !v.values.is_empty(), - Value::schema_value(ref v) => !v.config.values.is_empty(), + Value::bool_value(v) => *v, + Value::int_value(v) => *v != 0, + Value::float_value(v) => *v != 0.0, + Value::str_value(v) => !v.is_empty(), + Value::list_value(v) => !v.values.is_empty(), + Value::dict_value(v) => !v.values.is_empty(), + Value::schema_value(v) => !v.config.values.is_empty(), Value::func_value(_) => true, - Value::unit_value(ref v, _, _) => *v != 0.0, + Value::unit_value(v, _, _) => *v != 0.0, } } diff --git a/kclvm/runtime/src/value/val_overflow.rs b/crates/runtime/src/value/val_overflow.rs similarity index 100% rename from kclvm/runtime/src/value/val_overflow.rs rename to crates/runtime/src/value/val_overflow.rs diff --git a/kclvm/runtime/src/value/val_panic.rs b/crates/runtime/src/value/val_panic.rs similarity index 100% rename from kclvm/runtime/src/value/val_panic.rs rename to crates/runtime/src/value/val_panic.rs diff --git a/kclvm/runtime/src/value/val_plan.rs b/crates/runtime/src/value/val_plan.rs similarity index 98% rename from kclvm/runtime/src/value/val_plan.rs rename to crates/runtime/src/value/val_plan.rs index 3fb041202..0a920bb02 100644 --- a/kclvm/runtime/src/value/val_plan.rs +++ b/crates/runtime/src/value/val_plan.rs @@ -272,7 +272,7 @@ impl ValueRef { None => { return Err(format!( "invalid path select operand {path}, value not found" - )) + )); } }; values.list_append(&value); @@ -287,7 +287,7 @@ impl ValueRef { #[cfg(test)] mod test_value_plan { - use crate::{schema_runtime_type, val_plan::PlanOptions, Context, ValueRef, MAIN_PKG_PATH}; + use crate::{Context, MAIN_PKG_PATH, ValueRef, schema_runtime_type, val_plan::PlanOptions}; use super::filter_results; @@ -432,7 +432,10 @@ mod test_value_plan { config.dict_update_key_value("data_with_pkg", get_test_schema_value_with_pkg()); let (json_string, yaml_string) = config.plan(&ctx); - assert_eq!(json_string, "{\"_hidden\": 1, \"data\": {\"_type\": \"Data\"}, \"data_with_pkg\": {\"_type\": \"pkg.Data\"}}"); + assert_eq!( + json_string, + "{\"_hidden\": 1, \"data\": {\"_type\": \"Data\"}, \"data_with_pkg\": {\"_type\": \"pkg.Data\"}}" + ); assert_eq!( yaml_string, "_hidden: 1\ndata:\n _type: Data\ndata_with_pkg:\n _type: pkg.Data" diff --git a/kclvm/runtime/src/value/val_schema.rs b/crates/runtime/src/value/val_schema.rs similarity index 95% rename from kclvm/runtime/src/value/val_schema.rs rename to crates/runtime/src/value/val_schema.rs index 84022f845..ad8d93a42 100644 --- a/kclvm/runtime/src/value/val_schema.rs +++ b/crates/runtime/src/value/val_schema.rs @@ -1,6 +1,6 @@ //! Copyright The KCL Authors. All rights reserved. -use kclvm_primitives::{DefaultHashBuilder, IndexSet}; +use kcl_primitives::{DefaultHashBuilder, IndexSet}; use crate::*; @@ -94,7 +94,7 @@ impl ValueRef { pub fn schema_to_dict(&self) -> Self { match &*self.rc.borrow() { - Value::schema_value(ref schema) => { + Value::schema_value(schema) => { Self::from(Value::dict_value(Box::new(schema.config.as_ref().clone()))) } Value::dict_value(_) => self.clone(), @@ -211,7 +211,7 @@ impl ValueRef { /// Set the schema instance value with arguments and keyword arguments. pub fn set_schema_args(&mut self, args: &ValueRef, kwargs: &ValueRef) { - if let Value::schema_value(ref mut schema) = &mut *self.rc.borrow_mut() { + if let Value::schema_value(schema) = &mut *self.rc.borrow_mut() { schema.args = args.clone(); schema.kwargs = kwargs.clone(); } @@ -219,8 +219,8 @@ impl ValueRef { pub fn get_potential_schema_type(&self) -> Option { match &*self.rc.borrow() { - Value::dict_value(ref dict) => dict.potential_schema.clone(), - Value::schema_value(ref schema) => schema.config.potential_schema.clone(), + Value::dict_value(dict) => dict.potential_schema.clone(), + Value::schema_value(schema) => schema.config.potential_schema.clone(), _ => None, } } @@ -228,10 +228,8 @@ impl ValueRef { pub fn set_potential_schema_type(&mut self, runtime_type: &str) { if !runtime_type.is_empty() { match &mut *self.rc.borrow_mut() { - Value::dict_value(ref mut dict) => { - dict.potential_schema = Some(runtime_type.to_string()) - } - Value::schema_value(ref mut schema) => { + Value::dict_value(dict) => dict.potential_schema = Some(runtime_type.to_string()), + Value::schema_value(schema) => { schema.config.potential_schema = Some(runtime_type.to_string()) } _ => {} @@ -241,8 +239,8 @@ impl ValueRef { pub fn has_potential_schema_type(&self) -> bool { match &*self.rc.borrow() { - Value::dict_value(ref dict) => dict.potential_schema.is_some(), - Value::schema_value(ref schema) => schema.config.potential_schema.is_some(), + Value::dict_value(dict) => dict.potential_schema.is_some(), + Value::schema_value(schema) => schema.config.potential_schema.is_some(), _ => false, } } diff --git a/kclvm/runtime/src/value/val_str.rs b/crates/runtime/src/value/val_str.rs similarity index 93% rename from kclvm/runtime/src/value/val_str.rs rename to crates/runtime/src/value/val_str.rs index 32f104cc4..032e78cfe 100644 --- a/kclvm/runtime/src/value/val_str.rs +++ b/crates/runtime/src/value/val_str.rs @@ -73,28 +73,28 @@ impl RangeNormal for std::ops::Range { impl ValueRef { pub fn str_len(&self) -> usize { match &*self.rc.borrow() { - Value::str_value(ref v) => v.len(), + Value::str_value(v) => v.len(), _ => panic!("Invalid str object in str len"), } } pub fn str_lower(&self) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => ValueRef::str(&v.to_lowercase()), + Value::str_value(v) => ValueRef::str(&v.to_lowercase()), _ => panic!("Invalid str object in lower"), } } pub fn str_upper(&self) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => ValueRef::str(&v.to_uppercase()), + Value::str_value(v) => ValueRef::str(&v.to_uppercase()), _ => panic!("Invalid str object in upper"), } } pub fn str_capitalize(&self) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let mut chars = v.chars(); let value = if let Some(first_char) = chars.next() { format!( @@ -113,7 +113,7 @@ impl ValueRef { pub fn str_chars(&self) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let chars: Vec = v.chars().map(|c| c.to_string()).collect(); ValueRef::list_str(&chars) } @@ -131,7 +131,7 @@ impl ValueRef { let end = adjust_parameter(end); match (&*self.rc.borrow(), &*sub.rc.borrow()) { - (Value::str_value(ref v), Value::str_value(ref sub_str)) => { + (Value::str_value(v), Value::str_value(sub_str)) => { let range = adjust_indices(start, end, v.len()); let count = if range.is_normal() { v.get(range).unwrap().matches(sub_str).count() @@ -154,7 +154,7 @@ impl ValueRef { let end = adjust_parameter(end); match (&*self.rc.borrow(), &*prefix.rc.borrow()) { - (Value::str_value(ref v), Value::str_value(ref prefix)) => { + (Value::str_value(v), Value::str_value(prefix)) => { let range = adjust_indices(start, end, v.len()); let result = if range.is_normal() { v.get(range).unwrap().starts_with(prefix) @@ -177,7 +177,7 @@ impl ValueRef { let end = adjust_parameter(end); match (&*self.rc.borrow(), &*suffix.rc.borrow()) { - (Value::str_value(ref v), Value::str_value(ref suffix)) => { + (Value::str_value(v), Value::str_value(suffix)) => { let range = adjust_indices(start, end, v.len()); let result = if range.is_normal() { v.get(range).unwrap().ends_with(suffix) @@ -192,7 +192,7 @@ impl ValueRef { pub fn str_format(&self, args: &ValueRef, kwargs: &ValueRef) -> ValueRef { match (&*self.rc.borrow(), &*args.rc.borrow()) { - (Value::str_value(ref v), Value::list_value(_)) => { + (Value::str_value(v), Value::list_value(_)) => { match FormatString::from_str(v.as_str()) { Ok(format_string) => { let result = format_string.format(args, kwargs); @@ -215,7 +215,7 @@ impl ValueRef { let end = adjust_parameter(end); match (&*self.rc.borrow(), &*sub.rc.borrow()) { - (Value::str_value(ref v), Value::str_value(ref sub)) => { + (Value::str_value(v), Value::str_value(sub)) => { let range = adjust_indices(start, end, v.len()); let range_start = range.start; let result: i64 = if range.is_normal() { @@ -242,7 +242,7 @@ impl ValueRef { let end = adjust_parameter(end); match (&*self.rc.borrow(), &*sub.rc.borrow()) { - (Value::str_value(ref v), Value::str_value(ref sub)) => { + (Value::str_value(v), Value::str_value(sub)) => { let range = adjust_indices(start, end, v.len()); let range_start = range.start; let result: i64 = if range.is_normal() { @@ -269,7 +269,7 @@ impl ValueRef { let end = adjust_parameter(end); match (&*self.rc.borrow(), &*sub.rc.borrow()) { - (Value::str_value(ref v), Value::str_value(ref sub)) => { + (Value::str_value(v), Value::str_value(sub)) => { let range = adjust_indices(start, end, v.len()); let range_start = range.start; let result: i64 = if range.is_normal() { @@ -296,7 +296,7 @@ impl ValueRef { let end = adjust_parameter(end); match (&*self.rc.borrow(), &*sub.rc.borrow()) { - (Value::str_value(ref v), Value::str_value(ref sub)) => { + (Value::str_value(v), Value::str_value(sub)) => { let range = adjust_indices(start, end, v.len()); let range_start = range.start; let result: i64 = if range.is_normal() { @@ -315,7 +315,7 @@ impl ValueRef { pub fn str_isalnum(&self) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let result = !v.is_empty() && v.chars().all(char::is_alphanumeric); ValueRef::bool(result) } @@ -325,7 +325,7 @@ impl ValueRef { pub fn str_isalpha(&self) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let result = !v.is_empty() && v.chars().all(char::is_alphabetic); ValueRef::bool(result) } @@ -335,7 +335,7 @@ impl ValueRef { pub fn str_isdigit(&self) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let valid_unicodes: [u16; 10] = [ 0x2070, 0x00B9, 0x00B2, 0x00B3, 0x2074, 0x2075, 0x2076, 0x2077, 0x2078, 0x2079, ]; @@ -352,7 +352,7 @@ impl ValueRef { pub fn str_islower(&self) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let result = is_case(v, char::is_lowercase, char::is_uppercase); ValueRef::bool(result) } @@ -362,7 +362,7 @@ impl ValueRef { pub fn str_isspace(&self) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { if v.is_empty() { return ValueRef::bool(false); } @@ -379,7 +379,7 @@ impl ValueRef { pub fn str_istitle(&self) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { if v.is_empty() { return ValueRef::bool(false); } @@ -411,7 +411,7 @@ impl ValueRef { pub fn str_isupper(&self) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let result = is_case(v, char::is_uppercase, char::is_lowercase); ValueRef::bool(result) } @@ -421,7 +421,7 @@ impl ValueRef { pub fn str_isnumeric(&self) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let result = !v.is_empty() && v.chars().all(char::is_numeric); ValueRef::bool(result) } @@ -431,7 +431,7 @@ impl ValueRef { pub fn str_join(&self, value: &ValueRef) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let mut joined = String::new(); let mut iter = value.iter(); while !iter.is_end() { @@ -451,7 +451,7 @@ impl ValueRef { let value = adjust_parameter(value); match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let value = match value { Some(chars) => { let chars = chars.as_str(); @@ -470,7 +470,7 @@ impl ValueRef { let value = adjust_parameter(value); match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let value = match value { Some(chars) => { let chars = chars.as_str(); @@ -494,7 +494,7 @@ impl ValueRef { let count = adjust_parameter(count); match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let old = old.as_str(); let new = new.as_str(); let result = match count { @@ -518,7 +518,7 @@ impl ValueRef { /// Otherwise, return a copy of the original string. pub fn str_removeprefix(&self, prefix: &ValueRef) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let prefix = prefix.as_str(); match v.strip_prefix(&prefix) { Some(r) => ValueRef::str(r), @@ -533,7 +533,7 @@ impl ValueRef { /// Otherwise, return a copy of the original string. pub fn str_removesuffix(&self, suffix: &ValueRef) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let suffix = suffix.as_str(); match v.strip_suffix(&suffix) { Some(r) => ValueRef::str(r), @@ -549,7 +549,7 @@ impl ValueRef { let maxsplit = adjust_parameter(maxsplit); match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let convert = ValueRef::str; let maxsplit = match maxsplit { Some(v) => v.as_int(), @@ -599,7 +599,7 @@ impl ValueRef { let maxsplit = adjust_parameter(maxsplit); match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let convert = ValueRef::str; let maxsplit = match maxsplit { Some(v) => v.as_int(), @@ -647,7 +647,7 @@ impl ValueRef { let keepends = adjust_parameter(keepends); match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let convert = ValueRef::str; let keepends = match keepends { Some(v) => v.as_bool(), @@ -690,7 +690,7 @@ impl ValueRef { let value = adjust_parameter(value); match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let value = match value { Some(chars) => { let chars = chars.as_str(); @@ -707,7 +707,7 @@ impl ValueRef { pub fn str_title(&self) -> ValueRef { match &*self.rc.borrow() { - Value::str_value(ref v) => { + Value::str_value(v) => { let mut title = String::with_capacity(v.len()); let mut previous_is_cased = false; for c in v.chars() { @@ -738,7 +738,7 @@ impl ValueRef { pub fn str_equal(&self, value: &str) -> bool { match &*self.rc.borrow() { - Value::str_value(ref v) => *v == *value, + Value::str_value(v) => *v == *value, _ => false, } } diff --git a/kclvm/runtime/src/value/val_type.rs b/crates/runtime/src/value/val_type.rs similarity index 91% rename from kclvm/runtime/src/value/val_type.rs rename to crates/runtime/src/value/val_type.rs index 66b631e4c..47697f648 100644 --- a/kclvm/runtime/src/value/val_type.rs +++ b/crates/runtime/src/value/val_type.rs @@ -38,10 +38,10 @@ pub const NUMBER_MULTIPLIER_REGEX: &str = r"^([1-9][0-9]{0,63})(E|P|T|G|M|K|k|m|u|n|Ei|Pi|Ti|Gi|Mi|Ki)$"; pub type SchemaTypeFunc = unsafe extern "C-unwind" fn( - *mut kclvm_context_t, - *const kclvm_value_ref_t, - *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t; + *mut kcl_context_t, + *const kcl_value_ref_t, + *const kcl_value_ref_t, +) -> *const kcl_value_ref_t; // common impl ValueRef { @@ -58,7 +58,7 @@ impl ValueRef { Value::str_value(..) => String::from(BUILTIN_TYPE_STR), Value::list_value(..) => String::from(KCL_TYPE_LIST), Value::dict_value(..) => String::from(KCL_TYPE_DICT), - Value::schema_value(ref v) => v.name.clone(), + Value::schema_value(v) => v.name.clone(), Value::func_value(func) => { if func.runtime_type.is_empty() { String::from(KCL_TYPE_FUNCTION) @@ -94,29 +94,29 @@ pub fn resolve_schema(ctx: &mut Context, schema: &ValueRef, keys: &[String]) -> let config_meta_new = config_meta.clone(); let value = unsafe { let schema_fn: SchemaTypeFunc = transmute_copy(&schema_fn_ptr); - let cal_map = kclvm_value_Dict(ctx as *mut Context); + let cal_map = kcl_value_Dict(ctx as *mut Context); let list = schema_value.args.clone().into_raw(ctx); // Schema function closures // is sub schema - kclvm_list_append(list, ValueRef::bool(false).into_raw(ctx)); + kcl_list_append(list, ValueRef::bool(false).into_raw(ctx)); // config meta - kclvm_list_append(list, config_meta.into_raw(ctx)); + kcl_list_append(list, config_meta.into_raw(ctx)); // schema - kclvm_list_append(list, config.into_raw(ctx)); + kcl_list_append(list, config.into_raw(ctx)); // config - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // optional mapping - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // cal order map - kclvm_list_append(list, cal_map); + kcl_list_append(list, cal_map); // backtrack level map - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // backtrack cache - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // record instance - kclvm_list_append(list, ValueRef::bool(false).into_raw(ctx)); + kcl_list_append(list, ValueRef::bool(false).into_raw(ctx)); // instance pkgpath - kclvm_list_append( + kcl_list_append( list, ValueRef::str(&now_meta_info.kcl_pkgpath).into_raw(ctx), ); @@ -125,25 +125,25 @@ pub fn resolve_schema(ctx: &mut Context, schema: &ValueRef, keys: &[String]) -> let list = schema_value.args.clone().into_raw(ctx); // Schema function closures // is sub schema - kclvm_list_append(list, ValueRef::bool(true).into_raw(ctx)); + kcl_list_append(list, ValueRef::bool(true).into_raw(ctx)); // config meta - kclvm_list_append(list, config_meta_new.into_raw(ctx)); + kcl_list_append(list, config_meta_new.into_raw(ctx)); // schema - kclvm_list_append(list, config_new.into_raw(ctx)); + kcl_list_append(list, config_new.into_raw(ctx)); // config - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // optional mapping - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // cal order map - kclvm_list_append(list, cal_map); + kcl_list_append(list, cal_map); // backtrack level map - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // backtrack cache - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // record instance - kclvm_list_append(list, ValueRef::bool(true).into_raw(ctx)); + kcl_list_append(list, ValueRef::bool(true).into_raw(ctx)); // instance pkgpath - kclvm_list_append( + kcl_list_append( list, ValueRef::str(&now_meta_info.kcl_pkgpath).into_raw(ctx), ); @@ -296,35 +296,35 @@ pub fn convert_collection_value(ctx: &mut Context, value: &ValueRef, tpe: &str) let schema_fn_ptr = schema_fn.fn_ptr; let value = unsafe { let schema_fn: SchemaTypeFunc = transmute_copy(&schema_fn_ptr); - let cal_order = kclvm_value_Dict(ctx as *mut Context); - let list = kclvm_value_List(ctx as *mut Context); + let cal_order = kcl_value_Dict(ctx as *mut Context); + let list = kcl_value_List(ctx as *mut Context); // Schema function closures // is_sub_schema - kclvm_list_append(list, ValueRef::bool(false).into_raw(ctx)); + kcl_list_append(list, ValueRef::bool(false).into_raw(ctx)); // config meta - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // config - kclvm_list_append(list, value.clone().into_raw(ctx)); + kcl_list_append(list, value.clone().into_raw(ctx)); // schema - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // optional mapping - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // cal order map - kclvm_list_append(list, cal_order); + kcl_list_append(list, cal_order); // backtrack level map - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // backtrack cache - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // record instance - kclvm_list_append(list, ValueRef::bool(false).into_raw(ctx)); + kcl_list_append(list, ValueRef::bool(false).into_raw(ctx)); // instance pkgpath - kclvm_list_append( + kcl_list_append( list, ValueRef::str(&now_meta_info.kcl_pkgpath).into_raw(ctx), ); - let dict = kclvm_value_Dict(ctx as *mut Context); + let dict = kcl_value_Dict(ctx as *mut Context); schema_fn(ctx, list, dict); - let list = kclvm_value_List(ctx as *mut Context); + let list = kcl_value_List(ctx as *mut Context); // Try convert the config to schema, if failed, return the config if !value.is_fit_schema(&schema_type, ptr_as_ref(cal_order)) { @@ -333,25 +333,25 @@ pub fn convert_collection_value(ctx: &mut Context, value: &ValueRef, tpe: &str) // Schema function closures // is_sub_schema - kclvm_list_append(list, ValueRef::bool(true).into_raw(ctx)); + kcl_list_append(list, ValueRef::bool(true).into_raw(ctx)); // config meta - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // config - kclvm_list_append(list, value.clone().into_raw(ctx)); + kcl_list_append(list, value.clone().into_raw(ctx)); // schema - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // optional mapping - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // cal order map - kclvm_list_append(list, cal_order); + kcl_list_append(list, cal_order); // backtrack level map - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // backtrack cache - kclvm_list_append(list, kclvm_value_Dict(ctx as *mut Context)); + kcl_list_append(list, kcl_value_Dict(ctx as *mut Context)); // record instance - kclvm_list_append(list, ValueRef::bool(true).into_raw(ctx)); + kcl_list_append(list, ValueRef::bool(true).into_raw(ctx)); // instance pkgpath - kclvm_list_append( + kcl_list_append( list, ValueRef::str(&now_meta_info.kcl_pkgpath).into_raw(ctx), ); diff --git a/kclvm/runtime/src/value/val_unary.rs b/crates/runtime/src/value/val_unary.rs similarity index 90% rename from kclvm/runtime/src/value/val_unary.rs rename to crates/runtime/src/value/val_unary.rs index 4d964e5c7..2dc6bd6bd 100644 --- a/kclvm/runtime/src/value/val_unary.rs +++ b/crates/runtime/src/value/val_unary.rs @@ -6,8 +6,8 @@ impl ValueRef { // +x pub fn unary_plus(&self) -> Self { match &*self.rc.borrow() { - Value::int_value(ref a) => Self::int(*a), - Value::float_value(ref a) => Self::float(*a), + Value::int_value(a) => Self::int(*a), + Value::float_value(a) => Self::float(*a), _ => panic!("bad operand type for unary +: '{}'", self.type_str()), } } @@ -15,8 +15,8 @@ impl ValueRef { // -x pub fn unary_minus(&self) -> Self { match &*self.rc.borrow() { - Value::int_value(ref a) => Self::int(0 - *a), - Value::float_value(ref a) => Self::float(0.0 - *a), + Value::int_value(a) => Self::int(0 - *a), + Value::float_value(a) => Self::float(0.0 - *a), _ => panic!("bad operand type for unary -: '{}'", self.type_str()), } } diff --git a/kclvm/runtime/src/value/val_union.rs b/crates/runtime/src/value/val_union.rs similarity index 96% rename from kclvm/runtime/src/value/val_union.rs rename to crates/runtime/src/value/val_union.rs index 5cc74c610..81ea87685 100644 --- a/kclvm/runtime/src/value/val_union.rs +++ b/crates/runtime/src/value/val_union.rs @@ -130,10 +130,16 @@ impl ValueRef { let index = must_normalize_index(index, origin_value.len()); origin_value.list_set(index, &union_value); } else { - panic!("only non-empty list attribute can be union value with the index {}", index); + panic!( + "only non-empty list attribute can be union value with the index {}", + index + ); } } else { - panic!("only non-empty list attribute can be union value with the index {}", index); + panic!( + "only non-empty list attribute can be union value with the index {}", + index + ); } } None => { @@ -175,7 +181,10 @@ impl ValueRef { let origin_value = obj.values.get_mut(k); if let Some(origin_value) = origin_value { if !origin_value.is_list() { - panic!("only list attribute can be override value with the index {}", index); + panic!( + "only list attribute can be override value with the index {}", + index + ); } let index = must_normalize_index(index, origin_value.len()); if v.is_undefined() { @@ -184,7 +193,10 @@ impl ValueRef { origin_value.list_must_set(index as usize, v); } } else { - panic!("only list attribute can be override value with the index {}", index); + panic!( + "only list attribute can be override value with the index {}", + index + ); } } None => { @@ -208,8 +220,10 @@ impl ValueRef { match index { Some(index) => { let index = *index; - let mut insert_index = - must_normalize_index(index, origin_value.values.len()); + let mut insert_index = must_normalize_index( + index, + origin_value.values.len(), + ); for v in &value.values { origin_value.values.insert(insert_index, v.clone()); insert_index += 1; @@ -224,7 +238,8 @@ impl ValueRef { } _ => panic!( "only list attribute can be inserted value, the origin value type is {} and got value type is {}", - origin_value.type_str(), v.type_str() + origin_value.type_str(), + v.type_str() ), }; } diff --git a/kclvm/runtime/src/value/val_yaml.rs b/crates/runtime/src/value/val_yaml.rs similarity index 100% rename from kclvm/runtime/src/value/val_yaml.rs rename to crates/runtime/src/value/val_yaml.rs diff --git a/kclvm/runtime/src/value/walker.rs b/crates/runtime/src/value/walker.rs similarity index 100% rename from kclvm/runtime/src/value/walker.rs rename to crates/runtime/src/value/walker.rs diff --git a/crates/runtime/src/yaml/mod.rs b/crates/runtime/src/yaml/mod.rs new file mode 100644 index 000000000..b807840f8 --- /dev/null +++ b/crates/runtime/src/yaml/mod.rs @@ -0,0 +1,191 @@ +//! Copyright The KCL Authors. All rights reserved. +use crate::*; + +pub const YAML_STREAM_SEP: &str = "\n---\n"; +pub const JSON_STREAM_SEP: &str = "\n"; + +/// encode(data, sort_keys=False, ignore_private=False, ignore_none=False) +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_yaml_encode( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("data")) { + let s = ValueRef::str( + arg0.to_yaml_string_with_options(&args_to_opts(args, kwargs, 1)) + .as_ref(), + ); + return s.into_raw(mut_ptr_as_ref(ctx)); + } + panic!("encode_all() missing 1 required positional argument: 'data'") +} + +/// encode_all(data, sort_keys=False, ignore_private=False, ignore_none=False) +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_yaml_encode_all( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("data")) { + let opts = args_to_opts(args, kwargs, 1); + let results = arg0 + .as_list_ref() + .values + .iter() + .map(|r| r.to_yaml_string_with_options(&opts)) + .collect::>(); + let s = ValueRef::str(&results.join(YAML_STREAM_SEP)); + return s.into_raw(mut_ptr_as_ref(ctx)); + } + panic!("encode() missing 1 required positional argument: 'data'") +} + +/// decode(value) +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_yaml_decode( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("value")) { + match ValueRef::from_yaml(ctx, arg0.as_str().as_ref()) { + Ok(x) => return x.into_raw(ctx), + Err(err) => panic!("{}", err), + } + } + panic!("decode() missing 1 required positional argument: 'value'") +} + +/// decode_all(value) +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_yaml_decode_all( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("value")) { + match ValueRef::list_from_yaml_stream(ctx, arg0.as_str().as_ref()) { + Ok(x) => return x.into_raw(ctx), + Err(err) => panic!("{}", err), + } + } + panic!("decode_all() missing 1 required positional argument: 'value'") +} + +/// dump_to_file(data, sort_keys=False, ignore_private=False, ignore_none=False) +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_yaml_dump_to_file( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let data = args.arg_i(0).or(kwargs.get_by_key("data")); + let filename = args.arg_i(1).or(kwargs.get_by_key("filename")); + match (data, filename) { + (Some(data), Some(filename)) => { + let filename = filename.as_str(); + + let yaml = data.to_yaml_string_with_options(&args_to_opts(args, kwargs, 2)); + std::fs::write(&filename, yaml) + .unwrap_or_else(|e| panic!("Unable to write file '{}': {}", filename, e)); + kcl_value_Undefined(ctx) + } + _ => { + panic!("dump_to_file() missing 2 required positional arguments: 'data' and 'filename'") + } + } +} + +/// dump_all_to_file(data, sort_keys=False, ignore_private=False, ignore_none=False) +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_yaml_dump_all_to_file( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + + let data = args.arg_i(0).or(kwargs.get_by_key("data")); + let filename = args.arg_i(1).or(kwargs.get_by_key("filename")); + match (data, filename) { + (Some(data), Some(filename)) => { + let filename = filename.as_str(); + let opts = args_to_opts(args, kwargs, 2); + let results = data + .as_list_ref() + .values + .iter() + .map(|r| r.to_yaml_string_with_options(&opts)) + .collect::>(); + + std::fs::write(filename, results.join(YAML_STREAM_SEP)).expect("Unable to write file"); + kcl_value_Undefined(ctx) + } + _ => { + panic!( + "dump_all_to_file() missing 2 required positional arguments: 'data' and 'filename'" + ) + } + } +} + +/// validate(value: str) -> bool +#[unsafe(no_mangle)] + +pub extern "C-unwind" fn kcl_yaml_validate( + ctx: *mut kcl_context_t, + args: *const kcl_value_ref_t, + kwargs: *const kcl_value_ref_t, +) -> *const kcl_value_ref_t { + let args = ptr_as_ref(args); + let kwargs = ptr_as_ref(kwargs); + let ctx = mut_ptr_as_ref(ctx); + + if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("value")) { + match ValueRef::from_yaml_stream(ctx, arg0.as_str().as_ref()) { + Ok(_) => return kcl_value_True(ctx), + Err(_) => return kcl_value_False(ctx), + } + } + panic!("validate() missing 1 required positional argument: 'value'") +} + +fn args_to_opts(args: &ValueRef, kwargs: &ValueRef, index: usize) -> YamlEncodeOptions { + let mut opts = YamlEncodeOptions::default(); + if let Some(sort_keys) = get_call_arg_bool(args, kwargs, index, Some("sort_keys")) { + opts.sort_keys = sort_keys; + } + if let Some(ignore_private) = get_call_arg_bool(args, kwargs, index + 1, Some("ignore_private")) + { + opts.ignore_private = ignore_private; + } + if let Some(ignore_none) = get_call_arg_bool(args, kwargs, index + 2, Some("ignore_none")) { + opts.ignore_none = ignore_none; + } + opts +} diff --git a/crates/sema/Cargo.toml b/crates/sema/Cargo.toml new file mode 100644 index 000000000..50e8fc09c --- /dev/null +++ b/crates/sema/Cargo.toml @@ -0,0 +1,43 @@ +[package] +name = "kcl-sema" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +serde_json = "1.0" +serde = { version = "1", features = ["derive"] } +generational-arena = "0.2.9" +phf = { version = "0.9", features = ["macros"] } +bit-set = "0.5.0" +bitflags = "1.2.1" +once_cell = "1.5.2" +fancy-regex = "0.7.1" +unicode_names2 = "0.4" +petgraph = "0.6.0" +anyhow = "1.0" +regex = "1.7.0" +lazy_static = "1.4.0" + +kcl-primitives = { path = "../primitives" } +kcl-ast = { path = "../ast" } +kcl-ast-pretty = { path = "../ast_pretty" } +kcl-runtime = { path = "../runtime" } +kcl-error = { path = "../error" } +kcl-span = { path = "../span" } +kcl-utils = { path = "../utils" } +compiler_base_span = "0.1.2" +compiler_base_session = "0.1.3" +compiler_base_macros = "0.1.1" +compiler_base_error = "0.1.6" +suggestions = "0.1.1" +parking_lot = { version = "0.12.0", default-features = false } + +[dev-dependencies] +kcl-parser = { path = "../parser" } +criterion = "0.5" + +[[bench]] +name = "my_benchmark" +harness = false diff --git a/kclvm/sema/benches/my_benchmark.rs b/crates/sema/benches/my_benchmark.rs similarity index 88% rename from kclvm/sema/benches/my_benchmark.rs rename to crates/sema/benches/my_benchmark.rs index 309d22094..23a2f9fb6 100644 --- a/kclvm/sema/benches/my_benchmark.rs +++ b/crates/sema/benches/my_benchmark.rs @@ -1,5 +1,5 @@ -use criterion::{criterion_group, criterion_main, Criterion}; -use kclvm_sema::ty::*; +use criterion::{Criterion, criterion_group, criterion_main}; +use kcl_sema::ty::*; use std::sync::Arc; diff --git a/crates/sema/src/advanced_resolver/mod.rs b/crates/sema/src/advanced_resolver/mod.rs new file mode 100644 index 000000000..c76374d2c --- /dev/null +++ b/crates/sema/src/advanced_resolver/mod.rs @@ -0,0 +1,1560 @@ +/* + + core::Namer basic_resolver + │ │ + ▼ ▼ + ┌─────────────────────┐ ┌─────────────────────┐ + │ core::GlobalState │ │ ast_node_type_map │ + └─────────────────────┘ └─────────────────────┘ + │ │ + ▼ ▼ + ┌──────────────────────────────────────────────────────────────────────────────┐ + │ advanced_resolver │ + ├──────────────────────────────────────────────────────────────────────────────┤ + │ ┌─────────────────┐ │ + │ │ ast::Expression │ │ + │ └─────────────────┘ │ + │ │ │ + │ │ resolve_local_value │ + │ ▼ │ + │ ┌─────────────────┐ │ + │ │ ast::Expression │ │ + │ └─────────────────┘ │ + │ │ │ + │ │ resolve_symbol_ref (map Expression to DefinitionSymbols) | + │ ▼ │ + │ ┌─────────────────┐ │ + │ │ ast::Expression │ │ + │ └─────────────────┘ │ + └──────────────────────────────────────────────────────────────────────────────┘ + │ + ▼ build_sema_db (collect symbol locs and analyse scope) + ┌─────────────────────┐ + │ core::GlobalState │ + └─────────────────────┘ +*/ + +use std::{cell::RefCell, rc::Rc}; + +use kcl_error::Position; +use kcl_primitives::IndexSet; + +use crate::{ + core::{ + global_state::GlobalState, + package::ModuleInfo, + scope::{LocalSymbolScope, LocalSymbolScopeKind, RootSymbolScope, ScopeKind, ScopeRef}, + symbol::SymbolRef, + }, + resolver::scope::{NodeKey, NodeTyMap}, +}; + +use kcl_ast::ast::AstIndex; +use kcl_ast::ast::Program; +use kcl_ast::walker::MutSelfTypedResultWalker; +mod node; + +/// AdvancedResolver mainly does two tasks: +/// 1: Traverse AST to parse LocalSymbol and store it in GlobalState, while storing the parsed type in Symbol +/// 2: Establish a mapping between expressions and SymbolRef, specifically injecting symbol information into AST +/// +/// After the work of the advanced resolver is completed, the GlobalState will build the whole semantic database, +/// so that toolchain can query semantic information about the AST +pub struct AdvancedResolver<'ctx> { + pub(crate) ctx: Context<'ctx>, + pub(crate) gs: &'ctx mut GlobalState, +} + +pub struct Context<'ctx> { + pub program: &'ctx Program, + node_ty_map: Rc>, + scopes: Vec, + current_pkgpath: Option, + current_filename: Option, + schema_symbol_stack: Vec>, + start_pos: Position, + end_pos: Position, + cur_node: AstIndex, + + // whether the identifier currently being visited may be a definition + // it will only be true when visiting a l-value or parameter, + // which means advanced resolver will will create the corresponding + // ValueSymbol instead of an UnresolvedSymbol + maybe_def: bool, + // whether in schema config right value, affect lookup def + in_config_r_value: bool, + + is_type_expr: bool, +} + +impl<'ctx> Context<'ctx> { + pub fn get_node_key(&self, id: &AstIndex) -> NodeKey { + NodeKey { + pkgpath: self.current_pkgpath.clone().unwrap(), + id: id.clone(), + } + } +} + +impl<'ctx> AdvancedResolver<'ctx> { + pub fn resolve_program( + program: &'ctx Program, + gs: &'ctx mut GlobalState, + node_ty_map: Rc>, + ) -> anyhow::Result<()> { + let mut advanced_resolver = Self { + gs, + ctx: Context { + program, + node_ty_map, + scopes: vec![], + current_filename: None, + current_pkgpath: None, + schema_symbol_stack: vec![], + start_pos: Position::dummy_pos(), + end_pos: Position::dummy_pos(), + cur_node: AstIndex::default(), + maybe_def: false, + in_config_r_value: false, + is_type_expr: false, + }, + }; + // Scan all scehma symbol + for (name, modules) in advanced_resolver.ctx.program.pkgs.iter() { + advanced_resolver.scan_schemas(name, modules)?; + } + + for (name, modules) in advanced_resolver.ctx.program.pkgs.iter() { + advanced_resolver.walk_pkg(name, modules)?; + } + + advanced_resolver.gs.build_sema_db(); + advanced_resolver.gs.new_or_invalidate_pkgs.clear(); + Ok(()) + } + + fn scan_schemas(&mut self, name: &String, modules: &Vec) -> anyhow::Result<()> { + if !self.gs.new_or_invalidate_pkgs.contains(name) { + return Ok(()); + } + self.ctx.current_pkgpath = Some(name.clone()); + if let Some(pkg_info) = self.gs.get_packages().get_package_info(name) { + if modules.is_empty() { + return Ok(()); + } + if !self.ctx.scopes.is_empty() { + self.ctx.scopes.clear(); + } + + self.enter_root_scope( + name.clone(), + pkg_info.pkg_filepath.clone(), + pkg_info.kfile_paths.clone(), + ); + + let modules = self.ctx.program.get_modules_for_pkg(name); + for module in modules.iter() { + let module = module.read().expect("Failed to acquire module lock"); + self.ctx.current_filename = Some(module.filename.clone()); + self.walk_module_schemas(&module)?; + } + self.leave_scope() + } + Ok(()) + } + + fn walk_pkg(&mut self, name: &String, modules: &Vec) -> anyhow::Result<()> { + if !self.gs.new_or_invalidate_pkgs.contains(name) { + return Ok(()); + } + self.ctx.current_pkgpath = Some(name.clone()); + if let Some(_) = self.gs.get_packages().get_package_info(name) { + if modules.is_empty() { + return Ok(()); + } + if !self.ctx.scopes.is_empty() { + self.ctx.scopes.clear(); + } + + let scope_ref = self + .gs + .get_scopes_mut() + .get_root_scope(name.to_string()) + .unwrap(); + + self.ctx.scopes.push(scope_ref); + let modules = self.ctx.program.get_modules_for_pkg(name); + for module in modules.iter() { + let module = module.read().expect("Failed to acquire module lock"); + self.ctx.current_filename = Some(module.filename.clone()); + self.walk_module(&module)?; + } + self.leave_scope() + } + Ok(()) + } + + fn enter_root_scope( + &mut self, + pkgpath: String, + filename: String, + kfile_paths: IndexSet, + ) { + let package_ref = self + .gs + .get_symbols_mut() + .get_symbol_by_fully_qualified_name(&pkgpath) + .unwrap(); + + let root_scope = RootSymbolScope::new(pkgpath, filename, package_ref, kfile_paths); + let scope_ref = self.gs.get_scopes_mut().alloc_root_scope(root_scope); + self.ctx.scopes.push(scope_ref); + } + + fn enter_local_scope( + &mut self, + filepath: &str, + start: Position, + end: Position, + kind: LocalSymbolScopeKind, + ) { + let parent = *self.ctx.scopes.last().unwrap(); + let local_scope = LocalSymbolScope::new(parent, start, end, kind); + let scope_ref = self.gs.get_scopes_mut().alloc_local_scope(local_scope); + + match parent.get_kind() { + ScopeKind::Root => { + self.gs + .get_scopes_mut() + .roots + .get_mut(parent.get_id()) + .unwrap() + .add_child(filepath, scope_ref); + } + ScopeKind::Local => { + self.gs + .get_scopes_mut() + .locals + .get_mut(parent.get_id()) + .unwrap() + .add_child(scope_ref); + } + } + self.ctx.scopes.push(scope_ref); + } + + fn enter_schema_def_scope( + &mut self, + name: &str, + filepath: &str, + start: Position, + end: Position, + kind: LocalSymbolScopeKind, + ) { + let parent = *self.ctx.scopes.last().unwrap(); + let local_scope = LocalSymbolScope::new(parent, start, end, kind); + let pkg_path = self.ctx.current_pkgpath.clone().unwrap(); + let fqn_name = format!("{pkg_path}.{filepath}.{name}"); + let scope_ref = match self.gs.get_scopes().schema_scope_map.get(&fqn_name) { + Some(scope_ref) => scope_ref.clone(), + None => { + let scope_ref = self.gs.get_scopes_mut().alloc_local_scope(local_scope); + self.gs + .get_scopes_mut() + .schema_scope_map + .insert(fqn_name, scope_ref); + + match parent.get_kind() { + ScopeKind::Root => { + self.gs + .get_scopes_mut() + .roots + .get_mut(parent.get_id()) + .unwrap() + .add_child(filepath, scope_ref); + } + ScopeKind::Local => { + self.gs + .get_scopes_mut() + .locals + .get_mut(parent.get_id()) + .unwrap() + .add_child(scope_ref); + } + } + scope_ref + } + }; + self.ctx.scopes.push(scope_ref); + } + + fn leave_scope(&mut self) { + self.ctx.scopes.pop(); + } + + fn get_current_module_info(&self) -> Option<&ModuleInfo> { + self.gs + .get_packages() + .get_module_info(self.ctx.current_filename.as_ref()?) + } +} + +#[cfg(test)] +mod tests { + use crate::advanced_resolver::AdvancedResolver; + use crate::core::global_state::GlobalState; + use crate::core::symbol::SymbolKind; + use crate::namer::Namer; + use crate::resolver; + + use kcl_ast::MAIN_PKG; + use kcl_error::Position; + use kcl_parser::ParseSession; + use kcl_parser::load_program; + use std::path::Path; + use std::sync::Arc; + + #[cfg(not(target_os = "windows"))] + fn adjust_canonicalization>(p: P) -> String { + p.as_ref().display().to_string() + } + + #[cfg(target_os = "windows")] + fn adjust_canonicalization>(p: P) -> String { + const VERBATIM_PREFIX: &str = r#"\\?\"#; + let p = p.as_ref().display().to_string(); + if p.starts_with(VERBATIM_PREFIX) { + p[VERBATIM_PREFIX.len()..].to_string() + } else { + p + } + } + + #[allow(unused)] + fn print_symbols_info(gs: &GlobalState) { + let base_path = Path::new(".").canonicalize().unwrap(); + let symbols = gs.get_symbols(); + println!("vec!["); + for (key, val) in gs.sema_db.file_sema_map.iter() { + let key_path = Path::new(key) + .strip_prefix(base_path.clone()) + .unwrap_or_else(|_| Path::new(key)) + .to_str() + .unwrap() + .to_string(); + println!( + " (\n \"{}\".to_string().replace(\"/\", &std::path::MAIN_SEPARATOR.to_string()),", + key_path + ); + println!(" vec!["); + for symbol_ref in val.symbols.iter() { + let symbol = symbols.get_symbol(*symbol_ref).unwrap(); + let (start, end) = symbol.get_range(); + println!( + " ({},{},{},{},\"{}\".to_string(),SymbolKind::{:?}),", + start.line, + start.column.unwrap_or(0), + end.line, + end.column.unwrap_or(0), + symbol.get_name(), + symbol_ref.get_kind(), + ); + if let SymbolKind::Unresolved = symbol_ref.get_kind() { + let def_symbol_ref = symbol.get_definition().unwrap(); + let def_symbol = symbols.get_symbol(def_symbol_ref).unwrap(); + let (def_start, def_end) = def_symbol.get_range(); + let def_path = Path::new(&def_start.filename) + .strip_prefix(base_path.clone()) + .unwrap_or_else(|_| Path::new(&def_start.filename)) + .to_str() + .unwrap() + .to_string(); + println!( + " ({},{},{},{},\"{}\".to_string().replace(\"/\", &std::path::MAIN_SEPARATOR.to_string()),SymbolKind::{:?}),", + def_start.line, + def_start.column.unwrap_or(0), + def_end.line, + def_end.column.unwrap_or(0), + def_path, + def_symbol_ref.get_kind(), + ); + } + } + println!(" ],\n ),") + } + println!("]"); + } + + #[test] + fn test_look_up_exact_symbol() { + let sess = Arc::new(ParseSession::default()); + + let path = "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()); + let mut program = load_program(sess.clone(), &[&path], None, None) + .unwrap() + .program; + let mut gs = GlobalState::default(); + Namer::find_symbols(&program, &mut gs); + + let node_ty_map = resolver::resolve_program_with_opts( + &mut program, + resolver::Options { + merge_program: false, + type_erasure: false, + ..Default::default() + }, + None, + ) + .node_ty_map; + AdvancedResolver::resolve_program(&program, &mut gs, node_ty_map).unwrap(); + let base_path = Path::new(".").canonicalize().unwrap(); + // print_symbols_info(&gs); + let except_symbols = vec![ + ( + "src/advanced_resolver/test_data/import_test/e.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + vec![ + (1, 7, 1, 16, "UnionType".to_string(), SymbolKind::Schema), + (2, 4, 2, 5, "a".to_string(), SymbolKind::Attribute), + ], + ), + ( + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + vec![ + (1, 0, 1, 2, "_a".to_string(), SymbolKind::Value), + (2, 7, 2, 11, "Name".to_string(), SymbolKind::Schema), + (3, 4, 3, 13, "firstName".to_string(), SymbolKind::Attribute), + (4, 4, 4, 12, "lastName".to_string(), SymbolKind::Attribute), + (6, 7, 6, 13, "Person".to_string(), SymbolKind::Schema), + (7, 4, 7, 8, "name".to_string(), SymbolKind::Attribute), + (7, 10, 7, 14, "Name".to_string(), SymbolKind::Unresolved), + ( + 2, + 7, + 2, + 11, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Schema, + ), + (8, 4, 8, 7, "age".to_string(), SymbolKind::Attribute), + (10, 0, 10, 7, "_person".to_string(), SymbolKind::Value), + (10, 10, 10, 16, "Person".to_string(), SymbolKind::Unresolved), + ( + 6, + 7, + 6, + 13, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Schema, + ), + (11, 4, 11, 8, "name".to_string(), SymbolKind::Unresolved), + ( + 7, + 4, + 7, + 8, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + (11, 11, 11, 15, "Name".to_string(), SymbolKind::Unresolved), + ( + 2, + 7, + 2, + 11, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Schema, + ), + ( + 12, + 8, + 12, + 17, + "firstName".to_string(), + SymbolKind::Unresolved, + ), + ( + 3, + 4, + 3, + 13, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + ( + 13, + 8, + 13, + 16, + "lastName".to_string(), + SymbolKind::Unresolved, + ), + ( + 4, + 4, + 4, + 12, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + (15, 4, 15, 7, "age".to_string(), SymbolKind::Unresolved), + ( + 8, + 4, + 8, + 7, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + ], + ), + ( + "src/advanced_resolver/test_data/import_test/d.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + vec![ + (1, 7, 1, 13, "Parent".to_string(), SymbolKind::Schema), + (2, 4, 2, 8, "age1".to_string(), SymbolKind::Attribute), + ], + ), + ( + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + vec![ + ( + 1, + 7, + 1, + 20, + "import_test.a".to_string(), + SymbolKind::Unresolved, + ), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/a" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + ( + 2, + 7, + 2, + 20, + "import_test.b".to_string(), + SymbolKind::Unresolved, + ), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/b" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + ( + 3, + 7, + 3, + 20, + "import_test.c".to_string(), + SymbolKind::Unresolved, + ), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/c" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + ( + 4, + 7, + 4, + 20, + "import_test.d".to_string(), + SymbolKind::Unresolved, + ), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/d" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + ( + 5, + 7, + 5, + 20, + "import_test.e".to_string(), + SymbolKind::Unresolved, + ), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/e" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + ( + 6, + 24, + 6, + 25, + "import_test.f".to_string(), + SymbolKind::Unresolved, + ), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/f" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + (7, 7, 7, 10, "pkg".to_string(), SymbolKind::Unresolved), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/pkg" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + (8, 7, 8, 12, "regex".to_string(), SymbolKind::Unresolved), + ( + 1, + 0, + 1, + 0, + "".to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + (10, 7, 10, 11, "Main".to_string(), SymbolKind::Schema), + (10, 12, 10, 13, "d".to_string(), SymbolKind::Unresolved), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/d" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + (10, 14, 10, 20, "Parent".to_string(), SymbolKind::Unresolved), + ( + 1, + 7, + 1, + 13, + "src/advanced_resolver/test_data/import_test/d.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Schema, + ), + (11, 11, 11, 12, "c".to_string(), SymbolKind::Unresolved), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/c" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + ( + 11, + 13, + 11, + 24, + "TestOfMixin".to_string(), + SymbolKind::Unresolved, + ), + ( + 1, + 7, + 1, + 18, + "src/advanced_resolver/test_data/import_test/c.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Schema, + ), + (12, 4, 12, 8, "name".to_string(), SymbolKind::Attribute), + (13, 4, 13, 7, "age".to_string(), SymbolKind::Attribute), + (14, 4, 14, 10, "person".to_string(), SymbolKind::Attribute), + (14, 13, 14, 14, "a".to_string(), SymbolKind::Unresolved), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/a" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + (14, 15, 14, 21, "Person".to_string(), SymbolKind::Unresolved), + ( + 6, + 7, + 6, + 13, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Schema, + ), + ( + 15, + 4, + 15, + 19, + "list_union_type".to_string(), + SymbolKind::Attribute, + ), + (15, 23, 15, 24, "e".to_string(), SymbolKind::Unresolved), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/e" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + ( + 15, + 25, + 15, + 34, + "UnionType".to_string(), + SymbolKind::Unresolved, + ), + ( + 1, + 7, + 1, + 16, + "src/advanced_resolver/test_data/import_test/e.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Schema, + ), + ( + 16, + 4, + 16, + 19, + "dict_union_type".to_string(), + SymbolKind::Attribute, + ), + (16, 23, 16, 24, "g".to_string(), SymbolKind::Unresolved), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/f" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + ( + 16, + 25, + 16, + 34, + "UnionType".to_string(), + SymbolKind::Unresolved, + ), + ( + 1, + 7, + 1, + 16, + "src/advanced_resolver/test_data/import_test/f.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Schema, + ), + (19, 8, 19, 13, "regex".to_string(), SymbolKind::Unresolved), + ( + 1, + 0, + 1, + 0, + "".to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + (19, 14, 19, 19, "match".to_string(), SymbolKind::Unresolved), + ( + 1, + 0, + 1, + 0, + "".to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Function, + ), + (19, 20, 19, 24, "name".to_string(), SymbolKind::Unresolved), + ( + 12, + 4, + 12, + 8, + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + (19, 97, 19, 101, "name".to_string(), SymbolKind::Unresolved), + ( + 12, + 4, + 12, + 8, + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + (21, 3, 21, 4, "a".to_string(), SymbolKind::Unresolved), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/a" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + (21, 5, 21, 7, "_a".to_string(), SymbolKind::Unresolved), + ( + 1, + 0, + 1, + 2, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Value, + ), + (22, 4, 22, 6, "_c".to_string(), SymbolKind::Value), + (23, 5, 23, 6, "a".to_string(), SymbolKind::Unresolved), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/a" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + (23, 7, 23, 9, "_a".to_string(), SymbolKind::Unresolved), + ( + 1, + 0, + 1, + 2, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Value, + ), + (24, 4, 24, 6, "_c".to_string(), SymbolKind::Unresolved), + ( + 22, + 4, + 22, + 6, + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Value, + ), + (26, 4, 26, 6, "_c".to_string(), SymbolKind::Unresolved), + ( + 22, + 4, + 22, + 6, + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Value, + ), + (28, 0, 28, 1, "p".to_string(), SymbolKind::Value), + (28, 4, 28, 8, "Main".to_string(), SymbolKind::Unresolved), + ( + 10, + 7, + 10, + 11, + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Schema, + ), + (29, 4, 29, 8, "name".to_string(), SymbolKind::Unresolved), + ( + 12, + 4, + 12, + 8, + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + (29, 11, 29, 12, "a".to_string(), SymbolKind::Unresolved), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/a" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + ( + 29, + 13, + 29, + 20, + "_person".to_string(), + SymbolKind::Unresolved, + ), + ( + 10, + 0, + 10, + 7, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Value, + ), + (29, 21, 29, 25, "name".to_string(), SymbolKind::Unresolved), + ( + 7, + 4, + 7, + 8, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + ( + 29, + 26, + 29, + 35, + "firstName".to_string(), + SymbolKind::Unresolved, + ), + ( + 3, + 4, + 3, + 13, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + (29, 45, 29, 46, "a".to_string(), SymbolKind::Unresolved), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/a" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + ( + 29, + 47, + 29, + 54, + "_person".to_string(), + SymbolKind::Unresolved, + ), + ( + 10, + 0, + 10, + 7, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Value, + ), + (29, 56, 29, 60, "name".to_string(), SymbolKind::Unresolved), + ( + 7, + 4, + 7, + 8, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + ( + 29, + 61, + 29, + 69, + "lastName".to_string(), + SymbolKind::Unresolved, + ), + ( + 4, + 4, + 4, + 12, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + (30, 4, 30, 7, "age".to_string(), SymbolKind::Unresolved), + ( + 13, + 4, + 13, + 7, + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + (30, 10, 30, 11, "b".to_string(), SymbolKind::Unresolved), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/b" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + (30, 12, 30, 14, "_b".to_string(), SymbolKind::Unresolved), + ( + 1, + 0, + 1, + 2, + "src/advanced_resolver/test_data/import_test/b.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Value, + ), + (30, 17, 30, 18, "a".to_string(), SymbolKind::Unresolved), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/import_test/a" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + ( + 30, + 19, + 30, + 26, + "_person".to_string(), + SymbolKind::Unresolved, + ), + ( + 10, + 0, + 10, + 7, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Value, + ), + (30, 28, 30, 31, "age".to_string(), SymbolKind::Unresolved), + ( + 8, + 4, + 8, + 7, + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + (33, 0, 33, 6, "person".to_string(), SymbolKind::Value), + (33, 9, 33, 12, "pkg".to_string(), SymbolKind::Unresolved), + ( + 0, + 0, + 0, + 0, + "src/advanced_resolver/test_data/pkg" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Package, + ), + (33, 13, 33, 19, "Person".to_string(), SymbolKind::Unresolved), + ( + 4, + 7, + 4, + 13, + "src/advanced_resolver/test_data/pkg/pkg.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Schema, + ), + (34, 4, 34, 8, "name".to_string(), SymbolKind::Unresolved), + ( + 5, + 4, + 5, + 8, + "src/advanced_resolver/test_data/pkg/pkg.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + (34, 9, 34, 13, "name".to_string(), SymbolKind::Unresolved), + ( + 2, + 4, + 2, + 8, + "src/advanced_resolver/test_data/pkg/pkg.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + (37, 0, 37, 1, "x".to_string(), SymbolKind::Value), + (38, 16, 38, 17, "x".to_string(), SymbolKind::Unresolved), + ( + 37, + 0, + 37, + 1, + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Value, + ), + ], + ), + ( + "src/advanced_resolver/test_data/import_test/f.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + vec![ + (1, 7, 1, 16, "UnionType".to_string(), SymbolKind::Schema), + (2, 4, 2, 5, "b".to_string(), SymbolKind::Attribute), + ], + ), + ( + "src/advanced_resolver/test_data/import_test/c.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + vec![ + (1, 7, 1, 18, "TestOfMixin".to_string(), SymbolKind::Schema), + (2, 4, 2, 7, "age".to_string(), SymbolKind::Attribute), + ], + ), + ( + "src/advanced_resolver/test_data/pkg/pkg.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + vec![ + (1, 7, 1, 11, "Name".to_string(), SymbolKind::Schema), + (2, 4, 2, 8, "name".to_string(), SymbolKind::Attribute), + (4, 7, 4, 13, "Person".to_string(), SymbolKind::Schema), + (5, 4, 5, 8, "name".to_string(), SymbolKind::Attribute), + (5, 10, 5, 14, "Name".to_string(), SymbolKind::Unresolved), + ( + 1, + 7, + 1, + 11, + "src/advanced_resolver/test_data/pkg/pkg.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Schema, + ), + (5, 17, 5, 21, "Name".to_string(), SymbolKind::Unresolved), + ( + 1, + 7, + 1, + 11, + "src/advanced_resolver/test_data/pkg/pkg.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Schema, + ), + (5, 23, 5, 27, "name".to_string(), SymbolKind::Unresolved), + ( + 2, + 4, + 2, + 8, + "src/advanced_resolver/test_data/pkg/pkg.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + SymbolKind::Attribute, + ), + ], + ), + ( + "src/advanced_resolver/test_data/import_test/b.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + vec![(1, 0, 1, 2, "_b".to_string(), SymbolKind::Value)], + ), + ]; + let mut skip_def_info = false; + for (filepath, symbols) in except_symbols.iter() { + let abs_filepath = adjust_canonicalization(base_path.join(filepath)); + // symbols will be sorted according to their position in the file + // now we check all symbols + for (index, symbol_info) in symbols.iter().enumerate() { + if skip_def_info { + skip_def_info = false; + continue; + } + let (start_line, start_col, end_line, end_col, name, kind) = symbol_info; + if abs_filepath.is_empty() { + continue; + } + // test look up symbols + let inner_pos = Position { + filename: abs_filepath.clone(), + line: (start_line + end_line) / 2, + column: Some((start_col + end_col) / 2), + }; + let looked_symbol_ref = gs.look_up_exact_symbol(&inner_pos).unwrap(); + let looked_symbol = gs.get_symbols().get_symbol(looked_symbol_ref).unwrap(); + let (start, end) = looked_symbol.get_range(); + // test symbol basic infomation + assert_eq!(start.filename, abs_filepath); + assert_eq!(start.line, *start_line); + assert_eq!(start.column.unwrap_or(0), *start_col); + assert_eq!(end.line, *end_line); + assert_eq!(end.column.unwrap_or(0), *end_col); + assert_eq!(*name, looked_symbol.get_name()); + assert_eq!(looked_symbol_ref.get_kind(), *kind); + + // test find def + if SymbolKind::Unresolved == looked_symbol_ref.get_kind() { + let (start_line, start_col, end_line, end_col, path, kind) = + symbols.get(index + 1).unwrap(); + let def_ref = looked_symbol.get_definition().unwrap(); + let def = gs.get_symbols().get_symbol(def_ref).unwrap(); + let (start, end) = def.get_range(); + let def_filepath = adjust_canonicalization(base_path.join(path)); + assert_eq!(start.line, *start_line); + assert_eq!(start.column.unwrap_or(0), *start_col); + assert_eq!(end.line, *end_line); + assert_eq!(end.column.unwrap_or(0), *end_col); + if !path.is_empty() { + assert_eq!(start.filename, def_filepath); + } + assert_eq!(def_ref.get_kind(), *kind); + skip_def_info = true; + } + } + } + } + + #[test] + fn test_look_up_cloest_symbol() { + let sess = Arc::new(ParseSession::default()); + + let path = "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()); + let mut program = load_program(sess.clone(), &[&path], None, None) + .unwrap() + .program; + let mut gs = GlobalState::default(); + Namer::find_symbols(&program, &mut gs); + let node_ty_map = resolver::resolve_program(&mut program).node_ty_map; + AdvancedResolver::resolve_program(&program, &mut gs, node_ty_map).unwrap(); + let base_path = Path::new(".").canonicalize().unwrap(); + + let test_cases = vec![ + ( + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + 19_u64, + 25_u64, + Some((19, 20, 19, 24, "name".to_string(), SymbolKind::Unresolved)), + ), + ( + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + 32_u64, + 7_u64, + Some((28, 4, 28, 8, "Main".to_string(), SymbolKind::Unresolved)), + ), + ( + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + 35_u64, + 5_u64, + Some((33, 13, 33, 19, "Person".to_string(), SymbolKind::Unresolved)), + ), + ( + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + 28_u64, + 30_u64, + None, + ), + ]; + + for (filepath, line, col, symbol_info) in test_cases.iter() { + let abs_scope_file_path = adjust_canonicalization(base_path.join(filepath)); + let symbol_ref = gs.look_up_closest_symbol(&Position { + filename: abs_scope_file_path.clone(), + line: *line, + column: Some(*col), + }); + + match symbol_info { + Some((start_line, start_col, end_line, end_col, name, kind)) => { + let symbol_ref = symbol_ref.unwrap(); + let symbol = gs.get_symbols().get_symbol(symbol_ref).unwrap(); + + let (start, end) = symbol.get_range(); + assert_eq!(start.line, *start_line); + assert_eq!(start.column.unwrap_or(0), *start_col); + assert_eq!(end.line, *end_line); + assert_eq!(end.column.unwrap_or(0), *end_col); + assert_eq!(*name, symbol.get_name()); + assert_eq!(symbol_ref.get_kind(), *kind); + } + None => assert!(symbol_ref.is_none()), + } + } + } + + #[test] + fn test_look_up_scope() { + let sess = Arc::new(ParseSession::default()); + + let path = "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()); + let mut program = load_program(sess.clone(), &[&path], None, None) + .unwrap() + .program; + let mut gs = GlobalState::default(); + Namer::find_symbols(&program, &mut gs); + let node_ty_map = resolver::resolve_program(&mut program).node_ty_map; + AdvancedResolver::resolve_program(&program, &mut gs, node_ty_map).unwrap(); + let base_path = Path::new(".").canonicalize().unwrap(); + + let scope_test_cases = vec![ + // __main__.Main schema stmt scope + ( + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + 17_u64, + 26_u64, + 10_usize, + ), + // __main__.Main schema expr scope + ( + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + 30, + 6, + 6, + ), + // __main__.Main schema config entry value scope + ( + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + 30, + 20, + 7, + ), + // pkg.Person schema expr scope + ( + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + 33, + 21, + 1, + ), + // pkg.Person schema config entry value scope + ( + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + 34, + 17, + 6, + ), + // __main__ package scope + ( + "src/advanced_resolver/test_data/schema_symbols.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + 36, + 31, + 5, + ), + // import_test.a.Person expr scope + ( + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + 15, + 11, + 6, + ), + // import_test.a.Name expr scope + ( + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + 12, + 5, + 2, + ), + // import_test.a.Name config entry value scope + ( + "src/advanced_resolver/test_data/import_test/a.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()), + 12, + 21, + 8, + ), + ]; + + for (filepath, line, col, def_num) in scope_test_cases.iter() { + let abs_scope_file_path = adjust_canonicalization(base_path.join(filepath)); + let pos = Position { + filename: abs_scope_file_path.clone(), + line: *line, + column: Some(*col), + }; + let scope_ref = gs.look_up_scope(&pos).unwrap(); + let all_defs = gs.get_all_defs_in_scope(scope_ref, &pos).unwrap(); + assert_eq!(all_defs.len(), *def_num) + } + } + + #[test] + fn test_schema_def_scope() { + let sess = Arc::new(ParseSession::default()); + + let path = "src/advanced_resolver/test_data/schema_def_scope.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()); + let mut program = load_program(sess.clone(), &[&path], None, None) + .unwrap() + .program; + let mut gs = GlobalState::default(); + Namer::find_symbols(&program, &mut gs); + let node_ty_map = resolver::resolve_program(&mut program).node_ty_map; + AdvancedResolver::resolve_program(&program, &mut gs, node_ty_map).unwrap(); + let main_pkg_root_scope = gs + .get_scopes() + .get_root_scope(MAIN_PKG.to_string()) + .unwrap(); + assert_eq!( + gs.get_scopes() + .get_scope(&main_pkg_root_scope) + .unwrap() + .get_children() + .len(), + 2 + ); + } + + #[test] + fn test_schema_circle_dep() { + let sess = Arc::new(ParseSession::default()); + + let path = "src/advanced_resolver/test_data/circle_dep/circle_dep.k" + .to_string() + .replace("/", &std::path::MAIN_SEPARATOR.to_string()); + let mut program = load_program(sess.clone(), &[&path], None, None) + .unwrap() + .program; + let mut gs = GlobalState::default(); + Namer::find_symbols(&program, &mut gs); + let node_ty_map = resolver::resolve_program(&mut program).node_ty_map; + AdvancedResolver::resolve_program(&program, &mut gs, node_ty_map).unwrap(); + } +} diff --git a/crates/sema/src/advanced_resolver/node.rs b/crates/sema/src/advanced_resolver/node.rs new file mode 100644 index 000000000..dfca34b04 --- /dev/null +++ b/crates/sema/src/advanced_resolver/node.rs @@ -0,0 +1,2044 @@ +use anyhow::anyhow; +use std::sync::Arc; + +use kcl_ast::ast::{self, Stmt}; +use kcl_ast::pos::GetPos; +use kcl_ast::walker::MutSelfTypedResultWalker; +use kcl_error::{Position, diagnostic::Range}; +use kcl_primitives::{DefaultHashBuilder, IndexMap}; + +use crate::core::symbol::Symbol; +use crate::{ + core::{ + scope::{ConfigScopeContext, LocalSymbolScopeKind}, + symbol::{ + CommentOrDocSymbol, DecoratorSymbol, ExpressionSymbol, SymbolHint, SymbolHintKind, + SymbolRef, SymbolSemanticInfo, UnresolvedSymbol, ValueSymbol, + }, + }, + ty::{ANY_TYPE_STR, Parameter, SCHEMA_MEMBER_FUNCTIONS, Type, TypeKind}, +}; + +use super::AdvancedResolver; + +type ResolvedResult = anyhow::Result>; + +impl<'ctx> MutSelfTypedResultWalker<'ctx> for AdvancedResolver<'_> { + type Result = anyhow::Result>; + + fn walk_module(&mut self, module: &'ctx ast::Module) -> Self::Result { + for stmt in module.body.iter() { + self.stmt(&stmt)?; + } + for comment in module.comments.iter() { + let (start, end) = comment.get_span_pos(); + self.ctx.start_pos = start; + self.ctx.end_pos = end; + self.ctx.cur_node = comment.id.clone(); + self.walk_comment(&comment.node)?; + } + Ok(None) + } + + fn walk_expr_stmt(&mut self, expr_stmt: &'ctx ast::ExprStmt) -> Self::Result { + for expr in expr_stmt.exprs.iter() { + self.expr(&expr)?; + } + Ok(None) + } + + fn walk_unification_stmt( + &mut self, + unification_stmt: &'ctx ast::UnificationStmt, + ) -> Self::Result { + self.ctx.maybe_def = true; + self.walk_identifier_expr(&unification_stmt.target)?; + // Set schema attribute if it is in the schema stmt. + if let Some(parent_scope) = self.ctx.scopes.last() { + if let Some(parent_scope) = self.gs.get_scopes().get_scope(&parent_scope) { + let mut doc = None; + if let Some(schema_symbol) = parent_scope.get_owner() { + let schema_symbol = self + .gs + .get_symbols() + .get_symbol(schema_symbol) + .ok_or(anyhow!("schema_symbol not found1"))?; + if let Some(schema_ty) = schema_symbol.get_sema_info().ty.clone() { + if !unification_stmt.target.node.names.is_empty() { + let schema_ty = schema_ty.into_schema_type(); + if let Some(attr) = schema_ty + .attrs + .get(&unification_stmt.target.node.names[0].node) + { + doc = attr.doc.clone() + } + let attr_symbol = self + .gs + .get_symbols() + .symbols_info + .node_symbol_map + .get( + &self + .ctx + .get_node_key(&unification_stmt.target.node.names[0].id), + ) + .cloned(); + if let Some(attr_symbol) = attr_symbol { + if let Some(symbol) = self + .gs + .get_symbols_mut() + .attributes + .get_mut(attr_symbol.get_id()) + { + symbol.sema_info = SymbolSemanticInfo { + ty: self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key( + &unification_stmt.target.node.names[0].id, + )) + .map(|ty| ty.clone()), + doc, + }; + } + } + } + } + }; + } + } + self.ctx.maybe_def = false; + self.walk_schema_expr(&unification_stmt.value.node)?; + Ok(None) + } + + fn walk_type_alias_stmt(&mut self, type_alias_stmt: &'ctx ast::TypeAliasStmt) -> Self::Result { + let alias_symbol = self + .gs + .get_symbols() + .get_symbol_by_fully_qualified_name( + &(self.ctx.current_pkgpath.as_ref().unwrap().clone() + + "." + + &type_alias_stmt.type_name.node.get_name()), + ) + .ok_or(anyhow!("alias_symbol not found"))?; + if let Some(symbol) = self + .gs + .get_symbols_mut() + .type_aliases + .get_mut(alias_symbol.get_id()) + { + symbol.sema_info = SymbolSemanticInfo { + ty: self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&type_alias_stmt.type_name.id)) + .map(|ty| ty.clone()), + doc: None, + }; + } + self.walk_type_expr(Some(&type_alias_stmt.ty))?; + Ok(None) + } + + fn walk_assign_stmt(&mut self, assign_stmt: &'ctx ast::AssignStmt) -> Self::Result { + for target in &assign_stmt.targets { + self.ctx.maybe_def = true; + self.walk_target_expr_with_hint(target, assign_stmt.ty.is_none())?; + self.ctx.maybe_def = false; + } + self.walk_type_expr(assign_stmt.ty.as_ref().map(|ty| ty.as_ref()))?; + self.expr(&assign_stmt.value)?; + Ok(None) + } + + fn walk_aug_assign_stmt(&mut self, aug_assign_stmt: &'ctx ast::AugAssignStmt) -> Self::Result { + self.walk_target_expr(&aug_assign_stmt.target)?; + self.expr(&aug_assign_stmt.value)?; + Ok(None) + } + + fn walk_assert_stmt(&mut self, assert_stmt: &'ctx ast::AssertStmt) -> Self::Result { + self.expr(&assert_stmt.test)?; + if let Some(if_cond) = &assert_stmt.if_cond { + self.expr(if_cond)?; + } + if let Some(msg) = &assert_stmt.msg { + self.expr(msg)?; + } + Ok(None) + } + + fn walk_if_stmt(&mut self, if_stmt: &'ctx ast::IfStmt) -> Self::Result { + self.expr(&if_stmt.cond)?; + for stmt in if_stmt.body.iter() { + self.stmt(stmt)?; + } + for stmt in if_stmt.orelse.iter() { + self.stmt(stmt)?; + } + Ok(None) + } + + fn walk_import_stmt(&mut self, import_stmt: &'ctx ast::ImportStmt) -> Self::Result { + let ast_id = self.ctx.cur_node.clone(); + let (start_pos, end_pos) = import_stmt + .asname + .clone() + .unwrap_or(import_stmt.path.clone()) + .get_span_pos(); + + let unresolved = UnresolvedSymbol::new( + import_stmt.path.node.clone(), + start_pos, + end_pos, + None, + self.ctx.is_type_expr, + ); + let package_symbol = match self + .gs + .get_symbols() + .get_symbol_by_fully_qualified_name(&import_stmt.path.node) + { + Some(symbol) => symbol, + None => return Ok(None), + }; + let unresolved_ref = self.gs.get_symbols_mut().alloc_unresolved_symbol( + unresolved, + self.ctx.get_node_key(&ast_id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + self.gs + .get_symbols_mut() + .set_def_and_ref(package_symbol, unresolved_ref); + self.gs + .get_symbols_mut() + .symbols_info + .node_symbol_map + .insert(self.ctx.get_node_key(&ast_id), unresolved_ref); + let cur_scope = *self.ctx.scopes.last().unwrap(); + self.gs + .get_scopes_mut() + .add_ref_to_scope(cur_scope, unresolved_ref); + Ok(Some(unresolved_ref)) + } + + fn walk_schema_stmt(&mut self, schema_stmt: &'ctx ast::SchemaStmt) -> Self::Result { + let (start, end) = (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()); + let schema_ty = self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&schema_stmt.name.id)) + .ok_or(anyhow!( + "schema_ty not found when walk schema stmt {:?}", + schema_stmt + ))? + .clone(); + let schema_symbol = self + .gs + .get_symbols() + .get_type_symbol(&schema_ty, self.get_current_module_info()) + .ok_or(anyhow!("schema_symbol not found"))?; + if self + .gs + .get_symbols() + .schemas + .contains(schema_symbol.get_id()) + { + let mut schema_builtin_member = IndexMap::with_hasher(DefaultHashBuilder::default()); + for name in SCHEMA_MEMBER_FUNCTIONS.iter() { + let func_ty = Arc::new(Type::function( + Some(schema_ty.clone()), + Type::list_ref(Type::any_ref()), + &[], + "", + false, + None, + )); + let mut func_value = ValueSymbol::new( + name.to_string(), + Position::dummy_pos(), + Position::dummy_pos(), + Some(schema_symbol), + false, + ); + func_value.sema_info.ty = Some(func_ty); + let func_symbol_ref = self.gs.get_symbols_mut().alloc_value_symbol( + func_value, + self.ctx.get_node_key(&ast::AstIndex::default()), + self.ctx.current_pkgpath.clone().unwrap(), + ); + schema_builtin_member.insert(name.to_string(), func_symbol_ref); + } + self.gs + .get_symbols_mut() + .symbols_info + .schema_builtin_symbols + .insert(schema_symbol, schema_builtin_member); + self.gs + .get_symbols_mut() + .schemas + .get_mut(schema_symbol.get_id()) + .ok_or(anyhow!("schema_symbol not found"))? + .sema_info = SymbolSemanticInfo { + ty: Some(schema_ty.clone()), + doc: schema_stmt.doc.as_ref().map(|doc| doc.node.clone()), + }; + } + + self.resolve_decorator(&schema_stmt.decorators); + + let mut last_end_pos = start.clone(); + + self.enter_schema_def_scope( + &schema_ty.into_schema_type().name, + &self.ctx.current_filename.clone().unwrap(), + start, + end.clone(), + LocalSymbolScopeKind::SchemaDef, + ); + let cur_scope = *self.ctx.scopes.last().unwrap(); + self.gs + .get_scopes_mut() + .set_owner_to_scope(cur_scope, schema_symbol); + if let Some(parent) = &schema_stmt.parent_name { + self.gs + .get_symbols_mut() + .schemas + .get_mut(schema_symbol.get_id()) + .ok_or(anyhow!("schema_symbol not found"))? + .parent_schema = self.walk_identifier_expr(parent)?; + } + if let Some(for_host) = &schema_stmt.for_host_name { + self.gs + .get_symbols_mut() + .schemas + .get_mut(schema_symbol.get_id()) + .ok_or(anyhow!("schema_symbol not found"))? + .for_host = self.walk_identifier_expr(for_host)?; + } + let mut mixins = vec![]; + for mixin in schema_stmt.mixins.iter() { + if let Some(mixin) = self.walk_identifier_expr(mixin)? { + mixins.push(mixin); + } + last_end_pos = mixin.get_end_pos(); + } + self.gs + .get_symbols_mut() + .schemas + .get_mut(schema_symbol.get_id()) + .ok_or(anyhow!("schema_symbol not found"))? + .mixins = mixins; + + if let Some(args) = &schema_stmt.args { + self.walk_arguments(&args.node)?; + last_end_pos = args.get_end_pos(); + } + if let Some(index_signature) = &schema_stmt.index_signature { + if let Some(key_name) = &index_signature.node.key_name { + let (start, end) = key_name.get_span_pos(); + let value = self.gs.get_symbols_mut().alloc_value_symbol( + ValueSymbol::new( + key_name.node.clone(), + start, + end, + Some(schema_symbol), + false, + ), + self.ctx.get_node_key(&index_signature.id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + if let Some(symbol) = self.gs.get_symbols_mut().values.get_mut(value.get_id()) { + symbol.sema_info = SymbolSemanticInfo { + ty: self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&index_signature.id)) + .map(|ty| ty.clone()), + doc: None, + }; + } + + self.gs + .get_scopes_mut() + .add_def_to_scope(cur_scope, key_name.node.clone(), value); + } + self.walk_type_expr(Some(&index_signature.node.value_ty))?; + if let Some(value) = &index_signature.node.value { + self.expr(value)?; + }; + last_end_pos = index_signature.get_end_pos(); + } + + if let Some(doc) = &schema_stmt.doc { + let (start, end) = doc.get_span_pos(); + let comment_symbol = CommentOrDocSymbol::new(start, end, doc.node.clone()); + self.gs.get_symbols_mut().alloc_comment_symbol( + comment_symbol, + self.ctx.get_node_key(&self.ctx.cur_node), + self.ctx.current_pkgpath.clone().unwrap(), + ); + } + + for stmt in schema_stmt.body.iter() { + if let Some(attribute_symbol) = self.stmt(&stmt)? { + let name = self + .gs + .get_symbols() + .get_symbol(attribute_symbol) + .ok_or(anyhow!("attribute_symbol not found"))? + .get_name(); + self.gs + .get_symbols_mut() + .schemas + .get_mut(schema_symbol.get_id()) + .ok_or(anyhow!("schema_symbol not found"))? + .attributes + .insert(name, attribute_symbol); + } + last_end_pos = stmt.get_end_pos(); + } + + let has_check = !schema_stmt.checks.is_empty(); + if has_check { + self.enter_local_scope( + &self.ctx.current_filename.clone().unwrap(), + last_end_pos, + end, + LocalSymbolScopeKind::Check, + ); + } + + for check_expr in schema_stmt.checks.iter() { + self.walk_check_expr(&check_expr.node)?; + } + + if has_check { + self.leave_scope(); + } + self.leave_scope(); + + Ok(Some(schema_symbol)) + } + + fn walk_rule_stmt(&mut self, rule_stmt: &'ctx ast::RuleStmt) -> Self::Result { + let rule_ty = self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&rule_stmt.name.id)) + .ok_or(anyhow!("rule_ty not found"))? + .clone(); + let rule_symbol = self + .gs + .get_symbols() + .get_type_symbol(&rule_ty, self.get_current_module_info()) + .ok_or(anyhow!("rule_symbol not found"))?; + if let Some(symbol) = self + .gs + .get_symbols_mut() + .rules + .get_mut(rule_symbol.get_id()) + { + symbol.sema_info = SymbolSemanticInfo { + ty: self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&rule_stmt.name.id)) + .map(|ty| ty.clone()), + doc: rule_stmt.doc.as_ref().map(|doc| doc.node.clone()), + }; + } + + if let Some(for_host) = &rule_stmt.for_host_name { + self.gs + .get_symbols_mut() + .rules + .get_mut(rule_symbol.get_id()) + .ok_or(anyhow!("rule_symbol not found"))? + .for_host = self.walk_identifier_expr(for_host)?; + } + let mut parent_rules = vec![]; + for parent_rule in rule_stmt.parent_rules.iter() { + parent_rules.push( + self.walk_identifier_expr(parent_rule)? + .ok_or(anyhow!("parent_rule not found"))?, + ); + } + self.gs + .get_symbols_mut() + .rules + .get_mut(rule_symbol.get_id()) + .ok_or(anyhow!("rule_symbol not found"))? + .parent_rules = parent_rules; + self.resolve_decorator(&rule_stmt.decorators); + Ok(Some(rule_symbol)) + } + + fn walk_quant_expr(&mut self, quant_expr: &'ctx ast::QuantExpr) -> Self::Result { + let (start, end) = (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()); + self.expr(&quant_expr.target)?; + self.enter_local_scope( + &self.ctx.current_filename.as_ref().unwrap().clone(), + start, + end, + LocalSymbolScopeKind::Quant, + ); + let cur_scope = *self.ctx.scopes.last().unwrap(); + for target in quant_expr.variables.iter() { + if target.node.names.is_empty() { + continue; + } + let name = target.node.get_name(); + let (start_pos, end_pos): Range = target.get_span_pos(); + let ast_id = if target.node.names.is_empty() { + &target.id + } else { + &target.node.names.last().unwrap().id + }; + let value = self.gs.get_symbols_mut().alloc_value_symbol( + ValueSymbol::new(name.clone(), start_pos, end_pos.clone(), None, false), + self.ctx.get_node_key(&ast_id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + self.gs + .get_scopes_mut() + .add_def_to_scope(cur_scope, name, value); + let symbols = self.gs.get_symbols_mut(); + let ty = match symbols.values.get_mut(value.get_id()) { + Some(symbol) => { + let ty = self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(ast_id)) + .map(|ty| ty.clone()); + symbol.sema_info = SymbolSemanticInfo { + ty: ty.clone(), + doc: None, + }; + ty + } + None => None, + }; + if let Some(ty) = ty { + symbols.alloc_hint( + SymbolHint { + kind: SymbolHintKind::TypeHint(ty.ty_hint()), + pos: end_pos, + }, + self.ctx.current_pkgpath.clone().unwrap(), + ); + } + } + + if let Some(if_cond) = &quant_expr.if_cond { + self.expr(&if_cond)?; + } + self.expr(&quant_expr.test)?; + self.leave_scope(); + Ok(None) + } + + fn walk_schema_attr(&mut self, schema_attr: &'ctx ast::SchemaAttr) -> Self::Result { + let attr_symbol = *self + .gs + .get_symbols() + .symbols_info + .node_symbol_map + .get(&self.ctx.get_node_key(&schema_attr.name.id)) + .ok_or(anyhow!("attr_symbol not found"))?; + let parent_scope = *self.ctx.scopes.last().unwrap(); + let parent_scope = self.gs.get_scopes().get_scope(&parent_scope).unwrap(); + let mut doc = None; + if let Some(schema_symbol) = parent_scope.get_owner() { + let schema_symbol = self + .gs + .get_symbols() + .get_symbol(schema_symbol) + .ok_or(anyhow!("schema_symbol not found"))?; + if let Some(schema_ty) = schema_symbol.get_sema_info().ty.clone() { + let schema_ty = schema_ty.into_schema_type(); + if let Some(attr) = schema_ty.attrs.get(&schema_attr.name.node) { + doc = attr.doc.clone() + } + } + }; + + if let Some(symbol) = self + .gs + .get_symbols_mut() + .attributes + .get_mut(attr_symbol.get_id()) + { + symbol.sema_info = SymbolSemanticInfo { + ty: self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&schema_attr.name.id)) + .map(|ty| ty.clone()), + doc, + }; + }; + + self.walk_type_expr(Some(&schema_attr.ty))?; + if let Some(value) = &schema_attr.value { + self.expr(value)?; + } + + self.resolve_decorator(&schema_attr.decorators); + let cur_scope = *self.ctx.scopes.last().unwrap(); + let name = self + .gs + .get_symbols() + .get_symbol(attr_symbol) + .ok_or(anyhow!("attribute_symbol not found"))? + .get_name(); + self.gs + .get_scopes_mut() + .add_def_to_scope(cur_scope, name, attr_symbol); + Ok(Some(attr_symbol)) + } + + /// if else -> sup([body, orelse]) + fn walk_if_expr(&mut self, if_expr: &'ctx ast::IfExpr) -> Self::Result { + self.expr(&if_expr.cond)?; + self.expr(&if_expr.body)?; + self.expr(&if_expr.orelse)?; + Ok(None) + } + + fn walk_unary_expr(&mut self, unary_expr: &'ctx ast::UnaryExpr) -> Self::Result { + self.expr(&unary_expr.operand)?; + Ok(None) + } + + fn walk_binary_expr(&mut self, binary_expr: &'ctx ast::BinaryExpr) -> Self::Result { + self.expr(&binary_expr.left)?; + self.expr(&binary_expr.right)?; + Ok(None) + } + + fn walk_selector_expr(&mut self, selector_expr: &'ctx ast::SelectorExpr) -> Self::Result { + self.expr(&selector_expr.value)?; + let mut parent_ty = match self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&selector_expr.value.id)) + { + Some(ty) => ty.clone(), + None => return Ok(None), + }; + for name in &selector_expr.attr.node.names { + let def_symbol_ref = match self.gs.get_symbols().get_type_attribute( + &parent_ty, + &name.node, + self.get_current_module_info(), + ) { + Some(symbol) => symbol, + None => return Ok(None), + }; + + let (start_pos, end_pos): Range = name.get_span_pos(); + let ast_id = name.id.clone(); + let unresolved = UnresolvedSymbol::new( + name.node.clone(), + start_pos, + end_pos, + None, + self.ctx.is_type_expr, + ); + let unresolved_ref = self.gs.get_symbols_mut().alloc_unresolved_symbol( + unresolved, + self.ctx.get_node_key(&ast_id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + + self.gs + .get_symbols_mut() + .set_def_and_ref(def_symbol_ref, unresolved_ref); + + let cur_scope = *self.ctx.scopes.last().unwrap(); + self.gs + .get_scopes_mut() + .add_ref_to_scope(cur_scope, unresolved_ref); + + parent_ty = match self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&name.id)) + { + Some(ty) => ty.clone(), + None => return Ok(None), + }; + } + Ok(None) + } + + fn walk_call_expr(&mut self, call_expr: &'ctx ast::CallExpr) -> Self::Result { + let start = call_expr.func.get_end_pos(); + let end = self.ctx.end_pos.clone(); + let func_symbol = self.expr(&call_expr.func)?; + let call_ty = self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&call_expr.func.id)) + .map(|ty| ty.clone()); + + if let Some(ty) = call_ty { + match &ty.kind { + TypeKind::Schema(schema_ty) => { + if !schema_ty.is_instance { + self.enter_local_scope( + &self.ctx.current_filename.as_ref().unwrap().clone(), + start, + end, + LocalSymbolScopeKind::Config, + ); + + if let Some(owner) = func_symbol { + let cur_scope = self.ctx.scopes.last().unwrap(); + self.gs + .get_scopes_mut() + .set_owner_to_scope(*cur_scope, owner); + } + self.do_arguments_symbol_resolve_with_hint( + &call_expr.args, + &call_expr.keywords, + &schema_ty.func.params, + true, + )?; + + self.leave_scope(); + } + } + TypeKind::Function(func_ty) => { + self.enter_local_scope( + &self.ctx.current_filename.as_ref().unwrap().clone(), + start, + end, + LocalSymbolScopeKind::Callable, + ); + + if let Some(owner) = func_symbol { + let cur_scope = self.ctx.scopes.last().unwrap(); + self.gs + .get_scopes_mut() + .set_owner_to_scope(*cur_scope, owner); + } + + self.do_arguments_symbol_resolve_with_hint( + &call_expr.args, + &call_expr.keywords, + &func_ty.params, + true, + )?; + self.leave_scope(); + } + _ => {} + } + } + + Ok(None) + } + + fn walk_subscript(&mut self, subscript: &'ctx ast::Subscript) -> Self::Result { + self.expr(&subscript.value)?; + if let Some(index) = &subscript.index { + self.expr(index)?; + } else { + for expr in [&subscript.lower, &subscript.upper, &subscript.step] + .iter() + .copied() + .flatten() + { + self.expr(expr)?; + } + } + Ok(None) + } + + fn walk_paren_expr(&mut self, paren_expr: &'ctx ast::ParenExpr) -> Self::Result { + self.expr(&paren_expr.expr)?; + Ok(None) + } + + fn walk_list_expr(&mut self, list_expr: &'ctx ast::ListExpr) -> Self::Result { + for expr in list_expr.elts.iter() { + self.expr(expr)?; + } + Ok(None) + } + + fn walk_list_comp(&mut self, list_comp: &'ctx ast::ListComp) -> Self::Result { + let start = list_comp.elt.get_pos(); + let end = match list_comp.generators.last() { + Some(last) => last.get_end_pos(), + None => list_comp.elt.get_end_pos(), + }; + self.enter_local_scope( + &self.ctx.current_filename.clone().unwrap(), + start, + end, + LocalSymbolScopeKind::List, + ); + for comp_clause in &list_comp.generators { + self.walk_comp_clause(&comp_clause.node)?; + } + self.expr(&list_comp.elt)?; + self.leave_scope(); + Ok(None) + } + + fn walk_dict_comp(&mut self, dict_comp: &'ctx ast::DictComp) -> Self::Result { + let (start, key) = match dict_comp.entry.key.as_ref() { + Some(key) => (key.get_pos(), Some(key)), + None => (dict_comp.entry.value.get_pos(), None), + }; + + let end = match dict_comp.generators.last() { + Some(last) => last.get_end_pos(), + None => dict_comp.entry.value.get_end_pos(), + }; + self.enter_local_scope( + &self.ctx.current_filename.clone().unwrap(), + start, + end, + LocalSymbolScopeKind::Dict, + ); + for comp_clause in &dict_comp.generators { + self.walk_comp_clause(&comp_clause.node)?; + } + if let Some(key) = key { + self.expr(key)?; + } + self.expr(&dict_comp.entry.value)?; + self.leave_scope(); + Ok(None) + } + + fn walk_list_if_item_expr( + &mut self, + list_if_item_expr: &'ctx ast::ListIfItemExpr, + ) -> Self::Result { + self.expr(&list_if_item_expr.if_cond)?; + if let Some(orelse) = &list_if_item_expr.orelse { + self.expr(orelse)?; + } + for expr in list_if_item_expr.exprs.iter() { + self.expr(expr)?; + } + Ok(None) + } + + fn walk_starred_expr(&mut self, starred_expr: &'ctx ast::StarredExpr) -> Self::Result { + self.expr(&starred_expr.value)?; + Ok(None) + } + + fn walk_config_if_entry_expr( + &mut self, + config_if_entry_expr: &'ctx ast::ConfigIfEntryExpr, + ) -> Self::Result { + self.expr(&config_if_entry_expr.if_cond)?; + self.walk_config_entries(&config_if_entry_expr.items)?; + if let Some(expr) = config_if_entry_expr.orelse.as_ref() { + self.expr(expr)?; + } + Ok(None) + } + + fn walk_comp_clause(&mut self, comp_clause: &'ctx ast::CompClause) -> Self::Result { + self.expr(&comp_clause.iter)?; + for target in comp_clause.targets.iter() { + self.ctx.maybe_def = true; + self.walk_identifier_expr_with_hint(target, true)?; + self.ctx.maybe_def = false; + } + for if_expr in comp_clause.ifs.iter() { + self.expr(if_expr)?; + } + Ok(None) + } + + fn walk_schema_expr(&mut self, schema_expr: &'ctx ast::SchemaExpr) -> Self::Result { + self.walk_identifier_expr(&schema_expr.name)?; + let schema_ty = self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&schema_expr.name.id)) + .ok_or(anyhow!( + "schema_ty not found when walk schema expr {:?}", + schema_expr + ))? + .clone(); + match schema_ty.kind { + TypeKind::Schema(_) => { + self.expr(&schema_expr.config)?; + self.do_arguments_symbol_resolve(&schema_expr.args, &schema_expr.kwargs)?; + } + _ => { + // Invalid schema type, nothing todo + } + } + Ok(None) + } + + fn walk_config_expr(&mut self, config_expr: &'ctx ast::ConfigExpr) -> Self::Result { + self.walk_config_entries(&config_expr.items)?; + Ok(None) + } + + fn walk_check_expr(&mut self, check_expr: &'ctx ast::CheckExpr) -> Self::Result { + if let Some(msg) = &check_expr.msg { + self.expr(msg)?; + } + if let Some(if_cond) = &check_expr.if_cond { + self.expr(if_cond)?; + } + self.expr(&check_expr.test)?; + Ok(None) + } + + fn walk_lambda_expr(&mut self, lambda_expr: &'ctx ast::LambdaExpr) -> Self::Result { + let (start, end) = (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()); + self.enter_local_scope( + &self.ctx.current_filename.clone().unwrap(), + start, + end, + LocalSymbolScopeKind::Lambda, + ); + if let Some(args) = &lambda_expr.args { + self.walk_arguments(&args.node)?; + } + if let Some(ret_annotation_ty) = &lambda_expr.return_ty { + self.walk_type_expr(Some(&ret_annotation_ty))?; + } + for stmt in lambda_expr.body.iter() { + self.stmt(&stmt)?; + } + self.leave_scope(); + Ok(None) + } + + fn walk_keyword(&mut self, keyword: &'ctx ast::Keyword) -> Self::Result { + self.ctx.maybe_def = true; + self.walk_identifier_expr(&keyword.arg)?; + self.ctx.maybe_def = false; + if let Some(value) = &keyword.value { + self.expr(&value)?; + } + Ok(None) + } + + fn walk_arguments(&mut self, arguments: &'ctx ast::Arguments) -> Self::Result { + for (i, arg) in arguments.args.iter().enumerate() { + let ty = arguments.get_arg_type_node(i); + self.walk_type_expr(ty)?; + self.ctx.maybe_def = true; + self.walk_identifier_expr(arg)?; + self.ctx.maybe_def = false; + + if let Some(val) = &arguments.defaults[i] { + self.expr(val)?; + } + } + Ok(None) + } + + fn walk_compare(&mut self, compare: &'ctx ast::Compare) -> Self::Result { + self.expr(&compare.left)?; + for comparator in compare.comparators.iter() { + self.expr(&comparator)?; + } + Ok(None) + } + + fn walk_identifier(&mut self, identifier: &'ctx ast::Identifier) -> Self::Result { + let symbol_ref = self.resolve_names(&identifier.names, self.ctx.maybe_def)?; + Ok(symbol_ref) + } + + fn walk_target(&mut self, target: &'ctx ast::Target) -> Self::Result { + let symbol_ref = self.resolve_target(&target, self.ctx.maybe_def)?; + Ok(symbol_ref) + } + + fn walk_number_lit(&mut self, _number_lit: &'ctx ast::NumberLit) -> Self::Result { + Ok(None) + } + + fn walk_string_lit(&mut self, _string_lit: &'ctx ast::StringLit) -> Self::Result { + Ok(None) + } + + fn walk_name_constant_lit( + &mut self, + _name_constant_lit: &'ctx ast::NameConstantLit, + ) -> Self::Result { + Ok(None) + } + + fn walk_joined_string(&mut self, joined_string: &'ctx ast::JoinedString) -> Self::Result { + self.ctx.maybe_def = false; + for expr in joined_string.values.iter() { + self.expr(expr)?; + } + Ok(None) + } + + fn walk_formatted_value(&mut self, formatted_value: &'ctx ast::FormattedValue) -> Self::Result { + self.expr(&formatted_value.value)?; + Ok(None) + } + + fn walk_comment(&mut self, comment: &'ctx ast::Comment) -> Self::Result { + let (start, end) = (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()); + let comment_symbol = CommentOrDocSymbol::new(start, end, comment.text.clone()); + Ok(self.gs.get_symbols_mut().alloc_comment_symbol( + comment_symbol, + self.ctx.get_node_key(&self.ctx.cur_node), + self.ctx.current_pkgpath.clone().unwrap(), + )) + } + + fn walk_missing_expr(&mut self, _missing_expr: &'ctx ast::MissingExpr) -> Self::Result { + Ok(None) + } +} + +impl<'ctx> AdvancedResolver<'_> { + #[inline] + pub fn expr(&mut self, expr: &'ctx ast::NodeRef) -> ResolvedResult { + if matches!( + &expr.node, + ast::Expr::Identifier(_) + | ast::Expr::Config(_) + | ast::Expr::Schema(_) + | ast::Expr::ConfigIfEntry(_) + | ast::Expr::Quant(_) + | ast::Expr::Lambda(_) + | ast::Expr::Call(_) + ) { + let (start, end) = expr.get_span_pos(); + self.ctx.start_pos = start; + self.ctx.end_pos = end; + } + self.ctx.cur_node = expr.id.clone(); + + if let Some(expr_ty) = self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&expr.id)) + { + match &expr_ty.kind { + TypeKind::Schema(_) => { + let schema_symbol = self + .gs + .get_symbols() + .get_type_symbol(&expr_ty, self.get_current_module_info()) + .ok_or(anyhow!("schema_symbol not found"))?; + self.ctx.schema_symbol_stack.push(Some(schema_symbol)); + } + _ => { + self.ctx.schema_symbol_stack.push(None); + } + } + } + + let expr_symbol = self.walk_expr(&expr.node); + self.ctx.schema_symbol_stack.pop(); + + match expr_symbol { + Ok(None) => match self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&expr.id)) + { + Some(ty) => match expr.node { + ast::Expr::Missing(_) + | ast::Expr::Binary(_) + | ast::Expr::CompClause(_) + | ast::Expr::Keyword(_) + | ast::Expr::Arguments(_) + | ast::Expr::Compare(_) => return Ok(None), + _ => { + let (_, end) = expr.get_span_pos(); + let mut expr_symbol = ExpressionSymbol::new( + format!("@{}", expr.node.get_expr_name()), + end.clone(), + end, + None, + ); + expr_symbol.sema_info.ty = if matches!(&expr.node, | ast::Expr::Call(_)) { + if let TypeKind::Function(func_ty) = &ty.kind { + Some(func_ty.return_ty.clone()) + } else { + Some(ty.clone()) + } + } else { + Some(ty.clone()) + }; + + Ok(self.gs.get_symbols_mut().alloc_expression_symbol( + expr_symbol, + self.ctx.get_node_key(&expr.id), + self.ctx.current_pkgpath.clone().unwrap(), + )) + } + }, + None => Ok(None), + }, + res => res, + } + } + + #[inline] + pub fn stmt(&mut self, stmt: &'ctx ast::NodeRef) -> ResolvedResult { + let (start, end) = stmt.get_span_pos(); + self.ctx.start_pos = start; + self.ctx.end_pos = end; + self.ctx.cur_node = stmt.id.clone(); + let result = self.walk_stmt(&stmt.node); + result + } + + fn resolve_names(&mut self, names: &[ast::Node], maybe_def: bool) -> ResolvedResult { + let first_name = names.get(0).unwrap(); + let cur_scope = *self.ctx.scopes.last().unwrap(); + + let mut first_symbol = self.gs.look_up_symbol( + &first_name.node, + cur_scope, + self.get_current_module_info(), + maybe_def, + !self.ctx.in_config_r_value, + ); + if first_symbol.is_none() { + // Maybe import package symbol + let module_info = self.get_current_module_info().unwrap(); + + let import_info = module_info.get_import_info(&first_name.node); + if import_info.is_some() && !maybe_def { + first_symbol = self + .gs + .get_symbols() + .get_symbol_by_fully_qualified_name(&import_info.unwrap().fully_qualified_name); + } + + if let Some(first_symbol) = first_symbol { + if self + .gs + .get_symbols() + .get_symbol(first_symbol) + .ok_or(anyhow!("first name symbol not found"))? + .get_sema_info() + .ty + .is_none() + { + if let Some(ty) = self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&first_name.id)) + { + self.gs + .get_symbols_mut() + .set_symbol_type(first_symbol, ty.clone()); + } + } + } + } + match first_symbol { + Some(symbol_ref) => { + let mut ret_symbol = symbol_ref.clone(); + let (start_pos, end_pos): Range = first_name.get_span_pos(); + let def_symbol = self + .gs + .get_symbols() + .get_symbol(symbol_ref) + .ok_or(anyhow!("first name symbol not found"))?; + let (def_start_pos, def_end_pos) = def_symbol.get_range(); + + let cur_scope = *self.ctx.scopes.last().unwrap(); + let ast_id = first_name.id.clone(); + let mut first_unresolved = UnresolvedSymbol::new( + first_name.node.clone(), + start_pos.clone(), + end_pos.clone(), + None, + self.ctx.is_type_expr, + ); + let name = def_symbol.get_name(); + first_unresolved.def = Some(symbol_ref); + let first_unresolved_ref = self.gs.get_symbols_mut().alloc_unresolved_symbol( + first_unresolved, + self.ctx.get_node_key(&ast_id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + + match cur_scope.get_kind() { + crate::core::scope::ScopeKind::Local => { + let local_scope = self + .gs + .get_scopes() + .try_get_local_scope(&cur_scope) + .unwrap(); + match local_scope.get_kind() { + LocalSymbolScopeKind::Config => { + if let crate::core::symbol::SymbolKind::Attribute = + symbol_ref.get_kind() + { + if maybe_def { + self.gs.get_scopes_mut().add_def_to_scope( + cur_scope, + name, + first_unresolved_ref, + ); + ret_symbol = first_unresolved_ref; + } + } + } + _ => {} + } + } + _ => {} + } + + if def_start_pos != start_pos || def_end_pos != end_pos { + self.gs + .get_symbols_mut() + .set_def_and_ref(symbol_ref, first_unresolved_ref); + + let cur_scope = *self.ctx.scopes.last().unwrap(); + self.gs + .get_scopes_mut() + .add_ref_to_scope(cur_scope, first_unresolved_ref); + } + + if names.len() > 1 { + let mut parent_ty = match self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&first_name.id)) + { + Some(ty) => ty.clone(), + None => return Ok(None), + }; + + for index in 1..names.len() { + let name = names.get(index).unwrap(); + let def_symbol_ref = match self.gs.get_symbols().get_type_attribute( + &parent_ty, + &name.node, + self.get_current_module_info(), + ) { + Some(symbol) => symbol, + None => return Ok(None), + }; + + let (start_pos, end_pos): Range = name.get_span_pos(); + let ast_id = name.id.clone(); + let mut unresolved = UnresolvedSymbol::new( + name.node.clone(), + start_pos, + end_pos, + None, + self.ctx.is_type_expr, + ); + + unresolved.sema_info = SymbolSemanticInfo { + ty: self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&name.id)) + .map(|ty| ty.clone()), + doc: None, + }; + + let unresolved_ref = self.gs.get_symbols_mut().alloc_unresolved_symbol( + unresolved, + self.ctx.get_node_key(&ast_id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + + self.gs + .get_symbols_mut() + .set_def_and_ref(def_symbol_ref, unresolved_ref); + + let cur_scope = *self.ctx.scopes.last().unwrap(); + self.gs + .get_scopes_mut() + .add_ref_to_scope(cur_scope, unresolved_ref); + + parent_ty = match self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&name.id)) + { + Some(ty) => ty.clone(), + None => return Ok(None), + }; + if index == names.len() - 1 { + return Ok(Some(unresolved_ref)); + } + } + } + Ok(Some(ret_symbol)) + } + None => { + if maybe_def { + let (start_pos, end_pos): Range = first_name.get_span_pos(); + let ast_id = first_name.id.clone(); + let first_value = self.gs.get_symbols_mut().alloc_value_symbol( + ValueSymbol::new(first_name.node.clone(), start_pos, end_pos, None, false), + self.ctx.get_node_key(&ast_id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + self.gs.get_scopes_mut().add_def_to_scope( + cur_scope, + first_name.node.clone(), + first_value, + ); + + if let Some(symbol) = self + .gs + .get_symbols_mut() + .values + .get_mut(first_value.get_id()) + { + symbol.sema_info = SymbolSemanticInfo { + ty: self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&first_name.id)) + .map(|ty| ty.clone()), + doc: None, + }; + } + + for index in 1..names.len() { + let name = names.get(index).unwrap(); + let (start_pos, end_pos): Range = name.get_span_pos(); + let ast_id = name.id.clone(); + let value = self.gs.get_symbols_mut().alloc_value_symbol( + ValueSymbol::new(name.node.clone(), start_pos, end_pos, None, false), + self.ctx.get_node_key(&ast_id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + + self.gs.get_scopes_mut().add_def_to_scope( + cur_scope, + name.node.clone(), + value, + ); + + if let Some(symbol) = + self.gs.get_symbols_mut().values.get_mut(value.get_id()) + { + symbol.sema_info = SymbolSemanticInfo { + ty: self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&name.id)) + .map(|ty| ty.clone()), + doc: None, + }; + } + if index == names.len() - 1 { + return Ok(Some(value)); + } + } + } + Ok(None) + } + } + } + + fn resolve_target(&mut self, target: &'ctx ast::Target, maybe_def: bool) -> ResolvedResult { + let first_name = &target.name; + let cur_scope = *self.ctx.scopes.last().unwrap(); + + let first_symbol = self.gs.look_up_symbol( + &first_name.node, + cur_scope, + self.get_current_module_info(), + true, + !self.ctx.in_config_r_value, + ); + match first_symbol { + Some(symbol_ref) => { + let (start_pos, end_pos): Range = first_name.get_span_pos(); + let (def_start_pos, def_end_pos) = self + .gs + .get_symbols() + .get_symbol(symbol_ref) + .ok_or(anyhow!("first name symbol not found"))? + .get_range(); + + // Get an unresolved symbol + if def_start_pos != start_pos || def_end_pos != end_pos { + let ast_id = first_name.id.clone(); + let mut first_unresolved = UnresolvedSymbol::new( + first_name.node.clone(), + start_pos, + end_pos, + None, + self.ctx.is_type_expr, + ); + first_unresolved.def = Some(symbol_ref); + let first_unresolved_ref = self.gs.get_symbols_mut().alloc_unresolved_symbol( + first_unresolved, + self.ctx.get_node_key(&ast_id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + let cur_scope = *self.ctx.scopes.last().unwrap(); + self.gs + .get_scopes_mut() + .add_ref_to_scope(cur_scope, first_unresolved_ref); + } + if !target.paths.is_empty() { + let mut parent_ty = match self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&first_name.id)) + { + Some(ty) => ty.clone(), + None => return Ok(None), + }; + + for (index, path) in target.paths.iter().enumerate() { + match path { + ast::MemberOrIndex::Member(member) => { + let name = member; + let def_symbol_ref = match self.gs.get_symbols().get_type_attribute( + &parent_ty, + &name.node, + self.get_current_module_info(), + ) { + Some(symbol) => symbol, + None => return Ok(None), + }; + + let (start_pos, end_pos): Range = name.get_span_pos(); + let ast_id = name.id.clone(); + let mut unresolved = UnresolvedSymbol::new( + name.node.clone(), + start_pos, + end_pos, + None, + self.ctx.is_type_expr, + ); + unresolved.def = Some(def_symbol_ref); + unresolved.sema_info = SymbolSemanticInfo { + ty: self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&name.id)) + .map(|ty| ty.clone()), + doc: None, + }; + + let unresolved_ref = + self.gs.get_symbols_mut().alloc_unresolved_symbol( + unresolved, + self.ctx.get_node_key(&ast_id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + + let cur_scope = *self.ctx.scopes.last().unwrap(); + self.gs + .get_scopes_mut() + .add_ref_to_scope(cur_scope, unresolved_ref); + + parent_ty = match self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&name.id)) + { + Some(ty) => ty.clone(), + None => return Ok(None), + }; + if index == target.paths.len() - 1 { + return Ok(Some(unresolved_ref)); + } + } + ast::MemberOrIndex::Index(index_expr) => { + let last_maybe_def = self.ctx.maybe_def; + self.ctx.maybe_def = false; + let symbol = self.expr(index_expr); + parent_ty = match self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&index_expr.id)) + { + Some(ty) => ty.clone(), + None => return Ok(None), + }; + self.ctx.maybe_def = last_maybe_def; + if index == target.paths.len() { + return symbol; + } + } + } + } + } + Ok(Some(symbol_ref)) + } + None => { + if maybe_def { + let (start_pos, end_pos): Range = first_name.get_span_pos(); + let ast_id = first_name.id.clone(); + let first_value = self.gs.get_symbols_mut().alloc_value_symbol( + ValueSymbol::new(first_name.node.clone(), start_pos, end_pos, None, false), + self.ctx.get_node_key(&ast_id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + self.gs.get_scopes_mut().add_def_to_scope( + cur_scope, + first_name.node.clone(), + first_value, + ); + + if let Some(symbol) = self + .gs + .get_symbols_mut() + .values + .get_mut(first_value.get_id()) + { + symbol.sema_info = SymbolSemanticInfo { + ty: self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&first_name.id)) + .map(|ty| ty.clone()), + doc: None, + }; + } + + for (index, path) in target.paths.iter().enumerate() { + match path { + ast::MemberOrIndex::Member(member) => { + let name = member; + let (start_pos, end_pos): Range = name.get_span_pos(); + let ast_id = name.id.clone(); + let value = self.gs.get_symbols_mut().alloc_value_symbol( + ValueSymbol::new( + name.node.clone(), + start_pos, + end_pos, + None, + false, + ), + self.ctx.get_node_key(&ast_id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + + self.gs.get_scopes_mut().add_def_to_scope( + cur_scope, + name.node.clone(), + value, + ); + + if let Some(symbol) = + self.gs.get_symbols_mut().values.get_mut(value.get_id()) + { + symbol.sema_info = SymbolSemanticInfo { + ty: self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&name.id)) + .map(|ty| ty.clone()), + doc: None, + }; + } + if index == target.paths.len() { + return Ok(Some(value)); + } + } + ast::MemberOrIndex::Index(index_expr) => { + let last_maybe_def = self.ctx.maybe_def; + self.ctx.maybe_def = false; + let symbol = self.expr(index_expr); + self.ctx.maybe_def = last_maybe_def; + if index == target.paths.len() { + return symbol; + } + } + } + } + } + Ok(None) + } + } + } + + #[inline] + pub fn walk_target_expr(&mut self, target: &'ctx ast::NodeRef) -> ResolvedResult { + self.walk_target_expr_with_hint(target, false) + } + + pub fn walk_target_expr_with_hint( + &mut self, + target: &'ctx ast::NodeRef, + with_hint: bool, + ) -> ResolvedResult { + let symbol_ref = if let Some(identifier_symbol) = self + .gs + .get_symbols() + .symbols_info + .node_symbol_map + .get(&self.ctx.get_node_key(&&target.id)) + .map(|symbol_ref| *symbol_ref) + { + let symbols = self.gs.get_symbols_mut(); + + if let Some(symbol) = symbols.values.get_mut(identifier_symbol.get_id()) { + let id = if let Some(last) = target.node.paths.last() { + last.id() + } else { + target.node.name.id.clone() + }; + let ty = self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&id)) + .map(|ty| ty.clone()); + + symbol.sema_info = SymbolSemanticInfo { + ty: ty.clone(), + doc: None, + }; + if with_hint & ty.is_some() { + symbols.alloc_hint( + SymbolHint { + kind: SymbolHintKind::TypeHint(ty.unwrap().ty_hint()), + pos: target.get_end_pos(), + }, + self.ctx.current_pkgpath.clone().unwrap(), + ); + } + } + + let cur_scope = *self.ctx.scopes.last().unwrap(); + match cur_scope.kind { + crate::core::scope::ScopeKind::Local => { + self.gs.get_scopes_mut().add_def_to_scope( + cur_scope, + target.node.get_name().to_string(), + identifier_symbol, + ); + } + crate::core::scope::ScopeKind::Root => {} + } + identifier_symbol + } else { + match self.resolve_target(&target.node, self.ctx.maybe_def)? { + Some(symbol) => symbol, + None => return Ok(None), + } + }; + + Ok(Some(symbol_ref)) + } + + #[inline] + pub fn walk_identifier_expr( + &mut self, + identifier: &'ctx ast::NodeRef, + ) -> ResolvedResult { + self.walk_identifier_expr_with_hint(identifier, false) + } + + pub fn walk_identifier_expr_with_hint( + &mut self, + identifier: &'ctx ast::NodeRef, + with_hint: bool, + ) -> ResolvedResult { + let symbol_ref = if let Some(identifier_symbol) = self + .gs + .get_symbols() + .symbols_info + .node_symbol_map + .get(&self.ctx.get_node_key(&&identifier.id)) + .map(|symbol_ref| *symbol_ref) + { + let symbols = self.gs.get_symbols_mut(); + + if let Some(symbol) = symbols.values.get_mut(identifier_symbol.get_id()) { + let id = if identifier.node.names.is_empty() { + &identifier.id + } else { + &identifier.node.names.last().unwrap().id + }; + let ty = self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&id)) + .map(|ty| ty.clone()); + + symbol.sema_info = SymbolSemanticInfo { + ty: ty.clone(), + doc: None, + }; + if with_hint & ty.is_some() { + symbols.alloc_hint( + SymbolHint { + kind: SymbolHintKind::TypeHint(ty.unwrap().ty_hint()), + pos: identifier.get_end_pos(), + }, + self.ctx.current_pkgpath.clone().unwrap(), + ); + } + } + + if self.ctx.maybe_def && identifier.node.names.len() > 0 { + let cur_scope = *self.ctx.scopes.last().unwrap(); + match cur_scope.kind { + crate::core::scope::ScopeKind::Local => { + self.gs.get_scopes_mut().add_def_to_scope( + cur_scope, + identifier.node.names.last().unwrap().node.clone(), + identifier_symbol, + ); + } + crate::core::scope::ScopeKind::Root => {} + } + } + identifier_symbol + } else { + match self.resolve_names(&identifier.node.names, self.ctx.maybe_def)? { + Some(symbol) => symbol, + None => return Ok(None), + } + }; + + Ok(Some(symbol_ref)) + } + + pub fn walk_type_expr( + &mut self, + ty_node: Option<&'ctx ast::Node>, + ) -> ResolvedResult { + self.ctx.is_type_expr = true; + if let Some(ty_node) = ty_node { + match &ty_node.node { + ast::Type::Any => { + let (start, end) = ty_node.get_span_pos(); + let mut type_symbol = + UnresolvedSymbol::new(ANY_TYPE_STR.to_owned(), start, end, None, true); + + type_symbol.sema_info.ty = Some(Arc::new(Type::ANY)); + self.gs.get_symbols_mut().alloc_unresolved_symbol( + type_symbol, + self.ctx.get_node_key(&ty_node.id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + } + ast::Type::Named(identifier) => { + self.walk_identifier(identifier)?; + } + ast::Type::Basic(_) => {} + ast::Type::List(list_type) => { + self.walk_type_expr(list_type.inner_type.as_ref().map(|ty| ty.as_ref()))?; + } + ast::Type::Dict(dict_type) => { + self.walk_type_expr(dict_type.key_type.as_ref().map(|ty| ty.as_ref()))?; + self.walk_type_expr(dict_type.value_type.as_ref().map(|ty| ty.as_ref()))?; + } + ast::Type::Union(union_type) => { + for elem_ty in union_type.type_elements.iter() { + self.walk_type_expr(Some(elem_ty))?; + } + } + ast::Type::Literal(_) => {} + ast::Type::Function(func_type) => { + if let Some(params_ty) = &func_type.params_ty { + for param_ty in params_ty.iter() { + self.walk_type_expr(Some(param_ty))?; + } + } + if let Some(ret_ty) = &func_type.ret_ty { + self.walk_type_expr(Some(&ret_ty))?; + } + } + } + } + + if let Some(ty_node) = ty_node { + match self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&ty_node.id)) + { + Some(ty) => { + let (_, end) = ty_node.get_span_pos(); + let mut expr_symbol = + ExpressionSymbol::new(format!("@{}", ty.ty_hint()), end.clone(), end, None); + + expr_symbol.sema_info.ty = Some(ty.clone()); + self.gs.get_symbols_mut().alloc_expression_symbol( + expr_symbol, + self.ctx.get_node_key(&ty_node.id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + } + None => {} + } + } + self.ctx.is_type_expr = false; + Ok(None) + } + + pub fn do_arguments_symbol_resolve( + &mut self, + args: &'ctx [ast::NodeRef], + kwargs: &'ctx [ast::NodeRef], + ) -> anyhow::Result<()> { + for arg in args.iter() { + self.expr(arg)?; + } + for kw in kwargs.iter() { + if let Some(value) = &kw.node.value { + self.expr(value)?; + } + let (start_pos, end_pos): Range = kw.node.arg.get_span_pos(); + let value = self.gs.get_symbols_mut().alloc_value_symbol( + ValueSymbol::new(kw.node.arg.node.get_name(), start_pos, end_pos, None, false), + self.ctx.get_node_key(&kw.id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + + if let Some(value) = self.gs.get_symbols_mut().values.get_mut(value.get_id()) { + value.sema_info = SymbolSemanticInfo { + ty: self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&kw.id)) + .map(|ty| ty.clone()), + doc: None, + }; + } + } + Ok(()) + } + + pub fn do_arguments_symbol_resolve_with_hint( + &mut self, + args: &'ctx [ast::NodeRef], + kwargs: &'ctx [ast::NodeRef], + params: &[Parameter], + with_hint: bool, + ) -> anyhow::Result<()> { + if params.is_empty() { + self.do_arguments_symbol_resolve(args, kwargs)?; + } else { + for (arg, param) in args.iter().zip(params.iter()) { + self.expr(arg)?; + + if with_hint { + let symbol_data = self.gs.get_symbols_mut(); + let id = match &arg.node { + ast::Expr::Identifier(id) => id.names.last().unwrap().id.clone(), + _ => arg.id.clone(), + }; + match symbol_data + .symbols_info + .node_symbol_map + .get(&self.ctx.get_node_key(&id)) + { + Some(arg_ref) => match arg_ref.get_kind() { + crate::core::symbol::SymbolKind::Unresolved => { + let mut has_hint = false; + if let Some(unresolved) = + symbol_data.unresolved.get(arg_ref.get_id()) + { + if let Some(def) = unresolved.def { + if let Some(def) = symbol_data.get_symbol(def) { + if def.get_name() != param.name { + has_hint = true; + } + } + } + } + if has_hint { + symbol_data.alloc_hint( + SymbolHint { + kind: SymbolHintKind::VarHint(param.name.clone()), + pos: arg.get_pos(), + }, + self.ctx.current_pkgpath.clone().unwrap(), + ); + } + } + _ => { + symbol_data.alloc_hint( + SymbolHint { + kind: SymbolHintKind::VarHint(param.name.clone()), + pos: arg.get_pos(), + }, + self.ctx.current_pkgpath.clone().unwrap(), + ); + } + }, + None => { + symbol_data.alloc_hint( + SymbolHint { + kind: SymbolHintKind::VarHint(param.name.clone()), + pos: arg.get_pos(), + }, + self.ctx.current_pkgpath.clone().unwrap(), + ); + } + } + } + } + + for kw in kwargs.iter() { + if let Some(value) = &kw.node.value { + self.expr(value)?; + } + let (start_pos, end_pos): Range = kw.node.arg.get_span_pos(); + let value = self.gs.get_symbols_mut().alloc_value_symbol( + ValueSymbol::new(kw.node.arg.node.get_name(), start_pos, end_pos, None, false), + self.ctx.get_node_key(&kw.id), + self.ctx.current_pkgpath.clone().unwrap(), + ); + + if let Some(value) = self.gs.get_symbols_mut().values.get_mut(value.get_id()) { + value.sema_info = SymbolSemanticInfo { + ty: self + .ctx + .node_ty_map + .borrow() + .get(&self.ctx.get_node_key(&kw.id)) + .map(|ty| ty.clone()), + doc: None, + }; + } + } + } + Ok(()) + } + + pub(crate) fn walk_config_entries( + &mut self, + entries: &'ctx [ast::NodeRef], + ) -> anyhow::Result<()> { + let (start, end) = (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()); + + let schema_symbol = self.ctx.schema_symbol_stack.last().unwrap_or(&None).clone(); + let kind = LocalSymbolScopeKind::Config; + + self.enter_local_scope( + &self.ctx.current_filename.as_ref().unwrap().clone(), + start, + end, + kind, + ); + + if let Some(owner) = schema_symbol { + let cur_scope = self.ctx.scopes.last().unwrap(); + self.gs + .get_scopes_mut() + .set_owner_to_scope(*cur_scope, owner); + } + + let mut entries_range = vec![]; + for entry in entries.iter() { + entries_range.push(( + entry.node.key.clone().map(|k| k.get_span_pos()), + entry.node.value.get_span_pos(), + )); + self.ctx.in_config_r_value = true; + self.expr(&entry.node.value)?; + self.ctx.in_config_r_value = false; + + if let Some(key) = &entry.node.key { + self.ctx.maybe_def = true; + if let Some(symbol_ref) = self.expr(key)? { + if let Some(config_key_symbol) = + self.gs.get_symbols().unresolved.get(symbol_ref.get_id()) + { + if let Some(def_ref) = config_key_symbol.get_definition() { + if let Some(def_symbol) = self.gs.get_symbols().get_symbol(def_ref) { + let ty = def_symbol.get_sema_info().ty.clone(); + let symbols = self.gs.get_symbols_mut(); + if let Some(ty) = ty { + symbols.alloc_hint( + SymbolHint { + kind: SymbolHintKind::KeyTypeHint(ty.ty_hint()), + pos: key.get_end_pos(), + }, + self.ctx.current_pkgpath.clone().unwrap(), + ); + } + } + } + } + } + self.ctx.maybe_def = false; + } + } + + let cur_scope = self.ctx.scopes.last().unwrap(); + self.gs + .get_scopes_mut() + .config_scope_context + .insert(cur_scope.get_id(), ConfigScopeContext { entries_range }); + self.leave_scope(); + Ok(()) + } + + pub(crate) fn resolve_decorator(&mut self, decorators: &'ctx [ast::NodeRef]) { + for decorator in decorators { + let func_ident = &decorator.node.func; + let (start, end) = func_ident.get_span_pos(); + if let kcl_ast::ast::Expr::Identifier(id) = &func_ident.node { + let decorator_symbol = DecoratorSymbol::new(start, end, id.get_name()); + self.gs.get_symbols_mut().alloc_decorator_symbol( + decorator_symbol, + self.ctx.get_node_key(&self.ctx.cur_node), + self.ctx.current_pkgpath.clone().unwrap(), + ); + } + } + } + + pub(crate) fn walk_module_schemas(&mut self, module: &'ctx ast::Module) -> anyhow::Result<()> { + for stmt in module.body.iter() { + if matches!(stmt.node, Stmt::Schema(_)) { + self.stmt(stmt)?; + } + } + Ok(()) + } +} diff --git a/kclvm/sema/src/advanced_resolver/test_data/circle_dep/circle_dep.k b/crates/sema/src/advanced_resolver/test_data/circle_dep/circle_dep.k similarity index 100% rename from kclvm/sema/src/advanced_resolver/test_data/circle_dep/circle_dep.k rename to crates/sema/src/advanced_resolver/test_data/circle_dep/circle_dep.k diff --git a/kclvm/sema/src/advanced_resolver/test_data/import_test/a.k b/crates/sema/src/advanced_resolver/test_data/import_test/a.k similarity index 100% rename from kclvm/sema/src/advanced_resolver/test_data/import_test/a.k rename to crates/sema/src/advanced_resolver/test_data/import_test/a.k diff --git a/kclvm/sema/src/advanced_resolver/test_data/import_test/b.k b/crates/sema/src/advanced_resolver/test_data/import_test/b.k similarity index 100% rename from kclvm/sema/src/advanced_resolver/test_data/import_test/b.k rename to crates/sema/src/advanced_resolver/test_data/import_test/b.k diff --git a/kclvm/sema/src/advanced_resolver/test_data/import_test/c.k b/crates/sema/src/advanced_resolver/test_data/import_test/c.k similarity index 100% rename from kclvm/sema/src/advanced_resolver/test_data/import_test/c.k rename to crates/sema/src/advanced_resolver/test_data/import_test/c.k diff --git a/kclvm/sema/src/advanced_resolver/test_data/import_test/d.k b/crates/sema/src/advanced_resolver/test_data/import_test/d.k similarity index 100% rename from kclvm/sema/src/advanced_resolver/test_data/import_test/d.k rename to crates/sema/src/advanced_resolver/test_data/import_test/d.k diff --git a/kclvm/sema/src/advanced_resolver/test_data/import_test/e.k b/crates/sema/src/advanced_resolver/test_data/import_test/e.k similarity index 100% rename from kclvm/sema/src/advanced_resolver/test_data/import_test/e.k rename to crates/sema/src/advanced_resolver/test_data/import_test/e.k diff --git a/kclvm/sema/src/advanced_resolver/test_data/import_test/f.k b/crates/sema/src/advanced_resolver/test_data/import_test/f.k similarity index 100% rename from kclvm/sema/src/advanced_resolver/test_data/import_test/f.k rename to crates/sema/src/advanced_resolver/test_data/import_test/f.k diff --git a/kclvm/sema/src/advanced_resolver/test_data/kcl.mod b/crates/sema/src/advanced_resolver/test_data/kcl.mod similarity index 100% rename from kclvm/sema/src/advanced_resolver/test_data/kcl.mod rename to crates/sema/src/advanced_resolver/test_data/kcl.mod diff --git a/kclvm/sema/src/advanced_resolver/test_data/pkg/pkg.k b/crates/sema/src/advanced_resolver/test_data/pkg/pkg.k similarity index 100% rename from kclvm/sema/src/advanced_resolver/test_data/pkg/pkg.k rename to crates/sema/src/advanced_resolver/test_data/pkg/pkg.k diff --git a/kclvm/sema/src/advanced_resolver/test_data/schema_def_scope.k b/crates/sema/src/advanced_resolver/test_data/schema_def_scope.k similarity index 100% rename from kclvm/sema/src/advanced_resolver/test_data/schema_def_scope.k rename to crates/sema/src/advanced_resolver/test_data/schema_def_scope.k diff --git a/kclvm/sema/src/advanced_resolver/test_data/schema_symbols.k b/crates/sema/src/advanced_resolver/test_data/schema_symbols.k similarity index 100% rename from kclvm/sema/src/advanced_resolver/test_data/schema_symbols.k rename to crates/sema/src/advanced_resolver/test_data/schema_symbols.k diff --git a/kclvm/sema/src/builtin/decorator.rs b/crates/sema/src/builtin/decorator.rs similarity index 95% rename from kclvm/sema/src/builtin/decorator.rs rename to crates/sema/src/builtin/decorator.rs index 74ae5550c..916ade6de 100644 --- a/kclvm/sema/src/builtin/decorator.rs +++ b/crates/sema/src/builtin/decorator.rs @@ -1,7 +1,7 @@ use std::sync::Arc; -use kclvm_error::diagnostic::dummy_range; -use kclvm_primitives::IndexMap; +use kcl_error::diagnostic::dummy_range; +use kcl_primitives::IndexMap; use once_cell::sync::Lazy; use crate::ty::{Parameter, Type}; diff --git a/crates/sema/src/builtin/mod.rs b/crates/sema/src/builtin/mod.rs new file mode 100644 index 000000000..c3dc45774 --- /dev/null +++ b/crates/sema/src/builtin/mod.rs @@ -0,0 +1,588 @@ +//! This package mainly contains the type definitions of built-in system libraries, +//! functions, decorators and member methods. +pub mod decorator; +pub mod option; +pub mod string; +pub mod system_module; + +use std::sync::Arc; + +use kcl_error::diagnostic::dummy_range; +use kcl_primitives::IndexMap; +use once_cell::sync::Lazy; + +use crate::ty::{Parameter, Type}; +pub use decorator::BUILTIN_DECORATORS; +pub use string::STRING_MEMBER_FUNCTIONS; +pub use system_module::*; + +pub const KCL_BUILTIN_FUNCTION_MANGLE_PREFIX: &str = "kcl_builtin"; +pub const KCL_SYSTEM_MODULE_MANGLE_PREFIX: &str = "kcl_"; +pub const BUILTIN_FUNCTION_PREFIX: &str = "$builtin"; + +macro_rules! register_builtin { + ($($name:ident => $ty:expr)*) => ( + // Builtin function map. + pub const BUILTIN_FUNCTIONS: Lazy> = Lazy::new(|| { + let mut builtin_mapping = IndexMap::default(); + $( builtin_mapping.insert(stringify!($name).to_string(), $ty); )* + builtin_mapping + }); + pub static BUILTIN_FUNCTION_NAMES: &[&str] = &[ + $( stringify!($name), )* + ]; + ) +} + +register_builtin! { + option => Type::function( + None, + Arc::new(Type::ANY), + &[ + Parameter { + name: "key".to_string(), + ty: Arc::new(Type::STR), + has_default: false, + default_value: None, + range: dummy_range(), + }, + Parameter { + name: "type".to_string(), + ty: Arc::new(Type::STR), + has_default: true, + default_value: None, + range: dummy_range(), + }, + Parameter { + name: "required".to_string(), + ty: Arc::new(Type::BOOL), + has_default: true, + default_value: None, + range: dummy_range(), + }, + Parameter { + name: "default".to_string(), + ty: Arc::new(Type::ANY), + has_default: true, + default_value: None, + range: dummy_range(), + }, + Parameter { + name: "help".to_string(), + ty: Arc::new(Type::STR), + has_default: true, + default_value: None, + range: dummy_range(), + }, + ], + "Return the top level argument by the key", + false, + Some(1), + ) + print => Type::function( + None, + Arc::new(Type::NONE), + &[], + r#"Prints the values to a stream, or to the system stdout by default. +Optional keyword arguments: +sep: string inserted between values, default a space. +end: string appended after the last value, default a newline."#, + true, + None, + ) + multiplyof => Type::function( + None, + Arc::new(Type::BOOL), + &[ + Parameter { + name: "a".to_string(), + ty: Arc::new(Type::INT), + has_default: false, + default_value: None, + range: dummy_range(), + }, + Parameter { + name: "b".to_string(), + ty: Arc::new(Type::INT), + has_default: false, + default_value: None, + range: dummy_range(), + }, + ], + "Check if the modular result of a and b is 0.", + false, + None, + ) + isunique => Type::function( + None, + Arc::new(Type::BOOL), + &[ + Parameter { + name: "inval".to_string(), + ty: Type::list_ref(Arc::new(Type::ANY)), + has_default: false, + default_value: None, + range: dummy_range(), + }, + ], + "Check if a list has duplicated elements", + false, + None, + ) + isnullish => Type::function( + None, + Arc::new(Type::BOOL), + &[ + Parameter { + name: "inval".to_string(), + ty: Type::any_ref(), + has_default: false, + default_value: None, + range: dummy_range(), + }, + ], + "Return `True` if the input value is `None` or `Undefined`, and `False` otherwise.", + false, + None, + ) + len => Type::function( + None, + Arc::new(Type::INT), + &[ + Parameter { + name: "inval".to_string(), + ty: Type::iterable(), + has_default: false,default_value: None, + range: dummy_range(), + }, + ], + "Return the length of a value.", + false, + None, + ) + abs => Type::function( + None, + Arc::new(Type::ANY), + &[ + Parameter { + name: "inval".to_string(), + ty: Arc::new(Type::ANY), + has_default: false, + default_value: None, + range: dummy_range(), + }, + ], + "Return the absolute value of the argument.", + false, + None, + ) + all_true => Type::function( + None, + Arc::new(Type::BOOL), + &[ + Parameter { + name: "inval".to_string(), + ty: Type::list_ref(Arc::new(Type::ANY)), + has_default: false, + default_value: None, + range: dummy_range(), + }, + ], + r#"Return True if bool(x) is True for all values x in the iterable. + +If the iterable is empty, return True."#, + false, + None, + ) + any_true => Type::function( + None, + Arc::new(Type::BOOL), + &[ + Parameter { + name: "inval".to_string(), + ty: Type::list_ref(Arc::new(Type::ANY)), + has_default: false, + default_value: None, + range: dummy_range(), + }, + ], + r#"Return True if bool(x) is True for any x in the iterable. + +If the iterable is empty, return False."#, + false, + None, + ) + hex => Type::function( + None, + Arc::new(Type::STR), + &[ + Parameter { + name: "number".to_string(), + ty: Arc::new(Type::INT), + has_default: false, + default_value: None, + range: dummy_range(), + }, + ], + "Return the hexadecimal representation of an integer.", + false, + None, + ) + bin => Type::function( + None, + Arc::new(Type::STR), + &[ + Parameter { + name: "number".to_string(), + ty: Arc::new(Type::INT), + has_default: false, + default_value: None, + range: dummy_range(), + }, + ], + "Return the binary representation of an integer.", + false, + None, + ) + oct => Type::function( + None, + Arc::new(Type::STR), + &[ + Parameter { + name: "number".to_string(), + ty: Arc::new(Type::INT), + has_default: false, + default_value: None, + range: dummy_range(), + }, + ], + "Return the octal representation of an integer.", + false, + None, + ) + ord => Type::function( + None, + Arc::new(Type::INT), + &[ + Parameter { + name: "c".to_string(), + ty: Arc::new(Type::STR), + has_default: false, + default_value: None, + range: dummy_range(), + }, + ], + "Return the Unicode code point for a one-character string.", + false, + None, + ) + sorted => Type::function( + None, + Type::list_ref(Arc::new(Type::ANY)), + &[ + Parameter { + name: "inval".to_string(), + ty: Type::iterable(), + has_default: false, + default_value: None, + range: dummy_range(), + }, + Parameter { + name: "reverse".to_string(), + ty: Arc::new(Type::BOOL), + has_default: true,default_value: None, + range: dummy_range(), + }, + ], + r#"Return a new list containing all items from the iterable in ascending order. + +A custom key function can be supplied to customize the sort order, and the reverse +flag can be set to request the result in descending order."#, + false, + Some(1), + ) + range => Type::function( + None, + Type::list_ref(Arc::new(Type::INT)), + &[ + Parameter { + name: "start".to_string(), + ty: Arc::new(Type::INT), + has_default: true, + default_value: None, + range: dummy_range(), + }, + Parameter { + name: "stop".to_string(), + ty: Arc::new(Type::INT), + has_default: true, + default_value: None, + range: dummy_range(), + }, + Parameter { + name: "step".to_string(), + ty: Arc::new(Type::INT), + has_default: true, + default_value: None, + range: dummy_range(), + }, + ], + r#"Return the range of a value."#, + false, + None, + ) + max => Type::function( + None, + Arc::new(Type::ANY), + &[], + r#"With a single iterable argument, return its biggest item. +The default keyword-only argument specifies an object to return +if the provided iterable is empty. With two or more arguments, +return the largest argument."#, + true, + None, + ) + min => Type::function( + None, + Arc::new(Type::ANY), + &[], + r#"With a single iterable argument, return its smallest item. +The default keyword-only argument specifies an object to return +if the provided iterable is empty. With two or more arguments, +return the smallest argument."#, + true, + None, + ) + sum => Type::function( + None, + Arc::new(Type::ANY), + &[ + Parameter { + name: "iterable".to_string(), + ty: Type::list_ref(Arc::new(Type::ANY)), + has_default: false, + default_value: None, + range: dummy_range(), + }, + Parameter { + name: "start".to_string(), + ty: Arc::new(Type::ANY), + has_default: true, + default_value: None, + range: dummy_range(), + }, + ], + r#"When the iterable is empty, return the start value. This function is +intended specifically for use with numeric values and may reject +non-numeric types."#, + false, + None, + ) + pow => Type::function( + None, + Type::number(), + &[ + Parameter { + name: "x".to_string(), + ty: Type::number(), + has_default: false, + default_value: None, + range: dummy_range(), + }, + Parameter { + name: "y".to_string(), + ty: Type::number(), + has_default: false, + default_value: None, + range: dummy_range(), + }, + Parameter { + name: "z".to_string(), + ty: Type::number(), + has_default: true, + default_value: None, + range: dummy_range(), + }, + ], + r#"Equivalent to `x ** y` (with two arguments) or `x ** y % z` (with three arguments) + +Some types, such as ints, are able to use a more efficient algorithm when +invoked using the three argument form."#, + false, + None, + ) + round => Type::function( + None, + Type::number(), + &[ + Parameter { + name: "number".to_string(), + ty: Type::number(), + has_default: false, + default_value: None, + range: dummy_range(), + }, + Parameter { + name: "ndigits".to_string(), + ty: Arc::new(Type::INT), + has_default: true, + default_value: None, + range: dummy_range(), + }, + ], + r#"Round a number to a given precision in decimal digits. + +The return value is an integer if ndigits is omitted or None. +Otherwise the return value has the same type as the number. +ndigits may be negative."#, + false, + None, + ) + zip => Type::function( + None, + Type::list_ref(Arc::new(Type::ANY)), + &[], + r#"Return a zip object whose next method returns +a tuple where the i-th element comes from the i-th iterable +argument."#, + true, + None, + ) + int => Type::function( + None, + Arc::new(Type::INT), + &[ + Parameter { + name: "number".to_string(), + ty: Arc::new(Type::ANY), + has_default: false, + default_value: None, + range: dummy_range(), + }, + Parameter { + name: "base".to_string(), + ty: Arc::new(Type::INT), + has_default: true, + default_value: None, + range: dummy_range(), + }, + ], + r#"Convert a number or string to an integer, or return 0 if no arguments +are given. For floating point numbers, this truncates towards zero."#, + false, + None, + ) + float => Type::function( + None, + Arc::new(Type::FLOAT), + &[ + Parameter { + name: "number".to_string(), + ty: Arc::new(Type::ANY), + has_default: false, + default_value: None, + range: dummy_range(), + }, + ], + r#"Convert a string or number to a floating point number, if possible."#, + false, + None, + ) + bool => Type::function( + None, + Arc::new(Type::BOOL), + &[ + Parameter { + name: "x".to_string(), + ty: Arc::new(Type::ANY), + has_default: true, + default_value: None, + range: dummy_range(), + }, + ], + r#"Returns True when the argument x is true, False otherwise. +The builtin `True` and `False` are the only two instances of the class bool. +The class bool is a subclass of the class int, and cannot be subclassed."#, + false, + None, + ) + str => Type::function( + None, + Arc::new(Type::STR), + &[ + Parameter { + name: "x".to_string(), + ty: Arc::new(Type::ANY), + has_default: true, + default_value: None, + range: dummy_range(), + }, + ], + r#"Create a new string object from the given object. +If encoding or errors is specified, then the object must +expose a data buffer that will be decoded using the +given encoding and error handler."#, + false, + None, + ) + list => Type::function( + None, + Type::list_ref(Arc::new(Type::ANY)), + &[ + Parameter { + name: "x".to_string(), + ty: Arc::new(Type::ANY), + has_default: true, + default_value: None, + range: dummy_range(), + }, + ], + r#"Built-in list function, which can convert other data types or construct a list. + +If no argument is given, the constructor creates a new empty list. +The argument must be an iterable if specified."#, + false, + None, + ) + dict => Type::function( + None, + Type::dict_ref(Arc::new(Type::ANY), Arc::new(Type::ANY)), + &[ + Parameter { + name: "x".to_string(), + ty: Arc::new(Type::ANY), + has_default: true, + default_value: None, + range: dummy_range(), + }, + ], + r#"Built-in dict function. + +If no argument is given, the constructor creates a new empty dict."#, + true, + None, + ) + typeof => Type::function( + None, + Arc::new(Type::STR), + &[ + Parameter { + name: "x".to_string(), + ty: Arc::new(Type::ANY), + has_default: false, + default_value: None, + range: dummy_range(), + }, + Parameter { + name: "full_name".to_string(), + ty: Arc::new(Type::BOOL), + has_default: true, + default_value: None, + range: dummy_range(), + }, + ], + r#"Return the type of the object"#, + false, + None, + ) +} diff --git a/kclvm/sema/src/builtin/option.rs b/crates/sema/src/builtin/option.rs similarity index 100% rename from kclvm/sema/src/builtin/option.rs rename to crates/sema/src/builtin/option.rs diff --git a/kclvm/sema/src/builtin/string.rs b/crates/sema/src/builtin/string.rs similarity index 99% rename from kclvm/sema/src/builtin/string.rs rename to crates/sema/src/builtin/string.rs index 79ccdcec4..dc24343e0 100644 --- a/kclvm/sema/src/builtin/string.rs +++ b/crates/sema/src/builtin/string.rs @@ -1,7 +1,7 @@ use std::sync::Arc; -use kclvm_error::diagnostic::dummy_range; -use kclvm_primitives::IndexMap; +use kcl_error::diagnostic::dummy_range; +use kcl_primitives::IndexMap; use once_cell::sync::Lazy; use crate::ty::{Parameter, Type}; diff --git a/kclvm/sema/src/builtin/system_module.rs b/crates/sema/src/builtin/system_module.rs similarity index 99% rename from kclvm/sema/src/builtin/system_module.rs rename to crates/sema/src/builtin/system_module.rs index 0824ec915..8d62d3d35 100644 --- a/kclvm/sema/src/builtin/system_module.rs +++ b/crates/sema/src/builtin/system_module.rs @@ -3,8 +3,8 @@ use std::sync::Arc; use crate::ty::{Parameter, Type, TypeRef}; -use kclvm_error::diagnostic::dummy_range; -use kclvm_primitives::IndexMap; +use kcl_error::diagnostic::dummy_range; +use kcl_primitives::IndexMap; use once_cell::sync::Lazy; // ------------------------------ diff --git a/kclvm/sema/src/core/global_state.rs b/crates/sema/src/core/global_state.rs similarity index 99% rename from kclvm/sema/src/core/global_state.rs rename to crates/sema/src/core/global_state.rs index 6b1c44834..c2cd1c11d 100644 --- a/kclvm/sema/src/core/global_state.rs +++ b/crates/sema/src/core/global_state.rs @@ -1,7 +1,7 @@ use std::collections::HashSet; -use kclvm_error::Position; -use kclvm_primitives::{IndexMap, IndexSet}; +use kcl_error::Position; +use kcl_primitives::{IndexMap, IndexSet}; use super::{ package::{ModuleInfo, PackageDB}, diff --git a/kclvm/sema/src/core/mod.rs b/crates/sema/src/core/mod.rs similarity index 100% rename from kclvm/sema/src/core/mod.rs rename to crates/sema/src/core/mod.rs diff --git a/kclvm/sema/src/core/package.rs b/crates/sema/src/core/package.rs similarity index 98% rename from kclvm/sema/src/core/package.rs rename to crates/sema/src/core/package.rs index 4ffad0567..1df849459 100644 --- a/kclvm/sema/src/core/package.rs +++ b/crates/sema/src/core/package.rs @@ -1,6 +1,6 @@ use std::collections::HashSet; -use kclvm_primitives::{IndexMap, IndexSet}; +use kcl_primitives::{IndexMap, IndexSet}; #[derive(Default, Debug, Clone)] pub struct PackageDB { diff --git a/crates/sema/src/core/scope.rs b/crates/sema/src/core/scope.rs new file mode 100644 index 000000000..b4ea4d2e8 --- /dev/null +++ b/crates/sema/src/core/scope.rs @@ -0,0 +1,745 @@ +use std::collections::{HashMap, HashSet}; + +use kcl_ast::pos::ContainsPos; +use kcl_error::{Position, diagnostic::Range}; +use kcl_primitives::{IndexMap, IndexSet}; +use serde::Serialize; + +use crate::core::symbol::SymbolRef; + +use super::{package::ModuleInfo, symbol::SymbolData}; + +pub trait Scope { + type SymbolData; + fn get_filename(&self) -> &str; + fn get_parent(&self) -> Option; + fn get_children(&self) -> Vec; + + fn contains_pos(&self, pos: &Position) -> bool; + fn get_range(&self) -> Option<(Position, Position)>; + + fn get_owner(&self) -> Option; + fn look_up_def( + &self, + name: &str, + scope_data: &ScopeData, + symbol_data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + // lookup in local scope + local: bool, + // lookup in scope owner + get_def_from_owner: bool, + ) -> Option; + + /// Get all defs within current scope and parent scope + fn get_all_defs( + &self, + scope_data: &ScopeData, + symbol_data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + maybe_in_key: bool, + get_def_from_owner: bool, + ) -> HashMap; + + /// Get all defs within current scope + fn get_defs_within_scope( + &self, + scope_data: &ScopeData, + symbol_data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + maybe_in_key: bool, + get_def_from_owner: bool, + ) -> HashMap; + + fn dump(&self, scope_data: &ScopeData, symbol_data: &Self::SymbolData) -> Option; +} + +#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Serialize)] +pub enum ScopeKind { + Local, + Root, +} + +#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] +pub struct ScopeRef { + pub(crate) id: generational_arena::Index, + pub(crate) kind: ScopeKind, +} + +impl Serialize for ScopeRef { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + let (index, generation) = self.id.into_raw_parts(); + let data = SerializableScopeRef { + i: index as u64, + g: generation, + kind: self.kind.clone(), + }; + data.serialize(serializer) + } +} + +#[derive(Debug, Clone, Serialize)] + +struct SerializableScopeRef { + i: u64, + g: u64, + kind: ScopeKind, +} + +impl ScopeRef { + pub fn get_id(&self) -> generational_arena::Index { + self.id + } + + pub fn get_kind(&self) -> ScopeKind { + self.kind + } +} + +#[derive(Default, Debug, Clone)] +pub struct ScopeData { + /// map pkgpath to root_scope + pub(crate) root_map: IndexMap, + /// map schema fully qualified name to schema local scope + pub(crate) schema_scope_map: IndexMap, + pub(crate) locals: generational_arena::Arena, + pub(crate) roots: generational_arena::Arena, + pub(crate) config_scope_context: IndexMap, +} + +/// Determine the position of pos in the config scope for completion in lsp. +/// Refer to gopls `compLitInfo`: https://github.com/golang/tools/blob/28ba9914c6b79f6cf3a56cc477398f7fd686c84d/gopls/internal/golang/completion/completion.go#L298 +/// But the semantics are different. Complete item in: +/// Go: left = keys + right right = all def in scope and parent scope +/// kcl: left = keys if in schema, right = all def in left and parent scope +#[derive(Default, Debug, Clone)] +pub struct ConfigScopeContext { + pub entries_range: Vec<(Option, Range)>, +} + +impl ConfigScopeContext { + pub fn in_entry(&self, pos: &Position) -> bool { + self.entries_range.iter().any(|(key, value)| { + let start = if key.is_some() { + key.clone().unwrap().0 + } else { + value.0.clone() + }; + start.less_equal(pos) && pos.less_equal(&value.1) + }) + } + + pub fn maybe_in_key(&self, pos: &Position) -> bool { + !self.in_right_value(pos) + } + + pub fn in_right_value(&self, pos: &Position) -> bool { + self.entries_range + .iter() + .any(|(_, value)| value.contains_pos(pos)) + } +} + +impl ScopeData { + #[inline] + pub fn get_root_scope_map(&self) -> &IndexMap { + &self.root_map + } + + pub fn get_scope(&self, scope: &ScopeRef) -> Option<&dyn Scope> { + match scope.get_kind() { + ScopeKind::Local => { + Some(self.locals.get(scope.get_id())? as &dyn Scope) + } + ScopeKind::Root => { + Some(self.roots.get(scope.get_id())? as &dyn Scope) + } + } + } + + pub fn remove_scope(&mut self, scope: &ScopeRef) { + match scope.get_kind() { + ScopeKind::Local => { + self.locals.remove(scope.get_id()); + } + ScopeKind::Root => { + self.roots.remove(scope.get_id()); + } + } + } + + pub fn try_get_local_scope(&self, scope: &ScopeRef) -> Option<&LocalSymbolScope> { + match scope.get_kind() { + ScopeKind::Local => Some(self.locals.get(scope.get_id())?), + ScopeKind::Root => None, + } + } + + pub fn get_root_scope(&self, name: String) -> Option { + self.root_map.get(&name).copied() + } + + pub fn add_def_to_scope(&mut self, scope: ScopeRef, name: String, symbol: SymbolRef) { + match scope.get_kind() { + ScopeKind::Local => { + if let Some(local) = self.locals.get_mut(scope.get_id()) { + local.defs.insert(name, symbol); + } + } + ScopeKind::Root => { + unreachable!("never add symbol to root scope after namer pass") + } + } + } + + pub fn add_ref_to_scope(&mut self, scope: ScopeRef, symbol: SymbolRef) { + match scope.get_kind() { + ScopeKind::Local => { + if let Some(local) = self.locals.get_mut(scope.get_id()) { + local.refs.push(symbol); + } + } + ScopeKind::Root => { + if let Some(root) = self.roots.get_mut(scope.get_id()) { + root.refs.push(symbol); + } + } + } + } + + pub fn set_owner_to_scope(&mut self, scope: ScopeRef, owner: SymbolRef) { + match scope.get_kind() { + ScopeKind::Local => { + if let Some(local) = self.locals.get_mut(scope.get_id()) { + local.owner = Some(owner); + } + } + ScopeKind::Root => { + if let Some(root) = self.roots.get_mut(scope.get_id()) { + root.owner = owner; + } + } + } + } + + pub fn alloc_root_scope(&mut self, root: RootSymbolScope) -> ScopeRef { + let filepath = root.pkgpath.clone(); + let id = self.roots.insert(root); + let scope_ref = ScopeRef { + id, + kind: ScopeKind::Root, + }; + self.root_map.insert(filepath, scope_ref); + scope_ref + } + + pub fn alloc_local_scope(&mut self, local: LocalSymbolScope) -> ScopeRef { + let id = self.locals.insert(local); + ScopeRef { + id, + kind: ScopeKind::Local, + } + } + + pub fn clear_cache(&mut self, invalidate_pkgs: &HashSet) { + for invalidate_pkg in invalidate_pkgs { + if let Some(scope_ref) = self.root_map.swap_remove(invalidate_pkg) { + self.clear_scope_and_child(scope_ref); + self.roots.remove(scope_ref.get_id()); + } + self.schema_scope_map + .retain(|key, _| !key.starts_with(invalidate_pkg)); + } + } + + pub fn clear_scope_and_child(&mut self, scope_ref: ScopeRef) { + if let Some(scope) = self.get_scope(&scope_ref) { + for c in scope.get_children() { + self.clear_scope_and_child(c) + } + } + self.remove_scope(&scope_ref) + } + + pub fn set_config_scope_ctx(&mut self, scope: ScopeRef, ctx: ConfigScopeContext) { + self.config_scope_context.insert(scope.get_id(), ctx); + } + + pub fn get_config_scope_ctx(&self, scope: ScopeRef) -> Option { + self.config_scope_context.get(&scope.get_id()).cloned() + } +} + +#[derive(Debug, Clone)] +pub struct RootSymbolScope { + pub(crate) pkgpath: String, + + pub(crate) filename: String, + + pub(crate) kfile_path: IndexSet, + + /// PackageSymbol of this scope + pub(crate) owner: SymbolRef, + + /// map filepath to children + pub(crate) children: IndexMap>, + + pub(crate) refs: Vec, +} + +impl Scope for RootSymbolScope { + type SymbolData = SymbolData; + fn get_filename(&self) -> &str { + &self.filename + } + + fn get_children(&self) -> Vec { + let mut children = vec![]; + for scopes in self.children.values() { + children.append(&mut scopes.clone()) + } + children + } + + fn get_parent(&self) -> Option { + None + } + + fn contains_pos(&self, pos: &Position) -> bool { + self.kfile_path.contains(&pos.filename) + } + fn get_owner(&self) -> Option { + Some(self.owner) + } + + fn look_up_def( + &self, + name: &str, + _scope_data: &ScopeData, + symbol_data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + _local: bool, + _owner: bool, + ) -> Option { + let package_symbol = symbol_data.get_symbol(self.owner)?; + + package_symbol.get_attribute(name, symbol_data, module_info) + } + + fn get_all_defs( + &self, + _scope_data: &ScopeData, + symbol_data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + _maybe_in_key: bool, + _owner: bool, + ) -> HashMap { + let mut all_defs_map = HashMap::new(); + if let Some(owner) = symbol_data.get_symbol(self.owner) { + let all_defs = owner.get_all_attributes(symbol_data, module_info); + + for def_ref in all_defs { + if let Some(def) = symbol_data.get_symbol(def_ref) { + all_defs_map.insert(def.get_name(), def_ref); + } + } + } + all_defs_map + } + + fn dump(&self, scope_data: &ScopeData, symbol_data: &Self::SymbolData) -> Option { + let mut output = String::from(""); + output.push_str("{\n\"scope_kind\": \"Root\",\n"); + output.push_str(&format!("\n\"pkgpath\": \"{}\",\n", self.pkgpath)); + let owner_symbol = symbol_data.get_symbol(self.owner)?; + output.push_str(&format!( + "\"owner\": {},\n", + owner_symbol.full_dump(symbol_data)? + )); + output.push_str("\"refs\": [\n"); + for (index, symbol) in self.refs.iter().enumerate() { + let symbol = symbol_data.get_symbol(*symbol)?; + output.push_str(&format!("{}", symbol.full_dump(symbol_data)?)); + if index + 1 < self.refs.len() { + output.push_str(",\n") + } + } + output.push_str("\n],\n"); + output.push_str("\"children\": {\n"); + for (index, (key, scopes)) in self.children.iter().enumerate() { + output.push_str(&format!("\"{}\": [\n", key)); + for (index, scope) in scopes.iter().enumerate() { + let scope = scope_data.get_scope(scope)?; + output.push_str(&format!("{}", scope.dump(scope_data, symbol_data)?)); + if index + 1 < scopes.len() { + output.push_str(",\n"); + } + } + output.push_str("\n]"); + if index + 1 < self.children.len() { + output.push_str(",\n"); + } + } + output.push_str("\n}\n}"); + + let val: serde_json::Value = serde_json::from_str(&output).unwrap(); + Some(serde_json::to_string_pretty(&val).ok()?) + } + + fn get_range(&self) -> Option<(Position, Position)> { + None + } + + fn get_defs_within_scope( + &self, + scope_data: &ScopeData, + symbol_data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + maybe_in_key: bool, + owner: bool, + ) -> HashMap { + // get defs within root scope equal to get all defs + self.get_all_defs(scope_data, symbol_data, module_info, maybe_in_key, owner) + } +} + +impl RootSymbolScope { + pub fn new( + pkgpath: String, + filename: String, + owner: SymbolRef, + kfile_path: IndexSet, + ) -> Self { + Self { + pkgpath, + kfile_path, + filename, + owner, + children: IndexMap::default(), + refs: vec![], + } + } + + pub fn add_child(&mut self, filepath: &str, child: ScopeRef) { + if self.children.contains_key(filepath) { + self.children.get_mut(filepath).unwrap().push(child); + } else { + self.children.insert(filepath.to_string(), vec![child]); + } + } +} + +#[derive(Debug, Clone)] +pub struct LocalSymbolScope { + pub(crate) parent: ScopeRef, + pub(crate) owner: Option, + pub(crate) children: Vec, + pub(crate) defs: IndexMap, + pub(crate) refs: Vec, + + pub(crate) start: Position, + pub(crate) end: Position, + pub(crate) kind: LocalSymbolScopeKind, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum LocalSymbolScopeKind { + List, + Dict, + Quant, + Lambda, + SchemaDef, + Config, + Check, + Callable, +} + +impl Scope for LocalSymbolScope { + type SymbolData = SymbolData; + + fn get_filename(&self) -> &str { + &self.start.filename + } + + fn get_children(&self) -> Vec { + self.children.clone() + } + + fn get_parent(&self) -> Option { + Some(self.parent) + } + + fn contains_pos(&self, pos: &Position) -> bool { + self.start.filename == pos.filename + && self.start.less_equal(pos) + && pos.less_equal(&self.end) + } + + fn get_owner(&self) -> Option { + self.owner.clone() + } + + fn look_up_def( + &self, + name: &str, + scope_data: &ScopeData, + symbol_data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + local: bool, + get_def_from_owner: bool, + ) -> Option { + match self.defs.get(name) { + Some(symbol_ref) => return Some(*symbol_ref), + None => { + // Try to get the attributes in the schema's protocol and mixin, and get the schema attr by `get_def_from_owner` + if let LocalSymbolScopeKind::SchemaDef = self.kind { + if let Some(owner) = self.owner.as_ref() { + if let Some(owner_schema) = symbol_data.get_schema_symbol(*owner) { + let attrs = + owner_schema.get_protocol_and_mixin_attrs(symbol_data, module_info); + for attr in attrs { + if let Some(symbol) = symbol_data.get_symbol(attr) { + if symbol.get_name() == name { + return Some(attr); + } + } + } + } + } + } + + match (local, get_def_from_owner) { + // Search in the current scope and owner + (true, true) => { + if let Some(owner) = self.owner.as_ref() { + let owner_symbol = symbol_data.get_symbol(*owner)?; + if let Some(symbol_ref) = + owner_symbol.get_attribute(name, symbol_data, module_info) + { + return Some(symbol_ref); + } + } + None + } + // Search only in the current scope + (true, false) => None, + // Search in the current scope, parent scope and owner + (false, true) => { + if let Some(owner) = self.owner.as_ref() { + let owner_symbol = symbol_data.get_symbol(*owner)?; + if let Some(symbol_ref) = + owner_symbol.get_attribute(name, symbol_data, module_info) + { + return Some(symbol_ref); + } + }; + + let parent = scope_data.get_scope(&self.parent)?; + return parent.look_up_def( + name, + scope_data, + symbol_data, + module_info, + local, + get_def_from_owner, + ); + } + // Search in the current and parent scope + (false, false) => { + let parent = scope_data.get_scope(&self.parent)?; + return parent.look_up_def( + name, + scope_data, + symbol_data, + module_info, + local, + get_def_from_owner, + ); + } + } + } + } + } + + fn get_all_defs( + &self, + scope_data: &ScopeData, + symbol_data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + maybe_in_key: bool, + owner: bool, + ) -> HashMap { + let mut all_defs_map = HashMap::new(); + if owner { + if let Some(owner) = self.owner { + if let Some(owner) = symbol_data.get_symbol(owner) { + for def_ref in owner.get_all_attributes(symbol_data, module_info) { + if let Some(def) = symbol_data.get_symbol(def_ref) { + let name = def.get_name(); + if !all_defs_map.contains_key(&name) { + all_defs_map.insert(name, def_ref); + } + } + } + } + } + } + // In Config, available definitions only contain keys of schema attr,i.e., `left` values in schema expr. + // but right value in schema expr, available definitions contain all def in left parent definitions. + // ``` + // b = "bar" + // foo = Foo{ + // bar: b + // } + // ```` + // At position of `bar`, only get def from keys of Foo + // At position of seconde `b`, get def from left([bar]) and parent scope + if maybe_in_key { + return all_defs_map; + } + + for def_ref in self.defs.values() { + if let Some(def) = symbol_data.get_symbol(*def_ref) { + all_defs_map.insert(def.get_name(), *def_ref); + } + } + + if let Some(parent) = scope_data.get_scope(&self.parent) { + for (name, def_ref) in + parent.get_all_defs(scope_data, symbol_data, module_info, false, owner) + { + if !all_defs_map.contains_key(&name) { + all_defs_map.insert(name, def_ref); + } + } + } + all_defs_map + } + + fn dump(&self, scope_data: &ScopeData, symbol_data: &Self::SymbolData) -> Option { + let mut output = String::from(""); + output.push_str("{\n\"scope_kind\": \"Local\",\n"); + output.push_str(&format!( + "\"range\": \"{}:{}", + self.start.filename, self.start.line + )); + if let Some(start_col) = self.start.column { + output.push_str(&format!(":{}", start_col)); + } + + output.push_str(&format!(" to {}", self.end.line)); + if let Some(end_col) = self.end.column { + output.push_str(&format!(":{}", end_col)); + } + output.push_str("\",\n"); + if let Some(owner) = self.owner.as_ref() { + let owner_symbol = symbol_data.get_symbol(*owner)?; + output.push_str(&format!( + "\"owner\": {},\n", + owner_symbol.full_dump(symbol_data)? + )); + } + output.push_str("\"defs\": {\n"); + for (index, (key, symbol)) in self.defs.iter().enumerate() { + let symbol = symbol_data.get_symbol(*symbol)?; + output.push_str(&format!("\"{}\": {}", key, symbol.full_dump(symbol_data)?)); + if index + 1 < self.defs.len() { + output.push_str(",\n") + } + } + output.push_str("\n},\n"); + output.push_str("\"refs\": [\n"); + for (index, symbol) in self.refs.iter().enumerate() { + let symbol = symbol_data.get_symbol(*symbol)?; + output.push_str(&format!("{}", symbol.full_dump(symbol_data)?)); + if index + 1 < self.refs.len() { + output.push_str(",\n") + } + } + output.push_str("\n],"); + output.push_str("\n\"children\": [\n"); + for (index, scope) in self.children.iter().enumerate() { + let scope = scope_data.get_scope(scope)?; + output.push_str(&format!("{}", scope.dump(scope_data, symbol_data)?)); + if index + 1 < self.children.len() { + output.push_str(",\n") + } + } + output.push_str("\n]\n}"); + Some(output) + } + + fn get_range(&self) -> Option<(Position, Position)> { + Some((self.start.clone(), self.end.clone())) + } + + fn get_defs_within_scope( + &self, + _scope_data: &ScopeData, + symbol_data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + _maybe_in_key: bool, + owner: bool, + ) -> HashMap { + let mut all_defs_map = HashMap::new(); + if owner { + if let Some(owner) = self.owner { + if let Some(owner) = symbol_data.get_symbol(owner) { + for def_ref in owner.get_all_attributes(symbol_data, module_info) { + if let Some(def) = symbol_data.get_symbol(def_ref) { + let name = def.get_name(); + if !all_defs_map.contains_key(&name) { + all_defs_map.insert(name, def_ref); + } + } + } + } + } + } + + for def_ref in self.defs.values() { + if let Some(def) = symbol_data.get_symbol(*def_ref) { + all_defs_map.insert(def.get_name(), *def_ref); + } + } + all_defs_map + } +} + +impl LocalSymbolScope { + pub fn new( + parent: ScopeRef, + start: Position, + end: Position, + kind: LocalSymbolScopeKind, + ) -> Self { + Self { + parent, + owner: None, + children: vec![], + defs: IndexMap::default(), + refs: vec![], + start, + end, + kind, + } + } + + #[inline] + pub fn get_kind(&self) -> &LocalSymbolScopeKind { + &self.kind + } + + #[inline] + pub fn add_child(&mut self, child: ScopeRef) { + self.children.push(child) + } + + #[inline] + pub fn set_owner(&mut self, owner: SymbolRef) { + self.owner = Some(owner) + } +} diff --git a/kclvm/sema/src/core/semantic_information.rs b/crates/sema/src/core/semantic_information.rs similarity index 97% rename from kclvm/sema/src/core/semantic_information.rs rename to crates/sema/src/core/semantic_information.rs index 987786b31..86718d67e 100644 --- a/kclvm/sema/src/core/semantic_information.rs +++ b/crates/sema/src/core/semantic_information.rs @@ -1,5 +1,5 @@ -use kclvm_ast::ast::AstIndex; -use kclvm_primitives::IndexMap; +use kcl_ast::ast::AstIndex; +use kcl_primitives::IndexMap; use std::sync::Arc; use super::{ diff --git a/crates/sema/src/core/symbol.rs b/crates/sema/src/core/symbol.rs new file mode 100644 index 000000000..dd45b141a --- /dev/null +++ b/crates/sema/src/core/symbol.rs @@ -0,0 +1,2651 @@ +use std::{ + collections::{HashMap, HashSet}, + sync::Arc, +}; + +use generational_arena::Arena; +use kcl_primitives::{IndexMap, IndexSet}; + +use kcl_error::{Position, diagnostic::Range}; +use serde::Serialize; + +use super::package::ModuleInfo; +use crate::{ + resolver::scope::NodeKey, + ty::{Type, TypeKind, TypeRef}, +}; + +pub trait Symbol { + type SymbolData; + type SemanticInfo; + type SymbolHint; + + fn get_sema_info(&self) -> &Self::SemanticInfo; + fn is_global(&self) -> bool; + fn get_range(&self) -> Range; + fn get_owner(&self) -> Option; + fn get_definition(&self) -> Option; + fn get_references(&self) -> HashSet; + fn get_name(&self) -> String; + fn get_id(&self) -> Option; + fn get_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Option; + fn has_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> bool; + + fn get_all_attributes( + &self, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Vec; + + fn simple_dump(&self) -> String; + + fn full_dump(&self, data: &Self::SymbolData) -> Option; +} + +pub type KCLSymbol = + dyn Symbol; +#[derive(Debug, Clone, Default)] +pub struct SymbolSemanticInfo { + pub ty: Option>, + pub doc: Option, +} + +pub(crate) const BUILTIN_STR_PACKAGE: &'static str = "@str"; +pub(crate) const BUILTIN_FUNCTION_PACKAGE: &'static str = "@builtin"; + +#[derive(Default, Debug, Clone)] +pub struct SymbolData { + pub(crate) values: Arena, + pub(crate) packages: Arena, + pub(crate) attributes: Arena, + pub(crate) schemas: Arena, + pub(crate) type_aliases: Arena, + pub(crate) unresolved: Arena, + pub(crate) rules: Arena, + pub(crate) exprs: Arena, + pub(crate) comments: Arena, + pub(crate) decorators: Arena, + pub(crate) functions: Arena, + pub(crate) hints: HashMap>, + + pub(crate) symbols_info: SymbolDB, +} + +#[derive(Default, Debug, Clone)] +pub struct SymbolDB { + pub(crate) symbol_pos_set: IndexSet, + pub(crate) global_builtin_symbols: IndexMap, + pub(crate) fully_qualified_name_map: IndexMap, + pub(crate) schema_builtin_symbols: IndexMap>, + pub(crate) node_symbol_map: IndexMap, + pub(crate) symbol_node_map: IndexMap, + pub(crate) pkg_symbol_map: IndexMap>, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct SymbolHint { + pub kind: SymbolHintKind, + pub pos: Position, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum SymbolHintKind { + TypeHint(String), + VarHint(String), + KeyTypeHint(String), +} + +impl SymbolData { + pub fn get_all_schemas(&self) -> &Arena { + &self.schemas + } + + pub fn get_package_symbol(&self, id: SymbolRef) -> Option<&PackageSymbol> { + if matches!(id.get_kind(), SymbolKind::Package) { + self.packages.get(id.get_id()) + } else { + None + } + } + + pub fn get_value_symbol(&self, id: SymbolRef) -> Option<&ValueSymbol> { + if matches!(id.get_kind(), SymbolKind::Value) { + self.values.get(id.get_id()) + } else { + None + } + } + + pub fn get_attribute_symbol(&self, id: SymbolRef) -> Option<&AttributeSymbol> { + if matches!(id.get_kind(), SymbolKind::Attribute) { + self.attributes.get(id.get_id()) + } else { + None + } + } + + pub fn get_type_alias_symbol(&self, id: SymbolRef) -> Option<&TypeAliasSymbol> { + if matches!(id.get_kind(), SymbolKind::TypeAlias) { + self.type_aliases.get(id.get_id()) + } else { + None + } + } + + pub fn get_schema_symbol(&self, id: SymbolRef) -> Option<&SchemaSymbol> { + if matches!(id.get_kind(), SymbolKind::Schema) { + self.schemas.get(id.get_id()) + } else { + None + } + } + + pub fn get_rule_symbol(&self, id: SymbolRef) -> Option<&RuleSymbol> { + if matches!(id.get_kind(), SymbolKind::Rule) { + self.rules.get(id.get_id()) + } else { + None + } + } + + pub fn get_attr_symbol(&self, id: SymbolRef) -> Option<&AttributeSymbol> { + if matches!(id.get_kind(), SymbolKind::Attribute) { + self.attributes.get(id.get_id()) + } else { + None + } + } + + pub fn get_function_symbol(&self, id: SymbolRef) -> Option<&FunctionSymbol> { + if matches!(id.get_kind(), SymbolKind::Function) { + self.functions.get(id.get_id()) + } else { + None + } + } + + pub fn get_unresolved_symbol(&self, id: SymbolRef) -> Option<&UnresolvedSymbol> { + if matches!(id.get_kind(), SymbolKind::Unresolved) { + self.unresolved.get(id.get_id()) + } else { + None + } + } + + pub fn get_symbol(&self, id: SymbolRef) -> Option<&KCLSymbol> { + match id.get_kind() { + SymbolKind::Schema => self + .schemas + .get(id.get_id()) + .map(|symbol| symbol as &KCLSymbol), + SymbolKind::Attribute => self + .attributes + .get(id.get_id()) + .map(|symbol| symbol as &KCLSymbol), + SymbolKind::Value => self + .values + .get(id.get_id()) + .map(|symbol| symbol as &KCLSymbol), + SymbolKind::Package => self + .packages + .get(id.get_id()) + .map(|symbol| symbol as &KCLSymbol), + SymbolKind::TypeAlias => self + .type_aliases + .get(id.get_id()) + .map(|symbol| symbol as &KCLSymbol), + SymbolKind::Unresolved => self + .unresolved + .get(id.get_id()) + .map(|symbol| symbol as &KCLSymbol), + SymbolKind::Rule => self + .rules + .get(id.get_id()) + .map(|symbol| symbol as &KCLSymbol), + SymbolKind::Expression => self + .exprs + .get(id.get_id()) + .map(|symbol| symbol as &KCLSymbol), + SymbolKind::Comment => self + .comments + .get(id.get_id()) + .map(|symbol| symbol as &KCLSymbol), + SymbolKind::Decorator => self + .decorators + .get(id.get_id()) + .map(|symbol| symbol as &KCLSymbol), + SymbolKind::Function => self + .functions + .get(id.get_id()) + .map(|symbol| symbol as &KCLSymbol), + } + } + + pub fn remove_symbol(&mut self, id: &SymbolRef) { + if let Some(symbol) = self.get_symbol(id.clone()) { + self.symbols_info + .symbol_pos_set + .swap_remove(&symbol.get_range().1); + } + match id.get_kind() { + SymbolKind::Schema => { + self.schemas.remove(id.get_id()); + self.symbols_info.schema_builtin_symbols.swap_remove(id); + } + SymbolKind::Attribute => { + self.attributes.remove(id.get_id()); + } + SymbolKind::Value => { + self.values.remove(id.get_id()); + } + SymbolKind::Package => { + self.packages.remove(id.get_id()); + } + SymbolKind::TypeAlias => { + self.type_aliases.remove(id.get_id()); + } + SymbolKind::Unresolved => { + self.unresolved.remove(id.get_id()); + } + SymbolKind::Rule => { + self.rules.remove(id.get_id()); + } + SymbolKind::Expression => { + self.exprs.remove(id.get_id()); + } + SymbolKind::Comment => { + self.comments.remove(id.get_id()); + } + SymbolKind::Decorator => { + self.decorators.remove(id.get_id()); + } + SymbolKind::Function => { + self.functions.remove(id.get_id()); + } + } + } + + pub fn set_symbol_type(&mut self, id: SymbolRef, ty: TypeRef) { + match id.get_kind() { + SymbolKind::Schema => { + self.schemas.get_mut(id.get_id()).map(|symbol| { + symbol.sema_info.ty = Some(ty); + symbol + }); + } + SymbolKind::Attribute => { + self.attributes.get_mut(id.get_id()).map(|symbol| { + symbol.sema_info.ty = Some(ty); + symbol + }); + } + SymbolKind::Value => { + self.values.get_mut(id.get_id()).map(|symbol| { + symbol.sema_info.ty = Some(ty); + symbol + }); + } + SymbolKind::Package => { + self.packages.get_mut(id.get_id()).map(|symbol| { + symbol.sema_info.ty = Some(ty); + symbol + }); + } + SymbolKind::TypeAlias => { + self.type_aliases.get_mut(id.get_id()).map(|symbol| { + symbol.sema_info.ty = Some(ty); + symbol + }); + } + SymbolKind::Unresolved => { + self.unresolved.get_mut(id.get_id()).map(|symbol| { + symbol.sema_info.ty = Some(ty); + symbol + }); + } + SymbolKind::Rule => { + self.rules.get_mut(id.get_id()).map(|symbol| { + symbol.sema_info.ty = Some(ty); + symbol + }); + } + SymbolKind::Expression => { + self.exprs.get_mut(id.get_id()).map(|symbol| { + symbol.sema_info.ty = Some(ty); + symbol + }); + } + SymbolKind::Comment => { + self.comments.get_mut(id.get_id()).map(|symbol| { + symbol.sema_info.ty = Some(ty); + symbol + }); + } + SymbolKind::Decorator => { + self.decorators.get_mut(id.get_id()).map(|symbol| { + symbol.sema_info.ty = Some(ty); + symbol + }); + } + SymbolKind::Function => { + self.functions.get_mut(id.get_id()).map(|symbol| { + symbol.sema_info.ty = Some(ty); + symbol + }); + } + } + } + + pub fn get_type_symbol( + &self, + ty: &Type, + module_info: Option<&ModuleInfo>, + ) -> Option { + match &ty.kind { + //TODO: builtin ty symbol,now we just return none + TypeKind::None => None, + TypeKind::Any => None, + TypeKind::Void => None, + TypeKind::Bool => None, + TypeKind::BoolLit(_) => None, + TypeKind::Int => None, + TypeKind::IntLit(_) => None, + TypeKind::Float => None, + TypeKind::FloatLit(_) => None, + TypeKind::Str => self.get_symbol_by_fully_qualified_name(BUILTIN_STR_PACKAGE), + TypeKind::StrLit(_) => self.get_symbol_by_fully_qualified_name(BUILTIN_STR_PACKAGE), + TypeKind::List(_) => None, + TypeKind::Dict(_) => None, + TypeKind::NumberMultiplier(_) => None, + TypeKind::Function(_) => None, + TypeKind::Union(types) => { + if types + .iter() + .all(|ut| matches!(&ut.kind, TypeKind::StrLit(_) | TypeKind::Str)) + { + self.get_symbol_by_fully_qualified_name(BUILTIN_STR_PACKAGE) + } else { + None + } + } + TypeKind::Schema(schema_ty) => { + let fully_qualified_ty_name = schema_ty.pkgpath.clone() + "." + &schema_ty.name; + + self.get_symbol_by_fully_qualified_name(&fully_qualified_ty_name) + } + TypeKind::Module(module_ty) => { + self.get_symbol_by_fully_qualified_name(&module_ty.pkgpath) + } + TypeKind::Named(name) => { + let splits: Vec<&str> = name.rsplitn(2, '.').collect(); + let len = splits.len(); + let pkgname = splits[len - 1]; + + let pkgpath: &String = &module_info?.get_import_info(pkgname)?.fully_qualified_name; + let fully_qualified_ty_name = if name.contains('.') { + name.replacen(&pkgname, pkgpath, 1) + } else { + kcl_ast::MAIN_PKG.to_string() + name + }; + + self.get_symbol_by_fully_qualified_name(&fully_qualified_ty_name) + } + } + } + + pub fn get_type_all_attribute( + &self, + ty: &Type, + name: &str, + module_info: Option<&ModuleInfo>, + ) -> Vec { + match &ty.kind { + //TODO: builtin ty symbol,now we just return none + TypeKind::None => vec![], + TypeKind::Any => vec![], + TypeKind::Void => vec![], + TypeKind::Bool => vec![], + TypeKind::BoolLit(_) => vec![], + TypeKind::Int => vec![], + TypeKind::IntLit(_) => vec![], + TypeKind::Float => vec![], + TypeKind::FloatLit(_) => vec![], + TypeKind::Str | TypeKind::StrLit(_) => { + let mut result = vec![]; + if let Some(symbol_ref) = self.get_type_symbol(ty, module_info) { + if let Some(symbol) = self.get_symbol(symbol_ref) { + result = symbol.get_all_attributes(self, module_info); + } + } + result + } + TypeKind::List(_) => vec![], + TypeKind::Dict(_) => vec![], + TypeKind::NumberMultiplier(_) => vec![], + TypeKind::Function(_) => vec![], + TypeKind::Union(tys) => { + let mut result = vec![]; + for ty in tys.iter() { + result.append(&mut self.get_type_all_attribute(ty, name, module_info)); + } + result + } + TypeKind::Schema(_) => { + let mut result = vec![]; + if let Some(symbol_ref) = self.get_type_symbol(ty, module_info) { + if let Some(symbol) = self.get_symbol(symbol_ref) { + result = symbol.get_all_attributes(self, module_info); + } + } + result + } + TypeKind::Module(_) => { + let mut result = vec![]; + if let Some(symbol_ref) = self.get_type_symbol(ty, module_info) { + if let Some(symbol) = self.get_symbol(symbol_ref) { + result = symbol.get_all_attributes(self, module_info); + } + } + result + } + TypeKind::Named(_) => { + let mut result = vec![]; + if let Some(symbol_ref) = self.get_type_symbol(ty, module_info) { + if let Some(symbol) = self.get_symbol(symbol_ref) { + result = symbol.get_all_attributes(self, module_info); + } + } + result + } + } + } + + pub fn get_type_attribute( + &self, + ty: &Type, + name: &str, + module_info: Option<&ModuleInfo>, + ) -> Option { + match &ty.kind { + TypeKind::None => None, + TypeKind::Any => None, + TypeKind::Void => None, + TypeKind::Bool => None, + TypeKind::BoolLit(_) => None, + TypeKind::Int => None, + TypeKind::IntLit(_) => None, + TypeKind::Float => None, + TypeKind::FloatLit(_) => None, + TypeKind::Str => self + .get_symbol(self.get_type_symbol(ty, module_info)?)? + .get_attribute(name, self, module_info), + TypeKind::StrLit(_) => self + .get_symbol(self.get_type_symbol(ty, module_info)?)? + .get_attribute(name, self, module_info), + TypeKind::List(_) => None, + TypeKind::Dict(_) => None, + TypeKind::NumberMultiplier(_) => None, + TypeKind::Function(_) => None, + TypeKind::Union(tys) => { + for ty in tys.iter() { + if let Some(symbol_ref) = self.get_type_attribute(ty, name, module_info) { + return Some(symbol_ref); + } + } + None + } + TypeKind::Schema(_) => self + .get_symbol(self.get_type_symbol(ty, module_info)?)? + .get_attribute(name, self, module_info), + TypeKind::Module(_) => self + .get_symbol(self.get_type_symbol(ty, module_info)?)? + .get_attribute(name, self, module_info), + TypeKind::Named(_) => self + .get_symbol(self.get_type_symbol(ty, module_info)?)? + .get_attribute(name, self, module_info), + } + } + + pub fn get_symbol_by_fully_qualified_name(&self, fqn: &str) -> Option { + self.symbols_info.fully_qualified_name_map.get(fqn).cloned() + } + + pub fn get_fully_qualified_name(&self, symbol_ref: SymbolRef) -> Option { + match symbol_ref.get_kind() { + SymbolKind::Unresolved => None, + _ => { + let symbol = self.get_symbol(symbol_ref)?; + let owner = symbol.get_owner(); + if let Some(owner) = owner { + Some(self.get_fully_qualified_name(owner)? + "." + &symbol.get_name()) + } else { + Some(symbol.get_name()) + } + } + } + } + + pub fn build_fully_qualified_name_map(&mut self) { + for (id, _) in self.packages.iter() { + let symbol_ref = SymbolRef { + id, + kind: SymbolKind::Package, + }; + self.symbols_info.fully_qualified_name_map.insert( + self.get_fully_qualified_name(symbol_ref).unwrap(), + symbol_ref, + ); + } + + for (id, _) in self.schemas.iter() { + let symbol_ref = SymbolRef { + id, + kind: SymbolKind::Schema, + }; + self.symbols_info.fully_qualified_name_map.insert( + self.get_fully_qualified_name(symbol_ref).unwrap(), + symbol_ref, + ); + } + + for (id, _) in self.type_aliases.iter() { + let symbol_ref = SymbolRef { + id, + kind: SymbolKind::TypeAlias, + }; + self.symbols_info.fully_qualified_name_map.insert( + self.get_fully_qualified_name(symbol_ref).unwrap(), + symbol_ref, + ); + } + + for (id, _) in self.attributes.iter() { + let symbol_ref = SymbolRef { + id, + kind: SymbolKind::Attribute, + }; + self.symbols_info.fully_qualified_name_map.insert( + self.get_fully_qualified_name(symbol_ref).unwrap(), + symbol_ref, + ); + } + + for (id, _) in self.rules.iter() { + let symbol_ref = SymbolRef { + id, + kind: SymbolKind::Rule, + }; + self.symbols_info.fully_qualified_name_map.insert( + self.get_fully_qualified_name(symbol_ref).unwrap(), + symbol_ref, + ); + } + + for (id, _) in self.values.iter() { + let symbol_ref = SymbolRef { + id, + kind: SymbolKind::Value, + }; + self.symbols_info.fully_qualified_name_map.insert( + self.get_fully_qualified_name(symbol_ref).unwrap(), + symbol_ref, + ); + } + + for (id, _) in self.functions.iter() { + let symbol_ref = SymbolRef { + id, + kind: SymbolKind::Function, + }; + self.symbols_info.fully_qualified_name_map.insert( + self.get_fully_qualified_name(symbol_ref).unwrap(), + symbol_ref, + ); + } + } + + pub fn insert_package_symbol(&mut self, symbol_ref: SymbolRef, pkg_name: String) { + if !self.symbols_info.pkg_symbol_map.contains_key(&pkg_name) { + self.symbols_info + .pkg_symbol_map + .insert(pkg_name.clone(), IndexSet::default()); + } + + self.symbols_info + .pkg_symbol_map + .get_mut(&pkg_name) + .unwrap() + .insert(symbol_ref); + } + + pub fn alloc_package_symbol(&mut self, pkg: PackageSymbol, pkg_name: String) -> SymbolRef { + let symbol_id = self.packages.insert(pkg); + let symbol_ref = SymbolRef { + id: symbol_id, + kind: SymbolKind::Package, + }; + self.packages.get_mut(symbol_id).unwrap().id = Some(symbol_ref); + self.insert_package_symbol(symbol_ref, pkg_name); + symbol_ref + } + + pub fn alloc_schema_symbol( + &mut self, + schema: SchemaSymbol, + node_key: NodeKey, + pkg_name: String, + ) -> SymbolRef { + self.symbols_info.symbol_pos_set.insert(schema.end.clone()); + let symbol_id = self.schemas.insert(schema); + let symbol_ref = SymbolRef { + id: symbol_id, + kind: SymbolKind::Schema, + }; + self.symbols_info + .node_symbol_map + .insert(node_key.clone(), symbol_ref); + self.symbols_info + .symbol_node_map + .insert(symbol_ref, node_key); + self.schemas.get_mut(symbol_id).unwrap().id = Some(symbol_ref); + self.insert_package_symbol(symbol_ref, pkg_name); + symbol_ref + } + + pub fn alloc_unresolved_symbol( + &mut self, + unresolved: UnresolvedSymbol, + node_key: NodeKey, + pkg_name: String, + ) -> SymbolRef { + self.symbols_info + .symbol_pos_set + .insert(unresolved.end.clone()); + let symbol_id = self.unresolved.insert(unresolved); + let symbol_ref = SymbolRef { + id: symbol_id, + kind: SymbolKind::Unresolved, + }; + self.symbols_info + .node_symbol_map + .insert(node_key.clone(), symbol_ref); + self.symbols_info + .symbol_node_map + .insert(symbol_ref, node_key); + self.unresolved.get_mut(symbol_id).unwrap().id = Some(symbol_ref); + self.insert_package_symbol(symbol_ref, pkg_name); + symbol_ref + } + + pub fn alloc_type_alias_symbol( + &mut self, + alias: TypeAliasSymbol, + node_key: NodeKey, + pkg_name: String, + ) -> SymbolRef { + self.symbols_info.symbol_pos_set.insert(alias.end.clone()); + let symbol_id = self.type_aliases.insert(alias); + let symbol_ref = SymbolRef { + id: symbol_id, + kind: SymbolKind::TypeAlias, + }; + self.symbols_info + .node_symbol_map + .insert(node_key.clone(), symbol_ref); + self.symbols_info + .symbol_node_map + .insert(symbol_ref, node_key); + self.type_aliases.get_mut(symbol_id).unwrap().id = Some(symbol_ref); + self.insert_package_symbol(symbol_ref, pkg_name); + symbol_ref + } + + pub fn alloc_rule_symbol( + &mut self, + rule: RuleSymbol, + node_key: NodeKey, + pkg_name: String, + ) -> SymbolRef { + self.symbols_info.symbol_pos_set.insert(rule.end.clone()); + let symbol_id = self.rules.insert(rule); + let symbol_ref = SymbolRef { + id: symbol_id, + kind: SymbolKind::Rule, + }; + self.symbols_info + .node_symbol_map + .insert(node_key.clone(), symbol_ref); + self.symbols_info + .symbol_node_map + .insert(symbol_ref, node_key); + self.rules.get_mut(symbol_id).unwrap().id = Some(symbol_ref); + self.insert_package_symbol(symbol_ref, pkg_name); + symbol_ref + } + + pub fn alloc_attribute_symbol( + &mut self, + attribute: AttributeSymbol, + node_key: NodeKey, + pkg_name: String, + ) -> SymbolRef { + self.symbols_info + .symbol_pos_set + .insert(attribute.end.clone()); + let symbol_id = self.attributes.insert(attribute); + let symbol_ref = SymbolRef { + id: symbol_id, + kind: SymbolKind::Attribute, + }; + self.symbols_info + .node_symbol_map + .insert(node_key.clone(), symbol_ref); + self.symbols_info + .symbol_node_map + .insert(symbol_ref, node_key); + self.attributes.get_mut(symbol_id).unwrap().id = Some(symbol_ref); + self.insert_package_symbol(symbol_ref, pkg_name); + symbol_ref + } + + pub fn alloc_value_symbol( + &mut self, + value: ValueSymbol, + node_key: NodeKey, + pkg_name: String, + ) -> SymbolRef { + self.symbols_info.symbol_pos_set.insert(value.end.clone()); + let symbol_id = self.values.insert(value); + let symbol_ref = SymbolRef { + id: symbol_id, + kind: SymbolKind::Value, + }; + self.symbols_info + .node_symbol_map + .insert(node_key.clone(), symbol_ref); + self.symbols_info + .symbol_node_map + .insert(symbol_ref, node_key); + self.values.get_mut(symbol_id).unwrap().id = Some(symbol_ref); + self.insert_package_symbol(symbol_ref, pkg_name); + symbol_ref + } + + pub fn alloc_expression_symbol( + &mut self, + expr: ExpressionSymbol, + node_key: NodeKey, + pkg_name: String, + ) -> Option { + if self.symbols_info.symbol_pos_set.contains(&expr.end) { + return None; + } + self.symbols_info.symbol_pos_set.insert(expr.end.clone()); + let symbol_id = self.exprs.insert(expr); + let symbol_ref = SymbolRef { + id: symbol_id, + kind: SymbolKind::Expression, + }; + self.symbols_info + .node_symbol_map + .insert(node_key.clone(), symbol_ref); + self.symbols_info + .symbol_node_map + .insert(symbol_ref, node_key); + self.exprs.get_mut(symbol_id).unwrap().id = Some(symbol_ref); + self.insert_package_symbol(symbol_ref, pkg_name); + Some(symbol_ref) + } + + pub fn alloc_comment_symbol( + &mut self, + comment: CommentOrDocSymbol, + node_key: NodeKey, + pkg_name: String, + ) -> Option { + let symbol_id = self.comments.insert(comment); + let symbol_ref = SymbolRef { + id: symbol_id, + kind: SymbolKind::Comment, + }; + self.symbols_info + .node_symbol_map + .insert(node_key.clone(), symbol_ref); + self.symbols_info + .symbol_node_map + .insert(symbol_ref, node_key); + self.comments.get_mut(symbol_id).unwrap().id = Some(symbol_ref); + self.insert_package_symbol(symbol_ref, pkg_name); + Some(symbol_ref) + } + + pub fn alloc_decorator_symbol( + &mut self, + decorator: DecoratorSymbol, + node_key: NodeKey, + pkg_name: String, + ) -> Option { + let symbol_id = self.decorators.insert(decorator); + let symbol_ref = SymbolRef { + id: symbol_id, + kind: SymbolKind::Decorator, + }; + self.symbols_info + .node_symbol_map + .insert(node_key.clone(), symbol_ref); + self.symbols_info + .symbol_node_map + .insert(symbol_ref, node_key); + self.decorators.get_mut(symbol_id).unwrap().id = Some(symbol_ref); + self.insert_package_symbol(symbol_ref, pkg_name); + Some(symbol_ref) + } + + pub fn alloc_function_symbol( + &mut self, + func: FunctionSymbol, + node_key: NodeKey, + pkg_name: String, + ) -> SymbolRef { + self.symbols_info.symbol_pos_set.insert(func.end.clone()); + let symbol_id = self.functions.insert(func); + let symbol_ref = SymbolRef { + id: symbol_id, + kind: SymbolKind::Function, + }; + self.symbols_info + .node_symbol_map + .insert(node_key.clone(), symbol_ref); + self.symbols_info + .symbol_node_map + .insert(symbol_ref, node_key); + self.functions.get_mut(symbol_id).unwrap().id = Some(symbol_ref); + self.insert_package_symbol(symbol_ref, pkg_name); + symbol_ref + } + + pub fn alloc_hint(&mut self, hint: SymbolHint, pkg_name: String) { + match self.hints.get_mut(&pkg_name) { + Some(hints) => hints.push(hint), + None => { + self.hints.insert(pkg_name, vec![hint]); + } + } + } + + #[inline] + pub fn get_node_symbol_map(&self) -> &IndexMap { + &self.symbols_info.node_symbol_map + } + + #[inline] + pub fn get_node_symbol_map_mut(&mut self) -> &mut IndexMap { + &mut self.symbols_info.node_symbol_map + } + + #[inline] + pub fn get_symbol_node_map(&self) -> &IndexMap { + &self.symbols_info.symbol_node_map + } + + #[inline] + pub fn get_symbol_node_map_mut(&mut self) -> &mut IndexMap { + &mut self.symbols_info.symbol_node_map + } + + #[inline] + pub fn get_fully_qualified_name_map(&self) -> &IndexMap { + &self.symbols_info.fully_qualified_name_map + } + + #[inline] + pub fn get_builtin_symbols(&self) -> &IndexMap { + &self.symbols_info.global_builtin_symbols + } + + pub fn clear_cache(&mut self, invalidate_pkgs: &HashSet) { + let mut to_remove: Vec = Vec::new(); + + for invalidate_pkg in invalidate_pkgs { + if let Some(symbols) = self.symbols_info.pkg_symbol_map.get(invalidate_pkg) { + to_remove.extend(symbols.iter().cloned()); + } + self.hints.remove(invalidate_pkg); + } + for symbol in to_remove { + self.remove_symbol(&symbol); + if let Some(node_id) = self.get_symbol_node_map_mut().swap_remove(&symbol) { + self.get_node_symbol_map_mut().swap_remove(&node_id); + } + } + } + + pub fn set_def_and_ref(&mut self, def: SymbolRef, r#ref: SymbolRef) { + self.set_def(def, r#ref); + self.set_ref(def, r#ref); + } + + pub fn set_def(&mut self, def: SymbolRef, r#ref: SymbolRef) { + match r#ref.get_kind() { + SymbolKind::Unresolved => { + self.unresolved.get_mut(r#ref.get_id()).unwrap().def = Some(def) + } + _ => {} + } + } + + pub fn set_ref(&mut self, def: SymbolRef, r#ref: SymbolRef) { + match def.get_kind() { + SymbolKind::Schema => { + self.schemas + .get_mut(def.get_id()) + .unwrap() + .r#ref + .insert(r#ref); + } + + SymbolKind::Attribute => { + self.attributes + .get_mut(def.get_id()) + .unwrap() + .r#ref + .insert(r#ref); + } + SymbolKind::Value => { + self.values + .get_mut(def.get_id()) + .unwrap() + .r#ref + .insert(r#ref); + } + SymbolKind::Function => { + self.functions + .get_mut(def.get_id()) + .unwrap() + .r#ref + .insert(r#ref); + } + SymbolKind::Package => { + self.packages + .get_mut(def.get_id()) + .unwrap() + .r#ref + .insert(r#ref); + } + SymbolKind::TypeAlias => { + self.type_aliases + .get_mut(def.get_id()) + .unwrap() + .r#ref + .insert(r#ref); + } + SymbolKind::Rule => { + self.rules + .get_mut(def.get_id()) + .unwrap() + .r#ref + .insert(r#ref); + } + _ => {} + }; + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] +pub enum SymbolKind { + Schema, + Attribute, + Value, + Function, + Package, + TypeAlias, + Unresolved, + Rule, + Expression, + Comment, + Decorator, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct SymbolRef { + pub(crate) id: generational_arena::Index, + pub(crate) kind: SymbolKind, +} + +impl Serialize for SymbolRef { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + let (index, generation) = self.id.into_raw_parts(); + let data = SerializableSymbolRef { + i: index as u64, + g: generation, + kind: self.kind.clone(), + }; + data.serialize(serializer) + } +} + +#[derive(Debug, Clone, Serialize)] + +struct SerializableSymbolRef { + i: u64, + g: u64, + kind: SymbolKind, +} + +impl SymbolRef { + #[inline] + pub fn get_kind(&self) -> SymbolKind { + self.kind + } + #[inline] + pub fn get_id(&self) -> generational_arena::Index { + self.id + } +} +#[allow(unused)] +#[derive(Debug, Clone)] +pub struct SchemaSymbol { + pub(crate) id: Option, + pub(crate) name: String, + pub(crate) start: Position, + pub(crate) end: Position, + pub(crate) owner: SymbolRef, + pub(crate) sema_info: SymbolSemanticInfo, + pub(crate) r#ref: HashSet, + + pub(crate) parent_schema: Option, + pub(crate) for_host: Option, + pub(crate) mixins: Vec, + pub(crate) attributes: IndexMap, +} + +impl Symbol for SchemaSymbol { + type SymbolData = SymbolData; + type SemanticInfo = SymbolSemanticInfo; + type SymbolHint = SymbolHint; + + fn is_global(&self) -> bool { + true + } + fn get_range(&self) -> Range { + (self.start.clone(), self.end.clone()) + } + + fn get_owner(&self) -> Option { + Some(self.owner) + } + + fn get_definition(&self) -> Option { + self.id.clone() + } + + fn get_name(&self) -> String { + self.name.clone() + } + + fn get_id(&self) -> Option { + self.id.clone() + } + + fn get_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Option { + match self.attributes.get(name) { + Some(attribute) => Some(*attribute), + None => { + if let Some(for_host) = self.for_host { + if let Some(attribute) = + data.get_symbol(for_host)? + .get_attribute(name, data, module_info) + { + return Some(attribute); + } + } + + for mixin in self.mixins.iter() { + if let Some(attribute) = + data.get_symbol(*mixin)? + .get_attribute(name, data, module_info) + { + return Some(attribute); + } + } + + if let Some(_) = self.parent_schema { + let mut parents = vec![]; + parents.push(self.id.unwrap()); + self.get_parents(data, &mut parents); + if parents.len() > 1 { + for parent_schema in &parents[1..] { + if let Some(parent_schema) = data.get_schema_symbol(*parent_schema) { + let parent_attr = parent_schema.get_self_attr(data, module_info); + for attr in parent_attr { + if let Some(attribute) = data.get_symbol(attr) { + if attribute.get_name() == name { + return Some(attr); + } + } + } + } + } + } + } + None + } + } + } + + fn get_all_attributes( + &self, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Vec { + let mut result = self.get_self_attr(data, module_info); + if let Some(_) = self.parent_schema { + let mut parents = vec![]; + parents.push(self.id.unwrap()); + self.get_parents(data, &mut parents); + if parents.len() > 1 { + for parent in &parents[1..] { + if let Some(schema_symbol) = data.get_schema_symbol(*parent) { + result.append(&mut schema_symbol.get_self_attr(data, module_info)) + } + } + } + } + result + } + + fn has_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> bool { + self.get_attribute(name, data, module_info).is_some() + } + + fn simple_dump(&self) -> String { + let mut output = "{\n".to_string(); + output.push_str("\"kind\": \"SchemaSymbol\",\n"); + output.push_str(&format!("\"name\":\"{}\",\n", self.name)); + output.push_str(&format!( + "\"range\": \"{}:{}", + self.start.filename, self.start.line + )); + if let Some(start_col) = self.start.column { + output.push_str(&format!(":{}", start_col)); + } + + output.push_str(&format!(" to {}", self.end.line)); + if let Some(end_col) = self.end.column { + output.push_str(&format!(":{}", end_col)); + } + output.push_str("\"\n}"); + output + } + + fn full_dump(&self, data: &Self::SymbolData) -> Option { + let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); + output.push_str("\"additional_info\": {\n"); + let owner_symbol = data.get_symbol(self.owner)?; + output.push_str(&format!("\"owner\": {},\n", owner_symbol.simple_dump())); + if let Some(parent_schema) = self.parent_schema.as_ref() { + let parent_schema_symbol = data.get_symbol(*parent_schema)?; + output.push_str(&format!( + "\"parent_schema\": {},\n", + parent_schema_symbol.simple_dump() + )); + } + if let Some(parent_schema) = self.for_host.as_ref() { + let host_symbol = data.get_symbol(*parent_schema)?; + output.push_str(&format!("\"for_host\": {},\n", host_symbol.simple_dump())); + } + output.push_str("\"mixins\": [\n"); + for (index, mixin) in self.mixins.iter().enumerate() { + let mixin_symbol = data.get_symbol(*mixin)?; + output.push_str(&format!("{}", mixin_symbol.simple_dump())); + if index + 1 < self.mixins.len() { + output.push_str(",\n") + } + } + output.push_str("\n],\n"); + output.push_str("\"attributes\": {\n"); + for (index, (key, attribute)) in self.attributes.iter().enumerate() { + let attribute_symbol = data.get_symbol(*attribute)?; + output.push_str(&format!("\"{}\": {}", key, attribute_symbol.simple_dump())); + if index + 1 < self.attributes.len() { + output.push_str(",\n") + } + } + output.push_str("\n}\n}\n}"); + Some(output) + } + + fn get_sema_info(&self) -> &Self::SemanticInfo { + &self.sema_info + } + + fn get_references(&self) -> HashSet { + self.r#ref.clone() + } +} + +impl SchemaSymbol { + pub fn new(name: String, start: Position, end: Position, owner: SymbolRef) -> Self { + Self { + id: None, + name, + start, + end, + owner, + parent_schema: None, + for_host: None, + sema_info: SymbolSemanticInfo::default(), + mixins: Vec::default(), + attributes: IndexMap::default(), + r#ref: HashSet::default(), + } + } + + pub fn get_parents(&self, data: &SymbolData, parents: &mut Vec) { + if let Some(parent_schema_ref) = self.parent_schema { + if let Some(parent_schema) = data.get_symbol(parent_schema_ref) { + if let Some(schema_def) = parent_schema.get_definition() { + if let Some(parent_schema) = data.get_schema_symbol(schema_def) { + // circular reference + if !parents.contains(&schema_def) { + parents.push(schema_def); + parent_schema.get_parents(data, parents); + } + } + } + } + } + } + + pub fn get_protocol_and_mixin_attrs( + &self, + data: &SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Vec { + let mut result = vec![]; + if let Some(for_host) = self.for_host { + if let Some(for_host) = data.get_symbol(for_host) { + result.append(&mut for_host.get_all_attributes(data, module_info)) + } + } + for mixin in self.mixins.iter() { + if let Some(mixin) = data.get_symbol(*mixin) { + result.append(&mut mixin.get_all_attributes(data, module_info)) + } + } + + result + } + + pub fn get_self_attr( + &self, + data: &SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Vec { + let mut result = vec![]; + for attribute in self.attributes.values() { + result.push(*attribute); + } + result.extend(self.get_protocol_and_mixin_attrs(data, module_info)); + result + } +} + +#[allow(unused)] +#[derive(Debug, Clone)] +pub struct ValueSymbol { + pub(crate) id: Option, + pub(crate) name: String, + pub(crate) start: Position, + pub(crate) end: Position, + pub(crate) owner: Option, + pub(crate) sema_info: SymbolSemanticInfo, + pub(crate) r#ref: HashSet, + pub(crate) is_global: bool, +} + +impl Symbol for ValueSymbol { + type SymbolData = SymbolData; + type SemanticInfo = SymbolSemanticInfo; + type SymbolHint = SymbolHint; + + fn is_global(&self) -> bool { + self.is_global + } + + fn get_range(&self) -> Range { + (self.start.clone(), self.end.clone()) + } + + fn get_owner(&self) -> Option { + self.owner.clone() + } + + fn get_definition(&self) -> Option { + self.id.clone() + } + + fn get_name(&self) -> String { + self.name.clone() + } + + fn get_id(&self) -> Option { + self.id.clone() + } + + fn get_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Option { + data.get_type_attribute(self.sema_info.ty.as_ref()?, name, module_info) + } + + fn get_all_attributes( + &self, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Vec { + let mut result = vec![]; + if let Some(ty) = self.sema_info.ty.as_ref() { + if let Some(symbol_ref) = data.get_type_symbol(ty, module_info) { + if let Some(symbol) = data.get_symbol(symbol_ref) { + result.append(&mut symbol.get_all_attributes(data, module_info)) + } + } + } + + result + } + + fn has_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> bool { + self.get_attribute(name, data, module_info).is_some() + } + + fn simple_dump(&self) -> String { + let mut output = "{\n".to_string(); + output.push_str("\"kind\": \"ValueSymbol\",\n"); + output.push_str(&format!("\"name\":\"{}\",\n", self.name)); + output.push_str(&format!( + "\"range\": \"{}:{}", + self.start.filename, self.start.line + )); + if let Some(start_col) = self.start.column { + output.push_str(&format!(":{}", start_col)); + } + + output.push_str(&format!(" to {}", self.end.line)); + if let Some(end_col) = self.end.column { + output.push_str(&format!(":{}", end_col)); + } + output.push_str("\"\n}"); + output + } + + fn full_dump(&self, data: &Self::SymbolData) -> Option { + let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); + output.push_str("\"additional_info\": {\n"); + if let Some(owner) = self.owner.as_ref() { + let owner_symbol = data.get_symbol(*owner)?; + output.push_str(&format!("\"owner\": {}\n", owner_symbol.simple_dump())); + } + output.push_str("\n}\n}"); + Some(output) + } + + fn get_sema_info(&self) -> &Self::SemanticInfo { + &self.sema_info + } + + fn get_references(&self) -> HashSet { + self.r#ref.clone() + } +} + +impl ValueSymbol { + pub fn new( + name: String, + start: Position, + end: Position, + owner: Option, + is_global: bool, + ) -> Self { + Self { + id: None, + name, + start, + end, + owner, + sema_info: SymbolSemanticInfo::default(), + is_global, + r#ref: HashSet::default(), + } + } +} + +#[allow(unused)] +#[derive(Debug, Clone)] +pub struct AttributeSymbol { + pub(crate) id: Option, + pub(crate) name: String, + pub(crate) start: Position, + pub(crate) end: Position, + pub(crate) owner: SymbolRef, + pub(crate) sema_info: SymbolSemanticInfo, + pub(crate) is_optional: bool, + pub(crate) r#ref: HashSet, + pub(crate) default_value: Option, +} + +impl Symbol for AttributeSymbol { + type SymbolData = SymbolData; + type SemanticInfo = SymbolSemanticInfo; + type SymbolHint = SymbolHint; + + fn is_global(&self) -> bool { + true + } + fn get_range(&self) -> Range { + (self.start.clone(), self.end.clone()) + } + + fn get_owner(&self) -> Option { + Some(self.owner) + } + + fn get_definition(&self) -> Option { + self.id.clone() + } + + fn get_name(&self) -> String { + self.name.clone() + } + + fn get_id(&self) -> Option { + self.id.clone() + } + + fn get_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Option { + let ty = self.sema_info.ty.as_ref()?; + data.get_type_attribute(ty, name, module_info) + } + + fn get_all_attributes( + &self, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Vec { + let mut result = vec![]; + if module_info.is_none() { + return result; + } + if let Some(ty) = self.sema_info.ty.as_ref() { + if let Some(symbol_ref) = data.get_type_symbol(ty, module_info) { + if let Some(symbol) = data.get_symbol(symbol_ref) { + result.append(&mut symbol.get_all_attributes(data, module_info)) + } + } + } + + result + } + + fn has_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> bool { + self.get_attribute(name, data, module_info).is_some() + } + + fn simple_dump(&self) -> String { + let mut output = "{\n".to_string(); + output.push_str("\"kind\": \"AttributeSymbol\",\n"); + output.push_str(&format!("\"name\":\"{}\",\n", self.name)); + output.push_str(&format!( + "\"range\": \"{}:{}", + self.start.filename, self.start.line + )); + if let Some(start_col) = self.start.column { + output.push_str(&format!(":{}", start_col)); + } + + output.push_str(&format!(" to {}", self.end.line)); + if let Some(end_col) = self.end.column { + output.push_str(&format!(":{}", end_col)); + } + output.push_str("\"\n}"); + output + } + + fn full_dump(&self, data: &Self::SymbolData) -> Option { + let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); + output.push_str("\"additional_info\": {\n"); + let owner_symbol = data.get_symbol(self.owner)?; + output.push_str(&format!("\"owner\": {}\n", owner_symbol.simple_dump())); + output.push_str("\n}\n}"); + Some(output) + } + + fn get_sema_info(&self) -> &Self::SemanticInfo { + &self.sema_info + } + + fn get_references(&self) -> HashSet { + self.r#ref.clone() + } +} + +impl AttributeSymbol { + pub fn new( + name: String, + start: Position, + end: Position, + owner: SymbolRef, + is_optional: bool, + default_value: Option, + ) -> Self { + Self { + id: None, + name, + start, + end, + sema_info: SymbolSemanticInfo::default(), + owner, + is_optional, + r#ref: HashSet::default(), + default_value, + } + } + + pub fn is_optional(&self) -> bool { + self.is_optional + } + + pub fn get_default_value(&self) -> Option { + self.default_value.clone() + } +} +#[allow(unused)] +#[derive(Debug, Clone)] +pub struct PackageSymbol { + pub(crate) id: Option, + pub(crate) name: String, + pub(crate) members: IndexMap, + pub(crate) start: Position, + pub(crate) end: Position, + pub(crate) sema_info: SymbolSemanticInfo, + pub(crate) r#ref: HashSet, +} + +impl Symbol for PackageSymbol { + type SymbolData = SymbolData; + type SemanticInfo = SymbolSemanticInfo; + type SymbolHint = SymbolHint; + + fn is_global(&self) -> bool { + true + } + fn get_range(&self) -> Range { + (self.start.clone(), self.end.clone()) + } + + fn get_owner(&self) -> Option { + None + } + + fn get_definition(&self) -> Option { + self.id.clone() + } + + fn get_name(&self) -> String { + self.name.clone() + } + + fn get_id(&self) -> Option { + self.id.clone() + } + + fn get_attribute( + &self, + name: &str, + _data: &Self::SymbolData, + _module_info: Option<&ModuleInfo>, + ) -> Option { + self.members.get(name).cloned() + } + + fn get_all_attributes( + &self, + _data: &Self::SymbolData, + _module_info: Option<&ModuleInfo>, + ) -> Vec { + let mut result = vec![]; + for member in self.members.values() { + result.push(*member); + } + result + } + + fn has_attribute( + &self, + name: &str, + _data: &Self::SymbolData, + _module_info: Option<&ModuleInfo>, + ) -> bool { + self.members.contains_key(name) + } + + fn simple_dump(&self) -> String { + let mut output = "{\n".to_string(); + output.push_str("\"kind\": \"PackageSymbol\",\n"); + output.push_str(&format!("\"name\":\"{}\",\n", self.name)); + output.push_str(&format!( + "\"range\": \"{}:{}", + self.start.filename, self.start.line + )); + if let Some(start_col) = self.start.column { + output.push_str(&format!(":{}", start_col)); + } + + output.push_str(&format!(" to {}", self.end.line)); + if let Some(end_col) = self.end.column { + output.push_str(&format!(":{}", end_col)); + } + output.push_str("\"\n}"); + output + } + + fn full_dump(&self, data: &Self::SymbolData) -> Option { + let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); + output.push_str("\"additional_info\": {\n"); + output.push_str("\"members\": {\n"); + for (index, (key, member)) in self.members.iter().enumerate() { + let member_symbol = data.get_symbol(*member)?; + output.push_str(&format!("\"{}\": {}", key, member_symbol.simple_dump())); + if index + 1 < self.members.len() { + output.push_str(",\n"); + } + } + output.push_str("\n}\n}\n}"); + Some(output) + } + + fn get_sema_info(&self) -> &Self::SemanticInfo { + &self.sema_info + } + + fn get_references(&self) -> HashSet { + self.r#ref.clone() + } +} + +impl PackageSymbol { + pub fn new(name: String, start: Position, end: Position) -> Self { + Self { + id: None, + name, + start, + end, + sema_info: SymbolSemanticInfo::default(), + members: IndexMap::default(), + r#ref: HashSet::default(), + } + } +} +#[allow(unused)] +#[derive(Debug, Clone)] +pub struct TypeAliasSymbol { + pub(crate) id: Option, + pub(crate) name: String, + pub(crate) start: Position, + pub(crate) end: Position, + pub(crate) owner: SymbolRef, + pub(crate) sema_info: SymbolSemanticInfo, + pub(crate) r#ref: HashSet, +} + +impl Symbol for TypeAliasSymbol { + type SymbolData = SymbolData; + type SemanticInfo = SymbolSemanticInfo; + type SymbolHint = SymbolHint; + + fn is_global(&self) -> bool { + true + } + fn get_range(&self) -> Range { + (self.start.clone(), self.end.clone()) + } + + fn get_owner(&self) -> Option { + Some(self.owner) + } + + fn get_definition(&self) -> Option { + self.id.clone() + } + + fn get_name(&self) -> String { + self.name.clone() + } + + fn get_id(&self) -> Option { + self.id.clone() + } + + fn get_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Option { + let ty = self.sema_info.ty.as_ref()?; + data.get_type_attribute(ty, name, module_info) + } + + fn get_all_attributes( + &self, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Vec { + let mut result = vec![]; + if let Some(ty) = self.sema_info.ty.as_ref() { + if let Some(symbol_ref) = data.get_type_symbol(ty, module_info) { + if let Some(symbol) = data.get_symbol(symbol_ref) { + result.append(&mut symbol.get_all_attributes(data, module_info)) + } + } + } + result + } + + fn has_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> bool { + self.get_attribute(name, data, module_info).is_some() + } + + fn simple_dump(&self) -> String { + let mut output = "{\n".to_string(); + output.push_str("\"kind\": \"TypeAliasSymbol\",\n"); + output.push_str(&format!("\"name\":\"{}\",\n", self.name)); + output.push_str(&format!( + "\"range\": \"{}:{}", + self.start.filename, self.start.line + )); + if let Some(start_col) = self.start.column { + output.push_str(&format!(":{}", start_col)); + } + + output.push_str(&format!(" to {}", self.end.line)); + if let Some(end_col) = self.end.column { + output.push_str(&format!(":{}", end_col)); + } + output.push_str("\"\n}"); + output + } + + fn full_dump(&self, data: &Self::SymbolData) -> Option { + let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); + output.push_str("\"additional_info\": {\n"); + let owner_symbol = data.get_symbol(self.owner)?; + output.push_str(&format!( + "\"owner\": {}\n}}\n}}", + owner_symbol.simple_dump() + )); + Some(output) + } + + fn get_sema_info(&self) -> &Self::SemanticInfo { + &self.sema_info + } + + fn get_references(&self) -> HashSet { + self.r#ref.clone() + } +} + +impl TypeAliasSymbol { + pub fn new(name: String, start: Position, end: Position, owner: SymbolRef) -> Self { + Self { + id: None, + name, + start, + end, + sema_info: SymbolSemanticInfo::default(), + owner, + r#ref: HashSet::default(), + } + } +} +#[allow(unused)] +#[derive(Debug, Clone)] +pub struct RuleSymbol { + pub(crate) id: Option, + pub(crate) name: String, + pub(crate) start: Position, + pub(crate) end: Position, + pub(crate) owner: SymbolRef, + pub(crate) sema_info: SymbolSemanticInfo, + + pub(crate) parent_rules: Vec, + pub(crate) for_host: Option, + pub(crate) r#ref: HashSet, +} + +impl Symbol for RuleSymbol { + type SymbolData = SymbolData; + type SemanticInfo = SymbolSemanticInfo; + type SymbolHint = SymbolHint; + + fn is_global(&self) -> bool { + true + } + fn get_range(&self) -> Range { + (self.start.clone(), self.end.clone()) + } + + fn get_owner(&self) -> Option { + Some(self.owner) + } + + fn get_definition(&self) -> Option { + self.id.clone() + } + + fn get_name(&self) -> String { + self.name.clone() + } + + fn get_id(&self) -> Option { + self.id.clone() + } + + fn get_attribute( + &self, + _name: &str, + _data: &Self::SymbolData, + _module_info: Option<&ModuleInfo>, + ) -> Option { + None + } + + fn get_all_attributes( + &self, + _data: &Self::SymbolData, + _module_info: Option<&ModuleInfo>, + ) -> Vec { + vec![] + } + + fn has_attribute( + &self, + _name: &str, + _data: &Self::SymbolData, + _module_info: Option<&ModuleInfo>, + ) -> bool { + false + } + + fn simple_dump(&self) -> String { + let mut output = "{\n".to_string(); + output.push_str("\"kind\": \"RuleSymbol\",\n"); + output.push_str(&format!("\"name\":\"{}\",\n", self.name)); + output.push_str(&format!( + "\"range\": \"{}:{}", + self.start.filename, self.start.line + )); + if let Some(start_col) = self.start.column { + output.push_str(&format!(":{}", start_col)); + } + + output.push_str(&format!(" to {}", self.end.line)); + if let Some(end_col) = self.end.column { + output.push_str(&format!(":{}", end_col)); + } + output.push_str("\"\n}"); + output + } + + fn full_dump(&self, data: &Self::SymbolData) -> Option { + let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); + output.push_str("\"additional_info\": {\n"); + let owner_symbol = data.get_symbol(self.owner)?; + output.push_str(&format!("\"owner\": {},\n", owner_symbol.simple_dump())); + + if let Some(parent_schema) = self.for_host.as_ref() { + let host_symbol = data.get_symbol(*parent_schema)?; + output.push_str(&format!("\"for_host\": {},\n", host_symbol.simple_dump())); + } + output.push_str("\"parent_rules\": [\n"); + for (index, parent_rule) in self.parent_rules.iter().enumerate() { + let parent_symbol = data.get_symbol(*parent_rule)?; + output.push_str(&format!("{}", parent_symbol.simple_dump())); + if index + 1 < self.parent_rules.len() { + output.push_str(",\n") + } + } + output.push_str("\n]\n}\n}"); + + Some(output) + } + + fn get_sema_info(&self) -> &Self::SemanticInfo { + &self.sema_info + } + + fn get_references(&self) -> HashSet { + self.r#ref.clone() + } +} + +impl RuleSymbol { + pub fn new(name: String, start: Position, end: Position, owner: SymbolRef) -> Self { + Self { + id: None, + name, + start, + end, + owner, + sema_info: SymbolSemanticInfo::default(), + parent_rules: vec![], + for_host: None, + r#ref: HashSet::default(), + } + } +} +#[allow(unused)] +#[derive(Debug, Clone)] +pub struct UnresolvedSymbol { + pub(crate) id: Option, + pub(crate) def: Option, + pub(crate) name: String, + pub(crate) start: Position, + pub(crate) end: Position, + pub(crate) owner: Option, + pub(crate) sema_info: SymbolSemanticInfo, + pub(crate) is_type: bool, + pub(crate) r#ref: HashSet, +} + +impl Symbol for UnresolvedSymbol { + type SymbolData = SymbolData; + type SemanticInfo = SymbolSemanticInfo; + type SymbolHint = SymbolHint; + + fn is_global(&self) -> bool { + false + } + fn get_range(&self) -> Range { + (self.start.clone(), self.end.clone()) + } + + fn get_owner(&self) -> Option { + self.owner.clone() + } + + fn get_definition(&self) -> Option { + self.def.clone() + } + + fn get_name(&self) -> String { + self.name.clone() + } + + fn get_id(&self) -> Option { + self.id.clone() + } + + fn get_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Option { + if self.is_type() { + None + } else { + data.get_symbol(self.def?)? + .get_attribute(name, data, module_info) + } + } + + fn get_all_attributes( + &self, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Vec { + if !self.is_type() { + if let Some(def) = self.def { + if let Some(def_symbol) = data.get_symbol(def) { + return def_symbol.get_all_attributes(data, module_info); + } + } + } + + vec![] + } + + fn has_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> bool { + self.get_attribute(name, data, module_info).is_some() + } + + fn get_sema_info(&self) -> &Self::SemanticInfo { + &self.sema_info + } + + fn simple_dump(&self) -> String { + let mut output = "{\n".to_string(); + output.push_str("\"kind\": \"UnresolvedSymbol\",\n"); + output.push_str(&format!("\"name\":\"{}\",\n", self.name)); + output.push_str(&format!( + "\"range\": \"{}:{}", + self.start.filename, self.start.line + )); + if let Some(start_col) = self.start.column { + output.push_str(&format!(":{}", start_col)); + } + + output.push_str(&format!(" to {}", self.end.line)); + if let Some(end_col) = self.end.column { + output.push_str(&format!(":{}", end_col)); + } + output.push_str("\"\n}"); + output + } + + fn full_dump(&self, data: &Self::SymbolData) -> Option { + let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); + output.push_str("\"additional_info\": {\n"); + if let Some(def) = self.def.as_ref() { + let def_symbol = data.get_symbol(*def)?; + output.push_str(&format!("\"def\": {}\n", def_symbol.simple_dump())); + } + output.push_str("\n}\n}"); + Some(output) + } + + fn get_references(&self) -> HashSet { + self.r#ref.clone() + } +} + +impl UnresolvedSymbol { + pub fn new( + name: String, + start: Position, + end: Position, + owner: Option, + is_type: bool, + ) -> Self { + Self { + id: None, + def: None, + name, + start, + end, + sema_info: SymbolSemanticInfo::default(), + owner, + is_type, + r#ref: HashSet::default(), + } + } + + pub fn get_fully_qualified_name(&self, module_info: &ModuleInfo) -> String { + let names: Vec<_> = self.name.split('.').collect(); + let pkg_path = if names.len() == 1 { + kcl_ast::MAIN_PKG.to_string() + } else { + let pkg_alias = names.first().unwrap(); + let import_info = module_info.get_import_info(*pkg_alias); + match import_info { + Some(info) => info.fully_qualified_name.clone(), + None => kcl_ast::MAIN_PKG.to_string(), + } + }; + + pkg_path + "." + names.last().unwrap() + } + + pub fn is_type(&self) -> bool { + self.is_type + } +} + +#[derive(Debug, Clone)] +pub struct ExpressionSymbol { + pub(crate) id: Option, + pub(crate) start: Position, + pub(crate) end: Position, + pub(crate) owner: Option, + pub(crate) name: String, + + pub(crate) sema_info: SymbolSemanticInfo, + pub(crate) r#ref: HashSet, +} + +impl Symbol for ExpressionSymbol { + type SymbolData = SymbolData; + type SemanticInfo = SymbolSemanticInfo; + type SymbolHint = SymbolHint; + + fn is_global(&self) -> bool { + false + } + fn get_range(&self) -> Range { + (self.start.clone(), self.end.clone()) + } + + fn get_owner(&self) -> Option { + self.owner.clone() + } + + fn get_definition(&self) -> Option { + self.id + } + + fn get_name(&self) -> String { + self.name.clone() + } + + fn get_id(&self) -> Option { + self.id.clone() + } + + fn get_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Option { + data.get_type_attribute(self.sema_info.ty.as_ref()?, name, module_info) + } + + fn get_all_attributes( + &self, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Vec { + let mut result = vec![]; + if let Some(ty) = self.sema_info.ty.as_ref() { + if let Some(symbol_ref) = data.get_type_symbol(ty, module_info) { + if let Some(symbol) = data.get_symbol(symbol_ref) { + result.append(&mut symbol.get_all_attributes(data, module_info)) + } + } + } + + result + } + + fn has_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> bool { + self.get_attribute(name, data, module_info).is_some() + } + + fn get_sema_info(&self) -> &Self::SemanticInfo { + &self.sema_info + } + + fn simple_dump(&self) -> String { + let mut output = "{\n".to_string(); + output.push_str("\"kind\": \"ExpressionSymbol\",\n"); + output.push_str(&format!( + "\"range\": \"{}:{}", + self.start.filename, self.start.line + )); + if let Some(start_col) = self.start.column { + output.push_str(&format!(":{}", start_col)); + } + + output.push_str(&format!(" to {}", self.end.line)); + if let Some(end_col) = self.end.column { + output.push_str(&format!(":{}", end_col)); + } + output.push_str("\"\n}"); + output + } + + fn full_dump(&self, data: &Self::SymbolData) -> Option { + let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); + output.push_str("\"additional_info\": {\n"); + if let Some(owner) = self.owner.as_ref() { + let owner_symbol = data.get_symbol(*owner)?; + output.push_str(&format!("\"owner\": {}\n", owner_symbol.simple_dump())); + } + output.push_str("\n}\n}"); + Some(output) + } + + fn get_references(&self) -> HashSet { + self.r#ref.clone() + } +} + +impl ExpressionSymbol { + pub fn new(name: String, start: Position, end: Position, owner: Option) -> Self { + Self { + id: None, + name, + start, + end, + sema_info: SymbolSemanticInfo::default(), + owner, + r#ref: HashSet::default(), + } + } +} + +#[derive(Debug, Clone)] +pub struct CommentOrDocSymbol { + pub(crate) id: Option, + pub(crate) start: Position, + pub(crate) end: Position, + pub(crate) content: String, + pub(crate) sema_info: SymbolSemanticInfo, + pub(crate) r#ref: HashSet, +} + +impl Symbol for CommentOrDocSymbol { + type SymbolData = SymbolData; + type SemanticInfo = SymbolSemanticInfo; + type SymbolHint = SymbolHint; + + fn get_sema_info(&self) -> &Self::SemanticInfo { + &self.sema_info + } + + fn is_global(&self) -> bool { + true + } + + fn get_range(&self) -> Range { + (self.start.clone(), self.end.clone()) + } + + fn get_owner(&self) -> Option { + None + } + + fn get_definition(&self) -> Option { + self.id + } + + fn get_name(&self) -> String { + self.name() + } + + fn get_id(&self) -> Option { + self.id.clone() + } + + fn get_attribute( + &self, + _name: &str, + _data: &Self::SymbolData, + _module_info: Option<&ModuleInfo>, + ) -> Option { + None + } + + fn has_attribute( + &self, + _name: &str, + _data: &Self::SymbolData, + _module_info: Option<&ModuleInfo>, + ) -> bool { + false + } + + fn get_all_attributes( + &self, + _data: &Self::SymbolData, + _module_info: Option<&ModuleInfo>, + ) -> Vec { + vec![] + } + + fn simple_dump(&self) -> String { + let mut output = "{\n".to_string(); + output.push_str("\"kind\": \"CommentSymbol\",\n"); + output.push_str(&format!( + "\"range\": \"{}:{}", + self.start.filename, self.start.line + )); + if let Some(start_col) = self.start.column { + output.push_str(&format!(":{}", start_col)); + } + + output.push_str(&format!(" to {}", self.end.line)); + if let Some(end_col) = self.end.column { + output.push_str(&format!(":{}", end_col)); + } + output.push_str(&format!("content :{}", self.name())); + output.push_str("\"\n}"); + output + } + + fn full_dump(&self, _data: &Self::SymbolData) -> Option { + Some(self.simple_dump()) + } + + fn get_references(&self) -> HashSet { + self.r#ref.clone() + } +} + +impl CommentOrDocSymbol { + pub fn new(start: Position, end: Position, content: String) -> Self { + Self { + id: None, + start, + end, + content, + sema_info: SymbolSemanticInfo::default(), + r#ref: HashSet::default(), + } + } + + pub fn name(&self) -> String { + format!("# {}", self.content) + } +} + +#[derive(Debug, Clone)] +pub struct DecoratorSymbol { + pub(crate) id: Option, + pub(crate) start: Position, + pub(crate) end: Position, + pub(crate) name: String, + pub(crate) sema_info: SymbolSemanticInfo, + pub(crate) r#ref: HashSet, +} + +impl Symbol for DecoratorSymbol { + type SymbolData = SymbolData; + type SemanticInfo = SymbolSemanticInfo; + type SymbolHint = SymbolHint; + + fn get_sema_info(&self) -> &Self::SemanticInfo { + &self.sema_info + } + + fn is_global(&self) -> bool { + true + } + + fn get_range(&self) -> Range { + (self.start.clone(), self.end.clone()) + } + + fn get_owner(&self) -> Option { + None + } + + fn get_definition(&self) -> Option { + self.id + } + + fn get_name(&self) -> String { + self.name() + } + + fn get_id(&self) -> Option { + self.id.clone() + } + + fn get_attribute( + &self, + _name: &str, + _data: &Self::SymbolData, + _module_info: Option<&ModuleInfo>, + ) -> Option { + None + } + + fn has_attribute( + &self, + _name: &str, + _data: &Self::SymbolData, + _module_info: Option<&ModuleInfo>, + ) -> bool { + false + } + + fn get_all_attributes( + &self, + _data: &Self::SymbolData, + _module_info: Option<&ModuleInfo>, + ) -> Vec { + vec![] + } + + fn simple_dump(&self) -> String { + let mut output = "{\n".to_string(); + output.push_str("\"kind\": \"CommentSymbol\",\n"); + output.push_str(&format!( + "\"range\": \"{}:{}", + self.start.filename, self.start.line + )); + if let Some(start_col) = self.start.column { + output.push_str(&format!(":{}", start_col)); + } + + output.push_str(&format!(" to {}", self.end.line)); + if let Some(end_col) = self.end.column { + output.push_str(&format!(":{}", end_col)); + } + output.push_str(&format!("name :{}", self.name())); + output.push_str("\"\n}"); + output + } + + fn full_dump(&self, _data: &Self::SymbolData) -> Option { + Some(self.simple_dump()) + } + + fn get_references(&self) -> HashSet { + self.r#ref.clone() + } +} + +impl DecoratorSymbol { + pub fn new(start: Position, end: Position, name: String) -> Self { + Self { + id: None, + start, + end, + name, + sema_info: SymbolSemanticInfo::default(), + r#ref: HashSet::default(), + } + } + + pub fn name(&self) -> String { + self.name.clone() + } +} + +#[derive(Debug, Clone)] +pub struct FunctionSymbol { + pub(crate) id: Option, + pub(crate) name: String, + pub(crate) start: Position, + pub(crate) end: Position, + pub(crate) owner: Option, + pub(crate) sema_info: SymbolSemanticInfo, + pub(crate) is_global: bool, + pub(crate) r#ref: HashSet, +} + +impl Symbol for FunctionSymbol { + type SymbolData = SymbolData; + type SemanticInfo = SymbolSemanticInfo; + type SymbolHint = SymbolHint; + + fn is_global(&self) -> bool { + self.is_global + } + + fn get_range(&self) -> Range { + (self.start.clone(), self.end.clone()) + } + + fn get_owner(&self) -> Option { + self.owner.clone() + } + + fn get_definition(&self) -> Option { + self.id.clone() + } + + fn get_name(&self) -> String { + self.name.clone() + } + + fn get_id(&self) -> Option { + self.id.clone() + } + + fn get_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Option { + data.get_type_attribute(self.sema_info.ty.as_ref()?, name, module_info) + } + + fn get_all_attributes( + &self, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> Vec { + let mut result = vec![]; + if let Some(ty) = self.sema_info.ty.as_ref() { + if let Some(symbol_ref) = data.get_type_symbol(ty, module_info) { + if let Some(symbol) = data.get_symbol(symbol_ref) { + result.append(&mut symbol.get_all_attributes(data, module_info)) + } + } + } + + result + } + + fn has_attribute( + &self, + name: &str, + data: &Self::SymbolData, + module_info: Option<&ModuleInfo>, + ) -> bool { + self.get_attribute(name, data, module_info).is_some() + } + + fn get_sema_info(&self) -> &Self::SemanticInfo { + &self.sema_info + } + + fn simple_dump(&self) -> String { + let mut output = "{\n".to_string(); + output.push_str("\"kind\": \"FunctionSymbol\",\n"); + output.push_str(&format!("\"name\":\"{}\",\n", self.name)); + output.push_str(&format!( + "\"range\": \"{}:{}", + self.start.filename, self.start.line + )); + if let Some(start_col) = self.start.column { + output.push_str(&format!(":{}", start_col)); + } + + output.push_str(&format!(" to {}", self.end.line)); + if let Some(end_col) = self.end.column { + output.push_str(&format!(":{}", end_col)); + } + output.push_str("\"\n}"); + output + } + + fn full_dump(&self, data: &Self::SymbolData) -> Option { + let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); + output.push_str("\"additional_info\": {\n"); + if let Some(owner) = self.owner.as_ref() { + let owner_symbol = data.get_symbol(*owner)?; + output.push_str(&format!("\"owner\": {}\n", owner_symbol.simple_dump())); + } + output.push_str("\n}\n}"); + Some(output) + } + + fn get_references(&self) -> HashSet { + self.r#ref.clone() + } +} + +impl FunctionSymbol { + pub fn new( + name: String, + start: Position, + end: Position, + owner: Option, + is_global: bool, + ) -> Self { + Self { + id: None, + name, + start, + end, + owner, + sema_info: SymbolSemanticInfo::default(), + is_global, + r#ref: HashSet::default(), + } + } +} diff --git a/kclvm/sema/src/eval/mod.rs b/crates/sema/src/eval/mod.rs similarity index 100% rename from kclvm/sema/src/eval/mod.rs rename to crates/sema/src/eval/mod.rs diff --git a/kclvm/sema/src/info/mod.rs b/crates/sema/src/info/mod.rs similarity index 100% rename from kclvm/sema/src/info/mod.rs rename to crates/sema/src/info/mod.rs diff --git a/kclvm/sema/src/lib.rs b/crates/sema/src/lib.rs similarity index 100% rename from kclvm/sema/src/lib.rs rename to crates/sema/src/lib.rs diff --git a/kclvm/sema/src/lint/LICENSE b/crates/sema/src/lint/LICENSE similarity index 100% rename from kclvm/sema/src/lint/LICENSE rename to crates/sema/src/lint/LICENSE diff --git a/kclvm/sema/src/lint/combinedlintpass.rs b/crates/sema/src/lint/combinedlintpass.rs similarity index 98% rename from kclvm/sema/src/lint/combinedlintpass.rs rename to crates/sema/src/lint/combinedlintpass.rs index 9e1c82041..f1b9a53c0 100644 --- a/kclvm/sema/src/lint/combinedlintpass.rs +++ b/crates/sema/src/lint/combinedlintpass.rs @@ -5,8 +5,8 @@ use crate::lint::lints_def::ReImport; use crate::lint::lints_def::UnusedImport; use crate::lint_methods; use crate::resolver::scope::Scope; -use kclvm_ast::ast; -use kclvm_error::Handler; +use kcl_ast::ast; +use kcl_error::Handler; /// Call the `check_*` method of each lintpass in CombinedLintLass.check_*. /// ```ignore diff --git a/kclvm/sema/src/lint/lint.rs b/crates/sema/src/lint/lint.rs similarity index 97% rename from kclvm/sema/src/lint/lint.rs rename to crates/sema/src/lint/lint.rs index 7545c3c9f..614526c21 100644 --- a/kclvm/sema/src/lint/lint.rs +++ b/crates/sema/src/lint/lint.rs @@ -1,4 +1,4 @@ -use kclvm_error::{Level, Position}; +use kcl_error::{Level, Position}; /// Record the information at `LintContext` when traversing the AST for analysis across AST nodes, e.g., record /// used importstmt(used_import_names) when traversing `ast::Identifier` and `ast::SchemaAttr`, and detect unused diff --git a/kclvm/sema/src/lint/lintpass.rs b/crates/sema/src/lint/lintpass.rs similarity index 99% rename from kclvm/sema/src/lint/lintpass.rs rename to crates/sema/src/lint/lintpass.rs index 9e64a0a2d..cf30bc2bf 100644 --- a/kclvm/sema/src/lint/lintpass.rs +++ b/crates/sema/src/lint/lintpass.rs @@ -1,7 +1,7 @@ use crate::lint::lint::LintContext; use crate::resolver::scope::Scope; -use kclvm_ast::ast; -use kclvm_error::Handler; +use kcl_ast::ast; +use kcl_error::Handler; #[macro_export] /// A summary of the methods that need to be implemented in lintpass, to be added when constructing new lint diff --git a/kclvm/sema/src/lint/lints_def.rs b/crates/sema/src/lint/lints_def.rs similarity index 97% rename from kclvm/sema/src/lint/lints_def.rs rename to crates/sema/src/lint/lints_def.rs index 130d9b9c0..c524b403e 100644 --- a/kclvm/sema/src/lint/lints_def.rs +++ b/crates/sema/src/lint/lints_def.rs @@ -2,10 +2,10 @@ use crate::lint::lint::{Lint, LintArray, LintContext}; use crate::lint::lintpass::LintPass; use crate::resolver::scope::Scope; use crate::{declare_lint_pass, resolver::scope::ScopeObjectKind}; -use kclvm_ast::ast; -use kclvm_ast::pos::GetPos; -use kclvm_error::{Handler, Level, Message, Style, WarningKind}; -use kclvm_primitives::IndexSet; +use kcl_ast::ast; +use kcl_ast::pos::GetPos; +use kcl_error::{Handler, Level, Message, Style, WarningKind}; +use kcl_primitives::IndexSet; /// The 'import_position' lint detects import statements that are not declared at the top of file. /// ### Example diff --git a/crates/sema/src/lint/mod.rs b/crates/sema/src/lint/mod.rs new file mode 100644 index 000000000..d701f983c --- /dev/null +++ b/crates/sema/src/lint/mod.rs @@ -0,0 +1,402 @@ +//! The design and implementation of KCL Lint refer to the [rust-lang/rustc](https://github.com/rust-lang/rust) lint and follow Apache License Version 2.0 +//! +//! This file is the implementation of KCLLint, which is used to perform some additional checks on KCL code. +//! The main structures of the file are Lint, LintPass, CombinedLintPass and Linter. +//! For details see the: https://github.com/kcl-lang/kcl/issues/109 +//! +//! File dependencies: +//! mode -> combinedlintpass -> lints_def -> lintpass -> lint +//! +//! mode.rs: Definition of `Linter`, the entry for lint check +//! combinedlintpass.rs: `CombinedLintPass` collects all the lints defined in the lints_def.rs +//! lints_def.rs: Defined the various lints and the corresponding lintpasses implementation +//! lintpass.rs: Definition of `Lintpass` +//! lint.rs: Definition of `Lint` +//! +//! Steps to define a new lint: +//! 1. Define a static instance of the `Lint` structure in lints_def.rs,e.g., +//! +//! ```ignore +//! pub static IMPORT_POSITION: &Lint = &Lint { +//! ... +//! } +//! ``` +//! +//! 2. Define a lintpass, which is used to implement the checking process,e.g., +//! +//! ```ignore +//! declare_lint_pass!(ImportPosition => [IMPORT_POSITION]); +//! ``` +//! +//! The `ImportPosition` is the defined LintPass structure and the `IMPORT_POSITION` is the `Lint` structure +//! defined in step 1. Here is a `LintArray`, which means that multiple lint checks can be implemented +//! in a single lintpass. +//! +//! 3. Implement the lintpass check process, e.g., +//! +//! ```ignore +//! impl LintPass for ImportPosition { +//! fn check_module(&mut self, handler: &mut Handler, ctx: &mut LintContext,module: &ast::Module){ +//! ... +//! } +//! } +//! ``` +//! +//! 4. Add the `check_*` methods in lintpass to the macro `lint_methods`, or skip it if it exists +//! +//! ```ignore +//! macro_rules! lint_methods { +//! ($macro:path, $args:tt) => ( +//! $macro!($args, [ +//! fn check_module(module: &ast::Module); +//! ]); +//! ) +//! } +//! ``` +//! +//! 5. Add the new lintpass to the macro `default_lint_passes` in lintpass.rs , noting that `:` is preceded and followed by +//! the name of the lintpass. e.g., +//! +//! ```ignore +//! macro_rules! default_lint_passes { +//! ($macro:path, $args:tt) => { +//! $macro!( +//! $args, +//! [ +//! ImportPosition: ImportPosition, +//! ] +//! ); +//! }; +//! } +//! ``` +//! +//! 6. If new `check_*` method was added in step 4, it needs to override the walk_* method in Linter. +//! In addition to calling the self.pass.check_* function, the original walk method in MutSelfWalker +//! should be copied here so that it can continue to traverse the child nodes. + +use crate::resolver::{Resolver, scope::Scope}; +use kcl_ast::pos::GetPos; +use kcl_error::{Handler, Position}; +mod combinedlintpass; +mod lint; +mod lintpass; +mod lints_def; +use kcl_ast::ast; +use kcl_ast::walker::MutSelfWalker; + +pub use self::{combinedlintpass::CombinedLintPass, lint::LintContext, lintpass::LintPass}; + +/// The struct `Linter` is used to traverse the AST and call the `check_*` method defined in `CombinedLintPass`. +pub struct Linter { + pub pass: T, + pub handler: Handler, + pub ctx: LintContext, +} + +impl LintContext { + pub fn dummy_ctx() -> Self { + LintContext { + filename: "".to_string(), + start_pos: Position::dummy_pos(), + end_pos: Position::dummy_pos(), + } + } +} + +impl Linter { + pub fn new() -> Self { + Linter:: { + pass: CombinedLintPass::new(), + handler: Handler::default(), + ctx: LintContext::dummy_ctx(), + } + } + pub fn walk_scope(&mut self, scope: &Scope) { + self.pass + .check_scope(&mut self.handler, &mut self.ctx, scope); + } +} + +impl Resolver<'_> { + /// Iterate the module and run lint checks, generating diagnostics and save them in `lint.handler` + pub fn lint_check_module(&mut self, module: &ast::Module) { + self.linter.ctx.filename = module.filename.clone(); + self.linter.walk_module(module); + } + /// Recursively iterate the scope and its child scope, run lint checks, generating diagnostics and save them in `lint.handler` + pub fn lint_check_scope(&mut self, scope: &Scope) { + self.linter.walk_scope(scope); + for children in &scope.children { + self.lint_check_scope(&children.borrow().clone()) + } + } + + /// Iterate the resolver.scope_map and run lint checks, generating diagnostics and save them in `lint.handler` + pub fn lint_check_scope_map(&mut self) { + let scope_map = self.scope_map.clone(); + for (_, scope) in scope_map.iter() { + self.lint_check_scope(&scope.borrow()) + } + } +} + +macro_rules! walk_set_list { + ($walker: expr, $method: ident, $list: expr) => { + for elem in &$list { + set_pos!($walker, elem); + $walker.$method(&elem.node) + } + }; +} + +macro_rules! walk_set_if { + ($walker: expr, $method: ident, $value: expr) => { + match &$value { + Some(v) => { + set_pos!($walker, &v); + $walker.$method(&v.node); + } + None => (), + } + }; +} + +macro_rules! set_pos { + ($walker: expr, $value: expr) => { + $walker.set_pos(&$value.get_pos(), &$value.get_end_pos()); + }; +} + +impl Linter { + fn set_pos(&mut self, start_pos: &Position, end_pos: &Position) { + self.ctx.start_pos = start_pos.clone(); + self.ctx.end_pos = end_pos.clone(); + } +} + +impl MutSelfWalker for Linter { + fn walk_module(&mut self, module: &ast::Module) { + self.pass + .check_module(&mut self.handler, &mut self.ctx, module); + walk_set_list!(self, walk_stmt, module.body); + } + + fn walk_expr_stmt(&mut self, expr_stmt: &ast::ExprStmt) { + for expr in &expr_stmt.exprs { + set_pos!(self, &expr); + self.walk_expr(&expr.node) + } + } + + fn walk_type_alias_stmt(&mut self, type_alias_stmt: &ast::TypeAliasStmt) { + set_pos!(self, &type_alias_stmt.type_name); + self.walk_identifier(&type_alias_stmt.type_name.node); + } + fn walk_unification_stmt(&mut self, unification_stmt: &ast::UnificationStmt) { + set_pos!(self, &unification_stmt.target); + self.walk_identifier(&unification_stmt.target.node); + set_pos!(self, &unification_stmt.value); + self.walk_schema_expr(&unification_stmt.value.node); + } + fn walk_assign_stmt(&mut self, assign_stmt: &ast::AssignStmt) { + for target in &assign_stmt.targets { + set_pos!(self, &target); + self.walk_target(&target.node) + } + set_pos!(self, &assign_stmt.value); + self.walk_expr(&assign_stmt.value.node); + } + fn walk_aug_assign_stmt(&mut self, aug_assign_stmt: &ast::AugAssignStmt) { + set_pos!(self, &aug_assign_stmt.target); + self.walk_target(&aug_assign_stmt.target.node); + set_pos!(self, &aug_assign_stmt.value); + self.walk_expr(&aug_assign_stmt.value.node); + } + fn walk_assert_stmt(&mut self, assert_stmt: &ast::AssertStmt) { + set_pos!(self, &assert_stmt.test); + self.walk_expr(&assert_stmt.test.node); + walk_set_if!(self, walk_expr, assert_stmt.if_cond); + walk_set_if!(self, walk_expr, assert_stmt.msg); + } + fn walk_if_stmt(&mut self, if_stmt: &ast::IfStmt) { + set_pos!(self, &if_stmt.cond); + self.walk_expr(&if_stmt.cond.node); + walk_set_list!(self, walk_stmt, if_stmt.body); + walk_set_list!(self, walk_stmt, if_stmt.orelse); + } + fn walk_import_stmt(&mut self, import_stmt: &ast::ImportStmt) { + // Nothing to do. + let _ = import_stmt; + } + fn walk_schema_attr(&mut self, schema_attr: &ast::SchemaAttr) { + walk_set_list!(self, walk_call_expr, schema_attr.decorators); + walk_set_if!(self, walk_expr, schema_attr.value); + } + fn walk_schema_stmt(&mut self, schema_stmt: &ast::SchemaStmt) { + walk_set_if!(self, walk_identifier, schema_stmt.parent_name); + walk_set_if!(self, walk_identifier, schema_stmt.for_host_name); + walk_set_if!(self, walk_arguments, schema_stmt.args); + if let Some(schema_index_signature) = &schema_stmt.index_signature { + let value = &schema_index_signature.node.value; + walk_set_if!(self, walk_expr, value); + } + walk_set_list!(self, walk_identifier, schema_stmt.mixins); + walk_set_list!(self, walk_call_expr, schema_stmt.decorators); + walk_set_list!(self, walk_check_expr, schema_stmt.checks); + walk_set_list!(self, walk_stmt, schema_stmt.body); + } + fn walk_rule_stmt(&mut self, rule_stmt: &ast::RuleStmt) { + walk_set_list!(self, walk_identifier, rule_stmt.parent_rules); + walk_set_list!(self, walk_call_expr, rule_stmt.decorators); + walk_set_list!(self, walk_check_expr, rule_stmt.checks); + walk_set_if!(self, walk_arguments, rule_stmt.args); + walk_set_if!(self, walk_identifier, rule_stmt.for_host_name); + } + fn walk_quant_expr(&mut self, quant_expr: &ast::QuantExpr) { + set_pos!(self, &quant_expr.target); + self.walk_expr(&quant_expr.target.node); + walk_set_list!(self, walk_identifier, quant_expr.variables); + set_pos!(self, &quant_expr.test); + self.walk_expr(&quant_expr.test.node); + walk_set_if!(self, walk_expr, quant_expr.if_cond); + } + fn walk_if_expr(&mut self, if_expr: &ast::IfExpr) { + set_pos!(self, &if_expr.cond); + self.walk_expr(&if_expr.cond.node); + set_pos!(self, &if_expr.body); + self.walk_expr(&if_expr.body.node); + set_pos!(self, &if_expr.orelse); + self.walk_expr(&if_expr.orelse.node); + } + fn walk_unary_expr(&mut self, unary_expr: &ast::UnaryExpr) { + set_pos!(self, &unary_expr.operand); + self.walk_expr(&unary_expr.operand.node); + } + fn walk_binary_expr(&mut self, binary_expr: &ast::BinaryExpr) { + set_pos!(self, &binary_expr.left); + self.walk_expr(&binary_expr.left.node); + set_pos!(self, &binary_expr.right); + self.walk_expr(&binary_expr.right.node); + } + fn walk_selector_expr(&mut self, selector_expr: &ast::SelectorExpr) { + set_pos!(self, &selector_expr.value); + self.walk_expr(&selector_expr.value.node); + set_pos!(self, &selector_expr.attr); + self.walk_identifier(&selector_expr.attr.node); + } + fn walk_call_expr(&mut self, call_expr: &ast::CallExpr) { + set_pos!(self, &call_expr.func); + self.walk_expr(&call_expr.func.node); + walk_set_list!(self, walk_expr, call_expr.args); + walk_set_list!(self, walk_keyword, call_expr.keywords); + } + fn walk_subscript(&mut self, subscript: &ast::Subscript) { + set_pos!(self, &subscript.value); + self.walk_expr(&subscript.value.node); + walk_set_if!(self, walk_expr, subscript.index); + walk_set_if!(self, walk_expr, subscript.lower); + walk_set_if!(self, walk_expr, subscript.upper); + walk_set_if!(self, walk_expr, subscript.step); + } + fn walk_paren_expr(&mut self, paren_expr: &ast::ParenExpr) { + set_pos!(self, &paren_expr.expr); + self.walk_expr(&paren_expr.expr.node); + } + fn walk_list_expr(&mut self, list_expr: &ast::ListExpr) { + walk_set_list!(self, walk_expr, list_expr.elts); + } + fn walk_list_comp(&mut self, list_comp: &ast::ListComp) { + set_pos!(self, &list_comp.elt); + self.walk_expr(&list_comp.elt.node); + walk_set_list!(self, walk_comp_clause, list_comp.generators); + } + fn walk_list_if_item_expr(&mut self, list_if_item_expr: &ast::ListIfItemExpr) { + set_pos!(self, &list_if_item_expr.if_cond); + self.walk_expr(&list_if_item_expr.if_cond.node); + walk_set_list!(self, walk_expr, list_if_item_expr.exprs); + walk_set_if!(self, walk_expr, list_if_item_expr.orelse); + } + fn walk_starred_expr(&mut self, starred_expr: &ast::StarredExpr) { + set_pos!(self, &starred_expr.value); + self.walk_expr(&starred_expr.value.node); + } + fn walk_dict_comp(&mut self, dict_comp: &ast::DictComp) { + if let Some(key) = &dict_comp.entry.key { + set_pos!(self, &key); + self.walk_expr(&key.node); + } + set_pos!(self, &dict_comp.entry.value); + self.walk_expr(&dict_comp.entry.value.node); + walk_set_list!(self, walk_comp_clause, dict_comp.generators); + } + fn walk_config_if_entry_expr(&mut self, config_if_entry_expr: &ast::ConfigIfEntryExpr) { + set_pos!(self, &config_if_entry_expr.if_cond); + self.walk_expr(&config_if_entry_expr.if_cond.node); + for config_entry in &config_if_entry_expr.items { + walk_set_if!(self, walk_expr, config_entry.node.key); + set_pos!(self, &config_entry.node.value); + self.walk_expr(&config_entry.node.value.node); + } + walk_set_if!(self, walk_expr, config_if_entry_expr.orelse); + } + fn walk_comp_clause(&mut self, comp_clause: &ast::CompClause) { + walk_set_list!(self, walk_identifier, comp_clause.targets); + set_pos!(self, &comp_clause.iter); + self.walk_expr(&comp_clause.iter.node); + walk_set_list!(self, walk_expr, comp_clause.ifs); + } + fn walk_schema_expr(&mut self, schema_expr: &ast::SchemaExpr) { + set_pos!(self, &schema_expr.name); + self.walk_identifier(&schema_expr.name.node); + walk_set_list!(self, walk_expr, schema_expr.args); + walk_set_list!(self, walk_keyword, schema_expr.kwargs); + set_pos!(self, &schema_expr.config); + self.walk_expr(&schema_expr.config.node); + } + fn walk_config_expr(&mut self, config_expr: &ast::ConfigExpr) { + for config_entry in &config_expr.items { + walk_set_if!(self, walk_expr, config_entry.node.key); + set_pos!(self, &config_entry.node.value); + self.walk_expr(&config_entry.node.value.node); + } + } + fn walk_check_expr(&mut self, check_expr: &ast::CheckExpr) { + set_pos!(self, &check_expr.test); + self.walk_expr(&check_expr.test.node); + walk_set_if!(self, walk_expr, check_expr.if_cond); + walk_set_if!(self, walk_expr, check_expr.msg); + } + fn walk_lambda_expr(&mut self, lambda_expr: &ast::LambdaExpr) { + walk_set_if!(self, walk_arguments, lambda_expr.args); + walk_set_list!(self, walk_stmt, lambda_expr.body); + } + fn walk_keyword(&mut self, keyword: &ast::Keyword) { + set_pos!(self, &keyword.arg); + self.walk_identifier(&keyword.arg.node); + if let Some(v) = &keyword.value { + set_pos!(self, &v); + self.walk_expr(&v.node) + } + } + fn walk_arguments(&mut self, arguments: &ast::Arguments) { + walk_set_list!(self, walk_identifier, arguments.args); + for default in &arguments.defaults { + if let Some(d) = default { + set_pos!(self, d); + self.walk_expr(&d.node) + } + } + } + fn walk_compare(&mut self, compare: &ast::Compare) { + set_pos!(self, &compare.left); + self.walk_expr(&compare.left.node); + walk_set_list!(self, walk_expr, compare.comparators); + } + fn walk_joined_string(&mut self, joined_string: &ast::JoinedString) { + walk_set_list!(self, walk_expr, joined_string.values); + } + fn walk_formatted_value(&mut self, formatted_value: &ast::FormattedValue) { + set_pos!(self, &formatted_value.value); + self.walk_expr(&formatted_value.value.node); + } +} diff --git a/kclvm/sema/src/macros.rs b/crates/sema/src/macros.rs similarity index 100% rename from kclvm/sema/src/macros.rs rename to crates/sema/src/macros.rs diff --git a/crates/sema/src/namer/mod.rs b/crates/sema/src/namer/mod.rs new file mode 100644 index 000000000..305624784 --- /dev/null +++ b/crates/sema/src/namer/mod.rs @@ -0,0 +1,375 @@ +/* + ┌─────────────────────────────────────────────────────────────────────────────────────────────────┐ + │ namer │ + ├─────────────────────────────────────────────────────────────────────────────────────────────────┤ + │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ + │ │ ast::Expression │ │ ast::Expression │ │ ast::Expression │ │ + │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ + │ │ │ │ │ + │ │ find_symbols │ find_symbols │ find_symbols │ + │ ▼ ▼ ▼ │ + │ ┌─────────────────────────┐ ┌─────────────────────────┐ ┌─────────────────────────┐ │ + │ │ core::SymbolRef │ │ core::SymbolRef │ │ core::SymbolRef │ │ + │ └─────────────────────────┘ └─────────────────────────┘ └─────────────────────────┘ │ + │ │ │ │ │ + │ │ │ │ │ + │ └───────────────────────────────┼───────────────────────────────┘ │ + │ │ │ + │ │ merge findSymbols results │ + │ ▼ │ + │ ┌─────────────────────────┐ │ + │ │ core::SymbolRef │ │ + │ └─────────────────────────┘ │ + │ │ │ + │ │ define_symbols(FQN) │ + │ ■ │ + │ (mutates GlobalState) | + │ │ + └─────────────────────────────────────────────────────────────────────────────────────────────────┘ + + The early stage of the namer will be based on file level , which collects global symbols defined in the file, + and then merges the symbols based on FQN to obtain a unique GlobalState + + Based on file level, it means that we can easily perform incremental compilation in the future + + Now we just run namer pass serially + +*/ + +use std::path::Path; +use std::sync::Arc; + +use crate::builtin::{ + BUILTIN_FUNCTIONS, STANDARD_SYSTEM_MODULES, STRING_MEMBER_FUNCTIONS, + get_system_member_function_ty, get_system_module_members, +}; +use crate::core::global_state::GlobalState; +use crate::core::package::{ModuleInfo, PackageInfo}; +use crate::core::symbol::{ + BUILTIN_FUNCTION_PACKAGE, BUILTIN_STR_PACKAGE, FunctionSymbol, PackageSymbol, SymbolRef, +}; +use crate::resolver::scope::NodeKey; +use kcl_ast::ast::AstIndex; +use kcl_ast::ast::Program; +use kcl_ast::walker::MutSelfTypedResultWalker; +use kcl_error::Position; +use kcl_primitives::IndexSet; +mod node; + +pub const BUILTIN_SYMBOL_PKG_PATH: &str = "@builtin"; + +pub struct Namer<'ctx> { + gs: &'ctx mut GlobalState, + ctx: NamerContext<'ctx>, +} + +struct NamerContext<'ctx> { + pub program: &'ctx Program, + pub current_package_info: Option, + pub current_module_info: Option, + pub owner_symbols: Vec, + pub value_fully_qualified_name_set: IndexSet, +} + +impl<'ctx> NamerContext<'ctx> { + pub fn get_node_key(&self, id: &AstIndex) -> NodeKey { + NodeKey { + pkgpath: self + .current_package_info + .clone() + .unwrap() + .fully_qualified_name, + id: id.clone(), + } + } +} + +impl<'ctx> Namer<'ctx> { + fn new(program: &'ctx Program, gs: &'ctx mut GlobalState) -> Self { + Self { + ctx: NamerContext { + program, + current_package_info: None, + current_module_info: None, + owner_symbols: Vec::default(), + value_fully_qualified_name_set: IndexSet::default(), + }, + gs, + } + } + + // serial namer pass + pub fn find_symbols(program: &'ctx Program, gs: &'ctx mut GlobalState) { + let has_init_builtin = gs.ctx.has_init_builtin; + gs.ctx.has_init_builtin = true; + let mut namer = Self::new(program, gs); + namer.ctx.current_package_info = Some(PackageInfo::new( + BUILTIN_SYMBOL_PKG_PATH.to_string(), + "".to_string(), + true, + )); + if !has_init_builtin { + namer.init_builtin_symbols(); + } + + namer + .gs + .get_packages_mut() + .add_package(namer.ctx.current_package_info.take().unwrap()); + + for (name, modules) in namer.ctx.program.pkgs.iter() { + namer.walk_pkg(name, modules); + } + + namer.define_symbols(); + } + + fn walk_pkg(&mut self, name: &String, modules: &Vec) { + // new pkgs or invalidate pkg + if self.gs.get_packages().get_package_info(name).is_some() + && !self.gs.new_or_invalidate_pkgs.contains(name) + { + return; + } + + // add new pkgs to invalidate pkgs + self.gs.new_or_invalidate_pkgs.insert(name.clone()); + + { + if modules.is_empty() { + return; + } + self.ctx.value_fully_qualified_name_set.clear(); + let mut real_path = Path::new(&self.ctx.program.root) + .join(name.replace('.', &std::path::MAIN_SEPARATOR.to_string())) + .to_str() + .unwrap() + .to_string(); + if name == kcl_ast::MAIN_PKG { + real_path = self.ctx.program.root.clone() + } + let pkg_pos = Position { + filename: real_path.clone(), + line: 0, + column: None, + }; + + let pkg_symbol = PackageSymbol::new(name.clone(), pkg_pos.clone(), pkg_pos); + let symbol_ref = self + .gs + .get_symbols_mut() + .alloc_package_symbol(pkg_symbol, name.to_string()); + self.ctx.owner_symbols.push(symbol_ref); + + self.ctx.current_package_info = + Some(PackageInfo::new(name.to_string(), real_path, false)); + } + + let modules = self.ctx.program.get_modules_for_pkg(name); + for module in modules.iter() { + let module = module.read().expect("Failed to acquire module lock"); + self.ctx + .current_package_info + .as_mut() + .unwrap() + .kfile_paths + .insert(module.filename.clone()); + self.ctx.current_module_info = + Some(ModuleInfo::new(module.filename.clone(), name.to_string())); + self.walk_module(&module); + self.gs + .get_packages_mut() + .add_module_info(self.ctx.current_module_info.take().unwrap()); + } + + self.ctx.owner_symbols.pop(); + self.gs + .get_packages_mut() + .add_package(self.ctx.current_package_info.take().unwrap()) + } + + fn init_builtin_symbols(&mut self) { + //add global built functions + for (name, builtin_func) in BUILTIN_FUNCTIONS.iter() { + let mut func_symbol = FunctionSymbol::new( + name.to_string(), + Position::dummy_pos(), + Position::dummy_pos(), + None, + true, + ); + + func_symbol.sema_info.ty = Some(Arc::new(builtin_func.clone())); + func_symbol.sema_info.doc = builtin_func.ty_doc(); + let symbol_ref = self.gs.get_symbols_mut().alloc_function_symbol( + func_symbol, + self.ctx.get_node_key(&AstIndex::default()), + BUILTIN_FUNCTION_PACKAGE.to_string(), + ); + self.gs + .get_symbols_mut() + .symbols_info + .global_builtin_symbols + .insert(name.to_string(), symbol_ref); + } + + //add system modules + for system_pkg_name in STANDARD_SYSTEM_MODULES { + let package_symbol_ref = self.gs.get_symbols_mut().alloc_package_symbol( + PackageSymbol::new( + system_pkg_name.to_string(), + Position::dummy_pos(), + Position::dummy_pos(), + ), + system_pkg_name.to_string(), + ); + for func_name in get_system_module_members(system_pkg_name) { + let func_ty = get_system_member_function_ty(*system_pkg_name, func_name); + let mut func_symbol = FunctionSymbol::new( + func_name.to_string(), + Position::dummy_pos(), + Position::dummy_pos(), + Some(package_symbol_ref), + false, + ); + + func_symbol.sema_info.ty = Some(func_ty.clone()); + func_symbol.sema_info.doc = func_ty.ty_doc(); + let func_symbol_ref = self.gs.get_symbols_mut().alloc_function_symbol( + func_symbol, + self.ctx.get_node_key(&AstIndex::default()), + system_pkg_name.to_string(), + ); + self.gs + .get_symbols_mut() + .packages + .get_mut(package_symbol_ref.get_id()) + .unwrap() + .members + .insert(func_name.to_string(), func_symbol_ref); + } + } + + //add string builtin function + let package_symbol_ref = self.gs.get_symbols_mut().alloc_package_symbol( + PackageSymbol::new( + BUILTIN_STR_PACKAGE.to_string(), + Position::dummy_pos(), + Position::dummy_pos(), + ), + BUILTIN_STR_PACKAGE.to_string(), + ); + for (name, builtin_func) in STRING_MEMBER_FUNCTIONS.iter() { + let mut func_symbol = FunctionSymbol::new( + name.to_string(), + Position::dummy_pos(), + Position::dummy_pos(), + Some(package_symbol_ref), + true, + ); + + func_symbol.sema_info.ty = Some(Arc::new(builtin_func.clone())); + func_symbol.sema_info.doc = builtin_func.ty_doc(); + let symbol_ref = self.gs.get_symbols_mut().alloc_function_symbol( + func_symbol, + self.ctx.get_node_key(&AstIndex::default()), + BUILTIN_STR_PACKAGE.to_string(), + ); + self.gs + .get_symbols_mut() + .packages + .get_mut(package_symbol_ref.get_id()) + .unwrap() + .members + .insert(name.to_string(), symbol_ref); + } + } + + fn define_symbols(&mut self) { + self.gs.get_symbols_mut().build_fully_qualified_name_map(); + } +} + +#[cfg(test)] +mod tests { + use super::Namer; + use crate::core::global_state::GlobalState; + use crate::core::symbol::SymbolKind; + use kcl_parser::ParseSession; + use kcl_parser::load_program; + use std::sync::Arc; + + #[test] + fn test_find_symbols() { + let sess = Arc::new(ParseSession::default()); + let program = load_program( + sess.clone(), + &["./src/namer/test_data/schema_symbols.k"], + None, + None, + ) + .unwrap() + .program; + let mut gs = GlobalState::default(); + Namer::find_symbols(&program, &mut gs); + + let symbols = gs.get_symbols(); + + let excepts_symbols = vec![ + // package + ("import_test.a", SymbolKind::Package), + ("import_test.b", SymbolKind::Package), + ("import_test.c", SymbolKind::Package), + ("import_test.d", SymbolKind::Package), + ("import_test.e", SymbolKind::Package), + ("import_test.f", SymbolKind::Package), + ("__main__", SymbolKind::Package), + ("pkg", SymbolKind::Package), + // schema + ("import_test.f.UnionType", SymbolKind::Schema), + ("import_test.a.Person", SymbolKind::Schema), + ("import_test.c.TestOfMixin", SymbolKind::Schema), + ("import_test.d.Parent", SymbolKind::Schema), + ("import_test.e.UnionType", SymbolKind::Schema), + ("pkg.Name", SymbolKind::Schema), + ("pkg.Person", SymbolKind::Schema), + ("__main__.Main", SymbolKind::Schema), + // attribute + ("import_test.f.UnionType.b", SymbolKind::Attribute), + ("import_test.a.Person.name", SymbolKind::Attribute), + ("import_test.a.Person.age", SymbolKind::Attribute), + ("pkg.Name.name", SymbolKind::Attribute), + ("pkg.Person.name", SymbolKind::Attribute), + ("import_test.c.TestOfMixin.age", SymbolKind::Attribute), + ("import_test.d.Parent.age1", SymbolKind::Attribute), + ("import_test.e.UnionType.a", SymbolKind::Attribute), + ("__main__.Main.name", SymbolKind::Attribute), + ("__main__.Main.age", SymbolKind::Attribute), + ("__main__.Main.person", SymbolKind::Attribute), + ("__main__.Main.list_union_type", SymbolKind::Attribute), + ("__main__.Main.dict_union_type", SymbolKind::Attribute), + // value + ("__main__.p", SymbolKind::Value), + ("__main__.person", SymbolKind::Value), + ("__main__._c", SymbolKind::Value), + ("import_test.a._a", SymbolKind::Value), + ("import_test.b._b", SymbolKind::Value), + ]; + + for (fqn, kind) in excepts_symbols { + assert!( + symbols + .symbols_info + .fully_qualified_name_map + .contains_key(fqn) + ); + assert_eq!( + symbols + .get_symbol_by_fully_qualified_name(fqn) + .unwrap() + .get_kind(), + kind + ); + } + } +} diff --git a/crates/sema/src/namer/node.rs b/crates/sema/src/namer/node.rs new file mode 100644 index 000000000..fe8a09d47 --- /dev/null +++ b/crates/sema/src/namer/node.rs @@ -0,0 +1,429 @@ +use crate::core::package::ImportInfo; +use crate::core::symbol::{ + AttributeSymbol, RuleSymbol, SchemaSymbol, SymbolKind, SymbolRef, TypeAliasSymbol, ValueSymbol, +}; + +use super::Namer; +use kcl_ast::ast; +use kcl_ast::pos::GetPos; +use kcl_ast::walker::MutSelfTypedResultWalker; +use kcl_ast_pretty::{ASTNode, print_ast_node}; +use kcl_error::diagnostic::Range; + +impl<'ctx> MutSelfTypedResultWalker<'ctx> for Namer<'_> { + type Result = Option>; + fn walk_module(&mut self, module: &'ctx ast::Module) -> Self::Result { + let owner = *self.ctx.owner_symbols.last().unwrap(); + for stmt_node in module.body.iter() { + let symbol_refs = self.walk_stmt(&stmt_node.node); + + if let Some(symbol_refs) = symbol_refs { + for symbol_ref in symbol_refs { + let full_name = self + .gs + .get_symbols() + .get_fully_qualified_name(symbol_ref) + .unwrap(); + let name = full_name.split(".").last().unwrap().to_string(); + + let package_symbol = self + .gs + .get_symbols_mut() + .packages + .get_mut(owner.get_id()) + .unwrap(); + + if !package_symbol.members.contains_key(&name) { + package_symbol.members.insert(name, symbol_ref); + } + } + } + } + + None + } + + fn walk_expr_stmt(&mut self, _expr_stmt: &'ctx ast::ExprStmt) -> Self::Result { + None + } + + fn walk_unification_stmt( + &mut self, + unification_stmt: &'ctx ast::UnificationStmt, + ) -> Self::Result { + let (start_pos, end_pos): Range = unification_stmt.target.get_span_pos(); + let owner = self.ctx.owner_symbols.last().unwrap().clone(); + if unification_stmt.target.node.names.len() == 1 { + let owner_fully_qualified_name = self + .gs + .get_symbols() + .get_fully_qualified_name(owner) + .unwrap(); + let value_name = unification_stmt.target.node.get_name(); + if self.gs.get_symbols().get_schema_symbol(owner).is_some() { + let attribute_ref = self.gs.get_symbols_mut().alloc_attribute_symbol( + AttributeSymbol::new(value_name, start_pos, end_pos, owner, false, None), + self.ctx + .get_node_key(&unification_stmt.target.node.names[0].id), + self.ctx + .current_package_info + .clone() + .unwrap() + .fully_qualified_name, + ); + Some(vec![attribute_ref]) + } else { + let value_fully_qualified_name = owner_fully_qualified_name + "." + &value_name; + if !self + .ctx + .value_fully_qualified_name_set + .contains(&value_fully_qualified_name) + { + let value_ref = self.gs.get_symbols_mut().alloc_value_symbol( + ValueSymbol::new(value_name, start_pos, end_pos, Some(owner), true), + self.ctx.get_node_key(&unification_stmt.target.id), + self.ctx + .current_package_info + .clone() + .unwrap() + .fully_qualified_name, + ); + self.ctx + .value_fully_qualified_name_set + .insert(value_fully_qualified_name); + Some(vec![value_ref]) + } else { + None + } + } + } else { + None + } + } + + fn walk_type_alias_stmt(&mut self, type_alias_stmt: &'ctx ast::TypeAliasStmt) -> Self::Result { + let (start_pos, end_pos): Range = type_alias_stmt.type_name.get_span_pos(); + let owner = self.ctx.owner_symbols.last().unwrap().clone(); + let type_alias_ref = self.gs.get_symbols_mut().alloc_type_alias_symbol( + TypeAliasSymbol::new( + type_alias_stmt.type_name.node.get_name(), + start_pos, + end_pos, + owner, + ), + self.ctx.get_node_key(&type_alias_stmt.type_name.id), + self.ctx + .current_package_info + .clone() + .unwrap() + .fully_qualified_name, + ); + Some(vec![type_alias_ref]) + } + + fn walk_assign_stmt(&mut self, assign_stmt: &'ctx ast::AssignStmt) -> Self::Result { + let mut value_symbols = vec![]; + for target in assign_stmt.targets.iter() { + let (start_pos, end_pos): Range = target.get_span_pos(); + let owner = self.ctx.owner_symbols.last().unwrap().clone(); + if target.node.paths.is_empty() { + let owner_fully_qualified_name = self + .gs + .get_symbols() + .get_fully_qualified_name(owner) + .unwrap(); + let value_name = target.node.get_name(); + let value_fully_qualified_name = owner_fully_qualified_name + "." + &value_name; + if !self + .ctx + .value_fully_qualified_name_set + .contains(&value_fully_qualified_name) + { + let value_ref = self.gs.get_symbols_mut().alloc_value_symbol( + ValueSymbol::new( + value_name.to_string(), + start_pos, + end_pos, + Some(owner), + true, + ), + self.ctx.get_node_key(&target.id), + self.ctx + .current_package_info + .clone() + .unwrap() + .fully_qualified_name, + ); + self.ctx + .value_fully_qualified_name_set + .insert(value_fully_qualified_name); + value_symbols.push(value_ref) + } + } + } + Some(value_symbols) + } + + fn walk_aug_assign_stmt(&mut self, _aug_assign_stmt: &'ctx ast::AugAssignStmt) -> Self::Result { + None + } + + fn walk_assert_stmt(&mut self, _assert_stmt: &'ctx ast::AssertStmt) -> Self::Result { + None + } + + fn walk_if_stmt(&mut self, if_stmt: &'ctx ast::IfStmt) -> Self::Result { + let mut all_symbols = vec![]; + for stmt in if_stmt.body.iter() { + let mut symbols = self.walk_stmt(&stmt.node); + if let Some(symbols) = &mut symbols { + all_symbols.append(symbols); + } + } + for stmt in if_stmt.orelse.iter() { + let mut symbols = self.walk_stmt(&stmt.node); + if let Some(symbols) = &mut symbols { + all_symbols.append(symbols); + } + } + Some(all_symbols) + } + + fn walk_import_stmt(&mut self, import_stmt: &'ctx ast::ImportStmt) -> Self::Result { + self.ctx + .current_module_info + .as_mut() + .unwrap() + .add_import_info(ImportInfo::new( + import_stmt.name.clone(), + import_stmt.path.node.clone(), + )); + + None + } + + fn walk_schema_stmt(&mut self, schema_stmt: &'ctx ast::SchemaStmt) -> Self::Result { + let (start_pos, end_pos): Range = schema_stmt.name.get_span_pos(); + let owner = self.ctx.owner_symbols.last().unwrap(); + let shcema_ref = self.gs.get_symbols_mut().alloc_schema_symbol( + SchemaSymbol::new(schema_stmt.name.node.clone(), start_pos, end_pos, *owner), + self.ctx.get_node_key(&schema_stmt.name.id), + self.ctx + .current_package_info + .clone() + .unwrap() + .fully_qualified_name, + ); + self.ctx.owner_symbols.push(shcema_ref); + + for stmt in schema_stmt.body.iter() { + let symbol_refs = self.walk_stmt(&stmt.node); + if let Some(symbol_refs) = symbol_refs { + for symbol_ref in symbol_refs { + if matches!(&symbol_ref.get_kind(), SymbolKind::Attribute) { + let full_attribute_name = self + .gs + .get_symbols() + .get_fully_qualified_name(symbol_ref) + .unwrap(); + self.ctx + .value_fully_qualified_name_set + .insert(full_attribute_name.clone()); + let attribute_name = + full_attribute_name.split(".").last().unwrap().to_string(); + + let schema_symbol = self + .gs + .get_symbols_mut() + .schemas + .get_mut(shcema_ref.get_id()) + .unwrap(); + if !schema_symbol.attributes.contains_key(&attribute_name) { + schema_symbol.attributes.insert(attribute_name, symbol_ref); + } + } + } + } + } + self.ctx.owner_symbols.pop(); + Some(vec![shcema_ref]) + } + + fn walk_rule_stmt(&mut self, rule_stmt: &'ctx ast::RuleStmt) -> Self::Result { + let (start_pos, end_pos): Range = rule_stmt.name.get_span_pos(); + let owner = self.ctx.owner_symbols.last().unwrap().clone(); + let rule_ref = self.gs.get_symbols_mut().alloc_rule_symbol( + RuleSymbol::new(rule_stmt.name.node.clone(), start_pos, end_pos, owner), + self.ctx.get_node_key(&rule_stmt.name.id), + self.ctx + .current_package_info + .clone() + .unwrap() + .fully_qualified_name, + ); + Some(vec![rule_ref]) + } + + fn walk_quant_expr(&mut self, _quant_expr: &'ctx ast::QuantExpr) -> Self::Result { + None + } + + fn walk_schema_attr(&mut self, schema_attr: &'ctx ast::SchemaAttr) -> Self::Result { + let (start_pos, end_pos): Range = schema_attr.name.get_span_pos(); + let owner = self.ctx.owner_symbols.last().unwrap().clone(); + let default_value = schema_attr + .value + .as_ref() + .map(|v| print_ast_node(ASTNode::Expr(v))); + let attribute_ref = self.gs.get_symbols_mut().alloc_attribute_symbol( + AttributeSymbol::new( + schema_attr.name.node.clone(), + start_pos, + end_pos, + owner, + schema_attr.is_optional, + default_value, + ), + self.ctx.get_node_key(&schema_attr.name.id), + self.ctx + .current_package_info + .clone() + .unwrap() + .fully_qualified_name, + ); + Some(vec![attribute_ref]) + } + + /// if else -> sup([body, orelse]) + fn walk_if_expr(&mut self, _if_expr: &'ctx ast::IfExpr) -> Self::Result { + None + } + + fn walk_unary_expr(&mut self, _unary_expr: &'ctx ast::UnaryExpr) -> Self::Result { + None + } + + fn walk_binary_expr(&mut self, _binary_expr: &'ctx ast::BinaryExpr) -> Self::Result { + None + } + + fn walk_selector_expr(&mut self, _selector_expr: &'ctx ast::SelectorExpr) -> Self::Result { + None + } + + fn walk_call_expr(&mut self, _call_expr: &'ctx ast::CallExpr) -> Self::Result { + None + } + + fn walk_subscript(&mut self, _subscript: &'ctx ast::Subscript) -> Self::Result { + None + } + + fn walk_paren_expr(&mut self, _paren_expr: &'ctx ast::ParenExpr) -> Self::Result { + None + } + + fn walk_list_expr(&mut self, _list_expr: &'ctx ast::ListExpr) -> Self::Result { + None + } + + fn walk_list_comp(&mut self, _list_comp: &'ctx ast::ListComp) -> Self::Result { + None + } + + fn walk_dict_comp(&mut self, _dict_comp: &'ctx ast::DictComp) -> Self::Result { + None + } + + fn walk_list_if_item_expr( + &mut self, + _list_if_item_expr: &'ctx ast::ListIfItemExpr, + ) -> Self::Result { + None + } + + fn walk_starred_expr(&mut self, _starred_expr: &'ctx ast::StarredExpr) -> Self::Result { + None + } + + fn walk_config_if_entry_expr( + &mut self, + _config_if_entry_expr: &'ctx ast::ConfigIfEntryExpr, + ) -> Self::Result { + None + } + + fn walk_comp_clause(&mut self, _comp_clause: &'ctx ast::CompClause) -> Self::Result { + None + } + + fn walk_schema_expr(&mut self, _schema_expr: &'ctx ast::SchemaExpr) -> Self::Result { + None + } + + fn walk_config_expr(&mut self, _config_expr: &'ctx ast::ConfigExpr) -> Self::Result { + None + } + + fn walk_check_expr(&mut self, _check_expr: &'ctx ast::CheckExpr) -> Self::Result { + None + } + + fn walk_lambda_expr(&mut self, _lambda_expr: &'ctx ast::LambdaExpr) -> Self::Result { + None + } + + fn walk_keyword(&mut self, _keyword: &'ctx ast::Keyword) -> Self::Result { + None + } + + fn walk_arguments(&mut self, _arguments: &'ctx ast::Arguments) -> Self::Result { + None + } + + fn walk_compare(&mut self, _compare: &'ctx ast::Compare) -> Self::Result { + None + } + + fn walk_identifier(&mut self, _identifier: &'ctx ast::Identifier) -> Self::Result { + None + } + + fn walk_target(&mut self, _target: &'ctx ast::Target) -> Self::Result { + None + } + + fn walk_number_lit(&mut self, _number_lit: &'ctx ast::NumberLit) -> Self::Result { + None + } + + fn walk_string_lit(&mut self, _string_lit: &'ctx ast::StringLit) -> Self::Result { + None + } + + fn walk_name_constant_lit( + &mut self, + _name_constant_lit: &'ctx ast::NameConstantLit, + ) -> Self::Result { + None + } + + fn walk_joined_string(&mut self, _joined_string: &'ctx ast::JoinedString) -> Self::Result { + None + } + + fn walk_formatted_value( + &mut self, + _formatted_value: &'ctx ast::FormattedValue, + ) -> Self::Result { + None + } + + fn walk_comment(&mut self, _comment: &'ctx ast::Comment) -> Self::Result { + None + } + + fn walk_missing_expr(&mut self, _missing_expr: &'ctx ast::MissingExpr) -> Self::Result { + None + } +} diff --git a/kclvm/sema/src/namer/test_data/import_test/a.k b/crates/sema/src/namer/test_data/import_test/a.k similarity index 100% rename from kclvm/sema/src/namer/test_data/import_test/a.k rename to crates/sema/src/namer/test_data/import_test/a.k diff --git a/kclvm/sema/src/namer/test_data/import_test/b.k b/crates/sema/src/namer/test_data/import_test/b.k similarity index 100% rename from kclvm/sema/src/namer/test_data/import_test/b.k rename to crates/sema/src/namer/test_data/import_test/b.k diff --git a/kclvm/sema/src/namer/test_data/import_test/c.k b/crates/sema/src/namer/test_data/import_test/c.k similarity index 100% rename from kclvm/sema/src/namer/test_data/import_test/c.k rename to crates/sema/src/namer/test_data/import_test/c.k diff --git a/kclvm/sema/src/namer/test_data/import_test/d.k b/crates/sema/src/namer/test_data/import_test/d.k similarity index 100% rename from kclvm/sema/src/namer/test_data/import_test/d.k rename to crates/sema/src/namer/test_data/import_test/d.k diff --git a/kclvm/sema/src/namer/test_data/import_test/e.k b/crates/sema/src/namer/test_data/import_test/e.k similarity index 100% rename from kclvm/sema/src/namer/test_data/import_test/e.k rename to crates/sema/src/namer/test_data/import_test/e.k diff --git a/kclvm/sema/src/namer/test_data/import_test/f.k b/crates/sema/src/namer/test_data/import_test/f.k similarity index 100% rename from kclvm/sema/src/namer/test_data/import_test/f.k rename to crates/sema/src/namer/test_data/import_test/f.k diff --git a/kclvm/sema/src/namer/test_data/kcl.mod b/crates/sema/src/namer/test_data/kcl.mod similarity index 100% rename from kclvm/sema/src/namer/test_data/kcl.mod rename to crates/sema/src/namer/test_data/kcl.mod diff --git a/kclvm/sema/src/namer/test_data/pkg/pkg.k b/crates/sema/src/namer/test_data/pkg/pkg.k similarity index 100% rename from kclvm/sema/src/namer/test_data/pkg/pkg.k rename to crates/sema/src/namer/test_data/pkg/pkg.k diff --git a/kclvm/sema/src/namer/test_data/schema_symbols.k b/crates/sema/src/namer/test_data/schema_symbols.k similarity index 100% rename from kclvm/sema/src/namer/test_data/schema_symbols.k rename to crates/sema/src/namer/test_data/schema_symbols.k diff --git a/kclvm/sema/src/plugin/mod.rs b/crates/sema/src/plugin/mod.rs similarity index 100% rename from kclvm/sema/src/plugin/mod.rs rename to crates/sema/src/plugin/mod.rs diff --git a/crates/sema/src/pre_process/config.rs b/crates/sema/src/pre_process/config.rs new file mode 100644 index 000000000..b435a3427 --- /dev/null +++ b/crates/sema/src/pre_process/config.rs @@ -0,0 +1,366 @@ +use crate::info::is_private_field; +use kcl_ast::walker::MutSelfMutWalker; +use kcl_ast::{ast, walk_if_mut}; +use kcl_primitives::{IndexMap, IndexSet}; + +const NAME_NONE_BUCKET_KEY: &str = "$name_none"; + +#[derive(Debug, Default)] +struct ConfigNestAttrTransformer; + +impl ConfigNestAttrTransformer { + pub fn walk_config_entry(&mut self, config_entry: &mut Box>) { + if let Some(key) = config_entry.node.key.as_mut() { + if let ast::Expr::Identifier(identifier) = &mut key.node { + // desuger config expr, e.g., desuger + // ``` + // foo = Foo { + // bar.baz : xxx + // } + // ``` + // to: + // ``` + // foo = Foo { + // bar : Bar { + // baz : xxx + // } + // } + // ``` + if identifier.names.len() > 1 { + let mut names = identifier.names.clone(); + let names = &mut names[1..]; + names.reverse(); + identifier.names = vec![identifier.names[0].clone()]; + key.filename = identifier.names[0].filename.clone(); + key.line = identifier.names[0].line; + key.column = identifier.names[0].column; + key.end_line = identifier.names[0].end_line; + key.end_column = identifier.names[0].end_column; + + let mut value = config_entry.node.value.clone(); + for (i, name) in names.iter().enumerate() { + let is_last_item = i == 0; + let name_node = ast::Identifier { + names: vec![name.clone()], + pkgpath: "".to_string(), + ctx: ast::ExprContext::Load, + }; + let entry_value = ast::ConfigEntry { + key: Some(Box::new(ast::Node::new( + ast::Expr::Identifier(name_node), + name.filename.clone(), + name.line, + name.column, + name.end_line, + name.end_column, + ))), + value: value.clone(), + operation: if is_last_item { + config_entry.node.operation.clone() + } else { + ast::ConfigEntryOperation::Union + }, + }; + let config_expr = ast::ConfigExpr { + items: vec![Box::new(ast::Node::new( + entry_value, + config_entry.filename.clone(), + name.line, + name.column, + config_entry.end_line, + config_entry.end_column, + ))], + }; + value = Box::new(ast::Node::new( + ast::Expr::Config(config_expr), + value.filename.clone(), + name.line, + name.column, + value.end_line, + value.end_column, + )) + } + config_entry.node.value = value; + config_entry.node.operation = ast::ConfigEntryOperation::Union; + } + } + } + } +} + +impl<'ctx> MutSelfMutWalker<'ctx> for ConfigNestAttrTransformer { + fn walk_config_expr(&mut self, config_expr: &'ctx mut ast::ConfigExpr) { + for config_entry in config_expr.items.iter_mut() { + self.walk_config_entry(config_entry); + self.walk_expr(&mut config_entry.node.value.node); + } + } + fn walk_config_if_entry_expr( + &mut self, + config_if_entry_expr: &'ctx mut ast::ConfigIfEntryExpr, + ) { + for config_entry in config_if_entry_expr.items.iter_mut() { + self.walk_config_entry(config_entry); + self.walk_expr(&mut config_entry.node.value.node); + } + walk_if_mut!(self, walk_expr, config_if_entry_expr.orelse); + } +} + +#[derive(Debug, Default)] +struct ConfigMergeTransformer {} + +#[derive(Debug)] +enum ConfigMergeKind { + Override, + Union, +} + +impl ConfigMergeTransformer { + pub fn merge(&mut self, program: &mut ast::Program) { + // {name: (filename, module index in main package, statement index in the module body, kind)} + // module index is to prevent same filename in main package + let mut name_declaration_mapping: IndexMap< + String, + Vec<(String, usize, usize, ConfigMergeKind)>, + > = IndexMap::default(); + // 1. Collect merged config + let modules = program.get_modules_for_pkg(kcl_ast::MAIN_PKG); + for (module_id, module) in modules.iter().enumerate() { + let mut module = module.write().expect("Failed to acquire module lock"); + let filename = module.filename.to_string(); + for (i, stmt) in module.body.iter_mut().enumerate() { + match &mut stmt.node { + ast::Stmt::Unification(unification_stmt) + if !unification_stmt.target.node.names.is_empty() => + { + let name = &unification_stmt.target.node.names[0].node; + match name_declaration_mapping.get_mut(name) { + Some(declarations) => declarations.push(( + filename.clone(), + module_id, + i, + ConfigMergeKind::Union, + )), + None => { + name_declaration_mapping.insert( + name.to_string(), + vec![(filename.clone(), module_id, i, ConfigMergeKind::Union)], + ); + } + } + } + ast::Stmt::Assign(assign_stmt) => { + if let ast::Expr::Schema(_) = assign_stmt.value.node { + for target in &assign_stmt.targets { + if target.node.paths.is_empty() { + let name = &target.node.name.node; + match name_declaration_mapping.get_mut(name) { + Some(declarations) => { + // A hidden var is mutable. + if is_private_field(name) { + declarations.clear(); + declarations.push(( + filename.clone(), + module_id, + i, + ConfigMergeKind::Override, + )) + } + } + None => { + name_declaration_mapping.insert( + name.to_string(), + vec![( + filename.clone(), + module_id, + i, + ConfigMergeKind::Override, + )], + ); + } + } + } + } + } + } + _ => {} + } + } + } + // 2. Merge config + for (_, index_list) in &name_declaration_mapping { + let index_len = index_list.len(); + if index_len > 1 { + let (filename, merged_id, merged_index, merged_kind) = index_list.last().unwrap(); + let mut items: Vec> = vec![]; + for (merged_filename, merged_id, index, kind) in index_list { + let modules = program.get_modules_for_pkg(kcl_ast::MAIN_PKG); + for (module_id, module) in modules.iter().enumerate() { + let mut module = module.write().expect("Failed to acquire module lock"); + if &module.filename == merged_filename && module_id == *merged_id { + let stmt = module.body.get_mut(*index).unwrap(); + match &mut stmt.node { + ast::Stmt::Unification(unification_stmt) + if matches!(kind, ConfigMergeKind::Union) => + { + if let ast::Expr::Config(config_expr) = + &mut unification_stmt.value.node.config.node + { + let mut config_items = config_expr.items.clone(); + items.append(&mut config_items); + } + } + ast::Stmt::Assign(assign_stmt) + if matches!(kind, ConfigMergeKind::Override) => + { + if let ast::Expr::Schema(schema_expr) = + &mut assign_stmt.value.node + { + if let ast::Expr::Config(config_expr) = + &mut schema_expr.config.node + { + let mut config_items = config_expr.items.clone(); + items.append(&mut config_items); + } + } + } + _ => { + bug!("mismatch ast node and config merge kind: {:?}", kind) + } + } + } + } + } + for (module_id, module) in modules.iter().enumerate() { + let mut module = module.write().expect("Failed to acquire module lock"); + if &module.filename == filename && module_id == *merged_id { + if let Some(stmt) = module.body.get_mut(*merged_index) { + match &mut stmt.node { + ast::Stmt::Unification(unification_stmt) + if matches!(merged_kind, ConfigMergeKind::Union) => + { + if let ast::Expr::Config(config_expr) = + &mut unification_stmt.value.node.config.node + { + config_expr.items = unify_config_entries(&items); + } + } + ast::Stmt::Assign(assign_stmt) + if matches!(merged_kind, ConfigMergeKind::Override) => + { + if let ast::Expr::Schema(schema_expr) = + &mut assign_stmt.value.node + { + if let ast::Expr::Config(config_expr) = + &mut schema_expr.config.node + { + config_expr.items = unify_config_entries(&items); + } + } + } + _ => bug!( + "mismatch ast node and config merge kind: {:?}", + merged_kind + ), + } + } + break; + } + } + } + } + // 3. Delete redundant config. + for (i, module) in modules.iter().enumerate() { + let mut module = module.write().expect("Failed to acquire module lock"); + let mut delete_index_set: IndexSet = IndexSet::default(); + for (_, index_list) in &name_declaration_mapping { + let index_len = index_list.len(); + if index_len > 1 { + for (filename, module_id, index, _) in &index_list[..index_len - 1] { + // Use module filename and index to prevent the same compile filenames + // in the main package. + if &module.filename == filename && i == *module_id { + delete_index_set.insert(*index); + } + } + } + } + let mut body: Vec<(usize, &ast::NodeRef)> = + module.body.iter().enumerate().collect(); + body.retain(|(idx, _)| !delete_index_set.contains(idx)); + module.body = body + .iter() + .map(|(_, stmt)| (*stmt).clone()) + .collect::>>(); + } + } +} + +/// Unify config entries. +fn unify_config_entries( + entries: &[ast::NodeRef], +) -> Vec> { + // Using bucket map to check unique/merge option and store values + let mut bucket: IndexMap>> = Default::default(); + for entry in entries { + let name = match &entry.node.key { + Some(key) => match &key.node { + ast::Expr::Identifier(identifier) => identifier.get_name(), + ast::Expr::StringLit(string_lit) => string_lit.value.clone(), + _ => NAME_NONE_BUCKET_KEY.to_string(), + }, + None => NAME_NONE_BUCKET_KEY.to_string(), + }; + let entry = entry.clone(); + match bucket.get_mut(&name) { + Some(values) => { + // If the attribute operation is override, clear all previous entries and override + // with current entry. + if let ast::ConfigEntryOperation::Override = entry.node.operation { + values.clear(); + } + values.push(entry); + } + None => { + let values = vec![entry]; + bucket.insert(name, values); + } + } + } + let mut entries = vec![]; + for (_, items) in bucket.iter_mut() { + entries.append(items); + } + // Unify config entries recursively. + for entry in &mut entries { + match &mut entry.node.value.node { + ast::Expr::Schema(item_schema_expr) => { + if let ast::Expr::Config(item_config_expr) = &mut item_schema_expr.config.node { + item_config_expr.items = unify_config_entries(&item_config_expr.items); + } + } + ast::Expr::Config(item_config_expr) => { + item_config_expr.items = unify_config_entries(&item_config_expr.items); + } + _ => {} + } + } + entries +} + +/// Merge program for multiple file config. +#[inline] +pub fn merge_program(program: &mut ast::Program) { + let mut merger = ConfigMergeTransformer::default(); + merger.merge(program); +} + +/// Fix AST config expr nest attribute declarations. +/// +/// Examples +/// -------- +/// {a.b.c = 1} -> {a: {b: {c = 1}}} +pub fn fix_config_expr_nest_attr(module: &mut ast::Module) { + ConfigNestAttrTransformer::default().walk_module(module); +} diff --git a/kclvm/sema/src/pre_process/identifier.rs b/crates/sema/src/pre_process/identifier.rs similarity index 96% rename from kclvm/sema/src/pre_process/identifier.rs rename to crates/sema/src/pre_process/identifier.rs index fd2ef3462..4ca6f2f46 100644 --- a/kclvm/sema/src/pre_process/identifier.rs +++ b/crates/sema/src/pre_process/identifier.rs @@ -1,9 +1,9 @@ use crate::info::is_private_field; -use kclvm_ast::pos::GetPos; -use kclvm_ast::walker::MutSelfMutWalker; -use kclvm_ast::{ast, walk_if_mut, walk_list_mut}; -use kclvm_error::*; -use kclvm_primitives::{IndexMap, IndexSet}; +use kcl_ast::pos::GetPos; +use kcl_ast::walker::MutSelfMutWalker; +use kcl_ast::{ast, walk_if_mut, walk_list_mut}; +use kcl_error::*; +use kcl_primitives::{IndexMap, IndexSet}; pub const RAW_IDENTIFIER_PREFIX: &str = "$"; @@ -88,8 +88,8 @@ impl<'ctx> MutSelfMutWalker<'ctx> for QualifiedIdentifierTransformer { self.scope_level -= 1; } fn walk_list_comp(&mut self, list_comp: &'ctx mut ast::ListComp) { - for gen in &mut list_comp.generators { - for target in &gen.node.targets { + for g in &mut list_comp.generators { + for target in &g.node.targets { if !target.node.names.is_empty() { self.local_vars .insert(target.node.names[0].node.to_string()); @@ -101,8 +101,8 @@ impl<'ctx> MutSelfMutWalker<'ctx> for QualifiedIdentifierTransformer { self.local_vars.clear(); } fn walk_dict_comp(&mut self, dict_comp: &'ctx mut ast::DictComp) { - for gen in &dict_comp.generators { - for target in &gen.node.targets { + for g in &dict_comp.generators { + for target in &g.node.targets { if !target.node.names.is_empty() { self.local_vars .insert(target.node.names[0].node.to_string()); diff --git a/kclvm/sema/src/pre_process/lit_ty_default_value.rs b/crates/sema/src/pre_process/lit_ty_default_value.rs similarity index 96% rename from kclvm/sema/src/pre_process/lit_ty_default_value.rs rename to crates/sema/src/pre_process/lit_ty_default_value.rs index 1d91aef52..4e0b09981 100644 --- a/kclvm/sema/src/pre_process/lit_ty_default_value.rs +++ b/crates/sema/src/pre_process/lit_ty_default_value.rs @@ -1,5 +1,5 @@ -use kclvm_ast::ast; -use kclvm_ast::walker::MutSelfMutWalker; +use kcl_ast::ast; +use kcl_ast::walker::MutSelfMutWalker; #[derive(Default)] struct LitTypeDefaultValueTransformer; @@ -50,7 +50,7 @@ impl<'ctx> MutSelfMutWalker<'ctx> for LitTypeDefaultValueTransformer { ))); } ast::LiteralType::Float(val) => { - let value = kclvm_runtime::float_to_string(*val); + let value = kcl_runtime::float_to_string(*val); let column_offset = value.len() as u64; schema_attr.value = Some(Box::new(ast::Node::new( ast::Expr::NumberLit(ast::NumberLit { diff --git a/crates/sema/src/pre_process/mod.rs b/crates/sema/src/pre_process/mod.rs new file mode 100644 index 000000000..4cd13f7e1 --- /dev/null +++ b/crates/sema/src/pre_process/mod.rs @@ -0,0 +1,55 @@ +mod config; +mod identifier; +mod lit_ty_default_value; +mod multi_assign; + +use kcl_ast::ast; +use kcl_primitives::IndexMap; + +#[cfg(test)] +mod tests; + +pub use config::{fix_config_expr_nest_attr, merge_program}; +pub use identifier::{fix_qualified_identifier, fix_raw_identifier_prefix}; +pub use lit_ty_default_value::fix_lit_ty_default_value; +pub use multi_assign::transform_multi_assign; + +use crate::resolver::Options; + +/// Pre-process AST program. +pub fn pre_process_program(program: &mut ast::Program, opts: &Options) { + for (pkgpath, modules) in program.pkgs.iter() { + let mut import_names = IndexMap::default(); + if pkgpath == kcl_ast::MAIN_PKG { + for module in modules.iter() { + let module = program + .get_module(module) + .expect("Failed to acquire module lock") + .expect(&format!("module {:?} not found in program", module)); + for stmt in &module.body { + if let ast::Stmt::Import(import_stmt) = &stmt.node { + import_names + .insert(import_stmt.name.clone(), import_stmt.path.node.clone()); + } + } + } + } + for module in modules.iter() { + let mut module = program + .get_module_mut(module) + .expect("Failed to acquire module lock") + .expect(&format!("module {:?} not found in program", module)); + if pkgpath != kcl_ast::MAIN_PKG { + import_names.clear(); + } + // First we should transform the raw identifier to avoid raw identifier that happens to be a package path. + fix_raw_identifier_prefix(&mut module); + fix_qualified_identifier(&mut module, &mut import_names); + fix_config_expr_nest_attr(&mut module); + fix_lit_ty_default_value(&mut module); + } + } + if opts.merge_program { + merge_program(program); + } +} diff --git a/kclvm/sema/src/pre_process/multi_assign.rs b/crates/sema/src/pre_process/multi_assign.rs similarity index 95% rename from kclvm/sema/src/pre_process/multi_assign.rs rename to crates/sema/src/pre_process/multi_assign.rs index 5425fa8ca..b98e6496a 100644 --- a/kclvm/sema/src/pre_process/multi_assign.rs +++ b/crates/sema/src/pre_process/multi_assign.rs @@ -1,14 +1,14 @@ use std::collections::HashMap; -use kclvm_ast::{ast, walker::MutSelfMutWalker}; +use kcl_ast::{ast, walker::MutSelfMutWalker}; /// Transform AST and split multi target assign statements to multiple assign statements. /// /// # Examples /// /// ``` -/// use kclvm_parser::parse_file_force_errors; -/// use kclvm_sema::pre_process::transform_multi_assign; +/// use kcl_parser::parse_file_force_errors; +/// use kcl_sema::pre_process::transform_multi_assign; /// /// let mut module = parse_file_force_errors("", Some("a = b = Config {}".to_string())).unwrap(); /// assert_eq!(module.body.len(), 1); diff --git a/kclvm/sema/src/pre_process/test_data/config_merge/config1.k b/crates/sema/src/pre_process/test_data/config_merge/config1.k similarity index 100% rename from kclvm/sema/src/pre_process/test_data/config_merge/config1.k rename to crates/sema/src/pre_process/test_data/config_merge/config1.k diff --git a/kclvm/sema/src/pre_process/test_data/config_merge/config2.k b/crates/sema/src/pre_process/test_data/config_merge/config2.k similarity index 100% rename from kclvm/sema/src/pre_process/test_data/config_merge/config2.k rename to crates/sema/src/pre_process/test_data/config_merge/config2.k diff --git a/kclvm/sema/src/pre_process/test_data/config_merge/def.k b/crates/sema/src/pre_process/test_data/config_merge/def.k similarity index 100% rename from kclvm/sema/src/pre_process/test_data/config_merge/def.k rename to crates/sema/src/pre_process/test_data/config_merge/def.k diff --git a/kclvm/sema/src/pre_process/test_data/config_override.k b/crates/sema/src/pre_process/test_data/config_override.k similarity index 100% rename from kclvm/sema/src/pre_process/test_data/config_override.k rename to crates/sema/src/pre_process/test_data/config_override.k diff --git a/kclvm/sema/src/pre_process/test_data/lit_ty_default_val.k b/crates/sema/src/pre_process/test_data/lit_ty_default_val.k similarity index 100% rename from kclvm/sema/src/pre_process/test_data/lit_ty_default_val.k rename to crates/sema/src/pre_process/test_data/lit_ty_default_val.k diff --git a/kclvm/sema/src/pre_process/test_data/multi_assign.k b/crates/sema/src/pre_process/test_data/multi_assign.k similarity index 100% rename from kclvm/sema/src/pre_process/test_data/multi_assign.k rename to crates/sema/src/pre_process/test_data/multi_assign.k diff --git a/kclvm/sema/src/pre_process/test_data/qualified_identifier.k b/crates/sema/src/pre_process/test_data/qualified_identifier.k similarity index 100% rename from kclvm/sema/src/pre_process/test_data/qualified_identifier.k rename to crates/sema/src/pre_process/test_data/qualified_identifier.k diff --git a/kclvm/sema/src/pre_process/test_data/raw_identifier.k b/crates/sema/src/pre_process/test_data/raw_identifier.k similarity index 100% rename from kclvm/sema/src/pre_process/test_data/raw_identifier.k rename to crates/sema/src/pre_process/test_data/raw_identifier.k diff --git a/kclvm/sema/src/pre_process/test_data/skip_merge/config1.k b/crates/sema/src/pre_process/test_data/skip_merge/config1.k similarity index 100% rename from kclvm/sema/src/pre_process/test_data/skip_merge/config1.k rename to crates/sema/src/pre_process/test_data/skip_merge/config1.k diff --git a/kclvm/sema/src/pre_process/test_data/skip_merge/config2.k b/crates/sema/src/pre_process/test_data/skip_merge/config2.k similarity index 100% rename from kclvm/sema/src/pre_process/test_data/skip_merge/config2.k rename to crates/sema/src/pre_process/test_data/skip_merge/config2.k diff --git a/kclvm/sema/src/pre_process/test_data/skip_merge/def.k b/crates/sema/src/pre_process/test_data/skip_merge/def.k similarity index 100% rename from kclvm/sema/src/pre_process/test_data/skip_merge/def.k rename to crates/sema/src/pre_process/test_data/skip_merge/def.k diff --git a/crates/sema/src/pre_process/tests.rs b/crates/sema/src/pre_process/tests.rs new file mode 100644 index 000000000..36bbcb792 --- /dev/null +++ b/crates/sema/src/pre_process/tests.rs @@ -0,0 +1,354 @@ +use std::sync::Arc; + +use super::*; +use kcl_ast::path::get_attr_paths_from_config_expr; +use kcl_parser::{ParseSession, load_program, parse_file_force_errors}; +use kcl_primitives::IndexMap; + +#[test] +fn test_fix_qualified_identifier() { + let mut module = + parse_file_force_errors("./src/pre_process/test_data/qualified_identifier.k", None) + .unwrap(); + fix_qualified_identifier(&mut module, &mut IndexMap::default()); + if let ast::Stmt::Assign(assign_stmt) = &module.body[1].node { + if let ast::Expr::Identifier(identifier) = &assign_stmt.value.node { + assert_eq!(identifier.pkgpath, "pkg") + } else { + panic!("invalid assign statement value") + } + } else { + panic!("invalid assign statement") + } +} + +#[test] +fn test_fix_lit_ty_default_value() { + let mut module = + parse_file_force_errors("./src/pre_process/test_data/lit_ty_default_val.k", None).unwrap(); + fix_lit_ty_default_value(&mut module); + if let ast::Stmt::Schema(schema_stmt) = &module.body[0].node { + if let ast::Stmt::SchemaAttr(schema_attr) = &schema_stmt.body[0].node { + assert_eq!( + schema_attr.value.as_ref().unwrap().node, + ast::Expr::StringLit(ast::StringLit { + is_long_string: false, + raw_value: "\"val\"".to_string(), + value: "val".to_string(), + }) + ) + } else { + panic!("invalid schema attr value") + } + if let ast::Stmt::SchemaAttr(schema_attr) = &schema_stmt.body[1].node { + assert_eq!( + schema_attr.value.as_ref().unwrap().node, + ast::Expr::NumberLit(ast::NumberLit { + value: ast::NumberLitValue::Int(1), + binary_suffix: None, + }) + ) + } else { + panic!("invalid schema attr value") + } + if let ast::Stmt::SchemaAttr(schema_attr) = &schema_stmt.body[2].node { + assert_eq!( + schema_attr.value.as_ref().unwrap().node, + ast::Expr::NumberLit(ast::NumberLit { + value: ast::NumberLitValue::Int(1), + binary_suffix: Some(ast::NumberBinarySuffix::Ki), + }) + ) + } else { + panic!("invalid schema attr value") + } + if let ast::Stmt::SchemaAttr(schema_attr) = &schema_stmt.body[3].node { + assert_eq!( + schema_attr.value.as_ref().unwrap().node, + ast::Expr::NumberLit(ast::NumberLit { + value: ast::NumberLitValue::Float(2.0), + binary_suffix: None, + }) + ) + } else { + panic!("invalid schema attr value") + } + if let ast::Stmt::SchemaAttr(schema_attr) = &schema_stmt.body[4].node { + assert_eq!( + schema_attr.value.as_ref().unwrap().node, + ast::Expr::NameConstantLit(ast::NameConstantLit { + value: ast::NameConstant::True, + }) + ) + } else { + panic!("invalid schema attr value") + } + if let ast::Stmt::SchemaAttr(schema_attr) = &schema_stmt.body[5].node { + assert_eq!( + schema_attr.value.as_ref().unwrap().node, + ast::Expr::NameConstantLit(ast::NameConstantLit { + value: ast::NameConstant::False, + }) + ) + } else { + panic!("invalid schema attr value") + } + } else { + panic!("invalid schema statement") + } +} + +#[test] +fn test_fix_raw_identifier_prefix() { + let mut module = + parse_file_force_errors("./src/pre_process/test_data/raw_identifier.k", None).unwrap(); + if let ast::Stmt::Assign(assign_stmt) = &module.body[0].node { + assert_eq!(assign_stmt.targets[0].node.name.node, "$schema") + } else { + panic!("invalid assign statement") + } + fix_raw_identifier_prefix(&mut module); + if let ast::Stmt::Assign(assign_stmt) = &module.body[0].node { + assert_eq!(assign_stmt.targets[0].node.name.node, "schema") + } else { + panic!("invalid assign statement") + } + if let ast::Stmt::Schema(schema_stmt) = &module.body[1].node { + if let ast::Stmt::SchemaAttr(attr) = &schema_stmt.body[0].node { + assert_eq!(attr.name.node, "name"); + } else { + panic!("invalid schema attr") + } + if let ast::Stmt::SchemaAttr(attr) = &schema_stmt.body[1].node { + assert_eq!(attr.name.node, "$name"); + } else { + panic!("invalid schema attr") + } + } else { + panic!("invalid schema statement") + } +} + +#[test] +fn test_transform_multi_assign() { + let targets = ["a", "b", "c", "d"]; + let mut module = + parse_file_force_errors("./src/pre_process/test_data/multi_assign.k", None).unwrap(); + if let ast::Stmt::Assign(assign_stmt) = &module.body[1].node { + assert_eq!(assign_stmt.targets.len(), targets.len()); + for (i, target) in targets.iter().enumerate() { + assert_eq!(assign_stmt.targets[i].node.get_name(), *target); + } + } else { + panic!("invalid assign statement") + } + transform_multi_assign(&mut module); + for (i, target) in targets.iter().enumerate() { + if let ast::Stmt::Assign(assign_stmt) = &module.body[i + 1].node { + assert_eq!(assign_stmt.targets.len(), 1); + assert_eq!(assign_stmt.targets[0].node.get_name(), *target); + } else { + panic!("invalid assign statement") + } + } +} + +#[test] +fn test_config_merge() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess, + &[ + "./src/pre_process/test_data/config_merge/def.k", + "./src/pre_process/test_data/config_merge/config1.k", + "./src/pre_process/test_data/config_merge/config2.k", + "./src/pre_process/test_data/config_merge/config2.k", + ], + None, + None, + ) + .unwrap() + .program; + merge_program(&mut program); + let modules = program.pkgs.get(kcl_ast::MAIN_PKG).unwrap(); + assert_eq!(modules.len(), 3); + // Test the module merge result + let module = modules.last().unwrap(); + let module = program + .get_module(module) + .expect("Failed to acquire module lock") + .expect(&format!("module {:?} not found in program", module)); + if let ast::Stmt::Unification(unification) = &module.body[0].node { + let schema = &unification.value.node; + if let ast::Expr::Config(config) = &schema.config.node { + // 2 contains `name` in `config1.k`, `age` in `config2.k`. + // person: Person { + // name = "Alice" + // age = 18 + // } + assert_eq!(config.items.len(), 2); + assert_eq!( + get_attr_paths_from_config_expr(config), + vec!["name".to_string(), "age".to_string()] + ); + } else { + panic!( + "test failed, expect config expression, got {:?}", + schema.config + ) + } + } else { + panic!( + "test failed, expect unification statement, got {:?}", + module.body[0] + ) + } +} + +#[test] +fn test_config_override() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess, + &["./src/pre_process/test_data/config_override.k"], + None, + None, + ) + .unwrap() + .program; + merge_program(&mut program); + let modules = program.pkgs.get(kcl_ast::MAIN_PKG).unwrap(); + assert_eq!(modules.len(), 1); + // Test the module merge result + let module = modules.first().unwrap(); + let module = program + .get_module(module) + .expect("Failed to acquire module lock") + .expect(&format!("module {:?} not found in program", module)); + if let ast::Stmt::Unification(unification) = &module.body[2].node { + let schema = &unification.value.node; + if let ast::Expr::Config(config) = &schema.config.node { + // key = Config { + // data.key: "value1" + // } + assert_eq!(config.items.len(), 1); + assert_eq!( + get_attr_paths_from_config_expr(config), + vec!["key".to_string(), "key.data.key".to_string()] + ); + } else { + panic!( + "test failed, expect config expression, got {:?}", + schema.config + ) + } + } else { + panic!( + "test failed, expect unification statement, got {:?}", + module.body[2] + ) + } +} + +#[test] +fn test_skip_merge_program() { + let sess = Arc::new(ParseSession::default()); + let program = load_program( + sess, + &[ + "./src/pre_process/test_data/config_merge/def.k", + "./src/pre_process/test_data/config_merge/config1.k", + "./src/pre_process/test_data/config_merge/config2.k", + ], + None, + None, + ) + .unwrap() + .program; + // skip merge program and save raw config ast node + // merge_program(&mut program); + let modules = program.pkgs.get(kcl_ast::MAIN_PKG).unwrap(); + assert_eq!(modules.len(), 3); + let config1 = &modules[1]; + let config2 = &modules[1]; + let config1 = program + .get_module(config1) + .expect("Failed to acquire module lock") + .expect(&format!("module {:?} not found in program", config1)); + let config2 = program + .get_module(config2) + .expect("Failed to acquire module lock") + .expect(&format!("module {:?} not found in program", config2)); + if let ast::Stmt::Unification(unification) = &config1.body[0].node { + let schema = &unification.value.node; + if let ast::Expr::Config(config) = &schema.config.node { + assert_eq!(config.items.len(), 1); + } else { + panic!( + "test failed, expect config expression, got {:?}", + schema.config + ) + } + } else { + panic!( + "test failed, expect unification statement, got {:?}", + config1.body[0] + ) + } + + if let ast::Stmt::Unification(unification) = &config2.body[0].node { + let schema = &unification.value.node; + if let ast::Expr::Config(config) = &schema.config.node { + assert_eq!(config.items.len(), 1); + } else { + panic!( + "test failed, expect config expression, got {:?}", + schema.config + ) + } + } else { + panic!( + "test failed, expect unification statement, got {:?}", + config2.body[0] + ) + } +} + +#[test] +fn test_list_type_validation() { + let code = r#" + schema Resource: + kind: str + apiGroup: str + metadata: any + spec: any + + resource = Resource{ + kind = "Pod" + apiGroup = "core" + metadata = { + name = "test" + } + } + + resource2 = Resource{ + kind = "Pod" + apiGroup = "core" + metadata = { + name = "test" + } + } + + otherResource = { + name = "test" + } + + resourceList: [Resource] = [resource, resource2, otherResource] + "#; + + let result = parse_file_force_errors("test_list_type_validation.k", Some(code.to_string())); + assert!( + result.is_err(), + "Expected an evaluation error, but the code passed." + ); +} diff --git a/kclvm/sema/src/resolver/arg.rs b/crates/sema/src/resolver/arg.rs similarity index 98% rename from kclvm/sema/src/resolver/arg.rs rename to crates/sema/src/resolver/arg.rs index c3845587f..eeaad32db 100644 --- a/kclvm/sema/src/resolver/arg.rs +++ b/crates/sema/src/resolver/arg.rs @@ -1,11 +1,11 @@ use crate::resolver::Resolver; use crate::ty::FunctionType; use compiler_base_error::unit_type::{TypeWithUnit, UnitUsize}; -use kclvm_ast::ast; -use kclvm_primitives::IndexSet; +use kcl_ast::ast; +use kcl_primitives::IndexSet; -use kclvm_ast::pos::GetPos; -use kclvm_error::diagnostic::Range; +use kcl_ast::pos::GetPos; +use kcl_error::diagnostic::Range; use crate::ty::TypeRef; diff --git a/kclvm/sema/src/resolver/attr.rs b/crates/sema/src/resolver/attr.rs similarity index 96% rename from kclvm/sema/src/resolver/attr.rs rename to crates/sema/src/resolver/attr.rs index d95192715..fa8f33181 100644 --- a/kclvm/sema/src/resolver/attr.rs +++ b/crates/sema/src/resolver/attr.rs @@ -1,15 +1,15 @@ use std::sync::Arc; -use crate::builtin::system_module::{get_system_module_members, UNITS, UNITS_NUMBER_MULTIPLIER}; -use crate::builtin::{get_system_member_function_ty, STRING_MEMBER_FUNCTIONS}; +use crate::builtin::system_module::{UNITS, UNITS_NUMBER_MULTIPLIER, get_system_module_members}; +use crate::builtin::{STRING_MEMBER_FUNCTIONS, get_system_member_function_ty}; use crate::resolver::Resolver; use crate::ty::TypeKind::Schema; use crate::ty::{ - DictType, ModuleKind, Parameter, Type, TypeKind, TypeRef, SCHEMA_MEMBER_FUNCTIONS, + DictType, ModuleKind, Parameter, SCHEMA_MEMBER_FUNCTIONS, Type, TypeKind, TypeRef, }; -use kclvm_ast::ast; -use kclvm_error::diagnostic::{dummy_range, Range}; -use kclvm_error::*; +use kcl_ast::ast; +use kcl_error::diagnostic::{Range, dummy_range}; +use kcl_error::*; use super::node::ResolvedResult; diff --git a/crates/sema/src/resolver/calculation.rs b/crates/sema/src/resolver/calculation.rs new file mode 100644 index 000000000..ff8ffdcd4 --- /dev/null +++ b/crates/sema/src/resolver/calculation.rs @@ -0,0 +1,333 @@ +use std::sync::Arc; + +use crate::resolver::Resolver; +use crate::ty::{ + Type, TypeInferMethods, TypeKind, TypeRef, ZERO_LIT_TYPES, has_any_type, is_upper_bound, sup, +}; +use kcl_ast::ast; +use kcl_error::diagnostic::Range; +use kcl_primitives::{DefaultHashBuilder, IndexMap}; + +const DIV_OR_MOD_ZERO_MSG: &str = "integer division or modulo by zero"; + +impl<'ctx> Resolver<'ctx> { + /// Binary operator calculation table. + /// + /// Arithmetic (int or float; result has type float unless both operands have type int) + /// number + number # addition + /// number - number # subtraction + /// number * number # multiplication + /// number / number # real division (result is always a float) + /// number // number # floored division + /// number % number # remainder of floored division + /// number ^ number # bitwise XOR + /// number << number # bitwise left shift + /// number >> number # bitwise right shift + /// + /// Concatenation + /// string + string + /// list + list + /// + /// Repetition (string/list) + /// int * sequence + /// sequence * int + /// + /// Union + /// int | int + /// list | list + /// dict | dict + /// schema | schema + /// schema | dict + /// + /// Add: number + number, str + str, list + list + /// Sub: number - number + /// Mul: number * number, int * list, list * int, int * str, str * int + /// Div: number / number + /// FloorDiv: number // number + /// Mod: number % number + /// Pow: number ** number + /// LShift: int >> int + /// RShift: int << int + /// BitOr: int | int, list | list, dict | dict, schema | schema, schema | dict + /// BitXOr: int ^ int + /// BitAdd int & int + /// + /// And: any_type and any_type -> bool + /// Or: any_type1 or any_type1 -> sup([any_type1, any_type2]) + pub fn binary( + &mut self, + left: TypeRef, + right: TypeRef, + op: &ast::BinOp, + range: Range, + ) -> TypeRef { + let t1 = self + .ctx + .ty_ctx + .literal_union_type_to_variable_type(left.clone()); + let t2 = self + .ctx + .ty_ctx + .literal_union_type_to_variable_type(right.clone()); + if has_any_type(&[t1.clone(), t2.clone()]) { + return self.any_ty(); + } + let number_binary = |left: &TypeRef, right: &TypeRef| { + if left.is_float() || right.is_float() { + Arc::new(Type::FLOAT) + } else { + Arc::new(Type::INT) + } + }; + let (result, return_ty) = match op { + ast::BinOp::Add => { + if t1.is_number() && t2.is_number() { + (true, number_binary(&t1, &t2)) + } else if t1.is_str() && t2.is_str() { + (true, self.str_ty()) + } else if t1.is_list() && t2.is_list() { + ( + true, + Type::list_ref(sup(&[t1.list_item_ty(), t2.list_item_ty()])), + ) + } else { + (false, self.any_ty()) + } + } + ast::BinOp::Sub | ast::BinOp::Pow => { + if t1.is_number() && t2.is_number() { + (true, number_binary(&t1, &t2)) + } else { + (false, self.any_ty()) + } + } + ast::BinOp::Mul => { + if t1.is_number() && t2.is_number() { + (true, number_binary(&t1, &t2)) + } else if t1.is_int() + && self + .ctx + .ty_ctx + .is_mul_val_type_or_mul_val_union_type(t2.clone()) + { + (true, t2) + } else if self + .ctx + .ty_ctx + .is_mul_val_type_or_mul_val_union_type(t1.clone()) + && t2.is_int() + { + (true, t1) + } else { + (false, self.any_ty()) + } + } + ast::BinOp::Div | ast::BinOp::FloorDiv => { + if t1.is_number() && t2.is_number() { + if ZERO_LIT_TYPES.contains(&t2) { + self.handler + .add_type_error(DIV_OR_MOD_ZERO_MSG, range.clone()); + } + (true, number_binary(&t1, &t2)) + } else { + (false, self.any_ty()) + } + } + ast::BinOp::Mod => { + if t1.is_number() && t2.is_number() { + if ZERO_LIT_TYPES.contains(&t2) { + self.handler + .add_type_error(DIV_OR_MOD_ZERO_MSG, range.clone()); + } + (true, self.int_ty()) + } else { + (false, self.any_ty()) + } + } + ast::BinOp::LShift | ast::BinOp::RShift | ast::BinOp::BitXor | ast::BinOp::BitAnd => { + if t1.is_int() && t2.is_int() { + (true, self.int_ty()) + } else { + (false, self.any_ty()) + } + } + ast::BinOp::BitOr => { + if t1.is_int() && t2.is_int() { + (true, self.int_ty()) + } else if t1.is_none() { + (true, t2) + } else if t2.is_none() { + (true, t1) + } else if t1.is_list() && t2.is_list() { + ( + true, + Type::list_ref(sup(&[t1.list_item_ty(), t2.list_item_ty()])), + ) + } else if let (TypeKind::Dict(t1_dict_ty), TypeKind::Dict(t2_dict_ty)) = + (&t1.kind, &t2.kind) + { + let mut attrs = IndexMap::with_hasher(DefaultHashBuilder::default()); + for (k, v) in &t1_dict_ty.attrs { + attrs.insert(k.to_string(), v.clone()); + } + for (k, v) in &t2_dict_ty.attrs { + attrs.insert(k.to_string(), v.clone()); + } + ( + true, + Arc::new(Type::dict_with_attrs( + sup(&[t1_dict_ty.key_ty.clone(), t2_dict_ty.key_ty.clone()]), + sup(&[t1_dict_ty.val_ty.clone(), t2_dict_ty.val_ty.clone()]), + attrs, + )), + ) + } else if t1.is_schema() && (t2.is_schema() || t2.is_dict()) { + (true, t1) + } else { + (false, self.any_ty()) + } + } + ast::BinOp::And => (true, self.bool_ty()), + ast::BinOp::Or => (true, sup(&[t1, t2])), + ast::BinOp::As => { + if !is_upper_bound( + self.ctx.ty_ctx.infer_to_variable_type(t1.clone()), + t2.clone(), + ) { + self.handler.add_type_error( + &format!( + "Conversion of type '{}' to type '{}' may be a mistake because neither type sufficiently overlaps with the other", + t1.full_ty_str(), + t2.full_ty_str() + ), + range.clone(), + ); + } + (true, t2) + } + }; + + if !result { + self.handler.add_type_error( + &format!( + "unsupported operand type(s) for {}: '{}' and '{}'", + op.symbol(), + left.ty_str(), + right.ty_str() + ), + range, + ); + } + return_ty + } + + /// Unary operator calculation table + /// + /// + number unary positive (int, float) + /// - number unary negation (int, float) + /// ~ number unary bitwise inversion (int) + /// not x logical negation (any type) + pub fn unary(&mut self, ty: TypeRef, op: &ast::UnaryOp, range: Range) -> TypeRef { + if has_any_type(&[ty.clone()]) { + return self.any_ty(); + } + let var_ty = self + .ctx + .ty_ctx + .literal_union_type_to_variable_type(ty.clone()); + let result = match op { + ast::UnaryOp::UAdd | ast::UnaryOp::USub => var_ty.is_number(), + ast::UnaryOp::Invert => var_ty.is_int() || var_ty.is_bool(), + ast::UnaryOp::Not => true, + }; + if result { + var_ty + } else { + self.handler.add_type_error( + &format!( + "bad operand type for unary {}: '{}'", + op.symbol(), + ty.ty_str(), + ), + range, + ); + self.any_ty() + } + } + + /// Compare operator calculation table + /// + /// int # mathematical 1 < 2 + /// float # as defined by IEEE 754 1.0 < 2.0 + /// list/config/schema # lexicographical [1] == [2] + /// iterable # 1 in [1, 2, 3], "s" in "ss", "key" in Schema + /// relation # a is True, b is Undefined + pub fn compare( + &mut self, + left: TypeRef, + right: TypeRef, + op: &ast::CmpOp, + range: Range, + ) -> TypeRef { + let t1 = self.ctx.ty_ctx.literal_union_type_to_variable_type(left); + let t2 = self.ctx.ty_ctx.literal_union_type_to_variable_type(right); + if has_any_type(&[t1.clone(), t2.clone()]) { + return self.any_ty(); + } + if self + .ctx + .ty_ctx + .is_number_bool_type_or_number_bool_union_type(t1.clone()) + && self + .ctx + .ty_ctx + .is_number_bool_type_or_number_bool_union_type(t2.clone()) + && !matches!(op, ast::CmpOp::In | ast::CmpOp::NotIn) + { + return self.bool_ty(); + } + if self + .ctx + .ty_ctx + .is_primitive_type_or_primitive_union_type(t1.clone()) + && self + .ctx + .ty_ctx + .is_primitive_type_or_primitive_union_type(t2.clone()) + && matches!(op, ast::CmpOp::Eq | ast::CmpOp::NotEq) + { + return self.bool_ty(); + } + if matches!(op, ast::CmpOp::Eq) && t1.is_list() && t2.is_list() { + return self.bool_ty(); + } + if matches!(op, ast::CmpOp::Eq) && t1.is_dict_or_schema() && t2.is_dict_or_schema() { + return self.bool_ty(); + } + if matches!(op, ast::CmpOp::In | ast::CmpOp::NotIn) && t2.is_iterable() { + return self.bool_ty(); + } + if (t1.is_none() || t2.is_none()) + && matches!( + op, + ast::CmpOp::Eq + | ast::CmpOp::NotEq + | ast::CmpOp::Is + | ast::CmpOp::IsNot + | ast::CmpOp::Not + ) + { + return self.bool_ty(); + } + self.handler.add_type_error( + &format!( + "unsupported operand type(s) for {}: '{}' and '{}'", + op.symbol(), + t1.ty_str(), + t2.ty_str(), + ), + range, + ); + self.any_ty() + } +} diff --git a/crates/sema/src/resolver/config.rs b/crates/sema/src/resolver/config.rs new file mode 100644 index 000000000..a7d13f6a7 --- /dev/null +++ b/crates/sema/src/resolver/config.rs @@ -0,0 +1,879 @@ +use std::{collections::HashSet, sync::Arc}; + +use super::{ + Resolver, + scope::{ScopeKind, ScopeObject, ScopeObjectKind}, +}; +use crate::ty::{Attr, SchemaType}; +use crate::ty::{DictType, TypeInferMethods, TypeRef, sup}; +use crate::ty::{Type, TypeKind}; +use kcl_ast::ast; +use kcl_ast::pos::GetPos; +use kcl_error::{ErrorKind, Message, Position, Style, diagnostic::Range}; +use kcl_primitives::IndexMap; + +/// Config Expr type check state. +/// +/// e.g. +/// ```no_check +/// schema Person: +/// name: str +/// +/// person = Person { +/// name: 1 # Type error, expect str, got int(1) +/// } +/// ``` +pub enum SwitchConfigContextState { + KeepConfigUnchanged = 0, + SwitchConfigOnce = 1, +} + +impl<'ctx> Resolver<'_> { + #[inline] + pub(crate) fn new_config_expr_context_item( + &mut self, + name: &str, + ty: TypeRef, + start: Position, + end: Position, + ) -> ScopeObject { + ScopeObject { + name: name.to_string(), + start, + end, + ty, + kind: ScopeObjectKind::Attribute, + doc: None, + } + } + + /// Finds the items needed to switch the context by name 'key_name' + /// + /// At present, only when the top item of the stack is 'KCLSchemaTypeObject' or 'KCLDictTypeObject', + /// it will return the next item (the attribute named 'key_name' in 'KCLSchemaTypeObject' + /// or the value of 'key_name' in 'KCLDictTypeObject') needed to be pushed. + /// If the top item of the stack is not 'KCLSchemaTypeObject' or 'KCLDictTypeObject', + /// it will return 'None'. + /// + /// Args: + /// key_name: The name of the item needed to be pushed onto the 'config_expr_context' stack + /// + /// Returns: + /// The item needed to be pushed onto the 'config_expr_context' stack + pub(crate) fn find_schema_attr_obj_from_schema_expr_stack( + &mut self, + key_name: &str, + ) -> Option { + if key_name.is_empty() { + None + } else { + match self.ctx.config_expr_context.last() { + Some(obj) => { + let obj = obj.clone(); + match obj { + Some(obj) => match &obj.ty.kind { + TypeKind::List(elem_type) => Some(self.new_config_expr_context_item( + key_name, + elem_type.clone(), + obj.start.clone(), + obj.end.clone(), + )), + TypeKind::Dict(DictType { + key_ty: _, val_ty, .. + }) => Some(self.new_config_expr_context_item( + key_name, + val_ty.clone(), + obj.start.clone(), + obj.end.clone(), + )), + TypeKind::Schema(schema_ty) => { + match schema_ty.get_obj_of_attr(key_name) { + Some(attr_ty_obj) => { + let ty = match &attr_ty_obj.ty.kind { + TypeKind::Schema(schema_ty) => { + let runtime_type = kcl_runtime::schema_runtime_type( + &schema_ty.name, + &schema_ty.pkgpath, + ); + if let Some(runtime_scehma_ty) = + self.ctx.schema_mapping.get(&runtime_type) + { + Arc::new(Type::schema( + runtime_scehma_ty.borrow().clone(), + )) + } else { + attr_ty_obj.ty.clone() + } + } + _ => attr_ty_obj.ty.clone(), + }; + Some(self.new_config_expr_context_item( + key_name, + ty, + attr_ty_obj.range.0.clone(), + attr_ty_obj.range.1.clone(), + )) + } + None => match &schema_ty.index_signature { + Some(index_signature) => { + Some(self.new_config_expr_context_item( + key_name, + index_signature.val_ty.clone(), + obj.start.clone(), + obj.end.clone(), + )) + } + None => None, + }, + } + } + TypeKind::Union(types) => { + let mut possible_types = vec![]; + for ty in types { + match &ty.kind { + TypeKind::Schema(schema_ty) => { + match schema_ty.get_obj_of_attr(key_name) { + Some(attr_ty_obj) => { + possible_types.push(attr_ty_obj.ty.clone()); + } + None => match &schema_ty.index_signature { + Some(index_signature) => { + possible_types + .push(index_signature.val_ty.clone()); + } + None => continue, + }, + } + } + TypeKind::Dict(DictType { val_ty, .. }) => { + possible_types.push(val_ty.clone()); + } + _ => continue, + } + } + + Some(self.new_config_expr_context_item( + key_name, + crate::ty::sup(&possible_types).into(), + obj.start.clone(), + obj.end.clone(), + )) + } + _ => None, + }, + None => None, + } + } + None => None, + } + } + } + + /// Switch the context in 'config_expr_context' stack by AST nodes 'Identifier', 'Subscript' or 'Literal' + /// + /// Args: + /// key: AST nodes 'Identifier', 'Subscript' or 'Literal' + /// + /// Returns: + /// push stack times + pub(crate) fn switch_config_expr_context_by_key( + &mut self, + key: &'ctx Option>, + ) -> usize { + match key { + Some(key) => { + let names: Vec = match &key.node { + ast::Expr::Identifier(identifier) => identifier.get_names(), + ast::Expr::Subscript(subscript) => { + if let ast::Expr::Identifier(identifier) = &subscript.value.node { + if let Some(index) = &subscript.index { + if matches!(index.node, ast::Expr::NumberLit(_)) { + identifier.get_names() + } else { + return SwitchConfigContextState::KeepConfigUnchanged as usize; + } + } else { + return SwitchConfigContextState::KeepConfigUnchanged as usize; + } + } else { + return SwitchConfigContextState::KeepConfigUnchanged as usize; + } + } + ast::Expr::StringLit(string_lit) => vec![string_lit.value.clone()], + // There may be a valid configuration key for joined string and missing expressions here, + // and we will restore it to a null value to avoid unfriendly error messages. + ast::Expr::JoinedString(_) | ast::Expr::Missing(_) => vec!["".to_string()], + _ => return SwitchConfigContextState::KeepConfigUnchanged as usize, + }; + self.switch_config_expr_context_by_names(&names) + } + // Double star expression + None => SwitchConfigContextState::KeepConfigUnchanged as usize, + } + } + + /// Switch the context in 'config_expr_context' stack by the list index `[]` + /// + /// Returns: + /// push stack times + #[inline] + pub(crate) fn switch_list_expr_context(&mut self) -> usize { + self.switch_config_expr_context_by_names(&["[]".to_string()]) + } + + /// Switch the context in 'config_expr_context' stack by name + /// + /// find the next item that needs to be pushed into the stack, + /// according to name and the top context of the stack, and push the item into the stack. + /// + /// Args: + /// name: the name of item to be pushed + /// + /// Returns: + /// push stack times + pub(crate) fn switch_config_expr_context_by_name(&mut self, name: &str) -> usize { + let ctx_obj = self.find_schema_attr_obj_from_schema_expr_stack(name); + self.switch_config_expr_context(ctx_obj) as usize + } + + /// Push method for the 'config_expr_context' stack + /// + /// Args: + /// config_ctx_obj: the item needed to be pushed + /// + /// Returns: + /// push stack times + pub(crate) fn switch_config_expr_context( + &mut self, + config_ctx_obj: Option, + ) -> SwitchConfigContextState { + self.ctx.config_expr_context.push(config_ctx_obj); + SwitchConfigContextState::SwitchConfigOnce + } + + /// Pop method for the 'config_expr_context' stack + /// + /// Returns: + /// the item popped from stack. + #[inline] + pub(crate) fn restore_config_expr_context(&mut self) -> Option { + match self.ctx.config_expr_context.pop() { + Some(obj) => obj, + None => None, + } + } + + /// Pop all method for the 'config_expr_context' stack + /// + /// Args: + /// stack_depth: 'stack_depth' is the number of stacks that need to be popped + /// clear_all: 'clear_all' is True to clear all the items of the stack + /// + pub(crate) fn clear_config_expr_context(&mut self, stack_depth: usize, clear_all: bool) { + if clear_all { + self.ctx.config_expr_context.clear() + } else { + for _ in 0..stack_depth { + self.restore_config_expr_context(); + } + } + } + + /// Switch the context in 'config_expr_context' stack by names + /// + /// Traverse all name in 'names', find the next item that needs to be pushed into the stack, + /// according to name and the top context of the stack, and push the item into the stack. + /// + /// Args: + /// names: A list of string containing the names of items to be pushed + /// + /// Returns: + /// push stack times + pub(crate) fn switch_config_expr_context_by_names(&mut self, names: &[String]) -> usize { + let mut stack_depth = 0; + for name in names { + stack_depth += self.switch_config_expr_context_by_name(name); + } + stack_depth + } + + /// Check whether the key of config expr meets the constraints of schema attributes such as final, defined. + /// + /// Args: + /// name: the name of key + /// key: the ast node of key + /// check_rules: the constraints, such as 'check_defined' + pub(crate) fn check_config_expr_by_key_name( + &mut self, + name: &str, + key: &'ctx ast::NodeRef, + ) { + if !name.is_empty() { + if let Some(Some(obj)) = self.ctx.config_expr_context.last() { + let ty = obj.ty.clone(); + self.must_check_config_attr(name, &ty, &key.get_span_pos(), None); + } + } + } + + fn check_config_value_recursively(&mut self, value_ty: &TypeRef, value_span: &Range) { + match &value_ty.kind { + TypeKind::Dict(DictType { + key_ty: _, + val_ty: _, + attrs, + }) => { + for (key, attr) in attrs { + self.check_attr_recursively(&key, &attr.ty, &attr.range, value_span); + } + } + TypeKind::Schema(schema_ty) => { + for (key, attr) in &schema_ty.attrs { + self.check_attr_recursively(&key, &attr.ty, &attr.range, value_span); + } + } + _ => {} + } + } + + fn check_attr_recursively( + &mut self, + key: &str, + attr_ty: &TypeRef, + attr_span: &Range, + value_span: &Range, + ) { + if !key.is_empty() { + if let Some(Some(obj)) = self.ctx.config_expr_context.last() { + let ty = obj.ty.clone(); + self.must_check_config_attr(key, &ty, value_span, Some(attr_span)); + } + let stack_depth = self.switch_config_expr_context_by_name(key); + if let Some(Some(obj)) = self.ctx.config_expr_context.last() { + let ty = obj.ty.clone(); + self.attr_must_assignable_to( + attr_ty.clone(), + ty, + value_span.clone(), + Some(obj.get_span_pos()), + Some(attr_span.clone()), + ); + } + self.check_config_value_recursively(attr_ty, value_span); + self.clear_config_expr_context(stack_depth, false); + } + } + + /// Check the key-value in 'ConfigExpr', such as check_defined and check_type + /// + /// Notes: + /// If the top item of the 'config_expr_context' stack is 'None', the check will be skipped. + /// + /// Args: + /// key: the key of 'ConfigExpr'. + /// value: the value of 'ConfigExpr'. + /// check_rules: Some checks on the key individually,such as check_defined. + pub(crate) fn check_config_entry( + &mut self, + key: &'ctx Option>, + value: &'ctx ast::NodeRef, + ) -> Option { + if let Some(key) = key { + if let Some(Some(_)) = self.ctx.config_expr_context.last() { + let names: Vec = match &key.node { + ast::Expr::Identifier(identifier) => identifier.get_names(), + ast::Expr::Subscript(subscript) => { + if let ast::Expr::Identifier(identifier) = &subscript.value.node { + if let Some(index) = &subscript.index { + if matches!(index.node, ast::Expr::NumberLit(_)) { + identifier.get_names() + } else if let ast::Expr::Unary(unary_expr) = &index.node { + // Negative index constant + if matches!(unary_expr.operand.node, ast::Expr::NumberLit(_)) { + identifier.get_names() + } else { + return None; + } + } else { + return None; + } + } else { + return None; + } + } else { + return None; + } + } + ast::Expr::StringLit(string_lit) => vec![string_lit.value.clone()], + _ => return None, + }; + let mut stack_depth = 0; + for name in &names { + self.check_config_expr_by_key_name(name, key); + stack_depth += self.switch_config_expr_context_by_name(name); + } + let mut val_ty = self.expr(value); + + let return_ty = Some(val_ty.clone()); + + for _ in 0..names.len() - 1 { + val_ty = Type::dict_ref(self.str_ty(), val_ty); + } + if let Some(Some(obj_last)) = self.ctx.config_expr_context.last() { + let ty = obj_last.ty.clone(); + self.must_assignable_to( + val_ty, + ty, + key.get_span_pos(), + Some(obj_last.get_span_pos()), + ); + } + self.clear_config_expr_context(stack_depth, false); + return return_ty; + } + } else { + // For double star expression, we can recursively check nested configuration properties at compile time. + let value_ty = self.expr(value); + self.check_config_value_recursively(&value_ty, &value.get_span_pos()); + return Some(value_ty); + } + None + } + + #[inline] + pub(crate) fn get_config_attr_err_suggestion_from_schema( + &self, + attr: &str, + schema_ty: &SchemaType, + ) -> (Vec, String) { + self.get_config_attr_err_suggestion(attr, schema_ty.attrs.keys()) + } + + pub(crate) fn get_config_attr_err_suggestion( + &self, + attr: &str, + keys: I, + ) -> (Vec, String) + where + T: AsRef, + I: IntoIterator, + { + let mut suggestion = String::new(); + // Calculate the closest miss attributes. + let suggs = suggestions::provide_suggestions(attr, keys); + if suggs.len() > 0 { + suggestion = format!(", did you mean '{:?}'?", suggs); + } + (suggs, suggestion) + } + + /// Check config attr has been defined. + pub(crate) fn must_check_config_attr( + &mut self, + attr: &str, + ty: &TypeRef, + range: &Range, + attr_range: Option<&Range>, + ) { + if let TypeKind::Schema(schema_ty) = &ty.kind { + self.check_config_attr(attr, schema_ty, range, attr_range); + } else if let TypeKind::Union(types) = &ty.kind { + let mut schema_names = vec![]; + let mut total_suggs = vec![]; + for ty in types { + match &ty.kind { + TypeKind::Schema(schema_ty) => { + if schema_ty.get_obj_of_attr(attr).is_none() + && !schema_ty.is_mixin + && schema_ty.index_signature.is_none() + { + let mut suggs = + suggestions::provide_suggestions(attr, schema_ty.attrs.keys()); + total_suggs.append(&mut suggs); + schema_names.push(schema_ty.name.clone()); + } else { + // If there is a schema attribute that meets the condition, the type check passes + return; + } + } + TypeKind::Dict(..) => return, + _ => continue, + } + } + if !schema_names.is_empty() { + let mut msgs = vec![Message { + range: range.clone(), + style: Style::LineAndColumn, + message: format!( + "Cannot add member '{}' to '{}'{}", + attr, + if schema_names.len() > 1 { + format!("schemas {:?}", schema_names) + } else { + format!("schema {}", schema_names[0]) + }, + if total_suggs.is_empty() { + "".to_string() + } else { + format!(", did you mean '{:?}'?", total_suggs) + }, + ), + note: None, + suggested_replacement: Some(total_suggs), + }]; + if let Some(attr_range) = attr_range { + msgs.push(Message { + range: attr_range.clone(), + style: Style::LineAndColumn, + message: "config attribute is defined here".to_string(), + note: None, + suggested_replacement: None, + }); + } + self.handler.add_error(ErrorKind::CompileError, &msgs); + } + } + } + + /// Check config attr has been defined. + pub(crate) fn check_config_attr( + &mut self, + attr: &str, + schema_ty: &SchemaType, + range: &Range, + attr_range: Option<&Range>, + ) { + let runtime_type = kcl_runtime::schema_runtime_type(&schema_ty.name, &schema_ty.pkgpath); + match self.ctx.schema_mapping.get(&runtime_type) { + Some(schema_mapping_ty) => { + let schema_ty = schema_mapping_ty.clone(); + let schema_ty_ref = schema_ty.borrow(); + self.check_config_attr_without_schema_mapping( + attr, + &schema_ty_ref, + range, + attr_range, + ); + } + None => { + self.check_config_attr_without_schema_mapping(attr, schema_ty, range, attr_range); + } + }; + } + + fn check_config_attr_without_schema_mapping( + &mut self, + attr: &str, + schema_ty: &SchemaType, + range: &Range, + attr_range: Option<&Range>, + ) { + if schema_ty.get_obj_of_attr(attr).is_none() + && !schema_ty.is_mixin + && schema_ty.index_signature.is_none() + { + let (suggs, msg) = self.get_config_attr_err_suggestion_from_schema(attr, schema_ty); + self.add_config_attr_error(attr, schema_ty, range, attr_range, suggs, msg); + } + if let Some(index_signature) = &schema_ty.index_signature { + // Here we need to check whether the key of the index signature is a string literal type or a string literal union types + if !index_signature.any_other { + match &index_signature.key_ty.kind { + TypeKind::StrLit(name) => { + if name != attr { + let (suggs, msg) = self.get_config_attr_err_suggestion(attr, &[name]); + self.add_config_attr_error( + attr, schema_ty, range, attr_range, suggs, msg, + ); + } + } + TypeKind::Union(types) => { + let mut keys: HashSet = HashSet::default(); + for ty in types { + if let TypeKind::StrLit(name) = &ty.kind { + keys.insert(name.clone()); + } + } + if !keys.contains(attr) { + let (suggs, msg) = self.get_config_attr_err_suggestion(attr, &keys); + self.add_config_attr_error( + attr, schema_ty, range, attr_range, suggs, msg, + ); + } + } + _ => {} + } + } + } + } + + fn add_config_attr_error( + &mut self, + attr: &str, + schema_ty: &SchemaType, + range: &Range, + attr_range: Option<&Range>, + suggs: Vec, + msg: String, + ) { + let mut msgs = vec![Message { + range: range.clone(), + style: Style::LineAndColumn, + message: format!( + "Cannot add member '{}' to schema '{}'{}", + attr, schema_ty.name, msg, + ), + note: None, + suggested_replacement: Some(suggs), + }]; + if let Some(attr_range) = attr_range { + msgs.push(Message { + range: attr_range.clone(), + style: Style::LineAndColumn, + message: "config attribute is defined here".to_string(), + note: None, + suggested_replacement: None, + }); + } + self.handler.add_error(ErrorKind::CompileError, &msgs); + } + + /// Schema load atr + pub(crate) fn schema_load_attr( + &mut self, + schema_ty: &SchemaType, + attr: &str, + ) -> (bool, TypeRef) { + let runtime_type = kcl_runtime::schema_runtime_type(&schema_ty.name, &schema_ty.pkgpath); + match self.ctx.schema_mapping.get(&runtime_type) { + Some(schema_mapping_ty) => { + let schema_ty = schema_mapping_ty.borrow(); + match schema_ty.get_type_of_attr(attr) { + Some(ty) => (true, ty), + None => { + if schema_ty.is_mixin || schema_ty.index_signature.is_some() { + (true, self.any_ty()) + } else { + (false, self.any_ty()) + } + } + } + } + None => match schema_ty.get_type_of_attr(attr) { + Some(ty) => (true, ty), + None => { + if schema_ty.is_mixin || schema_ty.index_signature.is_some() { + (true, self.any_ty()) + } else { + (false, self.any_ty()) + } + } + }, + } + } + + pub(crate) fn walk_config_entries( + &mut self, + entries: &'ctx [ast::NodeRef], + ) -> TypeRef { + let (start, end) = match entries.len() { + 0 => (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()), + 1 => entries[0].get_span_pos(), + _ => ( + entries.first().unwrap().get_pos(), + entries.last().unwrap().get_end_pos(), + ), + }; + self.enter_scope(start, end, ScopeKind::Config); + let mut key_types: Vec = vec![]; + let mut val_types: Vec = vec![]; + let mut attrs: IndexMap = Default::default(); + for item in entries { + let key = &item.node.key; + let value = &item.node.value; + let op = &item.node.operation; + let mut stack_depth: usize = 0; + let value_ty = self.check_config_entry(key, value); + stack_depth += self.switch_config_expr_context_by_key(key); + let val_ty = match key { + Some(key) => match &key.node { + ast::Expr::Identifier(identifier) => { + let mut val_ty = value_ty.unwrap_or_else(|| self.expr(value)); + + for _ in 0..identifier.names.len() - 1 { + val_ty = Type::dict_ref(self.str_ty(), val_ty.clone()); + } + let key_ty = if identifier.names.len() == 1 { + let name = &identifier.names[0].node; + let key_ty = if self.ctx.local_vars.contains(name) { + // set key context expected schema as None + self.ctx.config_expr_context.push(None); + let key_ty = self.expr(key); + self.ctx.config_expr_context.pop(); + key_ty + } else { + Arc::new(Type::str_lit(name)) + }; + self.check_attr_ty(&key_ty, key.get_span_pos()); + let ty = if let Some(attr) = attrs.get(name) { + sup(&[attr.ty.clone(), val_ty.clone()]) + } else { + val_ty.clone() + }; + attrs.insert( + name.to_string(), + Attr { + ty: self.ctx.ty_ctx.infer_to_variable_type(ty.clone()), + range: key.get_span_pos(), + }, + ); + self.insert_object( + name, + ScopeObject { + name: name.to_string(), + start: key.get_pos(), + end: key.get_end_pos(), + ty, + kind: ScopeObjectKind::Attribute, + doc: None, + }, + ); + key_ty + } else { + self.str_ty() + }; + key_types.push(key_ty); + val_types.push(val_ty.clone()); + val_ty + } + ast::Expr::Subscript(subscript) if subscript.has_name_and_constant_index() => { + let val_ty = value_ty.unwrap_or_else(|| self.expr(value)); + key_types.push(self.str_ty()); + if matches!(op, ast::ConfigEntryOperation::Insert) { + val_types.push(val_ty.clone()); + } else { + val_types.push(Type::list_ref(val_ty.clone())); + } + val_ty + } + _ => { + // set key context expected schema as None + self.ctx.config_expr_context.push(None); + let key_ty = self.expr(key); + self.ctx.config_expr_context.pop(); + let val_ty = value_ty.unwrap_or_else(|| self.expr(value)); + self.check_attr_ty(&key_ty, key.get_span_pos()); + if let ast::Expr::StringLit(string_lit) = &key.node { + let ty = if let Some(attr) = attrs.get(&string_lit.value) { + sup(&[attr.ty.clone(), val_ty.clone()]) + } else { + val_ty.clone() + }; + attrs.insert( + string_lit.value.clone(), + Attr { + ty: self.ctx.ty_ctx.infer_to_variable_type(ty.clone()), + range: key.get_span_pos(), + }, + ); + self.insert_object( + &string_lit.value, + ScopeObject { + name: string_lit.value.clone(), + start: key.get_pos(), + end: key.get_end_pos(), + ty, + kind: ScopeObjectKind::Attribute, + doc: None, + }, + ); + } + key_types.push(key_ty); + val_types.push(val_ty.clone()); + val_ty + } + }, + None => { + let val_ty = value_ty.unwrap_or_else(|| self.expr(value)); + match &val_ty.kind { + TypeKind::None | TypeKind::Any => { + val_types.push(val_ty.clone()); + } + TypeKind::Dict(DictType { + key_ty, + val_ty, + attrs: merged_attrs, + }) => { + key_types.push(key_ty.clone()); + val_types.push(val_ty.clone()); + for (key, value) in merged_attrs { + attrs.insert(key.to_string(), value.clone()); + } + } + TypeKind::Schema(schema_ty) => { + key_types.push(schema_ty.key_ty()); + val_types.push(schema_ty.val_ty()); + for (key, attr) in &schema_ty.attrs { + attrs.insert( + key.to_string(), + Attr { + ty: attr.ty.clone(), + range: attr.range.clone(), + }, + ); + } + } + TypeKind::Union(types) + if self + .ctx + .ty_ctx + .is_config_type_or_config_union_type(val_ty.clone()) => + { + key_types.push(sup(&types + .iter() + .map(|ty| ty.config_key_ty()) + .collect::>())); + val_types.push(sup(&types + .iter() + .map(|ty| ty.config_val_ty()) + .collect::>())); + } + _ => { + self.handler.add_compile_error( + &format!( + "only dict and schema can be used ** unpack, got '{}'", + val_ty.ty_str() + ), + value.get_span_pos(), + ); + } + } + val_ty + } + }; + if matches!(op, ast::ConfigEntryOperation::Insert) + && !val_ty.is_any() + && !val_ty.is_list() + { + self.handler.add_error( + ErrorKind::IllegalAttributeError, + &[Message { + range: value.get_span_pos(), + style: Style::LineAndColumn, + message: format!( + "only list type can in inserted, got '{}'", + val_ty.ty_str() + ), + note: None, + suggested_replacement: None, + }], + ); + } + self.clear_config_expr_context(stack_depth, false); + } + self.leave_scope(); + let key_ty = sup(&key_types); + let val_ty = sup(&val_types); + Type::dict_ref_with_attrs(key_ty, val_ty, attrs) + } +} diff --git a/kclvm/sema/src/resolver/doc.rs b/crates/sema/src/resolver/doc.rs similarity index 98% rename from kclvm/sema/src/resolver/doc.rs rename to crates/sema/src/resolver/doc.rs index 089e4897d..591dc9c4e 100644 --- a/kclvm/sema/src/resolver/doc.rs +++ b/crates/sema/src/resolver/doc.rs @@ -1,4 +1,4 @@ -use kclvm_ast::ast::{self, SchemaStmt}; +use kcl_ast::ast::{self, SchemaStmt}; use std::collections::{HashMap, HashSet}; use std::iter::Iterator; use std::str; @@ -328,7 +328,9 @@ impl SchemaDoc { }) .collect::>() .join("\n"); - format!("{summary}\n\nAttributes\n----------\n{attrs_string}\n\nExamples\n--------{examples_string}\n") + format!( + "{summary}\n\nAttributes\n----------\n{attrs_string}\n\nExamples\n--------{examples_string}\n" + ) } } @@ -387,8 +389,8 @@ pub fn extract_doc_from_body(stmts: &[Box>]) -> Option Resolver<'_> { } _ => continue, }; - let base_attr_ty = match parent_ty { - Some(ref ty) => ty.get_type_of_attr(&name).map_or(self.any_ty(), |ty| ty), + let base_attr_ty = match &parent_ty { + Some(ty) => ty.get_type_of_attr(&name).map_or(self.any_ty(), |ty| ty), None => self.any_ty(), }; if !attr_obj_map.contains_key(&name) { @@ -682,7 +682,7 @@ impl<'ctx> Resolver<'_> { stmt.get_span_pos(), ); } - if let Some(ref index_signature_obj) = index_signature { + if let Some(index_signature_obj) = &index_signature { if !index_signature_obj.any_other && !is_upper_bound(index_signature_obj.val_ty.clone(), ty.clone()) { @@ -783,7 +783,7 @@ impl<'ctx> Resolver<'_> { let schema_full_ty_str = full_ty_str(&self.ctx.pkgpath, name); if should_add_schema_ref { - if let Some(ref parent_ty) = parent_ty { + if let Some(parent_ty) = &parent_ty { let parent_full_ty_str = parent_ty.full_ty_str(); self.ctx.ty_ctx.add_dependencies( &schema_full_ty_str, @@ -850,7 +850,7 @@ impl<'ctx> Resolver<'_> { index_signature, decorators, }; - let schema_runtime_ty = kclvm_runtime::schema_runtime_type(name, &self.ctx.pkgpath); + let schema_runtime_ty = kcl_runtime::schema_runtime_type(name, &self.ctx.pkgpath); self.ctx .schema_mapping .insert(schema_runtime_ty, Arc::new(RefCell::new(schema_ty.clone()))); diff --git a/kclvm/sema/src/resolver/import.rs b/crates/sema/src/resolver/import.rs similarity index 94% rename from kclvm/sema/src/resolver/import.rs rename to crates/sema/src/resolver/import.rs index 0251a286d..2ee76a215 100644 --- a/kclvm/sema/src/resolver/import.rs +++ b/crates/sema/src/resolver/import.rs @@ -1,21 +1,21 @@ use crate::plugin::PLUGIN_MODULE_PREFIX; -use crate::resolver::scope::Module; use crate::resolver::Resolver; +use crate::resolver::scope::Module; use crate::ty::ModuleKind; use crate::{ builtin::system_module::STANDARD_SYSTEM_MODULES, ty::{Type, TypeKind}, }; -use kclvm_ast::ast; -use kclvm_error::*; -use kclvm_primitives::IndexMap; +use kcl_ast::ast; +use kcl_error::*; +use kcl_primitives::IndexMap; use std::rc::Rc; use std::sync::Arc; use std::{cell::RefCell, path::Path}; use super::scope::{Scope, ScopeKind, ScopeObject, ScopeObjectKind}; -use kclvm_ast::pos::GetPos; -use kclvm_utils::pkgpath::parse_external_pkg_name; +use kcl_ast::pos::GetPos; +use kcl_utils::pkgpath::parse_external_pkg_name; impl<'ctx> Resolver<'ctx> { /// Check import error @@ -178,14 +178,14 @@ impl<'ctx> Resolver<'ctx> { Some(scope_obj) => { let mut obj = scope_obj.borrow_mut(); match &mut obj.kind { - ScopeObjectKind::Module(m) => { - m.import_stmts.push((stmt.clone(), false)) - }, - _ => bug!( - "invalid module type in the import check function {}", - scope_obj.borrow().ty.ty_str() - ) + ScopeObjectKind::Module(m) => { + m.import_stmts.push((stmt.clone(), false)) } + _ => bug!( + "invalid module type in the import check function {}", + scope_obj.borrow().ty.ty_str() + ), + } match &obj.ty.kind { TypeKind::Module(module_ty) => { let mut module_ty = module_ty.clone(); @@ -200,9 +200,9 @@ impl<'ctx> Resolver<'ctx> { matches!(module_ty.kind, ModuleKind::User) } _ => bug!( - "invalid module type in the import check function {}", - scope_obj.borrow().ty.ty_str() - ), + "invalid module type in the import check function {}", + scope_obj.borrow().ty.ty_str() + ), } } None => { diff --git a/kclvm/sema/src/resolver/loop.rs b/crates/sema/src/resolver/loop.rs similarity index 97% rename from kclvm/sema/src/resolver/loop.rs rename to crates/sema/src/resolver/loop.rs index 51cca4e8d..00ba06829 100644 --- a/kclvm/sema/src/resolver/loop.rs +++ b/crates/sema/src/resolver/loop.rs @@ -1,7 +1,7 @@ use crate::resolver::Resolver; -use crate::ty::{sup, DictType, TypeKind, TypeRef}; -use kclvm_ast::ast; -use kclvm_error::diagnostic::Range; +use crate::ty::{DictType, TypeKind, TypeRef, sup}; +use kcl_ast::ast; +use kcl_error::diagnostic::Range; impl<'ctx> Resolver<'ctx> { /// Do loop type check including quant and comp for expression. diff --git a/crates/sema/src/resolver/mod.rs b/crates/sema/src/resolver/mod.rs new file mode 100644 index 000000000..f85babd7b --- /dev/null +++ b/crates/sema/src/resolver/mod.rs @@ -0,0 +1,253 @@ +mod arg; +mod attr; +mod calculation; +mod config; +pub mod doc; +mod format; +pub mod global; +mod import; +mod r#loop; +mod node; +mod para; +mod schema; +pub mod scope; +pub(crate) mod ty; +mod ty_alias; +mod ty_erasure; +mod var; + +#[cfg(test)] +mod tests; + +use kcl_error::diagnostic::Range; +use kcl_primitives::{IndexMap, IndexSet}; +use std::sync::Arc; +use std::{cell::RefCell, rc::Rc}; + +use crate::lint::{CombinedLintPass, Linter}; +use crate::pre_process::pre_process_program; +use crate::resolver::scope::ScopeObject; +use crate::resolver::ty_alias::type_alias_pass; +use crate::resolver::ty_erasure::type_func_erasure_pass; +use crate::ty::TypeContext; +use crate::{resolver::scope::Scope, ty::SchemaType}; +use kcl_ast::ast::Program; +use kcl_error::*; + +use self::scope::{KCLScopeCache, NodeTyMap, ProgramScope, builtin_scope}; + +/// Resolver is responsible for program semantic checking, mainly +/// including type checking and contract model checking. +pub struct Resolver<'ctx> { + pub program: &'ctx Program, + pub scope_map: IndexMap>>, + pub scope: Rc>, + pub scope_level: usize, + pub node_ty_map: Rc>, + pub builtin_scope: Rc>, + pub ctx: Context, + pub options: Options, + pub handler: Handler, + pub linter: Linter, +} + +impl<'ctx> Resolver<'ctx> { + pub fn new(program: &'ctx Program, options: Options) -> Self { + let builtin_scope = Rc::new(RefCell::new(builtin_scope())); + let scope = Rc::clone(&builtin_scope); + Resolver { + program, + scope_map: IndexMap::default(), + builtin_scope, + scope, + scope_level: 0, + node_ty_map: Rc::new(RefCell::new(IndexMap::default())), + ctx: Context::default(), + options, + handler: Handler::default(), + linter: Linter::::new(), + } + } + + /// The check main function. + pub(crate) fn check(&mut self, pkgpath: &str) { + self.check_import(pkgpath); + self.init_global_types(); + match self + .program + .pkgs + .get(pkgpath) + .or(self.program.pkgs_not_imported.get(pkgpath)) + { + Some(modules) => { + for module in modules { + let module = self + .program + .get_module(module) + .expect("Failed to acquire module lock") + .expect(&format!("module {:?} not found in program", module)); + self.ctx.filename = module.filename.to_string(); + if let scope::ScopeKind::Package(files) = &mut self.scope.borrow_mut().kind { + files.insert(module.filename.to_string()); + } + for stmt in &module.body { + self.stmt(&stmt); + } + if self.options.lint_check { + self.lint_check_module(&module); + } + } + } + None => {} + } + } + + pub(crate) fn check_and_lint_all_pkgs(&mut self) -> ProgramScope { + self.check(kcl_ast::MAIN_PKG); + self.lint_check_scope_map(); + let mut handler = self.handler.clone(); + for diag in &self.linter.handler.diagnostics { + handler.diagnostics.insert(diag.clone()); + } + + for pkg in self.program.pkgs_not_imported.keys() { + if !self.scope_map.contains_key(pkg) { + self.check(pkg); + } + } + + let mut scope_map = self.scope_map.clone(); + for invalid_pkg_scope in &self.ctx.invalid_pkg_scope { + scope_map.swap_remove(invalid_pkg_scope); + } + let scope = ProgramScope { + scope_map, + import_names: self.ctx.import_names.clone(), + node_ty_map: self.node_ty_map.clone(), + handler, + schema_mapping: self.ctx.schema_mapping.clone(), + }; + scope + } +} + +/// Resolve context +#[derive(Debug, Default)] +pub struct Context { + /// What source file are we in. + pub filename: String, + /// What package path are we in. + pub pkgpath: String, + /// What schema are we in. + pub schema: Option>>, + /// Global schemas name and type mapping. + pub schema_mapping: IndexMap>>, + /// For loop local vars. + pub local_vars: Vec, + /// Import pkgpath and name + pub import_names: IndexMap>, + /// Global names at top level of the program. + pub global_names: IndexMap>, + /// Are we resolving the left value. + pub l_value: bool, + /// Are we resolving the statement start position. + pub start_pos: Position, + /// Are we resolving the statement end position. + pub end_pos: Position, + /// Is in lambda expression. + pub in_lambda_expr: Vec, + /// Current schema expr type stack + pub config_expr_context: Vec>, + /// Type context. + pub ty_ctx: TypeContext, + /// Type alias mapping + pub type_alias_mapping: IndexMap>, + /// invalid pkg scope, remove when after resolve + pub invalid_pkg_scope: IndexSet, +} + +/// Resolve options. +/// - lint_check: whether to run lint passes +/// - resolve_val: whether to resolve and print their AST to value for some nodes. +#[derive(Clone, Debug)] +pub struct Options { + pub lint_check: bool, + pub resolve_val: bool, + pub merge_program: bool, + pub type_erasure: bool, +} + +impl Default for Options { + fn default() -> Self { + Self { + lint_check: true, + resolve_val: false, + merge_program: true, + type_erasure: true, + } + } +} + +/// Resolve program with default options. +#[inline] +pub fn resolve_program(program: &mut Program) -> ProgramScope { + resolve_program_with_opts(program, Options::default(), None) +} + +/// Resolve program with options. See [Options] +pub fn resolve_program_with_opts( + program: &mut Program, + opts: Options, + cached_scope: Option, +) -> ProgramScope { + pre_process_program(program, &opts); + let mut resolver = Resolver::new(program, opts.clone()); + resolver.resolve_import(); + if let Some(cached_scope) = cached_scope.as_ref() { + if let Some(mut cached_scope) = cached_scope.try_write() { + cached_scope.invalidate_pkgs.clear(); + cached_scope.update(program); + resolver.scope_map = cached_scope.scope_map.clone(); + resolver.ctx.schema_mapping = cached_scope.schema_mapping.clone(); + cached_scope + .invalidate_pkgs + .insert(kcl_ast::MAIN_PKG.to_string()); + for pkg in &cached_scope.invalidate_pkgs { + resolver.scope_map.swap_remove(pkg); + } + let mut nodes = vec![]; + for node in cached_scope.node_ty_map.keys() { + if cached_scope.invalidate_pkgs.contains(&node.pkgpath) { + nodes.push(node.clone()); + } + } + for node in nodes { + cached_scope.node_ty_map.swap_remove(&node); + } + resolver.node_ty_map = Rc::new(RefCell::new(cached_scope.node_ty_map.clone())); + } + } + let scope = resolver.check_and_lint_all_pkgs(); + + if let Some(cached_scope) = cached_scope.as_ref() { + if let Some(mut cached_scope) = cached_scope.try_write() { + cached_scope.update(program); + cached_scope.scope_map = scope.scope_map.clone(); + cached_scope.node_ty_map = scope.node_ty_map.borrow().clone(); + cached_scope.scope_map.swap_remove(kcl_ast::MAIN_PKG); + cached_scope.schema_mapping = resolver.ctx.schema_mapping; + cached_scope + .invalidate_pkgs + .insert(kcl_ast::MAIN_PKG.to_string()); + cached_scope.invalidate_pkg_modules = None; + } + } + if opts.type_erasure { + let type_alias_mapping = resolver.ctx.type_alias_mapping.clone(); + // Erase all the function type to a named type "function" + type_func_erasure_pass(program); + // Erase types with their type alias + type_alias_pass(program, type_alias_mapping); + } + scope +} diff --git a/crates/sema/src/resolver/node.rs b/crates/sema/src/resolver/node.rs new file mode 100644 index 000000000..1a912eac5 --- /dev/null +++ b/crates/sema/src/resolver/node.rs @@ -0,0 +1,1344 @@ +use kcl_ast::ast; +use kcl_ast::pos::GetPos; +use kcl_ast::walker::MutSelfTypedResultWalker; +use kcl_ast_pretty::{ASTNode, print_ast_node}; +use kcl_error::*; +use kcl_primitives::IndexMap; +use std::sync::Arc; + +use crate::info::is_private_field; +use crate::ty::{ + DictType, FunctionType, Parameter, RESERVED_TYPE_IDENTIFIERS, Type, TypeInferMethods, TypeKind, + TypeRef, sup, +}; + +use super::Resolver; +use super::doc::extract_doc_from_body; +use super::format::VALID_FORMAT_SPEC_SET; +use super::scope::{ScopeKind, ScopeObject, ScopeObjectKind}; +use super::ty::ty_str_replace_pkgpath; +/// ResolvedResult denotes the result, when the result is error, +/// put the message string into the diagnostic vector. +pub type ResolvedResult = TypeRef; + +impl<'ctx> MutSelfTypedResultWalker<'ctx> for Resolver<'_> { + type Result = ResolvedResult; + + fn walk_module(&mut self, module: &'ctx ast::Module) -> Self::Result { + self.stmts(&module.body) + } + + fn walk_expr_stmt(&mut self, expr_stmt: &'ctx ast::ExprStmt) -> Self::Result { + let expr_types = self.exprs(&expr_stmt.exprs); + if let Some(last) = expr_types.last() { + let ty = last.clone(); + if expr_types.len() > 1 { + self.handler.add_compile_error( + "expression statement can only have one expression", + expr_stmt.exprs[1].get_span_pos(), + ); + } + ty + } else { + bug!("invalid expr statement exprs"); + } + } + + fn walk_unification_stmt( + &mut self, + unification_stmt: &'ctx ast::UnificationStmt, + ) -> Self::Result { + let names = &unification_stmt.target.node.names; + if names.len() > 1 { + self.handler.add_compile_error( + "unification identifier can not be selected", + unification_stmt.target.get_span_pos(), + ); + } + let (start, end) = unification_stmt.value.get_span_pos(); + if names.is_empty() { + self.handler.add_compile_error( + "missing target in the unification statement", + unification_stmt.value.get_span_pos(), + ); + return self.any_ty(); + } + self.ctx.l_value = true; + let expected_ty = self.walk_identifier_expr(&unification_stmt.target); + self.ctx.l_value = false; + let obj = + self.new_config_expr_context_item(&names[0].node, expected_ty.clone(), start, end); + let init_stack_depth = self.switch_config_expr_context(Some(obj)); + let ty = self.walk_schema_expr(&unification_stmt.value.node); + self.clear_config_expr_context(init_stack_depth as usize, false); + self.must_assignable_to( + ty.clone(), + expected_ty.clone(), + unification_stmt.target.get_span_pos(), + None, + ); + if !ty.is_any() && expected_ty.is_any() { + self.set_infer_type_to_scope(&names[0].node, ty, &names[0]); + } + expected_ty + } + + fn walk_type_alias_stmt(&mut self, type_alias_stmt: &'ctx ast::TypeAliasStmt) -> Self::Result { + let (start, end) = type_alias_stmt.type_name.get_span_pos(); + let mut ty = self + .parse_ty_with_scope(Some(&type_alias_stmt.ty), (start.clone(), end.clone())) + .as_ref() + .clone(); + if let TypeKind::Schema(schema_ty) = &mut ty.kind { + schema_ty.is_instance = false; + } + ty.is_type_alias = true; + let ty = Arc::new(ty); + let ty_str = ty.into_type_annotation_str(); + let name = type_alias_stmt.type_name.node.get_name(); + let mut mapping = IndexMap::default(); + mapping.insert(ty_str.clone(), "".to_string()); + self.ctx.import_names.insert(name.to_string(), mapping); + self.add_type_alias(&name, &ty_str); + if RESERVED_TYPE_IDENTIFIERS.contains(&name.as_str()) { + self.handler.add_type_error( + &format!( + "type alias '{}' cannot be the same as the built-in types ({:?})", + name, RESERVED_TYPE_IDENTIFIERS + ), + type_alias_stmt.type_name.get_span_pos(), + ); + } + self.insert_object( + &name, + ScopeObject { + name: name.clone(), + start, + end, + ty: ty.clone(), + kind: ScopeObjectKind::TypeAlias, + doc: None, + }, + ); + self.node_ty_map.borrow_mut().insert( + self.get_node_key(type_alias_stmt.type_name.id.clone()), + ty.clone(), + ); + ty + } + + fn walk_assign_stmt(&mut self, assign_stmt: &'ctx ast::AssignStmt) -> Self::Result { + self.ctx.local_vars.clear(); + let mut value_ty = self.any_ty(); + let start = if assign_stmt.targets.is_empty() { + assign_stmt.value.get_pos() + } else { + assign_stmt.targets[0].get_pos() + }; + let end = assign_stmt.value.get_end_pos(); + let is_config = matches!(assign_stmt.value.node, ast::Expr::Schema(_)); + for target in &assign_stmt.targets { + let name = &target.node.name.node; + // Add global names. + if (is_private_field(name) || is_config || !self.contains_global_name(name)) + && self.scope_level == 0 + { + self.insert_global_name(name, &target.get_span_pos()); + } + if target.node.paths.is_empty() { + self.ctx.l_value = true; + let expected_ty = self.walk_target_expr(target); + self.ctx.l_value = false; + match &expected_ty.kind { + TypeKind::Schema(ty) => { + let obj = self.new_config_expr_context_item( + &ty.name, + expected_ty.clone(), + start.clone(), + end.clone(), + ); + let init_stack_depth = self.switch_config_expr_context(Some(obj)); + value_ty = self.expr(&assign_stmt.value); + self.clear_config_expr_context(init_stack_depth as usize, false) + } + TypeKind::List(_) | TypeKind::Dict(_) | TypeKind::Union(_) => { + let obj = self.new_config_expr_context_item( + "[]", + expected_ty.clone(), + start.clone(), + end.clone(), + ); + let init_stack_depth = self.switch_config_expr_context(Some(obj)); + value_ty = self.expr(&assign_stmt.value); + self.check_assignment_type_annotation(assign_stmt, value_ty.clone()); + self.clear_config_expr_context(init_stack_depth as usize, false) + } + _ => { + value_ty = self.expr(&assign_stmt.value); + // Check type annotation if exists. + self.check_assignment_type_annotation(assign_stmt, value_ty.clone()); + } + } + self.must_assignable_to( + value_ty.clone(), + expected_ty.clone(), + target.get_span_pos(), + None, + ); + let upgrade_schema_type = + self.upgrade_dict_to_schema(value_ty.clone(), expected_ty.clone()); + self.node_ty_map.borrow_mut().insert( + self.get_node_key(assign_stmt.value.id.clone()), + upgrade_schema_type.clone(), + ); + + if !value_ty.is_any() && expected_ty.is_any() && assign_stmt.ty.is_none() { + // When the type is inferred and paths of target are empty, set the type to + // the whole AST node `target` and the first name of node `target.node.name` + self.set_infer_type_to_scope(name, value_ty.clone(), &target); + self.set_infer_type_to_scope(name, value_ty.clone(), &target.node.name); + if let Some(schema_ty) = &self.ctx.schema { + let mut schema_ty = schema_ty.borrow_mut(); + schema_ty.set_type_of_attr( + name, + self.ctx.ty_ctx.infer_to_variable_type(value_ty.clone()), + ); + } + } + } else { + self.lookup_type_from_scope(name, target.get_span_pos()); + self.ctx.l_value = true; + let expected_ty = self.walk_target_expr(target); + self.ctx.l_value = false; + value_ty = self.expr(&assign_stmt.value); + // Check type annotation if exists. + self.check_assignment_type_annotation(assign_stmt, value_ty.clone()); + self.must_assignable_to( + value_ty.clone(), + expected_ty.clone(), + target.get_span_pos(), + None, + ); + let upgrade_schema_type = + self.upgrade_dict_to_schema(value_ty.clone(), expected_ty.clone()); + self.node_ty_map.borrow_mut().insert( + self.get_node_key(assign_stmt.value.id.clone()), + upgrade_schema_type.clone(), + ); + } + } + value_ty + } + + fn walk_aug_assign_stmt(&mut self, aug_assign_stmt: &'ctx ast::AugAssignStmt) -> Self::Result { + self.ctx.l_value = false; + let is_config = matches!(aug_assign_stmt.value.node, ast::Expr::Schema(_)); + let name = &aug_assign_stmt.target.node.name.node; + // Add global names. + if is_private_field(name) || is_config || !self.contains_global_name(name) { + if self.scope_level == 0 { + self.insert_global_name(name, &aug_assign_stmt.target.get_span_pos()); + } + } else { + let mut msgs = vec![Message { + range: aug_assign_stmt.target.get_span_pos(), + style: Style::LineAndColumn, + message: format!("Immutable variable '{}' is modified during compiling", name), + note: None, + suggested_replacement: None, + }]; + if let Some(pos) = self.get_global_name_pos(name) { + msgs.push(Message { + range: pos.clone(), + style: Style::LineAndColumn, + message: format!("The variable '{}' is declared here firstly", name), + note: Some(format!( + "change the variable name to '_{}' to make it mutable", + name + )), + suggested_replacement: None, + }) + } + self.handler.add_error(ErrorKind::ImmutableError, &msgs); + } + + let left_ty = self.walk_target_expr(&aug_assign_stmt.target); + let right_ty = self.expr(&aug_assign_stmt.value); + let op = match aug_assign_stmt.op.clone().try_into() { + Ok(op) => op, + Err(msg) => bug!("{}", msg), + }; + let new_target_ty = self.binary( + left_ty, + right_ty, + &op, + aug_assign_stmt.target.get_span_pos(), + ); + self.ctx.l_value = true; + let expected_ty = self.walk_target_expr(&aug_assign_stmt.target); + self.must_assignable_to( + new_target_ty.clone(), + expected_ty, + aug_assign_stmt.target.get_span_pos(), + None, + ); + self.ctx.l_value = false; + new_target_ty + } + + fn walk_assert_stmt(&mut self, assert_stmt: &'ctx ast::AssertStmt) -> Self::Result { + self.expr(&assert_stmt.test); + self.expr_or_any_type(&assert_stmt.if_cond); + if let Some(msg) = &assert_stmt.msg { + self.must_be_type(msg, self.str_ty()); + } + self.any_ty() + } + + fn walk_if_stmt(&mut self, if_stmt: &'ctx ast::IfStmt) -> Self::Result { + self.expr(&if_stmt.cond); + let if_ty = self.stmts(&if_stmt.body); + let orelse_ty = self.stmts(&if_stmt.orelse); + sup(&[if_ty, orelse_ty]) + } + + fn walk_import_stmt(&mut self, _import_stmt: &'ctx ast::ImportStmt) -> Self::Result { + // Nothing to do. + self.any_ty() + } + + fn walk_schema_stmt(&mut self, schema_stmt: &'ctx ast::SchemaStmt) -> Self::Result { + self.resolve_schema_stmt(schema_stmt) + } + + fn walk_rule_stmt(&mut self, rule_stmt: &'ctx ast::RuleStmt) -> Self::Result { + self.resolve_rule_stmt(rule_stmt) + } + + fn walk_quant_expr(&mut self, quant_expr: &'ctx ast::QuantExpr) -> Self::Result { + let iter_ty = self.expr(&quant_expr.target); + let (start, mut end) = quant_expr.test.get_span_pos(); + if let Some(if_cond) = &quant_expr.if_cond { + end = if_cond.get_end_pos(); + } + self.enter_scope(start, end, ScopeKind::Loop); + let (mut key_name, mut val_name) = (None, None); + for (i, target) in quant_expr.variables.iter().enumerate() { + if target.node.names.is_empty() { + continue; + } + if target.node.names.len() > 1 { + self.handler.add_compile_error( + "loop variables can only be ordinary identifiers", + target.get_span_pos(), + ); + } + let name = &target.node.names[0]; + if i == 0 { + key_name = Some(name); + } else if i == 1 { + val_name = Some(name) + } else { + self.handler.add_compile_error( + &format!( + "the number of loop variables is {}, which can only be 1 or 2", + quant_expr.variables.len() + ), + target.get_span_pos(), + ); + break; + } + self.ctx.local_vars.push(name.node.to_string()); + let (start, end) = target.get_span_pos(); + self.insert_object( + &name.node, + ScopeObject { + name: name.node.to_string(), + start, + end, + ty: self.any_ty(), + kind: ScopeObjectKind::Variable, + doc: None, + }, + ); + } + self.do_loop_type_check( + key_name, + val_name, + iter_ty.clone(), + quant_expr.target.get_span_pos(), + ); + self.expr_or_any_type(&quant_expr.if_cond); + let item_ty = self.expr(&quant_expr.test); + self.leave_scope(); + match &quant_expr.op { + ast::QuantOperation::All | ast::QuantOperation::Any => self.bool_ty(), + ast::QuantOperation::Filter => iter_ty, + ast::QuantOperation::Map => Arc::new(Type::list(item_ty)), + } + } + + fn walk_schema_attr(&mut self, schema_attr: &'ctx ast::SchemaAttr) -> Self::Result { + self.ctx.local_vars.clear(); + let (start, end) = schema_attr.name.get_span_pos(); + let name = if schema_attr.is_ident_attr() && schema_attr.name.node.contains('.') { + self.handler.add_compile_error( + "schema attribute can not be selected", + schema_attr.name.get_span_pos(), + ); + schema_attr.name.node.split('.').collect::>()[0] + } else { + &schema_attr.name.node + }; + let schema = self.ctx.schema.as_ref().unwrap(); + let expected_ty = schema + .borrow() + .get_type_of_attr(name) + .map_or(self.any_ty(), |ty| ty); + + self.node_ty_map.borrow_mut().insert( + self.get_node_key(schema_attr.name.id.clone()), + expected_ty.clone(), + ); + + let doc_str = schema + .borrow() + .attrs + .get(name) + .map(|attr| attr.doc.clone()) + .flatten(); + + self.insert_object( + name, + ScopeObject { + name: name.to_string(), + start, + end, + ty: expected_ty.clone(), + kind: ScopeObjectKind::Attribute, + doc: doc_str, + }, + ); + if let Some(value) = &schema_attr.value { + let value_ty = if let TypeKind::Schema(ty) = &expected_ty.kind { + let (start, end) = value.get_span_pos(); + let obj = + self.new_config_expr_context_item(&ty.name, expected_ty.clone(), start, end); + let init_stack_depth = self.switch_config_expr_context(Some(obj)); + let value_ty = self.expr(value); + self.clear_config_expr_context(init_stack_depth as usize, false); + value_ty + } else { + self.expr(value) + }; + match &schema_attr.op { + Some(bin_or_aug) => match bin_or_aug { + // Union + ast::AugOp::BitOr => { + let op = ast::BinOp::BitOr; + let value_ty = self.binary( + value_ty, + expected_ty.clone(), + &op, + schema_attr.name.get_span_pos(), + ); + self.must_assignable_to( + value_ty, + expected_ty, + schema_attr.name.get_span_pos(), + None, + ); + } + // Assign + _ => self.must_assignable_to( + value_ty, + expected_ty, + schema_attr.name.get_span_pos(), + None, + ), + }, + // Default is Assign + None => self.must_assignable_to( + value_ty, + expected_ty, + schema_attr.name.get_span_pos(), + None, + ), + } + } + self.any_ty() + } + + /// if else -> sup([body, orelse]) + fn walk_if_expr(&mut self, if_expr: &'ctx ast::IfExpr) -> Self::Result { + self.expr(&if_expr.cond); + let body_ty = self.expr(&if_expr.body); + let orelse_ty = self.expr(&if_expr.orelse); + sup(&[body_ty, orelse_ty]) + } + + fn walk_unary_expr(&mut self, unary_expr: &'ctx ast::UnaryExpr) -> Self::Result { + let operand_ty = self.expr(&unary_expr.operand); + self.unary( + operand_ty, + &unary_expr.op, + unary_expr.operand.get_span_pos(), + ) + } + + fn walk_binary_expr(&mut self, binary_expr: &'ctx ast::BinaryExpr) -> Self::Result { + let left_ty = self.expr(&binary_expr.left); + let mut right_ty = self.expr(&binary_expr.right); + let range = (binary_expr.left.get_pos(), binary_expr.right.get_end_pos()); + match &binary_expr.op { + ast::BinOp::As => { + if let ast::Expr::Identifier(identifier) = &binary_expr.right.node { + right_ty = self.parse_ty_str_with_scope( + &identifier.get_name(), + binary_expr.right.get_span_pos(), + ); + if right_ty.is_schema() { + let mut schema_ty = right_ty.into_schema_type(); + schema_ty.is_instance = true; + right_ty = Arc::new(Type::schema(schema_ty)); + } + let ty_annotation_str = right_ty.into_type_annotation_str(); + self.add_type_alias( + &identifier.get_name(), + &ty_str_replace_pkgpath(&ty_annotation_str, &self.ctx.pkgpath), + ); + } else { + self.handler + .add_compile_error("keyword 'as' right operand must be a type", range); + return left_ty; + } + self.binary(left_ty, right_ty, &binary_expr.op, range) + } + _ => self.binary(left_ty, right_ty, &binary_expr.op, range), + } + } + + fn walk_selector_expr(&mut self, selector_expr: &'ctx ast::SelectorExpr) -> Self::Result { + let mut value_ty = self.expr(&selector_expr.value); + if value_ty.is_module() && selector_expr.has_question { + let attr = selector_expr.attr.node.get_name(); + + self.handler.add_compile_error_with_suggestions( + &format!( + "For the module type, the use of '?.{}' is unnecessary and it can be modified as '.{}'", + attr, + attr + ), + (selector_expr.value.get_end_pos(), selector_expr.attr.get_pos()), + Some(vec![".".to_string()]) + ); + } + + self.node_ty_map.borrow_mut().insert( + self.get_node_key(selector_expr.attr.id.clone()), + value_ty.clone(), + ); + + for name in &selector_expr.attr.node.names { + value_ty = self.load_attr( + value_ty.clone(), + &name.node, + selector_expr.attr.get_span_pos(), + ); + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(name.id.clone()), value_ty.clone()); + } + + if let TypeKind::Function(func) = &value_ty.kind { + self.insert_object( + &selector_expr.attr.node.get_name(), + ScopeObject { + name: selector_expr.attr.node.get_name(), + start: selector_expr.attr.get_pos(), + end: selector_expr.attr.get_end_pos(), + ty: value_ty.clone(), + kind: ScopeObjectKind::FunctionCall, + doc: Some(func.doc.clone()), + }, + ) + } + + value_ty + } + + fn walk_call_expr(&mut self, call_expr: &'ctx ast::CallExpr) -> Self::Result { + let call_ty = self.expr(&call_expr.func); + let range = call_expr.func.get_span_pos(); + if call_ty.is_any() { + self.do_arguments_type_check( + &call_expr.func, + &call_expr.args, + &call_expr.keywords, + &FunctionType::variadic_func(), + ); + self.any_ty() + } else if let TypeKind::Function(func_ty) = &call_ty.kind { + self.do_arguments_type_check( + &call_expr.func, + &call_expr.args, + &call_expr.keywords, + &func_ty, + ); + func_ty.return_ty.clone() + } else if let TypeKind::Schema(schema_ty) = &call_ty.kind { + if schema_ty.is_instance { + self.handler.add_compile_error( + &format!("schema '{}' instance is not callable", call_ty.ty_str()), + range, + ); + self.any_ty() + } else { + self.do_arguments_type_check( + &call_expr.func, + &call_expr.args, + &call_expr.keywords, + &schema_ty.func, + ); + let mut return_ty = schema_ty.clone(); + return_ty.is_instance = true; + Arc::new(Type::schema(return_ty)) + } + } else { + self.handler.add_compile_error( + &format!("'{}' object is not callable", call_ty.ty_str()), + range, + ); + self.any_ty() + } + } + + fn walk_subscript(&mut self, subscript: &'ctx ast::Subscript) -> Self::Result { + let value_ty = self.expr(&subscript.value); + let range = subscript.value.get_span_pos(); + self.subscript( + value_ty, + &subscript.index, + &subscript.lower, + &subscript.upper, + &subscript.step, + range, + ) + } + + fn walk_paren_expr(&mut self, paren_expr: &'ctx ast::ParenExpr) -> Self::Result { + self.expr(&paren_expr.expr) + } + + fn walk_list_expr(&mut self, list_expr: &'ctx ast::ListExpr) -> Self::Result { + let stack_depth = self.switch_list_expr_context(); + let item_type = sup(&self.exprs(&list_expr.elts).to_vec()); + self.clear_config_expr_context(stack_depth, false); + Type::list_ref(item_type) + } + + fn walk_list_comp(&mut self, list_comp: &'ctx ast::ListComp) -> Self::Result { + let start = list_comp.elt.get_pos(); + let stack_depth = self.switch_list_expr_context(); + let end = match list_comp.generators.last() { + Some(last) => last.get_end_pos(), + None => list_comp.elt.get_end_pos(), + }; + self.enter_scope(start.clone(), end, ScopeKind::Loop); + for comp_clause in &list_comp.generators { + self.walk_comp_clause(&comp_clause.node); + } + if let ast::Expr::Starred(_) = list_comp.elt.node { + self.handler.add_compile_error( + "list unpacking cannot be used in list comprehension", + list_comp.elt.get_span_pos(), + ); + } + let item_ty = self.expr(&list_comp.elt); + self.leave_scope(); + self.clear_config_expr_context(stack_depth, false); + Type::list_ref(item_ty) + } + + fn walk_dict_comp(&mut self, dict_comp: &'ctx ast::DictComp) -> Self::Result { + if dict_comp.entry.key.is_none() { + self.handler.add_compile_error( + "dict unpacking cannot be used in dict comprehension", + dict_comp.entry.value.get_span_pos(), + ); + let start = dict_comp.entry.value.get_pos(); + let end = match dict_comp.generators.last() { + Some(last) => last.get_end_pos(), + None => dict_comp.entry.value.get_end_pos(), + }; + self.enter_scope(start.clone(), end, ScopeKind::Loop); + for comp_clause in &dict_comp.generators { + self.walk_comp_clause(&comp_clause.node); + } + let stack_depth = self.switch_config_expr_context_by_key(&dict_comp.entry.key); + let val_ty = self.expr(&dict_comp.entry.value); + let key_ty = match &val_ty.kind { + TypeKind::None | TypeKind::Any => val_ty.clone(), + TypeKind::Dict(DictType { key_ty, .. }) => key_ty.clone(), + TypeKind::Schema(schema_ty) => schema_ty.key_ty().clone(), + TypeKind::Union(types) + if self + .ctx + .ty_ctx + .is_config_type_or_config_union_type(val_ty.clone()) => + { + sup(&types + .iter() + .map(|ty| ty.config_key_ty()) + .collect::>()) + } + _ => { + self.handler.add_compile_error( + &format!( + "only dict and schema can be used ** unpack, got '{}'", + val_ty.ty_str() + ), + dict_comp.entry.value.get_span_pos(), + ); + self.any_ty() + } + }; + self.clear_config_expr_context(stack_depth, false); + self.leave_scope(); + Type::dict_ref(key_ty, val_ty) + } else { + let key = dict_comp.entry.key.as_ref().unwrap(); + let end = match dict_comp.generators.last() { + Some(last) => last.get_end_pos(), + None => dict_comp.entry.value.get_end_pos(), + }; + let start = key.get_pos(); + self.enter_scope(start.clone(), end, ScopeKind::Loop); + for comp_clause in &dict_comp.generators { + self.walk_comp_clause(&comp_clause.node); + } + let key_ty = self.expr(key); + self.check_attr_ty(&key_ty, key.get_span_pos()); + let stack_depth = self.switch_config_expr_context_by_key(&dict_comp.entry.key); + let val_ty = self.expr(&dict_comp.entry.value); + self.clear_config_expr_context(stack_depth, false); + self.leave_scope(); + Type::dict_ref(key_ty, val_ty) + } + } + + fn walk_list_if_item_expr( + &mut self, + list_if_item_expr: &'ctx ast::ListIfItemExpr, + ) -> Self::Result { + self.expr(&list_if_item_expr.if_cond); + let mut or_else_ty = self.expr_or_any_type(&list_if_item_expr.orelse); + // `orelse` node maybe a list unpack node, use its item type instead. + if let TypeKind::List(item_ty) = &or_else_ty.kind { + or_else_ty = item_ty.clone(); + } + let exprs_ty = sup(&self.exprs(&list_if_item_expr.exprs).to_vec()); + sup(&[or_else_ty, exprs_ty]) + } + + fn walk_starred_expr(&mut self, starred_expr: &'ctx ast::StarredExpr) -> Self::Result { + let value_ty = self.expr(&starred_expr.value); + fn starred_ty_walk_fn(ty: &TypeRef) -> (TypeRef, bool) { + match &ty.kind { + TypeKind::None | TypeKind::Any => (ty.clone(), true), + TypeKind::List(item_ty) => (item_ty.clone(), true), + TypeKind::Dict(DictType { key_ty, .. }) => (key_ty.clone(), true), + TypeKind::Schema(schema_ty) => (schema_ty.key_ty(), true), + TypeKind::Union(types) => { + let results = types + .iter() + .map(starred_ty_walk_fn) + .collect::>(); + ( + sup(&results + .iter() + .map(|(ty, _)| ty) + .cloned() + .collect::>()), + results.iter().all(|(_, r)| *r), + ) + } + _ => (Arc::new(Type::ANY), false), + } + } + let (ty, result) = starred_ty_walk_fn(&value_ty); + if !result { + self.handler.add_compile_error( + &format!( + "only list, dict, schema object can be used * unpacked, got {}", + ty.ty_str() + ), + starred_expr.value.get_span_pos(), + ); + } + ty + } + + fn walk_config_if_entry_expr( + &mut self, + config_if_entry_expr: &'ctx ast::ConfigIfEntryExpr, + ) -> Self::Result { + self.expr(&config_if_entry_expr.if_cond); + let dict_ty = self.walk_config_entries(&config_if_entry_expr.items); + if let Some(orelse) = &config_if_entry_expr.orelse { + let or_else_ty = self.expr(orelse); + sup(&[dict_ty, or_else_ty]) + } else { + dict_ty + } + } + + fn walk_comp_clause(&mut self, comp_clause: &'ctx ast::CompClause) -> Self::Result { + let iter_ty = self.expr(&comp_clause.iter); + let (mut key_name, mut val_name) = (None, None); + let mut prev_target_pos = None; + for (i, target) in comp_clause.targets.iter().enumerate() { + if target.node.names.is_empty() { + continue; + } + if target.node.names.len() > 1 { + self.handler.add_compile_error( + "loop variables can only be ordinary identifiers", + target.get_span_pos(), + ); + } + let name = &target.node.names[0]; + if i == 0 { + key_name = Some(name); + } else if i == 1 { + val_name = Some(name); + } else { + let previous_pos = if let Some(prev_pos) = prev_target_pos { + prev_pos + } else { + target.get_end_pos() + }; + self.handler.add_compile_error_with_suggestions( + &format!( + "the number of loop variables is {}, which can only be 1 or 2", + comp_clause.targets.len() + ), + (previous_pos, target.get_end_pos()), + Some(vec![]), + ); + break; + } + self.ctx.local_vars.push(name.node.to_string()); + let (start, end) = target.get_span_pos(); + self.insert_object( + &name.node, + ScopeObject { + name: name.node.to_string(), + start, + end, + ty: self.any_ty(), + kind: ScopeObjectKind::Variable, + doc: None, + }, + ); + prev_target_pos = Some(target.get_end_pos()); + } + if iter_ty.is_any() { + self.exprs(&comp_clause.ifs); + iter_ty + } else { + self.do_loop_type_check(key_name, val_name, iter_ty, comp_clause.iter.get_span_pos()); + self.exprs(&comp_clause.ifs); + self.any_ty() + } + } + + fn walk_schema_expr(&mut self, schema_expr: &'ctx ast::SchemaExpr) -> Self::Result { + let def_ty = self.walk_identifier_expr(&schema_expr.name); + if !matches!(&schema_expr.config.node, ast::Expr::Config(_)) { + self.handler.add_compile_error( + "Invalid schema config expr, expect config entries, e.g., {k1 = v1, k2 = v2}", + schema_expr.config.get_span_pos(), + ); + } + let mut range = schema_expr.name.get_span_pos(); + let ret_ty = match &def_ty.kind { + TypeKind::Dict(DictType { .. }) => { + let obj = self.new_config_expr_context_item( + "", + def_ty.clone(), + Position::dummy_pos(), + Position::dummy_pos(), + ); + let init_stack_depth = self.switch_config_expr_context(Some(obj)); + let config_ty = self.expr(&schema_expr.config); + self.clear_config_expr_context(init_stack_depth as usize, false); + self.binary(def_ty.clone(), config_ty, &ast::BinOp::BitOr, range) + } + TypeKind::Schema(schema_ty) => { + if !schema_ty.is_instance { + let name = schema_expr.name.node.get_name(); + if !self.ctx.local_vars.contains(&name) { + let ty_annotation_str = ty_str_replace_pkgpath( + &def_ty.into_type_annotation_str(), + &self.ctx.pkgpath, + ); + self.add_type_alias(&name, &ty_annotation_str); + } + } + let obj = self.new_config_expr_context_item( + &schema_ty.name, + def_ty.clone(), + Position::dummy_pos(), + Position::dummy_pos(), + ); + let init_stack_depth = self.switch_config_expr_context(Some(obj)); + self.expr(&schema_expr.config); + self.node_ty_map.borrow_mut().insert( + self.get_node_key(schema_expr.config.id.clone()), + def_ty.clone(), + ); + self.clear_config_expr_context(init_stack_depth as usize, false); + if schema_ty.is_instance { + if !schema_expr.args.is_empty() || !schema_expr.kwargs.is_empty() { + self.handler.add_compile_error( + "Arguments cannot be used in the schema modification expression", + range, + ); + } + } else { + let func = Box::new(ast::Node::node_with_pos( + ast::Expr::Identifier(schema_expr.name.node.clone()), + schema_expr.name.pos(), + )); + self.do_arguments_type_check( + &func, + &schema_expr.args, + &schema_expr.kwargs, + &schema_ty.func, + ); + } + self.any_ty() + } + TypeKind::Any => { + return self.any_ty(); + } + _ => { + range.0.filename = self.ctx.filename.clone(); + range.1.filename = self.ctx.filename.clone(); + self.handler.add_compile_error( + &format!("Invalid schema type '{}'", def_ty.ty_str()), + range, + ); + return self.any_ty(); + } + }; + let mut def_ty_clone = def_ty.as_ref().clone(); + if let TypeKind::Schema(schema_ty) = &mut def_ty_clone.kind { + schema_ty.is_instance = true; + } + if def_ty_clone.is_schema() { + Arc::new(def_ty_clone) + } else { + ret_ty + } + } + + fn walk_config_expr(&mut self, config_expr: &'ctx ast::ConfigExpr) -> Self::Result { + self.walk_config_entries(&config_expr.items) + } + + fn walk_check_expr(&mut self, check_expr: &'ctx ast::CheckExpr) -> Self::Result { + if let Some(msg) = &check_expr.msg { + self.must_be_type(msg, self.str_ty()); + } + // Check type in if_cond expression + self.expr_or_any_type(&check_expr.if_cond); + self.expr(&check_expr.test) + } + + fn walk_lambda_expr(&mut self, lambda_expr: &'ctx ast::LambdaExpr) -> Self::Result { + let mut ret_ty = self.any_ty(); + let mut params = vec![]; + self.do_parameters_check(&lambda_expr.args); + if let Some(args) = &lambda_expr.args { + for (i, arg) in args.node.args.iter().enumerate() { + let name = arg.node.get_name(); + let arg_ty = args.node.get_arg_type_node(i); + let range = match arg_ty { + Some(arg_type_node) => arg_type_node.get_span_pos(), + None => arg.get_span_pos(), + }; + let ty = self.parse_ty_with_scope(arg_ty, range); + + // If the arguments type of a lambda is a schema type, + // It should be marked as an schema instance type. + let ty = if let TypeKind::Schema(sty) = &ty.kind { + let mut arg_ty = sty.clone(); + arg_ty.is_instance = true; + Arc::new(Type::schema(arg_ty)) + } else { + ty.clone() + }; + if let Some(name) = arg.node.names.last() { + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(name.id.clone()), ty.clone()); + } + + let value = &args.node.defaults[i]; + params.push(Parameter { + name, + ty: ty.clone(), + has_default: value.is_some(), + default_value: value.as_ref().map(|v| print_ast_node(ASTNode::Expr(v))), + range: args.node.args[i].get_span_pos(), + }); + self.expr_or_any_type(value); + } + } + let (start, end) = (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()); + if let Some(ret_annotation_ty) = &lambda_expr.return_ty { + ret_ty = + self.parse_ty_with_scope(Some(&ret_annotation_ty), (start.clone(), end.clone())); + } + self.enter_scope(start.clone(), end.clone(), ScopeKind::Lambda); + self.ctx.in_lambda_expr.push(true); + // Lambda parameters + for param in ¶ms { + self.insert_object( + ¶m.name, + ScopeObject { + name: param.name.clone(), + start: start.clone(), + end: end.clone(), + ty: param.ty.clone(), + kind: ScopeObjectKind::Parameter, + doc: None, + }, + ) + } + if let Some(stmt) = lambda_expr.body.last() { + if !matches!( + stmt.node, + ast::Stmt::Expr(_) + | ast::Stmt::Assign(_) + | ast::Stmt::AugAssign(_) + | ast::Stmt::Assert(_) + ) { + self.handler.add_compile_error( + "The last statement of the lambda body must be a expression e.g., x, 1, etc.", + stmt.get_span_pos(), + ); + } + } + // Walk lambda body statements except the last statement. + if lambda_expr.body.len() > 1 { + self.stmts(&lambda_expr.body[..lambda_expr.body.len() - 1]); + } + // Upgrade return value type to schema if return type is schema + let real_ret_ty = if let Some(stmt) = lambda_expr.body.last() { + if let ast::Stmt::Expr(expr_stmt) = &stmt.node { + if let Some(expr) = expr_stmt.exprs.last() { + self.upgrade_type_for_expr( + ret_ty.clone(), + expr, + expr.get_span_pos(), + lambda_expr.return_ty.as_ref().map(|ty| ty.get_span_pos()), + ) + } else { + let real_ret_ty = self.stmt(stmt); + self.must_assignable_to( + real_ret_ty.clone(), + ret_ty.clone(), + (start, end), + None, + ); + real_ret_ty + } + } else { + let real_ret_ty = self.stmt(stmt); + self.must_assignable_to(real_ret_ty.clone(), ret_ty.clone(), (start, end), None); + real_ret_ty + } + } else { + self.any_ty() + }; + // Leave the lambda scope. + self.leave_scope(); + self.ctx.in_lambda_expr.pop(); + + if !real_ret_ty.is_any() && ret_ty.is_any() && lambda_expr.return_ty.is_none() { + ret_ty = real_ret_ty; + } + let doc = extract_doc_from_body(&lambda_expr.body); + Arc::new(Type::function( + None, + ret_ty, + ¶ms, + &doc.unwrap_or_default(), + false, + None, + )) + } + + fn walk_keyword(&mut self, keyword: &'ctx ast::Keyword) -> Self::Result { + self.walk_identifier_expr(&keyword.arg); + self.expr_or_any_type(&keyword.value) + } + + fn walk_arguments(&mut self, arguments: &'ctx ast::Arguments) -> Self::Result { + for (i, arg) in arguments.args.iter().enumerate() { + let ty = arguments.get_arg_type_node(i); + let ty = self.parse_ty_with_scope(ty, arg.get_span_pos()); + if let Some(name) = arg.node.names.last() { + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(name.id.clone()), ty.clone()); + } + let value = &arguments.defaults[i]; + self.expr_or_any_type(value); + } + self.any_ty() + } + + fn walk_compare(&mut self, compare: &'ctx ast::Compare) -> Self::Result { + let t1 = self.expr(&compare.left); + let t2 = self.expr(&compare.comparators[0]); + self.compare( + t1.clone(), + t2.clone(), + &compare.ops[0], + (compare.left.get_pos(), compare.comparators[0].get_end_pos()), + ); + for i in 1..compare.comparators.len() - 1 { + let op = &compare.ops[i + 1]; + let t2 = self.expr(&compare.comparators[i]); + self.compare( + t1.clone(), + t2.clone(), + op, + compare.comparators[i].get_span_pos(), + ); + } + self.bool_ty() + } + + fn walk_identifier(&mut self, identifier: &'ctx ast::Identifier) -> Self::Result { + let tys = self.resolve_var( + &identifier.get_names(), + &identifier.pkgpath, + (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()), + ); + for (index, name) in identifier.names.iter().enumerate() { + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(name.id.clone()), tys[index].clone()); + } + tys.last().unwrap().clone() + } + + fn walk_target(&mut self, target: &'ctx ast::Target) -> Self::Result { + let tys = self.resolve_target( + &target, + (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()), + ); + if let Some(ty) = tys.first() { + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(target.name.id.clone()), ty.clone()); + } + for (index, name) in target.paths.iter().enumerate() { + self.node_ty_map.borrow_mut().insert( + self.get_node_key(name.id()), + tys.get(index + 1).unwrap_or(&self.any_ty()).clone(), + ); + } + let target_ty = tys.last().unwrap_or(&self.any_ty()).clone(); + target_ty + } + + fn walk_number_lit(&mut self, number_lit: &'ctx ast::NumberLit) -> Self::Result { + match &number_lit.binary_suffix { + Some(binary_suffix) => { + let raw_value = match number_lit.value { + ast::NumberLitValue::Int(int_val) => int_val, + ast::NumberLitValue::Float(float_val) => { + self.handler.add_compile_error( + "float literal can not be followed the unit suffix", + (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()), + ); + float_val as i64 + } + }; + let binary_suffix_str: String = binary_suffix.value(); + let value = kcl_runtime::units::cal_num(raw_value, &binary_suffix_str); + Arc::new(Type::number_multiplier( + value, + raw_value, + &binary_suffix_str, + )) + } + None => match number_lit.value { + ast::NumberLitValue::Int(int_val) => Arc::new(Type::int_lit(int_val)), + ast::NumberLitValue::Float(float_val) => Arc::new(Type::float_lit(float_val)), + }, + } + } + + fn walk_string_lit(&mut self, string_lit: &'ctx ast::StringLit) -> Self::Result { + Arc::new(Type::str_lit(&string_lit.value)) + } + + fn walk_name_constant_lit( + &mut self, + name_constant_lit: &'ctx ast::NameConstantLit, + ) -> Self::Result { + match &name_constant_lit.value { + ast::NameConstant::True => Arc::new(Type::bool_lit(true)), + ast::NameConstant::False => Arc::new(Type::bool_lit(false)), + ast::NameConstant::None | ast::NameConstant::Undefined => self.none_ty(), + } + } + + fn walk_joined_string(&mut self, joined_string: &'ctx ast::JoinedString) -> Self::Result { + self.ctx.l_value = false; + self.exprs(&joined_string.values); + self.str_ty() + } + + fn walk_formatted_value(&mut self, formatted_value: &'ctx ast::FormattedValue) -> Self::Result { + if let Some(spec) = &formatted_value.format_spec { + let spec_lower = spec.to_lowercase(); + if !VALID_FORMAT_SPEC_SET.contains(&spec_lower.as_str()) { + self.handler.add_compile_error( + &format!("{} is a invalid format spec", spec), + formatted_value.value.get_span_pos(), + ); + } + } + self.expr(&formatted_value.value) + } + + fn walk_comment(&mut self, _comment: &'ctx ast::Comment) -> Self::Result { + // Nothing to do. + self.any_ty() + } + + fn walk_missing_expr(&mut self, _missing_expr: &'ctx ast::MissingExpr) -> Self::Result { + // Nothing to do. + self.any_ty() + } +} + +impl<'ctx> Resolver<'_> { + pub fn stmts(&mut self, stmts: &'ctx [ast::NodeRef]) -> ResolvedResult { + let stmt_types: Vec = stmts.iter().map(|stmt| self.stmt(&stmt)).collect(); + match stmt_types.last() { + Some(ty) => ty.clone(), + _ => self.any_ty(), + } + } + + #[inline] + pub fn exprs(&mut self, exprs: &'ctx [ast::NodeRef]) -> Vec { + exprs.iter().map(|expr| self.expr(&expr)).collect() + } + + pub fn expr(&mut self, expr: &'ctx ast::NodeRef) -> ResolvedResult { + if let ast::Expr::Identifier(_) = &expr.node { + let (start, end) = expr.get_span_pos(); + self.ctx.start_pos = start; + self.ctx.end_pos = end; + } + + let expected_ty = match self.ctx.config_expr_context.last() { + Some(ty) => ty.clone().map(|o| o.ty), + None => None, + }; + + let ty = self.walk_expr(&expr.node); + + if let Some(expected_ty) = expected_ty { + let upgrade_ty = self.upgrade_dict_to_schema(ty.clone(), expected_ty); + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(expr.id.clone()), upgrade_ty); + } else { + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(expr.id.clone()), ty.clone()); + } + + ty + } + + pub fn stmt(&mut self, stmt: &'ctx ast::NodeRef) -> ResolvedResult { + let (start, end) = stmt.get_span_pos(); + self.ctx.start_pos = start; + self.ctx.end_pos = end; + let ty = self.walk_stmt(&stmt.node); + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(stmt.id.clone()), ty.clone()); + ty + } + + pub fn expr_or_any_type( + &mut self, + expr: &'ctx Option>, + ) -> ResolvedResult { + match expr { + Some(expr) => { + let ty = self.walk_expr(&expr.node); + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(expr.id.clone()), ty.clone()); + ty + } + None => self.any_ty(), + } + } + + pub fn walk_identifier_expr( + &mut self, + identifier: &'ctx ast::NodeRef, + ) -> ResolvedResult { + let tys = self.resolve_var( + &identifier.node.get_names(), + &identifier.node.pkgpath, + identifier.get_span_pos(), + ); + for (index, name) in identifier.node.names.iter().enumerate() { + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(name.id.clone()), tys[index].clone()); + } + let ident_ty = tys.last().unwrap().clone(); + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(identifier.id.clone()), ident_ty.clone()); + + ident_ty + } + + pub fn walk_target_expr(&mut self, target: &'ctx ast::NodeRef) -> ResolvedResult { + let tys = self.resolve_target(&target.node, target.get_span_pos()); + if let Some(ty) = tys.first() { + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(target.node.name.id.clone()), ty.clone()); + } + for (index, name) in target.node.paths.iter().enumerate() { + self.node_ty_map.borrow_mut().insert( + self.get_node_key(name.id()), + tys.get(index + 1).unwrap_or(&self.any_ty()).clone(), + ); + } + let target_ty = tys.last().unwrap_or(&self.any_ty()).clone(); + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(target.id.clone()), target_ty.clone()); + target_ty + } +} diff --git a/kclvm/sema/src/resolver/para.rs b/crates/sema/src/resolver/para.rs similarity index 94% rename from kclvm/sema/src/resolver/para.rs rename to crates/sema/src/resolver/para.rs index 461def87d..356771a12 100644 --- a/kclvm/sema/src/resolver/para.rs +++ b/crates/sema/src/resolver/para.rs @@ -1,7 +1,7 @@ use crate::resolver::Resolver; -use kclvm_ast::ast; -use kclvm_ast::pos::GetPos; -use kclvm_error::*; +use kcl_ast::ast; +use kcl_ast::pos::GetPos; +use kcl_error::*; impl<'ctx> Resolver<'_> { /// Do parameter type check. diff --git a/crates/sema/src/resolver/schema.rs b/crates/sema/src/resolver/schema.rs new file mode 100644 index 000000000..81b53f612 --- /dev/null +++ b/crates/sema/src/resolver/schema.rs @@ -0,0 +1,332 @@ +use std::cell::RefCell; +use std::collections::HashMap; +use std::rc::Rc; + +use crate::builtin::BUILTIN_DECORATORS; +use crate::resolver::Resolver; +use crate::ty::{Decorator, DecoratorTarget, TypeKind, TypeRef}; +use kcl_ast::ast; +use kcl_ast::pos::GetPos; +use kcl_ast::walker::MutSelfTypedResultWalker; +use kcl_ast_pretty::{ASTNode, print_ast_node}; +use kcl_error::diagnostic::Range; +use kcl_error::{ErrorKind, Message, Position, Style}; + +use super::node::ResolvedResult; +use super::scope::{ScopeKind, ScopeObject, ScopeObjectKind}; + +impl<'ctx> Resolver<'_> { + pub(crate) fn resolve_schema_stmt( + &mut self, + schema_stmt: &'ctx ast::SchemaStmt, + ) -> ResolvedResult { + let (start, end) = (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()); + self.resolve_unique_key(&schema_stmt.name.node, &schema_stmt.name.get_span_pos()); + let ty = + self.lookup_type_from_scope(&schema_stmt.name.node, schema_stmt.name.get_span_pos()); + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(schema_stmt.name.id.clone()), ty.clone()); + let scope_ty = if ty.is_schema() { + ty.into_schema_type() + } else { + self.handler.add_error( + ErrorKind::TypeError, + &[Message { + range: schema_stmt.get_span_pos(), + style: Style::LineAndColumn, + message: format!("expected schema type, got {}", ty.ty_str()), + note: None, + suggested_replacement: None, + }], + ); + return ty; + }; + self.ctx.schema = Some(Rc::new(RefCell::new(scope_ty.clone()))); + if let Some(args) = &schema_stmt.args { + for (i, arg) in args.node.args.iter().enumerate() { + let ty = args.node.get_arg_type_node(i); + let ty = self.parse_ty_with_scope(ty, arg.get_span_pos()); + if let Some(name) = arg.node.names.last() { + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(name.id.clone()), ty.clone()); + } + } + } + self.do_parameters_check(&schema_stmt.args); + self.enter_scope( + start.clone(), + end.clone(), + ScopeKind::Schema(schema_stmt.name.node.to_string()), + ); + for param in &scope_ty.func.params { + self.insert_object( + ¶m.name, + ScopeObject { + name: param.name.clone(), + start: start.clone(), + end: end.clone(), + ty: param.ty.clone(), + kind: ScopeObjectKind::Parameter, + doc: None, + }, + ) + } + // Schema index signature + if let (Some(index_signature), Some(index_signature_node)) = + (scope_ty.index_signature, &schema_stmt.index_signature) + { + // Insert the schema index signature key name into the scope. + if let Some(key_name) = index_signature.key_name { + let (start, end) = index_signature_node.get_span_pos(); + self.insert_object( + &key_name, + ScopeObject { + name: key_name.clone(), + start, + end, + ty: index_signature.key_ty.clone(), + kind: ScopeObjectKind::Variable, + doc: None, + }, + ) + } + // Check index signature default value type. + if let Some(value) = &index_signature_node.node.value { + let expected_ty = index_signature.val_ty; + let value_ty = if let TypeKind::Schema(ty) = &expected_ty.kind { + let (start, end) = value.get_span_pos(); + let obj = self.new_config_expr_context_item( + &ty.name, + expected_ty.clone(), + start, + end, + ); + let init_stack_depth = self.switch_config_expr_context(Some(obj)); + let value_ty = self.expr(value); + self.clear_config_expr_context(init_stack_depth as usize, false); + value_ty + } else { + self.expr(value) + }; + self.must_assignable_to( + value_ty, + expected_ty, + index_signature_node.get_span_pos(), + None, + ); + } + } + let schema_attr_names = schema_stmt.get_left_identifier_list(); + for (line, column, name) in schema_attr_names { + if !self.contains_object(&name) { + self.insert_object( + &name, + ScopeObject { + name: name.clone(), + start: Position { + filename: self.ctx.filename.clone(), + line, + column: Some(column), + }, + end: Position::dummy_pos(), + ty: self.any_ty(), + kind: ScopeObjectKind::Variable, + doc: None, + }, + ); + } + } + // Schema body. + self.stmts(&schema_stmt.body); + // Schema check blocks. + for check_expr in &schema_stmt.checks { + self.walk_check_expr(&check_expr.node); + } + self.leave_scope(); + self.ctx.schema = None; + ty + } + + pub(crate) fn resolve_rule_stmt(&mut self, rule_stmt: &'ctx ast::RuleStmt) -> ResolvedResult { + self.resolve_unique_key(&rule_stmt.name.node, &rule_stmt.name.get_span_pos()); + let ty = self.lookup_type_from_scope(&rule_stmt.name.node, rule_stmt.name.get_span_pos()); + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(rule_stmt.name.id.clone()), ty.clone()); + let scope_ty = if ty.is_schema() { + ty.into_schema_type() + } else { + self.handler.add_error( + ErrorKind::TypeError, + &[Message { + range: rule_stmt.get_span_pos(), + style: Style::LineAndColumn, + message: format!("expected rule type, got {}", ty.ty_str()), + note: None, + suggested_replacement: None, + }], + ); + return ty; + }; + self.ctx.schema = Some(Rc::new(RefCell::new(scope_ty.clone()))); + let (start, end) = rule_stmt.get_span_pos(); + self.do_parameters_check(&rule_stmt.args); + self.enter_scope( + start.clone(), + end.clone(), + ScopeKind::Schema(rule_stmt.name.node.to_string()), + ); + for param in &scope_ty.func.params { + self.insert_object( + ¶m.name, + ScopeObject { + name: param.name.clone(), + start: start.clone(), + end: end.clone(), + ty: param.ty.clone(), + kind: ScopeObjectKind::Parameter, + doc: None, + }, + ) + } + // Rule check blocks. + for check_expr in &rule_stmt.checks { + self.walk_check_expr(&check_expr.node); + } + self.leave_scope(); + self.ctx.schema = None; + ty + } + + pub(crate) fn resolve_decorators( + &mut self, + decorators: &'ctx [ast::NodeRef], + target: DecoratorTarget, + key: &str, + ) -> Vec { + let mut decorator_objs = vec![]; + for decorator in decorators { + let name = if let ast::Expr::Identifier(identifier) = &decorator.node.func.node { + if identifier.names.len() == 1 { + Some(identifier.names[0].node.clone()) + } else { + None + } + } else { + None + }; + match name { + Some(name) => match BUILTIN_DECORATORS.get(&name) { + Some(ty) => match &ty.kind { + TypeKind::Function(func_ty) => { + self.do_arguments_type_check( + &decorator.node.func, + &decorator.node.args, + &decorator.node.keywords, + &func_ty, + ); + let (arguments, keywords) = self.arguments_to_string( + &decorator.node.args, + &decorator.node.keywords, + ); + decorator_objs.push(Decorator { + target: target.clone(), + name, + key: key.to_string(), + arguments, + keywords, + }) + } + _ => bug!("invalid builtin decorator function type"), + }, + None => { + self.handler.add_compile_error_with_suggestions( + &format!("UnKnown decorator {}", name), + decorator.get_span_pos(), + Some(vec![]), + ); + } + }, + None => { + self.handler.add_type_error( + "decorator name must be a single identifier", + decorator.get_span_pos(), + ); + } + } + } + decorator_objs + } + + /// Walk expr and check the type and return the value type. + pub(crate) fn upgrade_type_for_expr( + &mut self, + expected_ty: TypeRef, + expr: &'ctx ast::NodeRef, + target_range: Range, + def_range: Option, + ) -> TypeRef { + let (start, end) = expr.get_span_pos(); + let value_ty = match &expected_ty.kind { + TypeKind::Schema(ty) => { + let obj = + self.new_config_expr_context_item(&ty.name, expected_ty.clone(), start, end); + let init_stack_depth = self.switch_config_expr_context(Some(obj)); + let value_ty = self.expr(expr); + self.clear_config_expr_context(init_stack_depth as usize, false); + value_ty + } + TypeKind::List(_) | TypeKind::Dict(_) | TypeKind::Union(_) => { + let obj = self.new_config_expr_context_item("[]", expected_ty.clone(), start, end); + let init_stack_depth = self.switch_config_expr_context(Some(obj)); + let value_ty = self.expr(expr); + self.clear_config_expr_context(init_stack_depth as usize, false); + value_ty + } + _ => { + self.ctx.config_expr_context.push(None); + let value_ty = self.expr(expr); + self.ctx.config_expr_context.pop(); + value_ty + } + }; + self.must_assignable_to( + value_ty.clone(), + expected_ty.clone(), + target_range, + def_range, + ); + value_ty + } + + fn arguments_to_string( + &mut self, + args: &'ctx [ast::NodeRef], + kwargs: &'ctx [ast::NodeRef], + ) -> (Vec, HashMap) { + if self.options.resolve_val { + ( + args.iter() + .map(|a| print_ast_node(ASTNode::Expr(a))) + .collect(), + kwargs + .iter() + .map(|a| { + ( + a.node.arg.node.get_name(), + a.node + .value + .as_ref() + .map(|v| print_ast_node(ASTNode::Expr(v))) + .unwrap_or_default(), + ) + }) + .collect(), + ) + } else { + (vec![], HashMap::new()) + } + } +} diff --git a/crates/sema/src/resolver/scope.rs b/crates/sema/src/resolver/scope.rs new file mode 100644 index 000000000..8dbefaa64 --- /dev/null +++ b/crates/sema/src/resolver/scope.rs @@ -0,0 +1,773 @@ +use anyhow::bail; +use compiler_base_session::Session; +use kcl_ast::ast::NodeRef; +use kcl_ast::ast::Stmt; +use kcl_ast::ast::Stmt::Import; +use kcl_ast::{MAIN_PKG, ast}; +use kcl_error::diagnostic::Range; +use kcl_error::{Handler, Level}; +use kcl_primitives::DefaultHashBuilder; +use kcl_primitives::{IndexMap, IndexSet}; +use std::collections::HashMap; +use std::collections::HashSet; +use std::collections::VecDeque; +use std::sync::Arc; +use std::{ + cell::RefCell, + rc::{Rc, Weak}, +}; + +use crate::resolver::Resolver; +use crate::ty::SchemaType; +use crate::ty::TypeRef; +use crate::{builtin::BUILTIN_FUNCTIONS, ty::TypeInferMethods}; +use kcl_ast::ast::AstIndex; +use kcl_ast::pos::ContainsPos; +use kcl_ast::pos::GetPos; +use kcl_error::Position; +use parking_lot::RwLock; +use serde::Serialize; + +/// The object stored in the scope. +#[derive(PartialEq, Clone, Debug)] +pub struct ScopeObject { + /// The scope object name. + pub name: String, + /// The scope object start position. + pub start: Position, + /// The scope object end position. + pub end: Position, + /// The type of the scope object. + pub ty: TypeRef, + /// The scope object kind. + pub kind: ScopeObjectKind, + /// The doc of the scope object, will be None unless the scope object represents a schema or schema attribute. + pub doc: Option, +} + +impl ScopeObject { + /// Positions of the scope object are valid. + #[inline] + pub fn pos_is_valid(&self) -> bool { + self.start.is_valid() && self.end.is_valid() + } +} + +impl ContainsPos for ScopeObject { + fn contains_pos(&self, pos: &Position) -> bool { + self.start.less_equal(pos) && pos.less_equal(&self.end) + } +} + +impl GetPos for ScopeObject { + fn get_span_pos(&self) -> Range { + (self.start.clone(), self.end.clone()) + } + fn get_pos(&self) -> Position { + self.start.clone() + } + + fn get_end_pos(&self) -> Position { + self.end.clone() + } +} + +#[derive(PartialEq, Clone, Debug)] +pub enum ScopeObjectKind { + Variable, + Attribute, + Definition, + Parameter, + TypeAlias, + FunctionCall, + Module(Module), +} + +/// A scope object of module type represents an import stmt on an AST and +/// is used to record information on the AST +#[derive(PartialEq, Clone, Debug)] +pub struct Module { + /// Record stmts which import this module and whether has been used, for check unused imported module and var definition + pub import_stmts: Vec<(NodeRef, bool)>, +} + +/// A Scope maintains a set of objects and links to its containing +/// (parent) and contained (children) scopes. Objects may be inserted +/// and looked up by name. The zero value for Scope is a ready-to-use +/// empty scope. +#[derive(Clone, Debug)] +pub struct Scope { + /// The parent scope. + pub parent: Option>>, + /// The child scope list. + pub children: Vec>>, + /// The scope object mapping with its name. + pub elems: IndexMap>>, + /// The scope start position. + pub start: Position, + /// The scope end position. + pub end: Position, + /// The scope kind. + pub kind: ScopeKind, +} + +impl Scope { + /// Lookup the scope object recursively with the name. + pub fn lookup(&self, name: &str) -> Option>> { + match self.elems.get(name) { + Some(obj) => Some(obj.clone()), + None => match &self.parent { + Some(parent) => match parent.upgrade() { + Some(parent) => { + let parent = parent.borrow(); + parent.lookup(name) + } + None => None, + }, + None => None, + }, + } + } + + /// Get all usable scope objects in current and parent scope. + pub fn all_usable_objects(&self) -> IndexMap>> { + let mut res = match &self.parent { + Some(parent) => match parent.upgrade() { + Some(parent) => parent.borrow().all_usable_objects(), + None => IndexMap::with_hasher(DefaultHashBuilder::default()), + }, + None => IndexMap::with_hasher(DefaultHashBuilder::default()), + }; + + for (name, obj) in &self.elems { + match &obj.borrow().kind { + ScopeObjectKind::Module(module) => { + for stmt in &module.import_stmts { + if let Import(import_stmt) = &stmt.0.node { + res.insert(import_stmt.name.clone(), obj.clone()); + } + } + } + _ => { + res.insert(name.clone(), obj.clone()); + } + } + } + res + } + + /// Set a type by name to existed object, return true if found. + pub fn set_ty(&mut self, name: &str, ty: TypeRef) -> bool { + match self.elems.get_mut(name) { + Some(obj) => { + let mut obj = obj.borrow_mut(); + obj.ty = ty; + true + } + None => false, + } + } +} + +impl ContainsPos for Scope { + /// Check if current scope contains a position + fn contains_pos(&self, pos: &Position) -> bool { + match &self.kind { + ScopeKind::Package(files) => files.contains(&pos.filename), + _ => self.start.less_equal(pos) && pos.less_equal(&self.end), + } + } +} + +#[derive(Clone, Debug)] +pub enum ScopeKind { + /// Package scope. + Package(IndexSet), + /// Builtin scope. + Builtin, + /// Schema name string. + Schema(String), + /// Loop scope. + Loop, + /// Condition statement. + CondStmt, + /// Lambda expression. + Lambda, + /// Config expression + Config, +} + +impl Scope { + /// Check if current scope contains a position on the AST statement. + pub fn contains_pos_on_stmt(&self, pos: &Position, stmt: &ast::Node) -> bool { + match &stmt.node { + ast::Stmt::Schema(schema) => { + schema.body.iter().any(|n| n.contains_pos(pos)) + || schema.checks.iter().any(|n| n.contains_pos(pos)) + || schema + .index_signature + .as_ref() + .map(|n| n.contains_pos(pos)) + .is_some() + } + ast::Stmt::Rule(rule) => rule.checks.iter().any(|n| n.contains_pos(pos)), + _ => self.contains_pos(pos), + } + } + /// Returns the inner most scope on the position. + pub fn inner_most(&self, pos: &Position) -> Option { + // Builtin scope + if self.parent.is_none() { + for child in self.children.iter() { + let child = child.borrow(); + if child.contains_pos(pos) { + return child.inner_most(pos); + } + } + return None; + } + // self is not BUILTIN_SCOPE + if self.contains_pos(pos) { + for child in self.children.iter() { + let child = child.borrow(); + if child.contains_pos(pos) { + return child.inner_most(pos); + } + } + return Some(self.clone()); + } + None + } + + /// Get the enclosing scope + #[inline] + pub fn get_enclosing_scope(&self) -> Option>> { + self.parent.as_ref().map(|scope| scope.upgrade().unwrap()) + } + + /// Search child scope by the scope name. + pub fn search_child_scope_by_name(&self, name: &str) -> Option>> { + match self.elems.get(name) { + Some(_) => { + for child in self.children.iter() { + let child_ref = child.borrow(); + if let ScopeKind::Schema(schema_name) = &child_ref.kind { + if name == schema_name { + return Some(Rc::clone(child)); + } + } + } + None + } + None => None, + } + } + + /// Search scope obj by the object name. + pub fn search_obj_by_name(&self, name: &str) -> Vec { + let mut res = vec![]; + for (obj_name, obj) in &self.elems { + if obj_name == name { + res.push(obj.borrow().clone()) + } + } + for c in &self.children { + let c = c.borrow(); + let mut objs = c.search_obj_by_name(name); + res.append(&mut objs); + } + res + } +} + +/// Program scope is scope contains a multiple scopes related to the +/// package path. +#[derive(Clone, Debug, Default)] +pub struct ProgramScope { + pub scope_map: IndexMap>>, + pub import_names: IndexMap>, + pub schema_mapping: IndexMap>>, + pub node_ty_map: Rc>, + pub handler: Handler, +} + +unsafe impl Send for ProgramScope {} + +unsafe impl Send for Scope {} +unsafe impl Sync for Scope {} + +impl ProgramScope { + /// Get all package paths. + #[inline] + pub fn pkgpaths(&self) -> Vec { + self.scope_map.keys().cloned().collect::>() + } + + /// Get the scope in the main package. + #[inline] + pub fn main_scope(&self) -> Option<&Rc>> { + self.scope_map.get(MAIN_PKG) + } + + /// Return diagnostic pretty string but do not abort if the session exists any diagnostic. + pub fn emit_diagnostics_to_string( + &self, + sess: Arc, + include_warning: bool, + ) -> Result<(), String> { + let emit_error = || -> anyhow::Result<()> { + // Add resolve errors into the session + for diag in &self.handler.diagnostics { + if matches!(diag.level, Level::Error) || matches!(diag.level, Level::Suggestions) { + sess.add_err(diag.clone())?; + } + if include_warning && matches!(diag.level, Level::Warning) { + sess.add_err(diag.clone())?; + } + } + // If has syntax and resolve errors, return its string format. + if sess.diag_handler.has_errors()? { + let errors = sess.emit_all_diags_into_string()?; + let mut error_strings = vec![]; + for error in errors { + error_strings.push(error?); + } + bail!(error_strings.join("\n")) + } else { + Ok(()) + } + }; + emit_error().map_err(|e| e.to_string()) + } + + /// Returns the inner most scope on the position. + pub fn inner_most_scope(&self, pos: &Position) -> Option { + for (_, scope) in &self.scope_map { + match scope.borrow().inner_most(&pos) { + Some(scope) => return Some(scope), + None => continue, + } + } + None + } +} + +/// Construct a builtin scope +pub fn builtin_scope() -> Scope { + let mut elems = IndexMap::default(); + for (name, builtin_func) in BUILTIN_FUNCTIONS.iter() { + elems.insert( + name.to_string(), + Rc::new(RefCell::new(ScopeObject { + name: name.to_string(), + start: Position::dummy_pos(), + end: Position::dummy_pos(), + ty: Arc::new(builtin_func.clone()), + kind: ScopeObjectKind::Definition, + doc: None, + })), + ); + } + Scope { + parent: None, + children: vec![], + elems, + start: Position::dummy_pos(), + end: Position::dummy_pos(), + kind: ScopeKind::Builtin, + } +} + +impl<'ctx> Resolver<'ctx> { + /// Enter scope such as schema statement, for loop expressions. + pub fn enter_scope(&mut self, start: Position, end: Position, kind: ScopeKind) { + let scope = Scope { + parent: Some(Rc::downgrade(&self.scope)), + children: vec![], + elems: IndexMap::default(), + start, + end, + kind, + }; + let scope = Rc::new(RefCell::new(scope)); + { + // Borrow self.scope + let mut scope_ref = self.scope.borrow_mut(); + let children = &mut scope_ref.children; + children.push(Rc::clone(&scope)); + // Deref self.scope + } + self.scope_level += 1; + self.scope = Rc::clone(&scope); + } + + /// Leave scope. + pub fn leave_scope(&mut self) { + self.ctx.local_vars.clear(); + let parent = match &self.scope.borrow().parent { + Some(parent) => parent.upgrade().unwrap(), + None => bug!("the scope parent is empty, can't leave the scope"), + }; + self.scope_level -= 1; + self.scope = Rc::clone(&parent); + } + + /// Find scope object type by name. + #[inline] + pub fn find_type_in_scope(&mut self, name: &str) -> Option { + self.scope + .borrow() + .lookup(name) + .map(|obj| obj.borrow().ty.clone()) + } + + /// Lookup type from the scope by name, if not found, emit a compile error and + /// return the any type. + pub fn lookup_type_from_scope(&mut self, name: &str, range: Range) -> TypeRef { + match self.find_type_in_scope(name) { + Some(ty) => ty, + None => { + let mut suggestion = String::new(); + let names = self + .scope + .borrow() + .all_usable_objects() + .keys() + .cloned() + .collect::>(); + let suggs = suggestions::provide_suggestions(name, &names); + if suggs.len() > 0 { + suggestion = format!(", did you mean '{:?}'?", suggs); + } + self.handler.add_compile_error_with_suggestions( + &format!( + "name '{}' is not defined{}", + name.replace('@', ""), + suggestion + ), + range, + Some(suggs.clone()), + ); + self.any_ty() + } + } + } + + /// Set type to the scope exited object, if not found, emit a compile error. + pub fn set_infer_type_to_scope(&mut self, name: &str, ty: TypeRef, node: &ast::Node) { + let mut scope = self.scope.borrow_mut(); + match scope.elems.get_mut(name) { + Some(obj) => { + let mut obj = obj.borrow_mut(); + let infer_ty = self.ctx.ty_ctx.infer_to_variable_type(ty); + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(node.id.clone()), infer_ty.clone()); + obj.ty = infer_ty; + } + None => { + self.handler.add_compile_error( + &format!("name '{}' is not defined", name.replace('@', "")), + node.get_span_pos(), + ); + } + } + } + + /// Set type to the scope exited object, if not found, emit a compile error. + pub fn set_type_to_scope(&mut self, name: &str, ty: TypeRef, node: &ast::Node) { + let mut scope = self.scope.borrow_mut(); + match scope.elems.get_mut(name) { + Some(obj) => { + let mut obj = obj.borrow_mut(); + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(node.id.clone()), ty.clone()); + obj.ty = ty; + } + None => { + self.handler.add_compile_error( + &format!("name '{}' is not defined", name.replace('@', "")), + node.get_span_pos(), + ); + } + } + } + + /// Insert object into the current scope. + #[inline] + pub fn insert_object(&mut self, name: &str, obj: ScopeObject) { + let mut scope = self.scope.borrow_mut(); + scope + .elems + .insert(name.to_string(), Rc::new(RefCell::new(obj))); + } + + /// Contains object into the current scope. + #[inline] + pub fn contains_object(&mut self, name: &str) -> bool { + self.scope.borrow().elems.contains_key(name) + } + + pub fn get_node_key(&self, id: AstIndex) -> NodeKey { + NodeKey { + pkgpath: self.ctx.pkgpath.clone(), + id, + } + } +} + +#[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize)] +pub struct NodeKey { + pub pkgpath: String, + pub id: AstIndex, +} + +pub type NodeTyMap = IndexMap; +pub type KCLScopeCache = Arc>; + +/// For CachedScope, we assume that all changed files must be located in kcl_ast::MAIN_PKG , +/// if this is not the case, please clear the cache directly +#[derive(Debug, Clone, Default)] +pub struct CachedScope { + pub program_root: String, + pub scope_map: IndexMap>>, + pub schema_mapping: IndexMap>>, + pub node_ty_map: NodeTyMap, + pub invalidate_pkgs: HashSet, + /// Specify the invalid module in the program packages, used for invalidate_module(). + /// If it is None, all modules in the main package will be invalidated + pub invalidate_pkg_modules: Option>, + dependency_graph: DependencyGraph, +} + +unsafe impl Send for CachedScope {} +unsafe impl Sync for CachedScope {} + +#[derive(Debug, Clone, Default)] +struct DependencyGraph { + /// map filename to pkgpath + pub module_map: HashMap>, + /// map pkgpath to node + pub node_map: HashMap, +} + +impl DependencyGraph { + pub fn clear(&mut self) { + self.module_map.clear(); + self.node_map.clear(); + } + + pub fn update( + &mut self, + program: &ast::Program, + invalidate_pkg_modules: &Option>, + ) -> Result, String> { + let mut new_modules = HashMap::new(); + for (pkgpath, modules) in program.pkgs.iter() { + if pkgpath == kcl_ast::MAIN_PKG { + continue; + } + if !self.node_map.contains_key(pkgpath) { + self.node_map.insert( + pkgpath.to_string(), + DependencyNode { + pkgpath: pkgpath.to_string(), + parents: HashSet::new(), + children: HashSet::new(), + }, + ); + } + for module in modules { + let module = program + .get_module(module) + .expect("Failed to acquire module lock") + .expect(&format!("module {:?} not found in program", module)); + let filename = module.filename.clone(); + if !self.module_map.contains_key(&filename) { + new_modules.insert(filename.clone(), module); + self.module_map.insert(filename.clone(), HashSet::new()); + } + self.module_map + .get_mut(&filename) + .unwrap() + .insert(pkgpath.to_string()); + } + } + + for new_module in new_modules.values() { + self.add_new_module(new_module); + } + + let mut invalidated_set = HashSet::new(); + + match invalidate_pkg_modules { + Some(modules) => { + for module_name in modules { + let result = self.invalidate_module(module_name)?; + for pkg in result { + invalidated_set.insert(pkg); + } + self.remove_dependency_from_pkg(&module_name); + if let Ok(m) = program.get_module(module_name) { + if let Some(module) = m { + self.add_new_module(&module); + } + } + } + } + None => { + if let Some(main_modules) = program.pkgs.get(kcl_ast::MAIN_PKG) { + for module in main_modules { + let module = program + .get_module(module) + .expect("Failed to acquire module lock") + .expect(&format!("module {:?} not found in program", module)); + let result = self.invalidate_module(&module.filename)?; + for pkg in result { + invalidated_set.insert(pkg); + } + self.remove_dependency_from_pkg(&module.filename); + self.add_new_module(&module); + } + } + } + } + Ok(invalidated_set) + } + + fn add_new_module(&mut self, new_module: &ast::Module) { + let module_file = new_module.filename.clone(); + if let Some(pkgpaths) = self.module_map.get(&module_file) { + for stmt in &new_module.body { + if let ast::Stmt::Import(import_stmt) = &stmt.node { + let parent_pkg = &import_stmt.path.node; + if let Some(parent_node) = self.node_map.get_mut(parent_pkg) { + parent_node.children.insert(new_module.filename.clone()); + } + for pkgpath in pkgpaths { + let cur_node = self.node_map.get_mut(pkgpath).unwrap(); + cur_node.parents.insert(parent_pkg.clone()); + } + } + } + } + } + + fn invalidate_module(&mut self, changed_module: &str) -> Result, String> { + let mut invalidated_set = HashSet::new(); + if let Some(pkgpaths) = self.module_map.get(changed_module).cloned() { + let mut pkg_queue = VecDeque::new(); + for pkgpath in pkgpaths.iter() { + pkg_queue.push_back(self.node_map.get(pkgpath)); + } + + let mut old_size: i64 = -1; + while old_size < invalidated_set.len() as i64 { + old_size = invalidated_set.len() as i64; + let cur_node = loop { + match pkg_queue.pop_front() { + Some(cur_node) => match cur_node { + None => continue, + Some(cur_node) => { + if invalidated_set.contains(&cur_node.pkgpath) { + continue; + } + invalidated_set.insert(cur_node.pkgpath.clone()); + break Some(cur_node); + } + }, + None => break None, + } + }; + if let Some(cur_node) = cur_node { + for child in cur_node.children.iter() { + if let Some(child_pkgs) = self.module_map.get(child) { + for child_pkg in child_pkgs { + if invalidated_set.contains(child_pkg) { + continue; + } + pkg_queue.push_back(self.node_map.get(child_pkg)); + } + } + } + } + } + }; + Ok(invalidated_set) + } + + fn remove_dependency_from_pkg(&mut self, filename: &str) { + if let Some(pkgpaths) = self.module_map.get(filename).cloned() { + for pkgpath in pkgpaths { + if let Some(node) = self.node_map.get(&pkgpath).cloned() { + for parent in node.parents { + if let Some(parent_node) = self.node_map.get_mut(&parent) { + parent_node.children.remove(filename); + } + } + } + } + } + } +} + +#[derive(Debug, Clone, Default)] +struct DependencyNode { + // The package path of the current node. + pkgpath: String, + // The pkgpath which is imported by this package. + parents: HashSet, + // Files which import this package. + children: HashSet, +} + +impl CachedScope { + pub fn new(scope: &ProgramScope, program: &ast::Program) -> Self { + let mut cached_scope = Self { + program_root: program.root.to_string(), + scope_map: scope.scope_map.clone(), + node_ty_map: scope.node_ty_map.borrow().clone(), + invalidate_pkgs: HashSet::default(), + dependency_graph: DependencyGraph::default(), + schema_mapping: scope.schema_mapping.clone(), + invalidate_pkg_modules: None, + }; + let invalidated_pkgs = cached_scope + .dependency_graph + .update(program, &cached_scope.invalidate_pkg_modules); + cached_scope.invalidate_cache(invalidated_pkgs.as_ref()); + cached_scope + } + + pub fn clear(&mut self) { + self.scope_map.clear(); + self.node_ty_map.clear(); + self.dependency_graph.clear(); + self.invalidate_pkgs.clear(); + self.invalidate_pkg_modules = None; + } + + pub fn invalidate_cache(&mut self, invalidated_pkgs: Result<&HashSet, &String>) { + match invalidated_pkgs { + Ok(invalidated_pkgs) => { + for invalidated_pkg in invalidated_pkgs.iter() { + self.scope_map.swap_remove(invalidated_pkg); + } + self.invalidate_pkgs = invalidated_pkgs.clone(); + } + Err(_) => self.clear(), + } + } + + pub fn update(&mut self, program: &ast::Program) { + if self.program_root != program.root { + self.clear(); + self.program_root = program.root.clone(); + } + let invalidated_pkgs = self + .dependency_graph + .update(program, &self.invalidate_pkg_modules); + self.invalidate_cache(invalidated_pkgs.as_ref()); + } +} diff --git a/kclvm/sema/src/resolver/test_data/annotation_check_assignment.k b/crates/sema/src/resolver/test_data/annotation_check_assignment.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/annotation_check_assignment.k rename to crates/sema/src/resolver/test_data/annotation_check_assignment.k diff --git a/kclvm/sema/src/resolver/test_data/assign.k b/crates/sema/src/resolver/test_data/assign.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/assign.k rename to crates/sema/src/resolver/test_data/assign.k diff --git a/kclvm/sema/src/resolver/test_data/assign_in_lambda.k b/crates/sema/src/resolver/test_data/assign_in_lambda.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/assign_in_lambda.k rename to crates/sema/src/resolver/test_data/assign_in_lambda.k diff --git a/kclvm/sema/src/resolver/test_data/attr_ty_check.k b/crates/sema/src/resolver/test_data/attr_ty_check.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/attr_ty_check.k rename to crates/sema/src/resolver/test_data/attr_ty_check.k diff --git a/kclvm/sema/src/resolver/test_data/cache/a/a.k b/crates/sema/src/resolver/test_data/cache/a/a.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/cache/a/a.k rename to crates/sema/src/resolver/test_data/cache/a/a.k diff --git a/kclvm/sema/src/resolver/test_data/cache/b/b.k b/crates/sema/src/resolver/test_data/cache/b/b.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/cache/b/b.k rename to crates/sema/src/resolver/test_data/cache/b/b.k diff --git a/kclvm/sema/src/resolver/test_data/cache/c/c.k b/crates/sema/src/resolver/test_data/cache/c/c.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/cache/c/c.k rename to crates/sema/src/resolver/test_data/cache/c/c.k diff --git a/kclvm/sema/src/resolver/test_data/cache/main.k b/crates/sema/src/resolver/test_data/cache/main.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/cache/main.k rename to crates/sema/src/resolver/test_data/cache/main.k diff --git a/kclvm/sema/src/resolver/test_data/doc.k b/crates/sema/src/resolver/test_data/doc.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/doc.k rename to crates/sema/src/resolver/test_data/doc.k diff --git a/kclvm/sema/src/resolver/test_data/doc.txt b/crates/sema/src/resolver/test_data/doc.txt similarity index 100% rename from kclvm/sema/src/resolver/test_data/doc.txt rename to crates/sema/src/resolver/test_data/doc.txt diff --git a/kclvm/sema/src/resolver/test_data/function_with_default_values.k b/crates/sema/src/resolver/test_data/function_with_default_values.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/function_with_default_values.k rename to crates/sema/src/resolver/test_data/function_with_default_values.k diff --git a/kclvm/sema/src/resolver/test_data/import_test/a.k b/crates/sema/src/resolver/test_data/import_test/a.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/import_test/a.k rename to crates/sema/src/resolver/test_data/import_test/a.k diff --git a/kclvm/sema/src/resolver/test_data/import_test/b.k b/crates/sema/src/resolver/test_data/import_test/b.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/import_test/b.k rename to crates/sema/src/resolver/test_data/import_test/b.k diff --git a/kclvm/sema/src/resolver/test_data/import_test/c.k b/crates/sema/src/resolver/test_data/import_test/c.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/import_test/c.k rename to crates/sema/src/resolver/test_data/import_test/c.k diff --git a/kclvm/sema/src/resolver/test_data/import_test/d.k b/crates/sema/src/resolver/test_data/import_test/d.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/import_test/d.k rename to crates/sema/src/resolver/test_data/import_test/d.k diff --git a/kclvm/sema/src/resolver/test_data/import_test/e.k b/crates/sema/src/resolver/test_data/import_test/e.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/import_test/e.k rename to crates/sema/src/resolver/test_data/import_test/e.k diff --git a/kclvm/sema/src/resolver/test_data/import_test/f.k b/crates/sema/src/resolver/test_data/import_test/f.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/import_test/f.k rename to crates/sema/src/resolver/test_data/import_test/f.k diff --git a/kclvm/sema/src/resolver/test_data/index_signature_check.k b/crates/sema/src/resolver/test_data/index_signature_check.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/index_signature_check.k rename to crates/sema/src/resolver/test_data/index_signature_check.k diff --git a/kclvm/sema/src/resolver/test_data/kcl.mod b/crates/sema/src/resolver/test_data/kcl.mod similarity index 100% rename from kclvm/sema/src/resolver/test_data/kcl.mod rename to crates/sema/src/resolver/test_data/kcl.mod diff --git a/kclvm/sema/src/resolver/test_data/lint.k b/crates/sema/src/resolver/test_data/lint.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/lint.k rename to crates/sema/src/resolver/test_data/lint.k diff --git a/kclvm/sema/src/resolver/test_data/pkg/pkg.k b/crates/sema/src/resolver/test_data/pkg/pkg.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/pkg/pkg.k rename to crates/sema/src/resolver/test_data/pkg/pkg.k diff --git a/kclvm/sema/src/resolver/test_data/pkg_asname/pkg/main.k b/crates/sema/src/resolver/test_data/pkg_asname/pkg/main.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/pkg_asname/pkg/main.k rename to crates/sema/src/resolver/test_data/pkg_asname/pkg/main.k diff --git a/kclvm/sema/src/resolver/test_data/pkg_asname/pkg/sub_pkg/main.k b/crates/sema/src/resolver/test_data/pkg_asname/pkg/sub_pkg/main.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/pkg_asname/pkg/sub_pkg/main.k rename to crates/sema/src/resolver/test_data/pkg_asname/pkg/sub_pkg/main.k diff --git a/kclvm/sema/src/resolver/test_data/pkg_asname/pkg_asname.k b/crates/sema/src/resolver/test_data/pkg_asname/pkg_asname.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/pkg_asname/pkg_asname.k rename to crates/sema/src/resolver/test_data/pkg_asname/pkg_asname.k diff --git a/kclvm/sema/src/resolver/test_data/pkg_init_in_schema.k b/crates/sema/src/resolver/test_data/pkg_init_in_schema.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/pkg_init_in_schema.k rename to crates/sema/src/resolver/test_data/pkg_init_in_schema.k diff --git a/kclvm/sema/src/resolver/test_data/pkg_not_found_suggestion.k b/crates/sema/src/resolver/test_data/pkg_not_found_suggestion.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/pkg_not_found_suggestion.k rename to crates/sema/src/resolver/test_data/pkg_not_found_suggestion.k diff --git a/kclvm/sema/src/resolver/test_data/pkg_scope.k b/crates/sema/src/resolver/test_data/pkg_scope.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/pkg_scope.k rename to crates/sema/src/resolver/test_data/pkg_scope.k diff --git a/kclvm/sema/src/resolver/test_data/record_used_module.k b/crates/sema/src/resolver/test_data/record_used_module.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/record_used_module.k rename to crates/sema/src/resolver/test_data/record_used_module.k diff --git a/kclvm/sema/src/resolver/test_data/schema_params_miss.k b/crates/sema/src/resolver/test_data/schema_params_miss.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/schema_params_miss.k rename to crates/sema/src/resolver/test_data/schema_params_miss.k diff --git a/kclvm/sema/src/resolver/test_data/system_package.k b/crates/sema/src/resolver/test_data/system_package.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/system_package.k rename to crates/sema/src/resolver/test_data/system_package.k diff --git a/kclvm/sema/src/resolver/test_data/test_builtin/glob.k b/crates/sema/src/resolver/test_data/test_builtin/glob.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/test_builtin/glob.k rename to crates/sema/src/resolver/test_data/test_builtin/glob.k diff --git a/kclvm/sema/src/resolver/test_data/test_builtin/read.k b/crates/sema/src/resolver/test_data/test_builtin/read.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/test_builtin/read.k rename to crates/sema/src/resolver/test_data/test_builtin/read.k diff --git a/kclvm/sema/src/resolver/test_data/ty_in_lambda.k b/crates/sema/src/resolver/test_data/ty_in_lambda.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/ty_in_lambda.k rename to crates/sema/src/resolver/test_data/ty_in_lambda.k diff --git a/kclvm/sema/src/resolver/test_data/undef_lambda_param.k b/crates/sema/src/resolver/test_data/undef_lambda_param.k similarity index 100% rename from kclvm/sema/src/resolver/test_data/undef_lambda_param.k rename to crates/sema/src/resolver/test_data/undef_lambda_param.k diff --git a/kclvm/sema/src/resolver/test_fail_data/attr.k b/crates/sema/src/resolver/test_fail_data/attr.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/attr.k rename to crates/sema/src/resolver/test_fail_data/attr.k diff --git a/kclvm/sema/src/resolver/test_fail_data/cannot_find_member_0.k b/crates/sema/src/resolver/test_fail_data/cannot_find_member_0.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/cannot_find_member_0.k rename to crates/sema/src/resolver/test_fail_data/cannot_find_member_0.k diff --git a/kclvm/sema/src/resolver/test_fail_data/cannot_find_member_1.k b/crates/sema/src/resolver/test_fail_data/cannot_find_member_1.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/cannot_find_member_1.k rename to crates/sema/src/resolver/test_fail_data/cannot_find_member_1.k diff --git a/kclvm/sema/src/resolver/test_fail_data/cannot_find_module.k b/crates/sema/src/resolver/test_fail_data/cannot_find_module.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/cannot_find_module.k rename to crates/sema/src/resolver/test_fail_data/cannot_find_module.k diff --git a/kclvm/sema/src/resolver/test_fail_data/comp_clause_error_0.k b/crates/sema/src/resolver/test_fail_data/comp_clause_error_0.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/comp_clause_error_0.k rename to crates/sema/src/resolver/test_fail_data/comp_clause_error_0.k diff --git a/kclvm/sema/src/resolver/test_fail_data/comp_clause_error_1.k b/crates/sema/src/resolver/test_fail_data/comp_clause_error_1.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/comp_clause_error_1.k rename to crates/sema/src/resolver/test_fail_data/comp_clause_error_1.k diff --git a/kclvm/sema/src/resolver/test_fail_data/comp_clause_error_2.k b/crates/sema/src/resolver/test_fail_data/comp_clause_error_2.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/comp_clause_error_2.k rename to crates/sema/src/resolver/test_fail_data/comp_clause_error_2.k diff --git a/kclvm/sema/src/resolver/test_fail_data/comp_clause_error_3.k b/crates/sema/src/resolver/test_fail_data/comp_clause_error_3.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/comp_clause_error_3.k rename to crates/sema/src/resolver/test_fail_data/comp_clause_error_3.k diff --git a/kclvm/sema/src/resolver/test_fail_data/comp_clause_error_4.k b/crates/sema/src/resolver/test_fail_data/comp_clause_error_4.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/comp_clause_error_4.k rename to crates/sema/src/resolver/test_fail_data/comp_clause_error_4.k diff --git a/kclvm/sema/src/resolver/test_fail_data/config_expr.k b/crates/sema/src/resolver/test_fail_data/config_expr.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/config_expr.k rename to crates/sema/src/resolver/test_fail_data/config_expr.k diff --git a/kclvm/sema/src/resolver/test_fail_data/cycle_reference/file1.k b/crates/sema/src/resolver/test_fail_data/cycle_reference/file1.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/cycle_reference/file1.k rename to crates/sema/src/resolver/test_fail_data/cycle_reference/file1.k diff --git a/kclvm/sema/src/resolver/test_fail_data/cycle_reference/file2.k b/crates/sema/src/resolver/test_fail_data/cycle_reference/file2.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/cycle_reference/file2.k rename to crates/sema/src/resolver/test_fail_data/cycle_reference/file2.k diff --git a/kclvm/sema/src/resolver/test_fail_data/invalid_mixin_0.k b/crates/sema/src/resolver/test_fail_data/invalid_mixin_0.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/invalid_mixin_0.k rename to crates/sema/src/resolver/test_fail_data/invalid_mixin_0.k diff --git a/kclvm/sema/src/resolver/test_fail_data/lambda_schema_ty_0.k b/crates/sema/src/resolver/test_fail_data/lambda_schema_ty_0.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/lambda_schema_ty_0.k rename to crates/sema/src/resolver/test_fail_data/lambda_schema_ty_0.k diff --git a/kclvm/sema/src/resolver/test_fail_data/lambda_schema_ty_1.k b/crates/sema/src/resolver/test_fail_data/lambda_schema_ty_1.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/lambda_schema_ty_1.k rename to crates/sema/src/resolver/test_fail_data/lambda_schema_ty_1.k diff --git a/kclvm/sema/src/resolver/test_fail_data/lambda_schema_ty_2.k b/crates/sema/src/resolver/test_fail_data/lambda_schema_ty_2.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/lambda_schema_ty_2.k rename to crates/sema/src/resolver/test_fail_data/lambda_schema_ty_2.k diff --git a/kclvm/sema/src/resolver/test_fail_data/lambda_schema_ty_3.k b/crates/sema/src/resolver/test_fail_data/lambda_schema_ty_3.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/lambda_schema_ty_3.k rename to crates/sema/src/resolver/test_fail_data/lambda_schema_ty_3.k diff --git a/kclvm/sema/src/resolver/test_fail_data/lambda_ty_error.k b/crates/sema/src/resolver/test_fail_data/lambda_ty_error.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/lambda_ty_error.k rename to crates/sema/src/resolver/test_fail_data/lambda_ty_error.k diff --git a/kclvm/sema/src/resolver/test_fail_data/module_optional_select.k b/crates/sema/src/resolver/test_fail_data/module_optional_select.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/module_optional_select.k rename to crates/sema/src/resolver/test_fail_data/module_optional_select.k diff --git a/kclvm/sema/src/resolver/test_fail_data/mutable_error_0.k b/crates/sema/src/resolver/test_fail_data/mutable_error_0.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/mutable_error_0.k rename to crates/sema/src/resolver/test_fail_data/mutable_error_0.k diff --git a/kclvm/sema/src/resolver/test_fail_data/mutable_error_1.k b/crates/sema/src/resolver/test_fail_data/mutable_error_1.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/mutable_error_1.k rename to crates/sema/src/resolver/test_fail_data/mutable_error_1.k diff --git a/kclvm/sema/src/resolver/test_fail_data/not_found_suggest/main.k b/crates/sema/src/resolver/test_fail_data/not_found_suggest/main.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/not_found_suggest/main.k rename to crates/sema/src/resolver/test_fail_data/not_found_suggest/main.k diff --git a/kclvm/sema/src/resolver/test_fail_data/not_found_suggest/sub/main.k b/crates/sema/src/resolver/test_fail_data/not_found_suggest/sub/main.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/not_found_suggest/sub/main.k rename to crates/sema/src/resolver/test_fail_data/not_found_suggest/sub/main.k diff --git a/kclvm/sema/src/resolver/test_fail_data/redefine_import/main.k b/crates/sema/src/resolver/test_fail_data/redefine_import/main.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/redefine_import/main.k rename to crates/sema/src/resolver/test_fail_data/redefine_import/main.k diff --git a/kclvm/sema/src/resolver/test_fail_data/redefine_import/sub/main.k b/crates/sema/src/resolver/test_fail_data/redefine_import/sub/main.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/redefine_import/sub/main.k rename to crates/sema/src/resolver/test_fail_data/redefine_import/sub/main.k diff --git a/kclvm/sema/src/resolver/test_fail_data/redefine_import/sub/sub/main.k b/crates/sema/src/resolver/test_fail_data/redefine_import/sub/sub/main.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/redefine_import/sub/sub/main.k rename to crates/sema/src/resolver/test_fail_data/redefine_import/sub/sub/main.k diff --git a/kclvm/sema/src/resolver/test_fail_data/unique_key_error_0.k b/crates/sema/src/resolver/test_fail_data/unique_key_error_0.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/unique_key_error_0.k rename to crates/sema/src/resolver/test_fail_data/unique_key_error_0.k diff --git a/kclvm/sema/src/resolver/test_fail_data/unique_key_error_1.k b/crates/sema/src/resolver/test_fail_data/unique_key_error_1.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/unique_key_error_1.k rename to crates/sema/src/resolver/test_fail_data/unique_key_error_1.k diff --git a/kclvm/sema/src/resolver/test_fail_data/unmatched_args.k b/crates/sema/src/resolver/test_fail_data/unmatched_args.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/unmatched_args.k rename to crates/sema/src/resolver/test_fail_data/unmatched_args.k diff --git a/kclvm/sema/src/resolver/test_fail_data/unmatched_index_sign_default_value.k b/crates/sema/src/resolver/test_fail_data/unmatched_index_sign_default_value.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/unmatched_index_sign_default_value.k rename to crates/sema/src/resolver/test_fail_data/unmatched_index_sign_default_value.k diff --git a/kclvm/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_0.k b/crates/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_0.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_0.k rename to crates/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_0.k diff --git a/kclvm/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_1.k b/crates/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_1.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_1.k rename to crates/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_1.k diff --git a/kclvm/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_2.k b/crates/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_2.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_2.k rename to crates/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_2.k diff --git a/kclvm/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_3.k b/crates/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_3.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_3.k rename to crates/sema/src/resolver/test_fail_data/unmatched_nest_schema_attr_3.k diff --git a/kclvm/sema/src/resolver/test_fail_data/unmatched_schema_attr_0.k b/crates/sema/src/resolver/test_fail_data/unmatched_schema_attr_0.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/unmatched_schema_attr_0.k rename to crates/sema/src/resolver/test_fail_data/unmatched_schema_attr_0.k diff --git a/kclvm/sema/src/resolver/test_fail_data/unmatched_schema_attr_1.k b/crates/sema/src/resolver/test_fail_data/unmatched_schema_attr_1.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/unmatched_schema_attr_1.k rename to crates/sema/src/resolver/test_fail_data/unmatched_schema_attr_1.k diff --git a/kclvm/sema/src/resolver/test_fail_data/unmatched_schema_attr_2.k b/crates/sema/src/resolver/test_fail_data/unmatched_schema_attr_2.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/unmatched_schema_attr_2.k rename to crates/sema/src/resolver/test_fail_data/unmatched_schema_attr_2.k diff --git a/kclvm/sema/src/resolver/test_fail_data/unmatched_schema_attr_3.k b/crates/sema/src/resolver/test_fail_data/unmatched_schema_attr_3.k similarity index 100% rename from kclvm/sema/src/resolver/test_fail_data/unmatched_schema_attr_3.k rename to crates/sema/src/resolver/test_fail_data/unmatched_schema_attr_3.k diff --git a/crates/sema/src/resolver/tests.rs b/crates/sema/src/resolver/tests.rs new file mode 100644 index 000000000..c1602373d --- /dev/null +++ b/crates/sema/src/resolver/tests.rs @@ -0,0 +1,1174 @@ +use super::Options; +use super::Resolver; +use crate::builtin::BUILTIN_FUNCTION_NAMES; +use crate::pre_process::pre_process_program; +use crate::resolver::resolve_program; +use crate::resolver::resolve_program_with_opts; +use crate::resolver::scope::*; +use crate::ty::{Type, TypeKind}; +use anyhow::Result; +use kcl_ast::MAIN_PKG; +use kcl_ast::ast; +use kcl_ast::pos::ContainsPos; +use kcl_error::*; +use kcl_parser::LoadProgramOptions; +use kcl_parser::ParseSession; +use kcl_parser::load_program; +use kcl_parser::parse_file_force_errors; +use kcl_utils::path::PathPrefix; +use parking_lot::lock_api::RwLock; +use std::collections::HashMap; +use std::collections::HashSet; +use std::path::Path; +use std::sync::Arc; +use std::sync::RwLock as Lock; + +pub fn parse_program(filename: &str) -> Result { + let abspath = std::fs::canonicalize(std::path::PathBuf::from(filename)).expect(filename); + + let mut prog = ast::Program { + root: abspath.parent().unwrap().adjust_canonicalization(), + pkgs: HashMap::new(), + modules: HashMap::new(), + pkgs_not_imported: HashMap::new(), + modules_not_imported: HashMap::new(), + }; + + let mut module = parse_file_force_errors(abspath.to_str().unwrap(), None)?; + module.filename = filename.to_string(); + + prog.pkgs + .insert(kcl_ast::MAIN_PKG.to_string(), vec![filename.to_string()]); + + prog.modules + .insert(filename.to_string(), Arc::new(Lock::new(module))); + + Ok(prog) +} + +#[test] +fn test_scope() { + let mut scope = builtin_scope(); + for name in BUILTIN_FUNCTION_NAMES { + let obj = scope.lookup(name).unwrap(); + let obj_ref = obj.borrow_mut(); + assert!(obj_ref.ty.is_func()); + } + for name in BUILTIN_FUNCTION_NAMES { + scope.set_ty(name, Arc::new(Type::ANY)); + } + for name in BUILTIN_FUNCTION_NAMES { + let obj = scope.lookup(name).unwrap(); + let obj_ref = obj.borrow_mut(); + assert!(obj_ref.ty.is_any()); + } +} + +#[test] +fn test_resolve_program() { + let mut program = parse_program("./src/resolver/test_data/assign.k").unwrap(); + let scope = resolve_program(&mut program); + assert_eq!(scope.pkgpaths(), vec!["__main__".to_string()]); + let main_scope = scope.main_scope().unwrap(); + let main_scope = main_scope.borrow_mut(); + assert!(main_scope.lookup("a").is_some()); + assert!(main_scope.lookup("b").is_some()); + assert!(main_scope.lookup("print").is_none()); +} + +#[test] +fn test_resolve_program_with_cache() { + let mut program = parse_program("./src/resolver/test_data/assign.k").unwrap(); + + let scope = resolve_program_with_opts( + &mut program, + Options { + merge_program: false, + type_erasure: false, + ..Default::default() + }, + None, + ); + let cached_scope = Arc::new(RwLock::new(CachedScope::new(&scope, &program))); + let scope = resolve_program_with_opts( + &mut program, + Options { + merge_program: false, + type_erasure: false, + ..Default::default() + }, + Some(cached_scope), + ); + assert_eq!(scope.pkgpaths(), vec!["__main__".to_string()]); + let main_scope = scope.main_scope().unwrap(); + let main_scope = main_scope.borrow_mut(); + assert!(main_scope.lookup("a").is_some()); + assert!(main_scope.lookup("b").is_some()); + assert!(main_scope.lookup("print").is_none()); +} + +#[test] +fn test_pkg_init_in_schema_resolve() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/pkg_init_in_schema.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + assert_eq!( + scope.pkgpaths(), + vec!["__main__".to_string(), "pkg".to_string()] + ); + let module = &program.pkgs["pkg"][0]; + let module = program + .get_module(&module) + .expect("Failed to acquire module lock") + .expect(&format!("module {:?} not found in program", module)); + if let ast::Stmt::Schema(schema) = &module.body[1].node { + if let ast::Stmt::SchemaAttr(attr) = &schema.body[0].node { + let value = attr.value.as_ref().unwrap(); + if let ast::Expr::Schema(schema_expr) = &value.node { + assert_eq!(schema_expr.name.node.get_names(), vec!["Name".to_string()]); + } else { + panic!("test failed, expect schema expr, got {:?}", value) + } + } else { + panic!( + "test failed, expect schema attribute, got {:?}", + schema.body[0] + ) + } + } else { + panic!( + "test failed, expect schema statement, got {:?}", + module.body[1] + ) + } +} + +#[test] +fn test_resolve_program_fail() { + let work_dir = "./src/resolver/test_fail_data/"; + let cases = &[ + "attr.k", + "cannot_find_member_0.k", + "cannot_find_member_1.k", + "cannot_find_module.k", + "comp_clause_error_0.k", + "comp_clause_error_1.k", + "comp_clause_error_2.k", + "comp_clause_error_3.k", + "comp_clause_error_4.k", + "config_expr.k", + "invalid_mixin_0.k", + "lambda_schema_ty_0.k", + "lambda_schema_ty_1.k", + "lambda_schema_ty_2.k", + "lambda_schema_ty_3.k", + "module_optional_select.k", + "mutable_error_0.k", + "mutable_error_1.k", + "unique_key_error_0.k", + "unique_key_error_1.k", + "unmatched_index_sign_default_value.k", + "unmatched_args.k", + "unmatched_nest_schema_attr_0.k", + "unmatched_nest_schema_attr_1.k", + "unmatched_nest_schema_attr_2.k", + "unmatched_nest_schema_attr_3.k", + "unmatched_schema_attr_0.k", + "unmatched_schema_attr_1.k", + "unmatched_schema_attr_2.k", + "unmatched_schema_attr_3.k", + ]; + for case in cases { + let path = Path::new(work_dir).join(case); + let mut program = parse_program(&path.to_string_lossy()).unwrap(); + let scope = resolve_program(&mut program); + assert!(scope.handler.diagnostics.len() > 0, "{}", case); + } +} + +#[test] +fn test_resolve_program_redefine() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_fail_data/redefine_import/main.k"], + None, + None, + ) + .unwrap() + .program; + + let scope = resolve_program(&mut program); + assert_eq!(scope.handler.diagnostics.len(), 2); + let diag = &scope.handler.diagnostics[0]; + assert_eq!( + diag.code, + Some(DiagnosticId::Error(ErrorKind::CompileError)) + ); + assert_eq!(diag.messages.len(), 1); + assert_eq!( + diag.messages[0].message, + "the name 's' is defined multiple times, 's' must be defined only once" + ); +} + +#[test] +fn test_resolve_program_mismatch_type_fail() { + let mut program = parse_program("./src/resolver/test_fail_data/config_expr.k").unwrap(); + let scope = resolve_program(&mut program); + assert_eq!(scope.handler.diagnostics.len(), 1); + let diag = &scope.handler.diagnostics[0]; + assert_eq!(diag.code, Some(DiagnosticId::Error(ErrorKind::TypeError))); + assert_eq!(diag.messages.len(), 1); + assert_eq!( + diag.messages[0].message, + "expected int, got {str(key):int(1)}" + ); +} + +#[test] +fn test_resolve_program_cycle_reference_fail() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_fail_data/cycle_reference/file2.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + let err_messages = [ + "There is a circular reference between modules file1, file2", + "There is a circular reference between modules file1, file2", + "There is a circular reference between schemas file1.SchemaBase, file1.SchemaSub", + "There is a circular reference between schemas file1.SchemaBase, file1.SchemaSub", + "There is a circular reference between rules file1.RuleBase, file1.RuleSub", + "There is a circular reference between rules file1.RuleBase, file1.RuleSub", + "There is a circular reference between schemas file1.A, file1.B, file1.C", + "There is a circular reference between schemas file1.A, file1.B, file1.C", + "There is a circular reference between schemas file1.A, file1.B, file1.C", + "Module 'file1' imported but unused", + "Module 'file2' imported but unused", + ]; + assert_eq!(scope.handler.diagnostics.len(), err_messages.len()); + for (diag, msg) in scope.handler.diagnostics.iter().zip(err_messages.iter()) { + assert_eq!(diag.messages[0].message, msg.to_string(),); + } +} + +#[test] +fn test_record_used_module() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/record_used_module.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + let main_scope = scope + .scope_map + .get(kcl_runtime::MAIN_PKG_PATH) + .unwrap() + .borrow_mut() + .clone(); + for (_, obj) in main_scope.elems { + let obj = obj.borrow_mut().clone(); + if let ScopeObjectKind::Module(m) = obj.kind { + for (_, used) in m.import_stmts { + if obj.name == "math" { + assert!(!used); + } else { + assert!(used); + } + } + } + } +} + +#[test] +fn test_resolve_program_illegal_attr_fail() { + let mut program = parse_program("./src/resolver/test_fail_data/attr.k").unwrap(); + let scope = resolve_program(&mut program); + assert_eq!(scope.handler.diagnostics.len(), 2); + let expect_err_msg = "A attribute must be string type, got 'Data'"; + let diag = &scope.handler.diagnostics[0]; + assert_eq!( + diag.code, + Some(DiagnosticId::Error(ErrorKind::IllegalAttributeError)) + ); + assert_eq!(diag.messages.len(), 1); + assert_eq!(diag.messages[0].range.0.line, 4); + assert_eq!(diag.messages[0].message, expect_err_msg,); + let diag = &scope.handler.diagnostics[1]; + assert_eq!( + diag.code, + Some(DiagnosticId::Error(ErrorKind::IllegalAttributeError)) + ); + assert_eq!(diag.messages.len(), 1); + assert_eq!(diag.messages[0].message, expect_err_msg,); + assert_eq!(diag.messages[0].range.0.line, 5); +} + +#[test] +fn test_resolve_program_unmatched_args_fail() { + let mut program = parse_program("./src/resolver/test_fail_data/unmatched_args.k").unwrap(); + let scope = resolve_program(&mut program); + assert_eq!(scope.handler.diagnostics.len(), 3); + let expect_err_msg = "\"Foo\" takes 1 positional argument but 3 were given"; + let diag = &scope.handler.diagnostics[0]; + assert_eq!( + diag.code, + Some(DiagnosticId::Error(ErrorKind::CompileError)) + ); + assert_eq!(diag.messages.len(), 1); + assert_eq!(diag.messages[0].range.0.line, 6); + assert_eq!(diag.messages[0].message, expect_err_msg); + + let expect_err_msg = "\"f\" takes 1 positional argument but 2 were given"; + let diag = &scope.handler.diagnostics[1]; + assert_eq!( + diag.code, + Some(DiagnosticId::Error(ErrorKind::CompileError)) + ); + assert_eq!(diag.messages.len(), 1); + assert_eq!(diag.messages[0].range.0.line, 7); + assert_eq!(diag.messages[0].message, expect_err_msg); + + let expect_err_msg = "\"Foo2\" takes 2 positional arguments but 3 were given"; + let diag = &scope.handler.diagnostics[2]; + assert_eq!( + diag.code, + Some(DiagnosticId::Error(ErrorKind::CompileError)) + ); + assert_eq!(diag.messages.len(), 1); + assert_eq!(diag.messages[0].range.0.line, 12); + assert_eq!(diag.messages[0].message, expect_err_msg); +} + +#[test] +fn test_resolve_program_module_optional_select_fail() { + let mut program = + parse_program("./src/resolver/test_fail_data/module_optional_select.k").unwrap(); + let scope = resolve_program(&mut program); + assert_eq!(scope.handler.diagnostics.len(), 2); + let expect_err_msg = + "For the module type, the use of '?.log' is unnecessary and it can be modified as '.log'"; + let diag = &scope.handler.diagnostics[0]; + assert_eq!( + diag.code, + Some(DiagnosticId::Error(ErrorKind::CompileError)) + ); + assert_eq!(diag.messages.len(), 1); + assert_eq!(diag.messages[0].range.0.line, 3); + assert_eq!(diag.messages[0].message, expect_err_msg); + + let expect_err_msg = "Module 'math' imported but unused"; + let diag = &scope.handler.diagnostics[1]; + assert_eq!( + diag.code, + Some(DiagnosticId::Warning(WarningKind::UnusedImportWarning)) + ); + assert_eq!(diag.messages.len(), 1); + assert_eq!(diag.messages[0].range.0.line, 1); + assert_eq!(diag.messages[0].message, expect_err_msg); +} + +#[test] +fn test_lint() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/lint.k"], + None, + None, + ) + .unwrap() + .program; + let opts = Options::default(); + pre_process_program(&mut program, &opts); + let mut resolver = Resolver::new(&program, opts); + resolver.resolve_import(); + resolver.check_and_lint_all_pkgs(); + + let root = &program.root.clone(); + let filename = Path::new(&root.clone()) + .join("lint.k") + .display() + .to_string(); + let mut handler = Handler::default(); + handler.add_warning( + WarningKind::ImportPositionWarning, + &[Message { + range: ( + Position { + filename: filename.clone(), + line: 11, + column: Some(0), + }, + Position { + filename: filename.clone(), + line: 11, + column: Some(20), + }, + ), + style: Style::Line, + message: format!("The import stmt should be placed at the top of the module"), + note: Some("Consider moving tihs statement to the top of the file".to_string()), + suggested_replacement: None, + }], + ); + handler.add_warning( + WarningKind::ReimportWarning, + &[Message { + range: ( + Position { + filename: filename.clone(), + line: 2, + column: Some(0), + }, + Position { + filename: filename.clone(), + line: 2, + column: Some(20), + }, + ), + style: Style::Line, + message: format!("Module 'a' is reimported multiple times"), + note: Some("Consider removing this statement".to_string()), + suggested_replacement: None, + }], + ); + handler.add_warning( + WarningKind::UnusedImportWarning, + &[Message { + range: ( + Position { + filename: filename.clone(), + line: 1, + column: Some(0), + }, + Position { + filename: filename.clone(), + line: 1, + column: Some(20), + }, + ), + style: Style::Line, + message: format!("Module 'a' imported but unused"), + note: Some("Consider removing this statement".to_string()), + suggested_replacement: None, + }], + ); + for (d1, d2) in resolver + .linter + .handler + .diagnostics + .iter() + .zip(handler.diagnostics.iter()) + { + assert_eq!(d1, d2); + } +} + +#[test] +fn test_resolve_schema_doc() { + let mut program = parse_program("./src/resolver/test_data/doc.k").unwrap(); + let scope = resolve_program(&mut program); + let main_scope = scope + .scope_map + .get(kcl_runtime::MAIN_PKG_PATH) + .unwrap() + .borrow_mut() + .clone(); + + let schema_scope_obj = &main_scope.elems[0].borrow().clone(); + let schema_summary = match &schema_scope_obj.ty.kind { + TypeKind::Schema(schema_ty) => schema_ty.doc.clone(), + _ => "".to_string(), + }; + + let schema_scope = &main_scope.children[0]; + let attrs_scope = &schema_scope.borrow().elems; + assert_eq!("Server is the common user interface for long-running services adopting the best practice of Kubernetes.".to_string(), schema_summary); + assert_eq!( + Some( + "Use this attribute to specify which kind of long-running service you want. +Valid values: Deployment, CafeDeployment. +See also: kusion_models/core/v1/workload_metadata.k." + .to_string() + ), + attrs_scope.get("workloadType").unwrap().borrow().doc + ); + assert_eq!( + Some( + "A Server-level attribute. +The name of the long-running service. +See also: kusion_models/core/v1/metadata.k." + .to_string() + ), + attrs_scope.get("name").unwrap().borrow().doc + ); + assert_eq!( + Some( + "A Server-level attribute. +The labels of the long-running service. +See also: kusion_models/core/v1/metadata.k." + .to_string() + ), + attrs_scope.get("labels").unwrap().borrow().doc + ); +} + +#[test] +fn test_pkg_scope() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/pkg_scope.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + + assert_eq!(scope.scope_map.len(), 2); + let main_scope = scope + .scope_map + .get(kcl_runtime::MAIN_PKG_PATH) + .unwrap() + .borrow_mut() + .clone(); + let pkg_scope = scope.scope_map.get("pkg").unwrap().borrow_mut().clone(); + + let root = &program.root.clone(); + let filename = Path::new(&root.clone()) + .join("pkg_scope.k") + .display() + .to_string(); + + let pos = Position { + filename: filename.clone(), + line: 2, + column: Some(0), + }; + + assert!(main_scope.contains_pos(&pos)); + + let filename = Path::new(&root.clone()) + .join("pkg") + .join("pkg.k") + .display() + .to_string(); + + let pos = Position { + filename: filename.clone(), + line: 4, + column: Some(0), + }; + + assert!(pkg_scope.contains_pos(&pos)); +} + +#[test] +fn test_system_package() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/system_package.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + let main_scope = scope + .scope_map + .get(kcl_runtime::MAIN_PKG_PATH) + .unwrap() + .borrow_mut() + .clone(); + + assert!(main_scope.lookup("base64").unwrap().borrow().ty.is_module()); + assert!( + main_scope + .lookup("base64_encode") + .unwrap() + .borrow() + .ty + .is_func() + ); + assert!( + main_scope + .lookup("base64_decode") + .unwrap() + .borrow() + .ty + .is_func() + ); + + // Add assertions for base32 module + assert!(main_scope.lookup("base32").unwrap().borrow().ty.is_module()); + assert!( + main_scope + .lookup("base32_encode") + .unwrap() + .borrow() + .ty + .is_func() + ); + assert!( + main_scope + .lookup("base32_decode") + .unwrap() + .borrow() + .ty + .is_func() + ); +} + +#[test] +fn test_resolve_program_import_suggest() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_fail_data/not_found_suggest/main.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + assert_eq!(scope.handler.diagnostics.len(), 2); + let diag = &scope.handler.diagnostics[0]; + assert_eq!( + diag.code, + Some(DiagnosticId::Error(ErrorKind::CompileError)) + ); + assert_eq!(diag.messages.len(), 1); + assert_eq!( + diag.messages[0].message, + "name 's' is not defined, did you mean '[\"s1\"]'?" + ); +} + +#[test] +fn test_resolve_assignment_in_lambda() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/assign_in_lambda.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + let main_scope = scope.scope_map.get("__main__").unwrap().clone(); + assert_eq!(main_scope.borrow().children.len(), 1); + let lambda_scope = main_scope.borrow().children[0].clone(); + assert_eq!(lambda_scope.borrow().elems.len(), 2); + let images_scope_obj = lambda_scope.borrow().elems.get("images").unwrap().clone(); + assert_eq!(images_scope_obj.borrow().ty.ty_str(), "[str]"); +} + +#[test] +fn test_resolve_function_with_default_values() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/function_with_default_values.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + assert!(!scope.handler.has_errors()); + let main_scope = scope.main_scope().unwrap(); + let func = main_scope.borrow().lookup("is_alpha").unwrap(); + assert!(func.borrow().ty.is_func()); + let func_ty = func.borrow().ty.into_func_type(); + assert_eq!(func_ty.params.len(), 3); + assert_eq!(func_ty.params[0].has_default, false); + assert_eq!(func_ty.params[1].has_default, true); + assert_eq!(func_ty.params[2].has_default, true); +} + +#[test] +fn test_assignment_type_annotation_check_in_lambda() { + let sess = Arc::new(ParseSession::default()); + let opts = LoadProgramOptions::default(); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/annotation_check_assignment.k"], + Some(opts), + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + assert_eq!(scope.handler.diagnostics.len(), 0); +} + +#[test] +fn test_resolve_lambda_assignment_diagnostic() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_fail_data/lambda_ty_error.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + assert_eq!(scope.handler.diagnostics.len(), 1); + let diag = &scope.handler.diagnostics[0]; + assert_eq!(diag.code, Some(DiagnosticId::Error(ErrorKind::TypeError))); + assert_eq!(diag.messages.len(), 1); + assert_eq!( + diag.messages[0].message, + "expected (int, int) -> int, got (int, int) -> str" + ); +} + +#[test] +fn test_ty_check_in_dict_assign_to_schema() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/attr_ty_check.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + assert_eq!(scope.handler.diagnostics.len(), 2); + let diag = &scope.handler.diagnostics[0]; + assert_eq!(diag.code, Some(DiagnosticId::Error(ErrorKind::TypeError))); + assert_eq!(diag.messages.len(), 2); + assert_eq!(diag.messages[0].message, "expected int, got str(1)"); + assert_eq!( + diag.messages[1].message, + "variable is defined here, its type is int, but got str(1)" + ); +} + +#[test] +fn test_pkg_not_found_suggestion() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/pkg_not_found_suggestion.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + assert_eq!(scope.handler.diagnostics.len(), 4); + let diag = &scope.handler.diagnostics[1]; + assert_eq!(diag.code, Some(DiagnosticId::Suggestions)); + assert_eq!(diag.messages.len(), 1); + assert_eq!( + diag.messages[0].message, + "try 'kcl mod add k9s' to download the missing package" + ); + let diag = &scope.handler.diagnostics[2]; + assert_eq!(diag.code, Some(DiagnosticId::Suggestions)); + assert_eq!(diag.messages.len(), 1); + assert_eq!( + diag.messages[0].message, + "browse more packages at 'https://artifacthub.io'" + ); +} + +#[test] +fn undef_lambda_param() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/undef_lambda_param.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + assert_eq!(scope.handler.diagnostics.len(), 1); + + let root = &program.root.clone(); + let filename = Path::new(&root.clone()) + .join("undef_lambda_param.k") + .display() + .to_string(); + + let range = scope.handler.diagnostics[0].messages[0].range.clone(); + + assert_eq!( + range, + ( + Position { + filename: filename.clone(), + line: 1, + column: Some(10), + }, + Position { + filename: filename.clone(), + line: 1, + column: Some(15), + } + ) + ); +} + +#[test] +fn test_schema_params_count() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/schema_params_miss.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + assert_eq!(scope.handler.diagnostics.len(), 1); + let diag = &scope.handler.diagnostics[0]; + assert_eq!( + diag.code, + Some(DiagnosticId::Error(ErrorKind::CompileError)) + ); + assert_eq!(diag.messages.len(), 1); + assert_eq!( + diag.messages[0].message, + "expected 1 positional argument, found 0" + ); +} + +#[test] +fn test_set_ty_in_lambda() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/ty_in_lambda.k"], + None, + None, + ) + .unwrap() + .program; + assert_eq!( + resolve_program(&mut program) + .main_scope() + .unwrap() + .borrow() + .lookup("result") + .unwrap() + .borrow() + .ty + .clone() + .ty_str(), + "{str:str}" + ); +} + +#[test] +fn test_pkg_asname() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/pkg_asname/pkg_asname.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + let diags = scope.handler.diagnostics; + assert_eq!(diags.len(), 4); + assert_eq!(diags[0].messages[0].message, "name 'pkg' is not defined"); + assert_eq!(diags[1].messages[0].message, "name 'subpkg' is not defined"); +} + +#[test] +fn test_builtin_file_invalid() { + let test_cases = [ + ( + "./src/resolver/test_data/test_builtin/read.k", + "expected 1 positional argument, found 0", + ), + ( + "./src/resolver/test_data/test_builtin/glob.k", + "expected 1 positional argument, found 0", + ), + ]; + + for (file, expected_message) in &test_cases { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program(sess.clone(), &[file], None, None) + .unwrap() + .program; + let scope = resolve_program(&mut program); + let diags = scope.handler.diagnostics; + assert_eq!(diags.len(), 1); + assert_eq!(diags[0].messages[0].message, *expected_message); + } +} + +#[test] +fn test_schema_index_signature_check() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/index_signature_check.k"], + None, + None, + ) + .unwrap() + .program; + let scope = resolve_program(&mut program); + let diags = scope.handler.diagnostics; + assert!(diags.is_empty()) +} + +#[test] +fn test_clear_cache_by_module() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/cache/main.k"], + None, + None, + ) + .unwrap() + .program; + + let scope = resolve_program_with_opts( + &mut program, + Options { + merge_program: false, + type_erasure: false, + ..Default::default() + }, + None, + ); + let cached_scope = Arc::new(RwLock::new(CachedScope::new(&scope, &program))); + // first compile + let _ = resolve_program_with_opts( + &mut program, + Options { + merge_program: false, + type_erasure: false, + ..Default::default() + }, + Some(cached_scope.clone()), + ); + + // recompile and clear cache + let invalidate_module = std::fs::canonicalize(std::path::PathBuf::from( + "./src/resolver/test_data/cache/main.k", + )) + .unwrap() + .to_str() + .unwrap() + .to_string() + .adjust_canonicalization(); + + if let Some(mut cached_scope) = cached_scope.try_write() { + let mut invalidate_pkg_modules = HashSet::new(); + invalidate_pkg_modules.insert(invalidate_module); + cached_scope.invalidate_pkg_modules = Some(invalidate_pkg_modules); + }; + + let _ = resolve_program_with_opts( + &mut program, + Options { + merge_program: false, + type_erasure: false, + ..Default::default() + }, + Some(cached_scope.clone()), + ); + if let Some(cached_scope) = cached_scope.try_write() { + // main - a + // - b - c + // invalidate main, invalidate_pkgs main + let mut expect = HashSet::new(); + expect.insert(MAIN_PKG.to_string()); + assert_eq!(cached_scope.invalidate_pkgs, expect); + }; + + // recompile and clear cache + let invalidate_module = std::fs::canonicalize(std::path::PathBuf::from( + "./src/resolver/test_data/cache/a/a.k", + )) + .unwrap() + .to_str() + .unwrap() + .to_string() + .adjust_canonicalization(); + + if let Some(mut cached_scope) = cached_scope.try_write() { + let mut invalidate_pkg_modules = HashSet::new(); + invalidate_pkg_modules.insert(invalidate_module); + cached_scope.invalidate_pkg_modules = Some(invalidate_pkg_modules); + }; + + let _ = resolve_program_with_opts( + &mut program, + Options { + merge_program: false, + type_erasure: false, + ..Default::default() + }, + Some(cached_scope.clone()), + ); + + if let Some(cached_scope) = cached_scope.try_write() { + // main - a + // - b - c + // invalidate a, invalidate_pkgs a, main + let mut expect = HashSet::new(); + expect.insert(MAIN_PKG.to_string()); + expect.insert("cache.a".to_string()); + assert_eq!(cached_scope.invalidate_pkgs, expect); + }; + + // recompile and clear cache + let invalidate_module = std::fs::canonicalize(std::path::PathBuf::from( + "./src/resolver/test_data/cache/b/b.k", + )) + .unwrap() + .to_str() + .unwrap() + .to_string() + .adjust_canonicalization(); + + if let Some(mut cached_scope) = cached_scope.try_write() { + let mut invalidate_pkg_modules = HashSet::new(); + invalidate_pkg_modules.insert(invalidate_module); + cached_scope.invalidate_pkg_modules = Some(invalidate_pkg_modules); + }; + + let _ = resolve_program_with_opts( + &mut program, + Options { + merge_program: false, + type_erasure: false, + ..Default::default() + }, + Some(cached_scope.clone()), + ); + + if let Some(cached_scope) = cached_scope.try_write() { + // main - a + // - b - c + // invalidate b, invalidate_pkgs b, main + let mut expect = HashSet::new(); + expect.insert(MAIN_PKG.to_string()); + expect.insert("cache.b".to_string()); + assert_eq!(cached_scope.invalidate_pkgs, expect); + }; + + // recompile and clear cache + let invalidate_module = std::fs::canonicalize(std::path::PathBuf::from( + "./src/resolver/test_data/cache/c/c.k", + )) + .unwrap() + .to_str() + .unwrap() + .to_string() + .adjust_canonicalization(); + + if let Some(mut cached_scope) = cached_scope.try_write() { + let mut invalidate_pkg_modules = HashSet::new(); + invalidate_pkg_modules.insert(invalidate_module); + cached_scope.invalidate_pkg_modules = Some(invalidate_pkg_modules); + }; + + let _ = resolve_program_with_opts( + &mut program, + Options { + merge_program: false, + type_erasure: false, + ..Default::default() + }, + Some(cached_scope.clone()), + ); + + if let Some(cached_scope) = cached_scope.try_write() { + // main - a + // - b - c + // invalidate c, invalidate_pkgs c, b, main + let mut expect = HashSet::new(); + expect.insert(MAIN_PKG.to_string()); + expect.insert("cache.b".to_string()); + expect.insert("cache.c".to_string()); + assert_eq!(cached_scope.invalidate_pkgs, expect); + }; +} + +#[test] +fn clear_cache_test() { + let sess = Arc::new(ParseSession::default()); + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/cache/main.k"], + None, + None, + ) + .unwrap() + .program; + + let scope_cache = Arc::new(RwLock::new(CachedScope::default())); + let first_scope = resolve_program_with_opts( + &mut program, + Options { + merge_program: false, + type_erasure: false, + ..Default::default() + }, + Some(scope_cache.clone()), + ); + + let mut program = load_program( + sess.clone(), + &["./src/resolver/test_data/cache/main.k"], + None, + None, + ) + .unwrap() + .program; + + let second_scope = resolve_program_with_opts( + &mut program, + Options { + merge_program: false, + type_erasure: false, + ..Default::default() + }, + Some(scope_cache.clone()), + ); + let first_node_ty_map_len = first_scope.node_ty_map.borrow().len(); + let second_node_ty_map_len = second_scope.node_ty_map.borrow().len(); + assert_eq!(first_node_ty_map_len, second_node_ty_map_len); + assert_eq!(first_scope.scope_map.len(), second_scope.scope_map.len()); + assert_eq!( + first_scope.schema_mapping.len(), + second_scope.schema_mapping.len() + ); +} diff --git a/crates/sema/src/resolver/ty.rs b/crates/sema/src/resolver/ty.rs new file mode 100644 index 000000000..fd6a81ee9 --- /dev/null +++ b/crates/sema/src/resolver/ty.rs @@ -0,0 +1,636 @@ +use std::sync::Arc; + +use super::node::ResolvedResult; +use crate::resolver::Resolver; +use crate::ty::parser::parse_type_str; +use crate::ty::{ + Attr, DictType, Parameter, SchemaType, Type, TypeKind, TypeRef, assignable_to, is_upper_bound, +}; +use kcl_ast::ast; +use kcl_ast::pos::GetPos; +use kcl_error::diagnostic::Range; +use kcl_error::*; +use kcl_primitives::IndexMap; + +fn ty_str_to_pkgpath(ty_str: &str) -> &str { + let splits: Vec<&str> = ty_str.rsplitn(2, '.').collect(); + let len = splits.len(); + splits[len - 1] +} + +pub fn ty_str_replace_pkgpath(ty_str: &str, pkgpath: &str) -> String { + let pkgpath = format!("@{}", pkgpath); + if ty_str.contains('.') && ty_str_to_pkgpath(ty_str) == pkgpath { + ty_str.replacen(&format!("{}.", pkgpath), "", 1) + } else { + ty_str.to_string() + } +} + +impl<'ctx> Resolver<'_> { + #[inline] + pub fn any_ty(&self) -> TypeRef { + self.ctx.ty_ctx.builtin_types.any.clone() + } + #[inline] + pub fn int_ty(&self) -> TypeRef { + self.ctx.ty_ctx.builtin_types.int.clone() + } + #[inline] + pub fn float_ty(&self) -> TypeRef { + self.ctx.ty_ctx.builtin_types.float.clone() + } + #[inline] + pub fn bool_ty(&self) -> TypeRef { + self.ctx.ty_ctx.builtin_types.bool.clone() + } + #[inline] + pub fn str_ty(&self) -> TypeRef { + self.ctx.ty_ctx.builtin_types.str.clone() + } + #[inline] + pub fn none_ty(&self) -> TypeRef { + self.ctx.ty_ctx.builtin_types.none.clone() + } + #[inline] + pub fn void_ty(&self) -> TypeRef { + self.ctx.ty_ctx.builtin_types.void.clone() + } + /// Parse the type string with the scope, if parse_ty returns a Named type(schema type or type alias), + /// found it from the scope. + pub fn parse_ty_with_scope( + &mut self, + ty_node: Option<&ast::Node>, + range: Range, + ) -> ResolvedResult { + let ty: TypeRef = if let Some(ty) = ty_node { + Arc::new(ty.node.clone().into()) + } else { + Arc::new(Type::ANY) + }; + // If a named type, find it from scope to get the specific type + let ret_ty = self.upgrade_named_ty_with_scope(ty.clone(), &range, ty_node); + self.add_type_alias( + &ty.into_type_annotation_str(), + &ret_ty.into_type_annotation_str(), + ); + if let Some(ty) = ty_node { + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(ty.id.clone()), ret_ty.clone()); + }; + ret_ty + } + + pub fn parse_ty_str_with_scope(&mut self, ty_str: &str, range: Range) -> ResolvedResult { + let ty: TypeRef = parse_type_str(ty_str); + // If a named type, find it from scope to get the specific type + let ret_ty = self.upgrade_named_ty_with_scope(ty, &range, None); + self.add_type_alias(ty_str, &ret_ty.into_type_annotation_str()); + ret_ty + } + + /// The given expression must be the expected type. + #[inline] + pub fn must_be_type(&mut self, expr: &'ctx ast::NodeRef, expected_ty: TypeRef) { + let ty = self.expr(expr); + self.must_assignable_to(ty, expected_ty, expr.get_span_pos(), None); + } + + /// Must assignable to the expected type. + #[inline] + pub fn must_assignable_to( + &mut self, + ty: TypeRef, + expected_ty: TypeRef, + range: Range, + def_range: Option, + ) { + self.attr_must_assignable_to(ty, expected_ty, range, def_range, None); + } + + /// Attribute must assignable to the expected type. + pub fn attr_must_assignable_to( + &mut self, + ty: TypeRef, + expected_ty: TypeRef, + range: Range, + def_range: Option, + attr_range: Option, + ) { + if !self.check_type(ty.clone(), expected_ty.clone(), &range) { + let mut msgs = vec![Message { + range, + style: Style::LineAndColumn, + message: format!("expected {}, got {}", expected_ty.ty_str(), ty.ty_str(),), + note: None, + suggested_replacement: None, + }]; + + if let Some(def_range) = def_range { + // If the range is not a dummy range, append the definition error message + // in the diagnostic. + if !def_range.0.filename.is_empty() && !def_range.1.filename.is_empty() { + msgs.push(Message { + range: def_range, + style: Style::LineAndColumn, + message: format!( + "variable is defined here, its type is {}, but got {}", + expected_ty.ty_str(), + ty.ty_str(), + ), + note: None, + suggested_replacement: None, + }); + } + } + if let Some(attr_range) = attr_range { + msgs.push(Message { + range: attr_range.clone(), + style: Style::LineAndColumn, + message: "config attribute is defined here".to_string(), + note: None, + suggested_replacement: None, + }); + } + self.handler.add_error(ErrorKind::TypeError, &msgs); + } + } + + // Upgrade the dict type into schema type if it is expected to schema + pub(crate) fn upgrade_dict_to_schema(&mut self, ty: TypeRef, expected_ty: TypeRef) -> TypeRef { + match (&ty.kind, &expected_ty.kind) { + (TypeKind::Dict(dict_ty), TypeKind::Schema(schema_ty)) => { + if self.upgrade_dict_to_schema_attr_check(dict_ty, schema_ty) { + expected_ty + } else { + ty + } + } + (TypeKind::List(item_ty), TypeKind::List(expected_item_ty)) => { + Type::list(self.upgrade_dict_to_schema(item_ty.clone(), expected_item_ty.clone())) + .into() + } + ( + TypeKind::Dict(DictType { key_ty, val_ty, .. }), + TypeKind::Dict(DictType { + key_ty: expected_key_ty, + val_ty: expected_val_ty, + .. + }), + ) => Type::dict( + self.upgrade_dict_to_schema(key_ty.clone(), expected_key_ty.clone()), + self.upgrade_dict_to_schema(val_ty.clone(), expected_val_ty.clone()), + ) + .into(), + (TypeKind::Dict(dict_ty), TypeKind::Union(expected_union_type)) => { + let types: Vec> = expected_union_type + .iter() + .filter(|ty| match ty.kind { + TypeKind::Schema(_) => true, + _ => false, + }) + .filter(|ty| { + self.upgrade_dict_to_schema_attr_check(dict_ty, &ty.into_schema_type()) + }) + .map(|ty| ty.clone()) + .collect(); + crate::ty::sup(&types).into() + } + _ => ty, + } + } + + /// Check the type assignment statement between type annotation and target. + pub fn check_assignment_type_annotation( + &mut self, + assign_stmt: &kcl_ast::ast::AssignStmt, + value_ty: TypeRef, + ) { + if assign_stmt.ty.is_none() { + return; + } + for target in &assign_stmt.targets { + let name = &target.node.name.node; + // If the assignment statement has type annotation, check the type of value and the type annotation of target + + if let Some(ty_annotation) = &assign_stmt.ty { + let annotation_ty = + self.parse_ty_with_scope(Some(&ty_annotation), ty_annotation.get_span_pos()); + // If the target defined in the scope, check the type of value and the type annotation of target + let target_ty = if let Some(obj) = self.scope.borrow().elems.get(name) { + let obj = obj.borrow(); + if obj.ty.is_any() { + annotation_ty + } else { + if !is_upper_bound(annotation_ty.clone(), obj.ty.clone()) { + self.handler.add_error( + ErrorKind::TypeError, + &[ + Message { + range: target.get_span_pos(), + style: Style::LineAndColumn, + message: format!( + "can not change the type of '{}' to {}", + name, + annotation_ty.ty_str() + ), + note: None, + suggested_replacement: None, + }, + Message { + range: obj.get_span_pos(), + style: Style::LineAndColumn, + message: format!("expected {}", obj.ty.ty_str()), + note: None, + suggested_replacement: None, + }, + ], + ); + } + obj.ty.clone() + } + } else { + annotation_ty + }; + + self.set_type_to_scope(name, target_ty.clone(), &target.node.name); + + // Check if this is a list assignment with schema type annotation + let is_list_with_schema_elements = match (&target_ty.kind, &value_ty.kind) { + (TypeKind::List(expected_item_ty), TypeKind::List(_)) => { + // Check if the expected type is a Schema + match &expected_item_ty.kind { + TypeKind::Schema(_) => true, + _ => false, + } + } + _ => false, + }; + + // For list with schema elements, we need stricter checking + if is_list_with_schema_elements { + // Type checking for lists with schema elements should be stricter to + // ensure all elements are of the expected schema type + self.must_assignable_to( + value_ty.clone(), + target_ty.clone(), + target.get_span_pos(), + None, + ); + } else { + // Regular type checking for other types + self.must_assignable_to( + value_ty.clone(), + target_ty, + target.get_span_pos(), + None, + ) + } + } + } + } + + /// The check type main function, returns a boolean result. + #[inline] + pub fn check_type(&mut self, ty: TypeRef, expected_ty: TypeRef, range: &Range) -> bool { + // Check assignable between types. + match (&ty.kind, &expected_ty.kind) { + (TypeKind::List(item_ty), TypeKind::List(expected_item_ty)) => { + // Check that the item type of the list is assignable to the expected item type + self.check_type(item_ty.clone(), expected_item_ty.clone(), range) + } + ( + TypeKind::Dict(DictType { key_ty, val_ty, .. }), + TypeKind::Dict(DictType { + key_ty: expected_key_ty, + val_ty: expected_val_ty, + .. + }), + ) => { + self.check_type(key_ty.clone(), expected_key_ty.clone(), range) + && self.check_type(val_ty.clone(), expected_val_ty.clone(), range) + } + (TypeKind::Dict(dict_ty), TypeKind::Schema(schema_ty)) => { + self.dict_assignable_to_schema(dict_ty, schema_ty, range) + } + (TypeKind::Union(types), _) => types + .iter() + .all(|ty| self.check_type(ty.clone(), expected_ty.clone(), range)), + (_, TypeKind::Union(types)) => types + .iter() + .any(|expected_ty| self.check_type(ty.clone(), expected_ty.clone(), range)), + _ => assignable_to(ty, expected_ty), + } + } + + /// Judge a dict can be converted to schema in compile time + /// Do relaxed schema check key and value type check. + pub(crate) fn dict_assignable_to_schema( + &mut self, + dict_ty: &DictType, + schema_ty: &SchemaType, + range: &Range, + ) -> bool { + let (key_ty, val_ty) = (dict_ty.key_ty.clone(), dict_ty.val_ty.clone()); + if let Some(index_signature) = &schema_ty.index_signature { + let val_ty = match (&key_ty.kind, &val_ty.kind) { + (TypeKind::Union(key_tys), TypeKind::Union(val_tys)) => { + let mut index_signature_val_tys: Vec = vec![]; + for (i, key_ty) in key_tys.iter().enumerate() { + if let TypeKind::StrLit(s) = &key_ty.kind { + if schema_ty.attrs.get(s).is_none() && val_tys.get(i).is_some() { + index_signature_val_tys.push(val_tys.get(i).unwrap().clone()); + } + } + } + crate::ty::sup(&index_signature_val_tys).into() + } + _ => val_ty, + }; + if dict_ty.attrs.is_empty() { + if !self.check_type(val_ty.clone(), index_signature.val_ty.clone(), range) { + self.handler.add_type_error( + &format!( + "expected schema index signature value type {}, got {}", + index_signature.val_ty.ty_str(), + val_ty.ty_str() + ), + range.clone(), + ); + } + } else { + for (name, attr) in &dict_ty.attrs { + if index_signature.any_other { + if let Some(attr_obj) = schema_ty.attrs.get(name) { + self.must_assignable_to( + attr.ty.clone(), + attr_obj.ty.clone(), + range.clone(), + Some(attr_obj.range.clone()), + ); + } else { + self.must_assignable_to( + attr.ty.clone(), + index_signature.val_ty.clone(), + attr.range.clone(), + None, + ); + } + } else { + self.must_assignable_to( + attr.ty.clone(), + index_signature.val_ty.clone(), + attr.range.clone(), + None, + ); + } + } + } + true + } else { + // When assigning a dict type to an instance of a schema type, + // check whether the type of key value pair in dict matches the attribute type in the schema. + if let TypeKind::StrLit(key_name) = &key_ty.kind { + if let Some(attr_obj) = schema_ty.attrs.get(key_name) { + if let Some(attr) = dict_ty.attrs.get(key_name) { + self.must_assignable_to( + attr.ty.clone(), + attr_obj.ty.clone(), + range.clone(), + Some(attr_obj.range.clone()), + ); + } + return true; + } + } + true + } + } + + /// Judge a dict can be upgrade to schema. + /// More strict than `dict_assign_to_schema()`: schema attr contains all attributes in key + pub fn upgrade_dict_to_schema_attr_check( + &mut self, + dict_ty: &DictType, + schema_ty: &SchemaType, + ) -> bool { + if schema_ty.index_signature.is_some() { + return true; + } + match &dict_ty.key_ty.kind { + // empty dict {} + TypeKind::Any => true, + // single key: {key1: value1} + TypeKind::StrLit(s) => schema_ty.attrs.len() >= 1 && schema_ty.attrs.contains_key(s), + // multi key: { + // key1: value1 + // key2: value2 + // ... + // } + TypeKind::Union(types) => { + let (attrs, has_index_signature) = Self::get_schema_attrs(schema_ty); + match (attrs.len() >= types.len(), has_index_signature) { + (true, _) => types.iter().all(|ty| match &ty.kind { + TypeKind::StrLit(s) => attrs.contains(s), + _ => false, + }), + // TODO: do more index_signature check with dict type attrs + (false, true) => true, + (false, false) => false, + } + } + _ => false, + } + } + + fn get_schema_attrs(schema_ty: &SchemaType) -> (Vec, bool) { + let mut attrs: Vec = schema_ty.attrs.keys().map(|attr| attr.clone()).collect(); + let mut has_index_signature = schema_ty.index_signature.is_some(); + if let Some(base) = &schema_ty.base { + let (base_attrs, index_signature) = Self::get_schema_attrs(base); + attrs.extend(base_attrs); + has_index_signature &= index_signature; + } + (attrs, has_index_signature) + } + + fn upgrade_named_ty_with_scope( + &mut self, + ty: TypeRef, + range: &Range, + ty_node: Option<&ast::Node>, + ) -> ResolvedResult { + match &ty.kind { + TypeKind::List(item_ty) => { + let mut inner_node = None; + if let Some(ty_node) = ty_node { + if let ast::Type::List(list_type) = &ty_node.node { + inner_node = list_type.inner_type.as_ref().map(|ty| ty.as_ref()) + } + }; + Type::list_ref(self.upgrade_named_ty_with_scope(item_ty.clone(), range, inner_node)) + } + TypeKind::Dict(DictType { + key_ty, + val_ty, + attrs, + }) => { + let mut key_node = None; + let mut value_node = None; + if let Some(ty_node) = ty_node { + if let ast::Type::Dict(dict_type) = &ty_node.node { + key_node = dict_type.key_type.as_ref().map(|ty| ty.as_ref()); + value_node = dict_type.value_type.as_ref().map(|ty| ty.as_ref()); + } + }; + Type::dict_ref_with_attrs( + self.upgrade_named_ty_with_scope(key_ty.clone(), range, key_node), + self.upgrade_named_ty_with_scope(val_ty.clone(), range, value_node), + attrs + .into_iter() + .map(|(key, attr)| { + ( + key.to_string(), + Attr { + ty: self.upgrade_named_ty_with_scope( + val_ty.clone(), + range, + None, + ), + range: attr.range.clone(), + }, + ) + }) + .collect(), + ) + } + TypeKind::Union(types) => Type::union_ref( + &types + .iter() + .enumerate() + .map(|(index, ty)| { + let mut elem_node = None; + if let Some(ty_node) = ty_node { + if let ast::Type::Union(union_type) = &ty_node.node { + elem_node = + union_type.type_elements.get(index).map(|ty| ty.as_ref()) + } + }; + self.upgrade_named_ty_with_scope(ty.clone(), range, elem_node) + }) + .collect::>(), + ), + TypeKind::Named(ty_str) => { + let ty_str = ty_str_replace_pkgpath(ty_str, &self.ctx.pkgpath); + let names: Vec<&str> = if ty_str.starts_with('@') { + let names: Vec<&str> = ty_str.rsplitn(2, '.').collect(); + names.iter().rev().cloned().collect() + } else { + ty_str.split('.').collect() + }; + if names.is_empty() { + self.handler + .add_compile_error("missing type annotation", range.clone()); + return self.any_ty(); + } + let mut pkgpath = "".to_string(); + let name = names[0]; + if names.len() > 1 && !self.ctx.local_vars.contains(&name.to_string()) { + if let Some(mapping) = self.ctx.import_names.get(&self.ctx.filename) { + pkgpath = mapping + .get(name) + .map_or("".to_string(), |pkgpath| pkgpath.to_string()); + } + } + self.ctx.l_value = false; + let tys = self.resolve_var( + &names.iter().map(|n| n.to_string()).collect::>(), + &pkgpath, + range.clone(), + ); + + if let Some(ty_node) = ty_node { + if let ast::Type::Named(identifier) = &ty_node.node { + for (index, name) in identifier.names.iter().enumerate() { + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(name.id.clone()), tys[index].clone()); + } + let ident_ty = tys.last().unwrap().clone(); + self.node_ty_map + .borrow_mut() + .insert(self.get_node_key(ty_node.id.clone()), ident_ty.clone()); + } + }; + tys.last().unwrap().clone() + } + TypeKind::Function(fn_ty) => { + // Replace the type 'Named' to the real type in function params and return type + let mut params_ty = vec![]; + let mut ret_ty = Type::any_ref(); + if let Some(ty_node) = ty_node { + if let ast::Type::Function(fn_ast_type) = &ty_node.node { + if let Some(params_ast_ty) = fn_ast_type.params_ty.as_ref() { + for (ast_ty, ty) in params_ast_ty.iter().zip(fn_ty.params.iter()) { + params_ty.push(Parameter { + name: ty.name.clone(), + ty: self.upgrade_named_ty_with_scope( + ty.ty.clone(), + range, + Some(ast_ty.as_ref()), + ), + has_default: ty.has_default, + default_value: ty.default_value.clone(), + range: ty_node.get_span_pos(), + }); + } + } + + ret_ty = if let Some(ret_ast_ty) = fn_ast_type.ret_ty.as_ref() { + self.upgrade_named_ty_with_scope( + fn_ty.return_ty.clone(), + range, + Some(ret_ast_ty.as_ref()), + ) + } else { + Type::any_ref() + }; + } + }; + + Arc::new(Type::function( + fn_ty.self_ty.clone(), + ret_ty, + params_ty.as_slice(), + &fn_ty.doc, + fn_ty.is_variadic, + fn_ty.kw_only_index, + )) + } + _ => ty.clone(), + } + } + + pub fn add_type_alias(&mut self, name: &str, alias: &str) { + if alias.starts_with('@') { + if name == &alias[1..] { + return; + } + } else if name == alias { + return; + } + match self.ctx.type_alias_mapping.get_mut(&self.ctx.pkgpath) { + Some(mapping) => { + mapping.insert(name.to_string(), alias.to_string()); + } + None => { + let mut mapping = IndexMap::default(); + mapping.insert(name.to_string(), alias.to_string()); + self.ctx + .type_alias_mapping + .insert(self.ctx.pkgpath.clone(), mapping); + } + } + } +} diff --git a/kclvm/sema/src/resolver/ty_alias.rs b/crates/sema/src/resolver/ty_alias.rs similarity index 97% rename from kclvm/sema/src/resolver/ty_alias.rs rename to crates/sema/src/resolver/ty_alias.rs index 066fb0c71..64ac4adf4 100644 --- a/kclvm/sema/src/resolver/ty_alias.rs +++ b/crates/sema/src/resolver/ty_alias.rs @@ -1,7 +1,7 @@ -use kclvm_ast::ast::Node; -use kclvm_ast::walker::MutSelfMutWalker; -use kclvm_ast::{ast, walk_if_mut, walk_list_mut}; -use kclvm_primitives::IndexMap; +use kcl_ast::ast::Node; +use kcl_ast::walker::MutSelfMutWalker; +use kcl_ast::{ast, walk_if_mut, walk_list_mut}; +use kcl_primitives::IndexMap; #[derive(Default)] struct TypeAliasTransformer { diff --git a/kclvm/sema/src/resolver/ty_erasure.rs b/crates/sema/src/resolver/ty_erasure.rs similarity index 82% rename from kclvm/sema/src/resolver/ty_erasure.rs rename to crates/sema/src/resolver/ty_erasure.rs index eead1b252..d594e41eb 100644 --- a/kclvm/sema/src/resolver/ty_erasure.rs +++ b/crates/sema/src/resolver/ty_erasure.rs @@ -1,5 +1,5 @@ -use kclvm_ast::walker::MutSelfMutWalker; -use kclvm_ast::{ast, walk_if_mut, walk_list_mut}; +use kcl_ast::walker::MutSelfMutWalker; +use kcl_ast::{ast, walk_if_mut, walk_list_mut}; #[derive(Default)] struct TypeErasureTransformer; @@ -8,8 +8,7 @@ const FUNCTION: &str = "function"; impl<'ctx> MutSelfMutWalker<'ctx> for TypeErasureTransformer { fn walk_schema_stmt(&mut self, schema_stmt: &'ctx mut ast::SchemaStmt) { if let Some(schema_index_signature) = schema_stmt.index_signature.as_deref_mut() { - if let kclvm_ast::ast::Type::Function(_) = - &mut schema_index_signature.node.value_ty.node + if let kcl_ast::ast::Type::Function(_) = &mut schema_index_signature.node.value_ty.node { schema_index_signature.node.value_ty.node = FUNCTION.to_string().into(); } @@ -22,13 +21,13 @@ impl<'ctx> MutSelfMutWalker<'ctx> for TypeErasureTransformer { fn walk_schema_attr(&mut self, schema_attr: &'ctx mut ast::SchemaAttr) { walk_list_mut!(self, walk_call_expr, schema_attr.decorators); walk_if_mut!(self, walk_expr, schema_attr.value); - if let kclvm_ast::ast::Type::Function(_) = schema_attr.ty.as_ref().node { + if let kcl_ast::ast::Type::Function(_) = schema_attr.ty.as_ref().node { schema_attr.ty.node = FUNCTION.to_string().into(); } } fn walk_assign_stmt(&mut self, assign_stmt: &'ctx mut ast::AssignStmt) { if let Some(ty) = &mut assign_stmt.ty { - if let kclvm_ast::ast::Type::Function(_) = ty.as_ref().node { + if let kcl_ast::ast::Type::Function(_) = ty.as_ref().node { if let Some(ty_anno) = &mut assign_stmt.ty { ty_anno.node = FUNCTION.to_string().into(); } @@ -37,13 +36,13 @@ impl<'ctx> MutSelfMutWalker<'ctx> for TypeErasureTransformer { self.walk_expr(&mut assign_stmt.value.node); } fn walk_type_alias_stmt(&mut self, type_alias_stmt: &'ctx mut ast::TypeAliasStmt) { - if let kclvm_ast::ast::Type::Function(_) = type_alias_stmt.ty.as_ref().node { + if let kcl_ast::ast::Type::Function(_) = type_alias_stmt.ty.as_ref().node { type_alias_stmt.type_value.node = FUNCTION.to_string(); } } fn walk_arguments(&mut self, arguments: &'ctx mut ast::Arguments) { for ty in (&mut arguments.ty_list.iter_mut()).flatten() { - if let kclvm_ast::ast::Type::Function(_) = ty.as_ref().node { + if let kcl_ast::ast::Type::Function(_) = ty.as_ref().node { ty.node = FUNCTION.to_string().into(); } } @@ -57,7 +56,7 @@ impl<'ctx> MutSelfMutWalker<'ctx> for TypeErasureTransformer { walk_if_mut!(self, walk_arguments, lambda_expr.args); walk_list_mut!(self, walk_stmt, lambda_expr.body); if let Some(ty) = lambda_expr.return_ty.as_mut() { - if let kclvm_ast::ast::Type::Function(_) = ty.as_ref().node { + if let kcl_ast::ast::Type::Function(_) = ty.as_ref().node { ty.node = FUNCTION.to_string().into(); } } diff --git a/kclvm/sema/src/resolver/var.rs b/crates/sema/src/resolver/var.rs similarity index 98% rename from kclvm/sema/src/resolver/var.rs rename to crates/sema/src/resolver/var.rs index 7f69a5cb4..d895b4f05 100644 --- a/kclvm/sema/src/resolver/var.rs +++ b/crates/sema/src/resolver/var.rs @@ -1,9 +1,9 @@ use crate::resolver::Resolver; -use kclvm_ast::ast; -use kclvm_ast::pos::GetPos; -use kclvm_error::diagnostic::Range; -use kclvm_error::*; -use kclvm_primitives::IndexMap; +use kcl_ast::ast; +use kcl_ast::pos::GetPos; +use kcl_error::diagnostic::Range; +use kcl_error::*; +use kcl_primitives::IndexMap; use super::node::ResolvedResult; use super::scope::{ScopeObject, ScopeObjectKind}; @@ -37,7 +37,7 @@ impl<'ctx> Resolver<'_> { return vec![scope_ty.map_or(self.any_ty(), |ty| ty)]; } // If it is a schema attribute, return the attribute type. - if let Some(ref ty) = ty { + if let Some(ty) = &ty { if !ty.is_any() { return vec![ty.clone()]; } diff --git a/kclvm/sema/src/ty/constants.rs b/crates/sema/src/ty/constants.rs similarity index 99% rename from kclvm/sema/src/ty/constants.rs rename to crates/sema/src/ty/constants.rs index bb190744a..91838e1d7 100644 --- a/kclvm/sema/src/ty/constants.rs +++ b/crates/sema/src/ty/constants.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use super::{Type, TypeFlags, TypeKind}; -use kclvm_primitives::IndexMap; +use kcl_primitives::IndexMap; use once_cell::sync::Lazy; /* Type string constants */ diff --git a/kclvm/sema/src/ty/constructor.rs b/crates/sema/src/ty/constructor.rs similarity index 100% rename from kclvm/sema/src/ty/constructor.rs rename to crates/sema/src/ty/constructor.rs diff --git a/crates/sema/src/ty/context.rs b/crates/sema/src/ty/context.rs new file mode 100644 index 000000000..39e238efa --- /dev/null +++ b/crates/sema/src/ty/context.rs @@ -0,0 +1,223 @@ +use std::collections::HashMap; +use std::sync::Arc; + +use super::{DictType, Type, TypeFlags, TypeKind, TypeRef, sup}; +use kcl_error::diagnostic::Range; +use petgraph::algo::kosaraju_scc; +use petgraph::graph::{DiGraph, NodeIndex}; +use petgraph::visit::{DfsEvent, depth_first_search}; + +/// TypeContext responsible for type generation, calculation, +/// and equality and subtype judgment between types. +#[derive(Debug)] +pub struct TypeContext { + pub dep_graph: DiGraph, + pub builtin_types: BuiltinTypes, + node_index_map: HashMap, + node_range_map: HashMap, +} + +#[derive(Debug)] +pub struct BuiltinTypes { + pub any: TypeRef, + pub bool: TypeRef, + pub int: TypeRef, + pub float: TypeRef, + pub str: TypeRef, + pub void: TypeRef, + pub none: TypeRef, +} + +impl Default for TypeContext { + fn default() -> Self { + Self::new() + } +} + +impl TypeContext { + /// New a type context. + pub fn new() -> Self { + TypeContext { + dep_graph: DiGraph::new(), + builtin_types: BuiltinTypes { + any: Arc::new(Type::ANY), + bool: Arc::new(Type::BOOL), + int: Arc::new(Type::INT), + float: Arc::new(Type::FLOAT), + str: Arc::new(Type::STR), + void: Arc::new(Type::VOID), + none: Arc::new(Type::NONE), + }, + node_index_map: HashMap::new(), + node_range_map: HashMap::new(), + } + } + + /// Return true if the dep graph contains a cycle from node. + #[inline] + pub fn is_cyclic_from_node(&self, node: &String) -> bool { + let idx = match self.node_index_map.get(node) { + Some(idx) => idx, + None => return false, + }; + depth_first_search(&self.dep_graph, vec![idx.clone()], |event| match event { + DfsEvent::BackEdge(_, _) => Err(()), + _ => Ok(()), + }) + .is_err() + } + + pub fn find_cycle_nodes(&self, node: &String) -> Vec> { + let idx = match self.node_index_map.get(node) { + Some(idx) => idx, + None => return vec![], + }; + let mut res = vec![]; + let strongly_connected_components: Vec> = kosaraju_scc(&self.dep_graph); + for comp in strongly_connected_components { + if comp.len() > 1 && comp.contains(idx) { + res.push(comp) + } + } + res + } + + #[inline] + pub fn get_node_range(&self, idx: &NodeIndex) -> Option { + self.node_range_map.get(idx).cloned() + } + + /// Add dependencies between "from" and "to". + pub fn add_dependencies(&mut self, from: &str, to: &str, from_node_range: Range) { + let from_idx = self.get_or_insert_node_index(from); + let to_idx = self.get_or_insert_node_index(to); + self.dep_graph.add_edge(from_idx, to_idx, ()); + self.node_range_map.insert(from_idx, from_node_range); + } + + /// Get the node index from the node index map or insert it into the dependency graph. + #[inline] + fn get_or_insert_node_index(&mut self, name: &str) -> NodeIndex { + match self.node_index_map.get(name) { + Some(idx) => *idx, + None => { + let idx = self.dep_graph.add_node(name.to_string()); + self.node_index_map.insert(name.to_string(), idx); + idx + } + } + } + + /// Convert the literal union type to its variable type + /// e.g., 1|2 -> int, 's'|'ss' -> str. + pub fn literal_union_type_to_variable_type(&self, ty: TypeRef) -> TypeRef { + if ty.is_union() { + self.infer_to_variable_type(ty) + } else { + ty + } + } + + /// Judge a type kind in the type kind list or the union + /// type kinds are all in the type kind. + pub fn is_kind_type_or_kind_union_type(&self, ty: TypeRef, flags: &[TypeFlags]) -> bool { + match &ty.kind { + TypeKind::Union(types) => types + .iter() + .all(|ty| flags.iter().any(|flag| ty.contains_flags(*flag))), + _ => flags.iter().any(|flag| ty.contains_flags(*flag)), + } + } + + #[inline] + pub fn is_number_type_or_number_union_type(&self, ty: TypeRef) -> bool { + self.is_kind_type_or_kind_union_type(ty, &[TypeFlags::INT, TypeFlags::FLOAT]) + } + + #[inline] + pub fn is_number_bool_type_or_number_bool_union_type(&self, ty: TypeRef) -> bool { + self.is_kind_type_or_kind_union_type( + ty, + &[TypeFlags::INT, TypeFlags::FLOAT, TypeFlags::BOOL], + ) + } + + #[inline] + pub fn is_config_type_or_config_union_type(&self, ty: TypeRef) -> bool { + self.is_kind_type_or_kind_union_type(ty, &[TypeFlags::DICT, TypeFlags::SCHEMA]) + } + + #[inline] + pub fn is_str_type_or_str_union_type(&self, ty: TypeRef) -> bool { + self.is_kind_type_or_kind_union_type(ty, &[TypeFlags::STR]) + } + + #[inline] + pub fn is_primitive_type_or_primitive_union_type(&self, ty: TypeRef) -> bool { + self.is_kind_type_or_kind_union_type( + ty, + &[ + TypeFlags::INT, + TypeFlags::FLOAT, + TypeFlags::BOOL, + TypeFlags::STR, + ], + ) + } + + #[inline] + pub fn is_mul_val_type_or_mul_val_union_type(&self, ty: TypeRef) -> bool { + self.is_kind_type_or_kind_union_type( + ty, + &[ + TypeFlags::INT, + TypeFlags::FLOAT, + TypeFlags::STR, + TypeFlags::LIST, + ], + ) + } + + /// Convert type to the real type annotation + #[inline] + pub fn into_type_annotation_str(&self, ty: TypeRef) -> String { + ty.into_type_annotation_str() + } +} + +pub trait TypeInferMethods { + /// Infer the value type to the variable type" + fn infer_to_variable_type(&self, ty: TypeRef) -> TypeRef; +} + +impl TypeInferMethods for TypeContext { + /// Infer the value type to the variable type" + fn infer_to_variable_type(&self, ty: TypeRef) -> TypeRef { + match &ty.kind { + // None/Undefined type to any type e.g., None -> any + TypeKind::None => self.builtin_types.any.clone(), + // Literal type to its named type e.g., 1 -> int, "s" -> str + TypeKind::BoolLit(_) => self.builtin_types.bool.clone(), + TypeKind::IntLit(_) => self.builtin_types.int.clone(), + TypeKind::FloatLit(_) => self.builtin_types.float.clone(), + TypeKind::StrLit(_) => self.builtin_types.str.clone(), + TypeKind::List(item_ty) => Type::list_ref(self.infer_to_variable_type(item_ty.clone())), + // Dict type e.g., {str:1|2} -> {str:int} + TypeKind::Dict(DictType { + key_ty, + val_ty, + attrs, + }) => Type::dict_ref_with_attrs( + self.infer_to_variable_type(key_ty.clone()), + self.infer_to_variable_type(val_ty.clone()), + attrs.clone(), + ), + // Union type e.g., 1|2|"s" -> int|str + TypeKind::Union(types) => sup(&types + .iter() + .map(|ty| self.infer_to_variable_type(ty.clone())) + .collect::>()), + _ => ty.clone(), + } + } +} diff --git a/crates/sema/src/ty/into.rs b/crates/sema/src/ty/into.rs new file mode 100644 index 000000000..03a76cd54 --- /dev/null +++ b/crates/sema/src/ty/into.rs @@ -0,0 +1,201 @@ +use super::*; +use kcl_ast::pos::GetPos; + +impl Type { + /// Downcast ty into the list type. + #[inline] + pub fn list_item_ty(&self) -> TypeRef { + match &self.kind { + TypeKind::List(item_ty) => item_ty.clone(), + _ => bug!("invalid list type {}", self.ty_str()), + } + } + /// Downcast ty into the dict entry type. + #[inline] + pub fn dict_entry_ty(&self) -> (TypeRef, TypeRef) { + match &self.kind { + TypeKind::Dict(DictType { key_ty, val_ty, .. }) => (key_ty.clone(), val_ty.clone()), + _ => bug!("invalid dict type {}", self.ty_str()), + } + } + /// Downcast ty into the config key type. + #[inline] + pub fn config_key_ty(&self) -> TypeRef { + match &self.kind { + TypeKind::Dict(DictType { key_ty, .. }) => key_ty.clone(), + TypeKind::Schema(schema_ty) => schema_ty.key_ty(), + _ => bug!("invalid config type {}", self.ty_str()), + } + } + /// Downcast ty into the config value type. + #[inline] + pub fn config_val_ty(&self) -> TypeRef { + match &self.kind { + TypeKind::Dict(DictType { + key_ty: _, val_ty, .. + }) => val_ty.clone(), + TypeKind::Schema(schema_ty) => schema_ty.val_ty(), + _ => bug!("invalid config type {}", self.ty_str()), + } + } + /// Get types from the union type. + #[inline] + pub fn union_types(&self) -> Vec { + match &self.kind { + TypeKind::Union(types) => types.clone(), + _ => bug!("invalid {} into union type", self.ty_str()), + } + } + /// Into schema type. + #[inline] + pub fn into_schema_type(&self) -> SchemaType { + match &self.kind { + TypeKind::Schema(schema_ty) => schema_ty.clone(), + _ => bug!("invalid type {} into schema type", self.ty_str()), + } + } + /// Into function type. + #[inline] + pub fn into_func_type(&self) -> FunctionType { + match &self.kind { + TypeKind::Function(func_ty) => func_ty.clone(), + _ => bug!("invalid type {} into function type", self.ty_str()), + } + } + /// Into number multiplier type. + #[inline] + pub fn into_number_multiplier(&self) -> NumberMultiplierType { + match &self.kind { + TypeKind::NumberMultiplier(number_multiplier) => number_multiplier.clone(), + _ => bug!("invalid type {} into number multiplier type", self.ty_str()), + } + } + /// Get the type string. + pub fn into_type_annotation_str(&self) -> String { + match &self.kind { + TypeKind::None => NAME_CONSTANT_NONE.to_string(), + TypeKind::BoolLit(v) => (if *v { + NAME_CONSTANT_TRUE + } else { + NAME_CONSTANT_FALSE + }) + .to_string(), + TypeKind::IntLit(v) => v.to_string(), + TypeKind::FloatLit(v) => { + let mut float_str = v.to_string(); + if !float_str.contains('.') { + float_str.push_str(".0"); + } + float_str + } + TypeKind::StrLit(v) => format!("\"{}\"", v.replace('"', "\\\"")), + TypeKind::List(item_ty) => format!("[{}]", item_ty.into_type_annotation_str()), + TypeKind::Dict(DictType { key_ty, val_ty, .. }) => { + format!( + "{{{}:{}}}", + key_ty.into_type_annotation_str(), + val_ty.into_type_annotation_str() + ) + } + TypeKind::Union(types) => types + .iter() + .map(|ty| ty.into_type_annotation_str()) + .collect::>() + .join(" | "), + TypeKind::Schema(schema_ty) => schema_ty.ty_str_with_at_pkgpath_prefix(), + TypeKind::NumberMultiplier(number_multiplier) => { + if number_multiplier.is_literal { + format!( + "{}({}{})", + NUMBER_MULTIPLIER_TYPE_STR, + number_multiplier.raw_value, + number_multiplier.binary_suffix + ) + } else { + NUMBER_MULTIPLIER_PKG_TYPE_STR.to_string() + } + } + TypeKind::Function(fn_ty) => fn_ty.ty_str(), + _ => self.ty_str(), + } + } +} + +impl From for Type { + fn from(ty: ast::Type) -> Type { + match ty { + ast::Type::Any => Type::ANY, + ast::Type::Basic(basic_ty) => match basic_ty { + ast::BasicType::Bool => Type::BOOL, + ast::BasicType::Int => Type::INT, + ast::BasicType::Float => Type::FLOAT, + ast::BasicType::Str => Type::STR, + }, + ast::Type::Named(identifier) => Type::named(&identifier.get_name()), + ast::Type::List(list_ty) => Type::list( + list_ty + .inner_type + .as_ref() + .map_or(Arc::new(Type::ANY), |ty| Arc::new(ty.node.clone().into())), + ), + ast::Type::Dict(dict_ty) => Type::dict( + dict_ty + .key_type + .as_ref() + .map_or(Arc::new(Type::ANY), |ty| Arc::new(ty.node.clone().into())), + dict_ty + .value_type + .as_ref() + .map_or(Arc::new(Type::ANY), |ty| Arc::new(ty.node.clone().into())), + ), + ast::Type::Union(union_ty) => Type::union( + &union_ty + .type_elements + .iter() + .map(|ty| Arc::new(ty.node.clone().into())) + .collect::>(), + ), + ast::Type::Literal(literal_ty) => match literal_ty { + ast::LiteralType::Bool(v) => Type::bool_lit(v), + ast::LiteralType::Int(ast::IntLiteralType { + value: v, + suffix: suffix_option, + }) => match suffix_option { + Some(suffix) => Type::number_multiplier( + kcl_runtime::cal_num(v, &suffix.value()), + v, + &suffix.value(), + ), + None => Type::int_lit(v), + }, + ast::LiteralType::Float(v) => Type::float_lit(v), + ast::LiteralType::Str(v) => Type::str_lit(&v), + }, + // Ast::function => Sema::function, + ast::Type::Function(func_ty) => Type::function( + None, + func_ty + .ret_ty + .as_ref() + .map_or(Arc::new(Type::ANY), |ty| Arc::new(ty.node.clone().into())), + func_ty + .params_ty + .map_or(vec![], |tys| { + tys.iter() + .map(|ty| Parameter { + name: "".to_string(), + ty: Arc::new(ty.node.clone().into()), + has_default: false, + range: ty.get_span_pos(), + default_value: None, + }) + .collect::>() + }) + .as_slice(), + "", + false, + None, + ), + } + } +} diff --git a/crates/sema/src/ty/mod.rs b/crates/sema/src/ty/mod.rs new file mode 100644 index 000000000..c8d24a0c3 --- /dev/null +++ b/crates/sema/src/ty/mod.rs @@ -0,0 +1,557 @@ +mod constants; +mod constructor; +mod context; +mod into; +pub mod parser; +mod unify; +mod walker; + +use std::collections::HashMap; +use std::sync::Arc; + +pub use constants::*; +pub use context::{TypeContext, TypeInferMethods}; +use kcl_ast::MAIN_PKG; +use kcl_ast::ast; +use kcl_error::Position; +use kcl_error::diagnostic::Range; +use kcl_primitives::IndexMap; +pub use unify::*; +pub use walker::walk_type; + +use super::resolver::doc::Example; + +#[cfg(test)] +mod tests; + +/// TypeRef represents a reference to a type that exists to avoid copying types everywhere affecting +/// performance. For example, for two instances that are both integer types, there is actually no +/// difference between them. +pub type TypeRef = Arc; + +#[derive(Debug, Clone, PartialEq)] +pub struct Type { + // The type kind. + pub kind: TypeKind, + // Is a type alias. + pub is_type_alias: bool, + /// This field provides fast access to information that is + /// also contained in `kind`. + flags: TypeFlags, +} + +unsafe impl Send for Type {} + +impl Type { + /// Whether the type contains the flag. + #[inline] + pub fn contains_flags(&self, flag: TypeFlags) -> bool { + self.flags.contains(flag) + } + /// Returns the type string used for the error handler. + pub fn ty_str(&self) -> String { + match &self.kind { + TypeKind::None => NONE_TYPE_STR.to_string(), + TypeKind::Any => ANY_TYPE_STR.to_string(), + TypeKind::Bool => BOOL_TYPE_STR.to_string(), + TypeKind::BoolLit(v) => { + format!( + "{}({})", + BOOL_TYPE_STR, + if *v { + NAME_CONSTANT_TRUE + } else { + NAME_CONSTANT_FALSE + } + ) + } + TypeKind::Int => INT_TYPE_STR.to_string(), + TypeKind::IntLit(v) => format!("{}({})", INT_TYPE_STR, v), + TypeKind::Float => FLOAT_TYPE_STR.to_string(), + TypeKind::FloatLit(v) => format!("{}({})", FLOAT_TYPE_STR, v), + TypeKind::Str => STR_TYPE_STR.to_string(), + TypeKind::StrLit(v) => format!("{}({})", STR_TYPE_STR, v), + TypeKind::List(item_ty) => format!("[{}]", item_ty.ty_str()), + TypeKind::Dict(DictType { key_ty, val_ty, .. }) => { + format!("{{{}:{}}}", key_ty.ty_str(), val_ty.ty_str()) + } + TypeKind::Union(types) => types + .iter() + .map(|ty| ty.ty_str()) + .collect::>() + .join(" | "), + TypeKind::Schema(schema_ty) => schema_ty.name.to_string(), + TypeKind::NumberMultiplier(number_multiplier) => number_multiplier.ty_str(), + TypeKind::Function(func_ty) => func_ty.ty_str(), + TypeKind::Void => VOID_TYPE_STR.to_string(), + TypeKind::Module(module_ty) => format!("{} '{}'", MODULE_TYPE_STR, module_ty.pkgpath), + TypeKind::Named(name) => name.to_string(), + } + } + + pub fn ty_hint(&self) -> String { + match &self.kind { + TypeKind::StrLit(s) => format!("\"{}\"", s), + TypeKind::IntLit(v) => v.to_string(), + TypeKind::FloatLit(v) => v.to_string(), + TypeKind::List(item_ty) => format!("[{}]", item_ty.ty_hint()), + TypeKind::Dict(DictType { key_ty, val_ty, .. }) => { + format!("{{{}:{}}}", key_ty.ty_hint(), val_ty.ty_hint()) + } + TypeKind::Union(types) => types + .iter() + .map(|ty| ty.ty_hint()) + .collect::>() + .join(" | "), + _ => self.ty_str(), + } + } + + /// Returns the full type string with the package path used for the error handler. + pub fn full_ty_str(&self) -> String { + match &self.kind { + TypeKind::List(item_ty) => format!("[{}]", item_ty.full_ty_str()), + TypeKind::Dict(DictType { key_ty, val_ty, .. }) => { + format!("{{{}:{}}}", key_ty.full_ty_str(), val_ty.full_ty_str()) + } + TypeKind::Union(types) => types + .iter() + .map(|ty| ty.full_ty_str()) + .collect::>() + .join(" | "), + TypeKind::Schema(schema_ty) => schema_ty.full_ty_str(), + _ => self.ty_str(), + } + } + + pub fn ty_doc(&self) -> Option { + match &self.kind { + TypeKind::Schema(schema) => Some(schema.doc.clone()), + TypeKind::Function(func) => Some(func.doc.clone()), + _ => None, + } + } +} + +unsafe impl Send for TypeKind {} +unsafe impl Sync for TypeKind {} + +#[derive(Debug, Clone, PartialEq)] +pub enum TypeKind { + /// A primitive None name constant. + None, + /// The any type. + Any, + /// The primitive boolean type. Written as `bool`. + Bool, + BoolLit(bool), + /// A primitive integer type. Written as `int`. + Int, + /// A primitive integer literal type. + IntLit(i64), + /// A primitive float type. Written as `float`. + Float, + /// A primitive float literal type. + FloatLit(f64), + /// The primitive string type; holds a Unicode scalar value + /// (a non-surrogate code point). Written as `str`. + Str, + /// A primitive string literal type. + StrLit(String), + /// The pointer of an array slice. Written as `[T]`. + List(TypeRef), + /// A map type. Written as `{kT, vT}`. + Dict(DictType), + /// A union type. Written as ty1 | ty2 | ... | tyn + Union(Vec), + /// A schema type. + Schema(SchemaType), + /// A number multiplier type. + NumberMultiplier(NumberMultiplierType), + /// The function type. + Function(FunctionType), + /// The bottom never type. + Void, + /// The module type. + Module(ModuleType), + /// A named type alias. + Named(String), +} + +bitflags::bitflags! { + /// TypeFlags provides fast access to information that is also contained + /// in `kind`. + pub struct TypeFlags: u16 { + const VOID = 1 << 0; + const INT = 1 << 1; + const FLOAT = 1 << 2; + const STR = 1 << 3; + const BOOL = 1 << 4; + const ANY = 1 << 5; + const NONE = 1 << 6; + const LIST = 1 << 7; + const DICT = 1 << 8; + const SCHEMA = 1 << 9; + const UNION = 1 << 10; + const LITERAL = 1 << 11; + const NUMBER_MULTIPLIER = 1 << 12; + const FUNCTION = 1 << 13; + const MODULE = 1 << 14; + const NAMED = 1 << 15; + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct DictType { + pub key_ty: TypeRef, + pub val_ty: TypeRef, + pub attrs: IndexMap, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Attr { + pub ty: TypeRef, + pub range: Range, +} + +/// The schema type. +#[derive(Debug, Clone, PartialEq)] +pub struct SchemaType { + /// The schema name. + pub name: String, + /// The schema definition package path + pub pkgpath: String, + /// The schema definition file path. + pub filename: String, + /// The schema definition document string. + pub doc: String, + /// The code snippets of the schema usage examples + pub examples: HashMap, + /// Indicates whether the schema is a type of a instance or + /// a type (value). Besides, it is necessary to distinguish + /// between a type instance and a type value, such as the following code: + /// ```no_check + /// # `Person` in `schema Person` is a type and it is not a schema instance. + /// schema Person: + /// name: str + /// + /// # `person` is a schema instance. + /// person = Person {name = "Alice"} + /// # `person` is a schema instance used in the value expression. + /// name = person.name + /// # `Person` in `persons: [Person]` is a type, `Person` in `Person.instances()` + /// # is a type value, and they are not schema instances. + /// persons: [Person] = Person.instances() + /// ``` + pub is_instance: bool, + /// Indicates whether it is a schema mixin. + pub is_mixin: bool, + /// Indicates whether it is a schema protocol. + pub is_protocol: bool, + /// Indicates whether it is a rule. + pub is_rule: bool, + /// Base schema. + pub base: Option>, + /// Protocol schema. + pub protocol: Option>, + /// Schema Mixins. + pub mixins: Vec, + /// Schema attributes. + pub attrs: IndexMap, + /// Schema function type. + pub func: Box, + /// Schema index signature. + pub index_signature: Option>, + /// Schema decorators including self and attribute decorators. + pub decorators: Vec, +} + +impl SchemaType { + /// Get the object type string with @pkgpath prefix. + pub fn ty_str_with_at_pkgpath_prefix(&self) -> String { + if self.pkgpath.is_empty() || self.pkgpath == MAIN_PKG { + self.name.clone() + } else { + format!("@{}.{}", self.pkgpath, self.name) + } + } + + /// Get the object type string. + pub fn full_ty_str(&self) -> String { + full_ty_str(&self.pkgpath, &self.name) + } + + /// Is `name` a schema member function + pub fn is_member_functions(&self, name: &str) -> bool { + !self.is_instance && SCHEMA_MEMBER_FUNCTIONS.contains(&name) + } + + pub fn set_type_of_attr(&mut self, attr: &str, ty: TypeRef) { + match self.attrs.get_mut(attr) { + Some(attr) => attr.ty = ty, + None => { + let schema_attr = SchemaAttr { + is_optional: true, + has_default: false, + default: None, + ty, + range: (Position::dummy_pos(), Position::dummy_pos()), + doc: None, + decorators: vec![], + }; + self.attrs.insert(attr.to_string(), schema_attr); + } + } + } + + #[inline] + pub fn get_type_of_attr(&self, attr: &str) -> Option { + self.get_obj_of_attr(attr).map(|attr| attr.ty.clone()) + } + + #[inline] + pub fn get_obj_of_attr(&self, attr: &str) -> Option<&SchemaAttr> { + match self.attrs.get(attr) { + Some(attr) => Some(attr), + None => self.base.as_ref().map_or( + self.protocol + .as_ref() + .and_then(|protocol| protocol.get_obj_of_attr(attr)), + |base| base.get_obj_of_attr(attr), + ), + } + } + + pub fn key_ty(&self) -> TypeRef { + Arc::new(Type::STR) + } + + pub fn val_ty(&self) -> TypeRef { + if let Some(index_signature) = &self.index_signature { + index_signature.val_ty.clone() + } else { + Arc::new(Type::ANY) + } + } + + pub fn schema_ty_signature_str(&self) -> (String, String) { + let base: String = if let Some(base) = &self.base { + format!("({})", base.name) + } else { + "".to_string() + }; + let params: String = if self.func.params.is_empty() { + "".to_string() + } else { + format!( + "[{}]", + self.func + .params + .iter() + .map(|p| format!("{}: {}", p.name.clone(), p.ty.ty_str())) + .collect::>() + .join(", ") + ) + }; + + let rest_sign = format!("schema {}{}{}:", self.name, params, base); + + (self.pkgpath.clone(), rest_sign) + } + + pub fn schema_ty_signature_no_pkg(&self) -> String { + let base: String = if let Some(base) = &self.base { + format!("({})", base.name) + } else { + "".to_string() + }; + let params: String = if self.func.params.is_empty() { + "".to_string() + } else { + format!( + "[{}]", + self.func + .params + .iter() + .map(|p| format!("{}: {}", p.name.clone(), p.ty.ty_str())) + .collect::>() + .join(", ") + ) + }; + let params_str = if !params.is_empty() && !base.is_empty() { + format!("\\{}{}", params, base) + } else if !params.is_empty() { + format!("{}", params) + } else if !base.is_empty() { + format!("{}", base) + } else { + "".to_string() + }; + format!("schema {}{}", self.name, params_str) + } +} + +pub fn full_ty_str(pkgpath: &str, name: &str) -> String { + if pkgpath.is_empty() || pkgpath == MAIN_PKG { + name.to_string() + } else { + format!("{}.{}", pkgpath, name) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct SchemaAttr { + pub is_optional: bool, + pub has_default: bool, + /// `default` denotes the schema attribute optional value string. For example, + /// for the schema attribute definition `name?: str = "Alice"`, the value of + /// `default` is [Some("Alice")]. + /// For the schema attribute definition `name?: str`, the value of `default` + /// is [None]. + pub default: Option, + pub ty: TypeRef, + pub range: Range, + pub doc: Option, + pub decorators: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct SchemaIndexSignature { + pub key_name: Option, + pub key_ty: TypeRef, + pub val_ty: TypeRef, + pub any_other: bool, +} + +impl SchemaIndexSignature { + pub fn ty_str(&self) -> String { + let key_name_str = match &self.key_name { + Some(name) => format!("[{}: ", name), + None => "[".to_string(), + }; + let any_other_str = if self.any_other { "..." } else { "" }; + key_name_str + + any_other_str + + &format!("{}]: {}", self.key_ty.ty_str(), self.val_ty.ty_str()) + } +} + +/// The module type. +#[derive(Debug, Clone, PartialEq)] +pub struct ModuleType { + pub pkgpath: String, + pub imported: Vec, + pub kind: ModuleKind, +} + +/// The module kind. +#[derive(Debug, Clone, PartialEq)] +pub enum ModuleKind { + User, + System, + Plugin, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Decorator { + /// The decorator target e.g., the schema statement or schema attribute. + pub target: DecoratorTarget, + /// The decorator name. + pub name: String, + /// The schema or attribute name of decorator dimension. + pub key: String, + /// The decorator argument list values. + pub arguments: Vec, + /// The decorator keyword mapping values. + pub keywords: HashMap, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum DecoratorTarget { + Schema, + Attribute, +} + +/// The number multiplier type. +#[derive(Debug, Clone, PartialEq)] +pub struct NumberMultiplierType { + pub value: f64, + pub raw_value: i64, + pub binary_suffix: String, + pub is_literal: bool, +} + +impl NumberMultiplierType { + pub fn ty_str(&self) -> String { + if self.is_literal { + format!( + "{}({}{})", + NUMBER_MULTIPLIER_TYPE_STR, self.raw_value, self.binary_suffix + ) + } else { + NUMBER_MULTIPLIER_TYPE_STR.to_string() + } + } +} + +/// The function type. +#[derive(Debug, Clone, PartialEq)] +pub struct FunctionType { + pub doc: String, + pub params: Vec, + pub self_ty: Option, + pub return_ty: TypeRef, + pub is_variadic: bool, + pub kw_only_index: Option, +} + +impl FunctionType { + pub fn ty_str(&self) -> String { + format!( + "({}) -> {}", + self.params + .iter() + .map(|param| param.ty.ty_str()) + .collect::>() + .join(", "), + self.return_ty.ty_str() + ) + } + + pub fn func_signature_str(&self, name: &String) -> String { + format!( + "function {}({}) -> {}", + name, + self.params + .iter() + .map(|param| format!("{}: {}", param.name, param.ty.ty_str())) + .collect::>() + .join(", "), + self.return_ty.ty_str() + ) + } +} + +impl FunctionType { + #[inline] + pub fn variadic_func() -> Self { + Self { + doc: "".to_string(), + params: vec![], + self_ty: None, + return_ty: Type::any_ref(), + is_variadic: true, + kw_only_index: None, + } + } +} + +/// The function parameter type and position information. +#[derive(Debug, Clone, PartialEq)] +pub struct Parameter { + pub name: String, + pub ty: TypeRef, + pub has_default: bool, + pub default_value: Option, + pub range: Range, +} diff --git a/kclvm/sema/src/ty/parser.rs b/crates/sema/src/ty/parser.rs similarity index 98% rename from kclvm/sema/src/ty/parser.rs rename to crates/sema/src/ty/parser.rs index 285a4720a..0f1d962a6 100644 --- a/kclvm/sema/src/ty/parser.rs +++ b/crates/sema/src/ty/parser.rs @@ -190,7 +190,7 @@ pub fn parse_lit_type_str(ty_str: &str) -> TypeRef { /// Parse number multiplier literal type. pub fn parse_number_multiplier_literal_type_str(ty_str: &str) -> TypeRef { - let suffix_index = if &ty_str[ty_str.len() - 1..] == kclvm_runtime::IEC_SUFFIX { + let suffix_index = if &ty_str[ty_str.len() - 1..] == kcl_runtime::IEC_SUFFIX { ty_str.len() - 2 } else { ty_str.len() - 1 @@ -203,7 +203,7 @@ pub fn parse_number_multiplier_literal_type_str(ty_str: &str) -> TypeRef { &ty_str[suffix_index..], ); Arc::new(Type::number_multiplier( - kclvm_runtime::cal_num(value, suffix), + kcl_runtime::cal_num(value, suffix), value, suffix, )) diff --git a/kclvm/sema/src/ty/tests.rs b/crates/sema/src/ty/tests.rs similarity index 100% rename from kclvm/sema/src/ty/tests.rs rename to crates/sema/src/ty/tests.rs diff --git a/kclvm/sema/src/ty/unify.rs b/crates/sema/src/ty/unify.rs similarity index 99% rename from kclvm/sema/src/ty/unify.rs rename to crates/sema/src/ty/unify.rs index b116f67aa..9ca9e5d39 100644 --- a/kclvm/sema/src/ty/unify.rs +++ b/crates/sema/src/ty/unify.rs @@ -1,6 +1,6 @@ use std::{collections::HashSet, sync::Arc}; -use kclvm_primitives::IndexMap; +use kcl_primitives::IndexMap; use super::{SchemaType, Type, TypeKind, TypeRef}; diff --git a/kclvm/sema/src/ty/walker.rs b/crates/sema/src/ty/walker.rs similarity index 100% rename from kclvm/sema/src/ty/walker.rs rename to crates/sema/src/ty/walker.rs diff --git a/crates/span/Cargo.toml b/crates/span/Cargo.toml new file mode 100644 index 000000000..267096a85 --- /dev/null +++ b/crates/span/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "kcl-span" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +compiler_base_span = "0.1.2" + +kcl-macros = { path = "../macros" } +scoped-tls = "1.0" +parking_lot = "0.11" diff --git a/kclvm/span/LICENSE b/crates/span/LICENSE similarity index 100% rename from kclvm/span/LICENSE rename to crates/span/LICENSE diff --git a/crates/span/src/lib.rs b/crates/span/src/lib.rs new file mode 100644 index 000000000..35d504a68 --- /dev/null +++ b/crates/span/src/lib.rs @@ -0,0 +1,22 @@ +//! Source positions and related helper functions. +//! +//! Important concepts in this module include: +//! +//! - the *span*, represented by [`Span`] and related types; +//! - interned strings, represented by [`Symbol`]s, with some common symbols available statically in the [`sym`] module. +//! +//! Reference: https://github.com/rust-lang/rust/blob/master/compiler/rustc_span/src/lib.rs + +mod session_globals; +pub mod symbol; + +#[cfg(test)] +mod tests; + +pub use compiler_base_span::{BytePos, FilePathMapping, Loc, SourceFile, SourceMap, Span}; +pub use session_globals::create_session_globals_then; +use session_globals::with_session_globals; +pub use symbol::{Ident, Symbol}; + +#[macro_use] +extern crate kcl_macros; diff --git a/kclvm/span/src/session_globals.rs b/crates/span/src/session_globals.rs similarity index 97% rename from kclvm/span/src/session_globals.rs rename to crates/span/src/session_globals.rs index c655a369a..2ac67768c 100644 --- a/kclvm/span/src/session_globals.rs +++ b/crates/span/src/session_globals.rs @@ -7,7 +7,7 @@ use std::{collections::HashMap, sync::Arc}; /// threads within the compilation session, but is not accessible outside the /// session. /// -/// The `kclvm_span::Symbol` uses `SessionGlobals` to implement a fast global +/// The `kcl_span::Symbol` uses `SessionGlobals` to implement a fast global /// string cache. #[derive(Debug)] pub struct SessionGlobals { diff --git a/crates/span/src/symbol.rs b/crates/span/src/symbol.rs new file mode 100644 index 000000000..eb08cc535 --- /dev/null +++ b/crates/span/src/symbol.rs @@ -0,0 +1,246 @@ +use compiler_base_span::{DUMMY_SP, Span}; +use std::{ + fmt, + hash::{Hash, Hasher}, +}; + +use crate::session_globals::Interner; +use crate::with_session_globals; + +// The proc macro code for this is in `kcl_macros/src/symbols.rs`. +symbols! { + // After modifying this list adjust `is_special`, `is_used_keyword`/`is_unused_keyword`, + // this should be rarely necessary though if the keywords are kept in alphabetic order. + Keywords { + // Special reserved identifiers used internally for elided lifetimes, + // unnamed method parameters, crate root module, error recovery etc. + Empty: "", + As: "as", + Import: "import", + Rule: "rule", + Schema: "schema", + Mixin: "mixin", + Protocol: "protocol", + Check: "check", + For: "for", + Assert: "assert", + If: "if", + Elif: "elif", + Else: "else", + Or: "or", + And: "and", + Not: "not", + In: "in", + Is: "is", + Lambda: "lambda", + All: "all", + Any: "any", + Filter: "filter", + Map: "map", + Type: "type", + True: "True", + False: "False", + None: "None", + Undefined: "Undefined", + } + // Pre-interned symbols that can be referred to with `kcl_span::sym::*`. + Symbols { + bool, + float, + int, + str, + } +} + +/// Ident denotes a identifier with a symbol name and span +/// +/// ``` +/// use kcl_span::*; +/// use compiler_base_span::span::new_byte_pos; +/// +/// create_session_globals_then(||{ +/// let ident = Ident::new( +/// Symbol::intern("identifier"), +/// Span::new(new_byte_pos(0), new_byte_pos(10)), +/// ); +/// }) +/// ``` +#[derive(Debug, Copy, Clone, Eq)] +pub struct Ident { + pub name: Symbol, + pub span: Span, +} + +impl std::str::FromStr for Ident { + type Err = String; + /// Maps a string to an identifier with a dummy span. + fn from_str(s: &str) -> Result { + Ok(Ident::with_dummy_span(Symbol::intern(s))) + } +} + +impl Ident { + #[inline] + /// Constructs a new identifier from a symbol and a span. + pub const fn new(name: Symbol, span: Span) -> Ident { + Ident { name, span } + } + + /// Constructs a new identifier with a dummy span. + #[inline] + pub const fn with_dummy_span(name: Symbol) -> Ident { + Ident::new(name, DUMMY_SP) + } + + /// Maps a string and a span to an identifier. + pub fn from_str_and_span(string: &str, span: Span) -> Ident { + Ident::new(Symbol::intern(string), span) + } + + pub fn without_first_quote(self) -> Ident { + Ident::new( + Symbol::intern(self.as_str().trim_start_matches('\'')), + self.span, + ) + } + + /// Access the underlying string. This is a slowish operation because it + /// requires locking the symbol interner. + /// + /// Note that the lifetime of the return value is a lie. See + /// `Symbol::as_str()` for details. + pub fn as_str(&self) -> String { + self.name.as_str() + } +} + +impl PartialEq for Ident { + fn eq(&self, rhs: &Self) -> bool { + self.name == rhs.name + } +} + +impl Hash for Ident { + fn hash(&self, state: &mut H) { + self.name.hash(state); + self.span.hash(state); + } +} + +/// An interned string. +/// +/// Internally, a `Symbol` is implemented as an index, and all operations +/// (including hashing, equality, and ordering) operate on that index. +/// +/// ``` +/// use kcl_span::*; +/// create_session_globals_then(||{ +/// let sym = Symbol::intern("name"); +/// }); +/// ``` +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +pub struct Symbol(pub(crate) SymbolIndex); + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +pub struct SymbolIndex { + pub(crate) idx: u32, +} + +impl Symbol { + pub(crate) const fn new(n: u32) -> Self { + Symbol(SymbolIndex { idx: n }) + } + + /// Maps a string to its interned representation. + pub fn intern(string: &str) -> Self { + with_session_globals(|session_globals| session_globals.symbol_interner.intern(string)) + } + + /// Access the underlying string. This is a slowish operation because it + /// requires locking the symbol interner. + /// + /// Note that the lifetime of the return value is a lie. It's not the same + /// as `&self`, but actually tied to the lifetime of the underlying + /// interner. Interners are long-lived, and there are very few of them, and + /// this function is typically used for short-lived things, so in practice + /// it works out ok. + pub fn as_str(&self) -> String { + with_session_globals(|session_globals| session_globals.symbol_interner.get(*self)) + } + + pub fn as_u32(self) -> u32 { + self.0.idx + } + + /// This method is supposed to be used in error messages, so it's expected to be + /// identical to printing the original identifier token written in source code + /// (`token_to_string`, `Ident::to_string`), except that symbols don't keep the rawness flag + /// or edition, so we have to guess the rawness using the global edition. + pub fn to_ident_string(self) -> String { + format!("{:?}", Ident::with_dummy_span(self)) + } +} + +impl fmt::Display for Symbol { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&self.as_str(), f) + } +} + +impl From for String { + fn from(val: Symbol) -> Self { + val.as_str() + } +} + +// This module has a very short name because it's used a lot. +/// This module contains all the defined keyword `Symbol`s. +/// +/// Given that `kw` is imported, use them like `kw::keyword_name`. +/// For example `kw::Loop` or `kw::Break`. +pub mod kw { + pub use super::kw_generated::*; +} + +// This module has a very short name because it's used a lot. +/// This module contains all the defined non-keyword `Symbol`s. +/// +/// Given that `sym` is imported, use them like `sym::symbol_name`. +/// For example `sym::rustfmt` or `sym::u8`. +pub mod sym { + use super::Symbol; + use std::convert::TryInto; + + #[doc(inline)] + pub use super::sym_generated::*; + + /// Get the symbol for an integer. + /// + /// The first few non-negative integers each have a static symbol and therefore + /// are fast. + pub fn integer + Copy + ToString>(n: N) -> Symbol { + if let Result::Ok(idx) = n.try_into() { + if idx < 10 { + return Symbol::new(super::SYMBOL_DIGITS_BASE + idx as u32); + } + } + Symbol::intern(&n.to_string()) + } +} + +pub mod reserved { + + pub use super::reserved_word; + + pub fn is_reserved_word(word: &str) -> bool { + reserved_word::reserved_words.contains(&word) + } +} + +/// Special symbols related to KCL keywords. +impl Symbol { + /// Returns `true` if the symbol is `true` or `false`. + pub fn is_bool_lit(self) -> bool { + self == kw::True || self == kw::False + } +} diff --git a/kclvm/span/src/tests.rs b/crates/span/src/tests.rs similarity index 100% rename from kclvm/span/src/tests.rs rename to crates/span/src/tests.rs diff --git a/crates/tools/Cargo.toml b/crates/tools/Cargo.toml new file mode 100644 index 000000000..96d1d2520 --- /dev/null +++ b/crates/tools/Cargo.toml @@ -0,0 +1,43 @@ +[package] +name = "kcl-tools" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +fancy-regex = "0.7.1" +walkdir = "2" +anyhow = "1.0" +compiler_base_session = "0.1.3" + +rustc_lexer = "0.1.0" +kcl-ast = { path = "../ast" } +kcl-error = { path = "../error" } +kcl-parser = { path = "../parser" } +kcl-sema = { path = "../sema" } +kcl-config = { path = "../config" } +kcl-ast-pretty = { path = "../ast_pretty" } +kcl-query = { path = "../query" } +kcl-runner = { path = "../runner" } +kcl-runtime = { path = "../runtime" } +kcl-driver = { path = "../driver" } +kcl-utils = { path = "../utils" } +kcl-primitives = { path = "../primitives" } + +serde_json = "1.0" +serde_yaml_ng = "0.10.0" +once_cell = "1.15.0" +regex = "1.3" +json-spanned-value = "0.2.2" +compiler_base_span = "0.1.2" +located_yaml = "0.2.1" + +[dev-dependencies] +pretty_assertions = "1.2.1" +criterion = "0.5" +insta = "1.8.0" + +[[bench]] +name = "benchmark" +harness = false diff --git a/kclvm/tools/benches/benchmark.rs b/crates/tools/benches/benchmark.rs similarity index 94% rename from kclvm/tools/benches/benchmark.rs rename to crates/tools/benches/benchmark.rs index e9288ea6e..c4a8c83f8 100644 --- a/kclvm/tools/benches/benchmark.rs +++ b/crates/tools/benches/benchmark.rs @@ -1,6 +1,6 @@ -use criterion::{criterion_group, criterion_main, Criterion}; -use kclvm_query::override_file; -use kclvm_tools::format::{format, FormatOptions}; +use criterion::{Criterion, criterion_group, criterion_main}; +use kcl_query::override_file; +use kcl_tools::format::{FormatOptions, format}; use std::{ fmt, time::{Duration, Instant}, diff --git a/crates/tools/benches/proc_macro_crate/Cargo.toml b/crates/tools/benches/proc_macro_crate/Cargo.toml new file mode 100644 index 000000000..84f0065b6 --- /dev/null +++ b/crates/tools/benches/proc_macro_crate/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "proc_macro_crate" +version = "0.1.0" +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[lib] +proc-macro = true + +[dependencies] +proc-macro2 = "1.0.7" +quote = "1" +syn = { version = "2.0.29", features = ["full","extra-traits"] } diff --git a/crates/tools/benches/proc_macro_crate/src/lib.rs b/crates/tools/benches/proc_macro_crate/src/lib.rs new file mode 100644 index 000000000..471bed74a --- /dev/null +++ b/crates/tools/benches/proc_macro_crate/src/lib.rs @@ -0,0 +1,32 @@ +use proc_macro::TokenStream; +use quote::quote; +use syn::{ItemFn, parse_macro_input}; + +#[proc_macro_attribute] +pub fn bench_test(_attr: TokenStream, item: TokenStream) -> TokenStream { + let mut input_fn = parse_macro_input!(item as ItemFn); + + let fn_name = &input_fn.sig.ident; + let fn_body = &input_fn.block; + + let timing_code = quote! { + { + let start_time = std::time::Instant::now(); + let result = #fn_body; + let end_time = std::time::Instant::now(); + let time = (end_time - start_time).as_micros(); + println!("{} took {} μs", stringify!(#fn_name), (end_time - start_time).as_micros()); + // 400 ms + assert!(time < 400000, "Bench mark test failed"); + result + } + }; + + input_fn.block = Box::new(syn::parse2(timing_code).unwrap()); + + let output = quote! { + #input_fn + }; + + output.into() +} diff --git a/kclvm/tools/benches/test_data/format.k b/crates/tools/benches/test_data/format.k similarity index 100% rename from kclvm/tools/benches/test_data/format.k rename to crates/tools/benches/test_data/format.k diff --git a/kclvm/tools/benches/test_data/simple.k b/crates/tools/benches/test_data/simple.k similarity index 100% rename from kclvm/tools/benches/test_data/simple.k rename to crates/tools/benches/test_data/simple.k diff --git a/crates/tools/src/LSP/Cargo.toml b/crates/tools/src/LSP/Cargo.toml new file mode 100644 index 000000000..6b44b8ac5 --- /dev/null +++ b/crates/tools/src/LSP/Cargo.toml @@ -0,0 +1,53 @@ +[package] +name = "kcl-language-server" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +chrono = "0.4.19" +env_logger = "0.11.2" +ropey = "1.3.2" +tokio-test = "0.4.2" +serde = { version = "1.0", features = ["derive"] } +dashmap = "5.1.0" +log = "0.4.14" +im-rc = "15.0.0" +rustc_lexer = "0.1.0" +clap = { version = "4.3.0", features = ["string"] } +maplit = "1.0.2" +compiler_base_session = "0.1.3" + +kcl-tools = { path = "../../../tools" } +kcl-error = { path = "../../../error" } +kcl-config = { path = "../../../config" } +kcl-driver = { path = "../../../driver" } +kcl-parser = { path = "../../../parser" } +kcl-sema = { path = "../../../sema" } +kcl-ast = { path = "../../../ast" } +kcl-utils = { path = "../../../utils" } +kcl-version = { path = "../../../version" } +kcl-query = { path = "../../../query" } +kcl-span = { path = "../../../span" } +kcl-primitives = { path = "../../../primitives" } + +lsp-server = { version = "0.7.7", default-features = false } +anyhow = { version = "1.0", default-features = false, features = ["std"] } +crossbeam-channel = { version = "0.5.7", default-features = false } +ra_ap_vfs = "0.0.149" +ra_ap_vfs-notify = "0.0.149" +lsp-types = { version = "0.93.0", features = ["proposed"] } +threadpool = { version = "1.8.1", default-features = false } +salsa = { version = "0.16.1", default-features = false } +serde_json = { version = "1.0", default-features = false } +parking_lot = { version = "0.12.0", default-features = false } +rustc-hash = { version = "1.1.0", default-features = false } +proc_macro_crate = { path = "../../benches/proc_macro_crate" } +notify = "7.0.0" + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +tokio = { version = "1.37.0", features = ["full"] } + +[dev-dependencies] +insta = "1.8.0" diff --git a/kclvm/tools/src/LSP/src/analysis.rs b/crates/tools/src/LSP/src/analysis.rs similarity index 81% rename from kclvm/tools/src/LSP/src/analysis.rs rename to crates/tools/src/LSP/src/analysis.rs index a3cac9e92..a8e72c550 100644 --- a/kclvm/tools/src/LSP/src/analysis.rs +++ b/crates/tools/src/LSP/src/analysis.rs @@ -1,8 +1,8 @@ -use kclvm_ast::ast::Program; -use kclvm_driver::WorkSpaceKind; -use kclvm_error::Diagnostic; -use kclvm_primitives::{IndexMap, IndexSet}; -use kclvm_sema::{core::global_state::GlobalState, ty::SchemaType}; +use kcl_ast::ast::Program; +use kcl_driver::WorkSpaceKind; +use kcl_error::Diagnostic; +use kcl_primitives::{IndexMap, IndexSet}; +use kcl_sema::{core::global_state::GlobalState, ty::SchemaType}; use parking_lot::RwLock; use std::{ collections::{HashMap, HashSet}, diff --git a/kclvm/tools/src/LSP/src/app.rs b/crates/tools/src/LSP/src/app.rs similarity index 86% rename from kclvm/tools/src/LSP/src/app.rs rename to crates/tools/src/LSP/src/app.rs index 0e57011c6..53376bfb9 100644 --- a/kclvm/tools/src/LSP/src/app.rs +++ b/crates/tools/src/LSP/src/app.rs @@ -1,5 +1,5 @@ use crate::state::LanguageServerState; -use clap::{builder::Str, Command}; +use clap::{Command, builder::Str}; use lsp_server::Connection; use lsp_types::InitializeParams; @@ -14,7 +14,7 @@ pub fn main_loop( /// Get the kcl language server CLI application. pub fn app() -> Command { Command::new("kcl-language-server") - .version(Str::from(kclvm_version::get_version_info())) + .version(Str::from(kcl_version::get_version_info())) .about("KCL language server CLI.") .subcommand(Command::new("version").about("Show the KCL language server version")) } diff --git a/kclvm/tools/src/LSP/src/capabilities.rs b/crates/tools/src/LSP/src/capabilities.rs similarity index 100% rename from kclvm/tools/src/LSP/src/capabilities.rs rename to crates/tools/src/LSP/src/capabilities.rs diff --git a/kclvm/tools/src/LSP/src/compile.rs b/crates/tools/src/LSP/src/compile.rs similarity index 91% rename from kclvm/tools/src/LSP/src/compile.rs rename to crates/tools/src/LSP/src/compile.rs index dd4ae1e89..5ba7f58cb 100644 --- a/kclvm/tools/src/LSP/src/compile.rs +++ b/crates/tools/src/LSP/src/compile.rs @@ -1,13 +1,13 @@ -use kclvm_ast::ast::Program; -use kclvm_driver::{lookup_compile_workspace, toolchain}; -use kclvm_error::Diagnostic; -use kclvm_parser::{ - entry::get_normalized_k_files_from_paths, load_all_files_under_paths, KCLModuleCache, - LoadProgramOptions, ParseSessionRef, +use kcl_ast::ast::Program; +use kcl_driver::{lookup_compile_workspace, toolchain}; +use kcl_error::Diagnostic; +use kcl_parser::{ + KCLModuleCache, LoadProgramOptions, ParseSessionRef, entry::get_normalized_k_files_from_paths, + load_all_files_under_paths, }; -use kclvm_primitives::{IndexMap, IndexSet}; -use kclvm_query::query::filter_pkg_schemas; -use kclvm_sema::{ +use kcl_primitives::{IndexMap, IndexSet}; +use kcl_query::query::filter_pkg_schemas; +use kcl_sema::{ advanced_resolver::AdvancedResolver, core::global_state::GlobalState, namer::Namer, @@ -48,7 +48,7 @@ pub fn compile( return ( Default::default(), Err(anyhow::anyhow!("Compile failed: {:?}", e)), - ) + ); } }; let normalized_files: Vec<&str> = normalized_files.iter().map(|s| s.as_str()).collect(); @@ -60,7 +60,7 @@ pub fn compile( return ( Default::default(), Err(anyhow::anyhow!("Compile failed: {:?}", e)), - ) + ); } }; opts.k_code_list.append(&mut k_code_list); @@ -93,7 +93,7 @@ pub fn compile( "Failed to get module cache RwLock: {:?}", e )), - ) + ); } } } @@ -118,7 +118,7 @@ pub fn compile( let prog_scope = resolve_program_with_opts( &mut program, - kclvm_sema::resolver::Options { + kcl_sema::resolver::Options { merge_program: false, type_erasure: false, ..Default::default() @@ -167,7 +167,7 @@ pub fn compile( pub fn compile_with_params( params: Params, ) -> ( - IndexSet, + IndexSet, anyhow::Result<(Program, IndexMap>, GlobalState)>, ) { let file = PathBuf::from(params.file.clone().unwrap()) diff --git a/kclvm/tools/src/LSP/src/completion.rs b/crates/tools/src/LSP/src/completion.rs similarity index 97% rename from kclvm/tools/src/LSP/src/completion.rs rename to crates/tools/src/LSP/src/completion.rs index f64d33e58..1168767d2 100644 --- a/kclvm/tools/src/LSP/src/completion.rs +++ b/crates/tools/src/LSP/src/completion.rs @@ -17,25 +17,25 @@ use crate::goto_def::{find_def, find_symbol}; use crate::to_lsp::lsp_pos; -use kclvm_ast::ast::{self, ImportStmt, Program, Stmt}; -use kclvm_ast::MAIN_PKG; -use kclvm_config::modfile::KCL_FILE_EXTENSION; -use kclvm_driver::toolchain::{get_real_path_from_external, Metadata, Toolchain}; -use kclvm_error::diagnostic::Range; -use kclvm_parser::get_kcl_files; -use kclvm_primitives::{DefaultHashBuilder, IndexMap, IndexSet}; -use kclvm_sema::core::global_state::GlobalState; +use kcl_ast::MAIN_PKG; +use kcl_ast::ast::{self, ImportStmt, Program, Stmt}; +use kcl_config::modfile::KCL_FILE_EXTENSION; +use kcl_driver::toolchain::{Metadata, Toolchain, get_real_path_from_external}; +use kcl_error::diagnostic::Range; +use kcl_parser::get_kcl_files; +use kcl_primitives::{DefaultHashBuilder, IndexMap, IndexSet}; +use kcl_sema::core::global_state::GlobalState; use std::io; use std::{fs, path::Path}; -use kclvm_error::Position as KCLPos; -use kclvm_sema::builtin::{BUILTIN_FUNCTIONS, STANDARD_SYSTEM_MODULES}; -use kclvm_sema::core::package::ModuleInfo; -use kclvm_sema::core::scope::{LocalSymbolScopeKind, ScopeKind}; -use kclvm_sema::core::symbol::SymbolKind; -use kclvm_sema::resolver::doc::{parse_schema_doc_string, SchemaDoc}; -use kclvm_sema::ty::{FunctionType, SchemaType, Type, TypeKind}; -use kclvm_utils::path::PathPrefix; +use kcl_error::Position as KCLPos; +use kcl_sema::builtin::{BUILTIN_FUNCTIONS, STANDARD_SYSTEM_MODULES}; +use kcl_sema::core::package::ModuleInfo; +use kcl_sema::core::scope::{LocalSymbolScopeKind, ScopeKind}; +use kcl_sema::core::symbol::SymbolKind; +use kcl_sema::resolver::doc::{SchemaDoc, parse_schema_doc_string}; +use kcl_sema::ty::{FunctionType, SchemaType, Type, TypeKind}; +use kcl_utils::path::PathPrefix; use lsp_types::{CompletionItem, CompletionItemKind, InsertTextFormat}; use crate::util::{inner_most_expr_in_stmt, is_in_docstring}; @@ -124,10 +124,10 @@ pub fn completion( if let Some(scope) = gs.look_up_scope(pos) { // Complete builtin functions in root scope and lambda match scope.get_kind() { - kclvm_sema::core::scope::ScopeKind::Local => { + kcl_sema::core::scope::ScopeKind::Local => { if let Some(local_scope) = gs.get_scopes().try_get_local_scope(&scope) { match local_scope.get_kind() { - kclvm_sema::core::scope::LocalSymbolScopeKind::Lambda => { + kcl_sema::core::scope::LocalSymbolScopeKind::Lambda => { completions.extend(BUILTIN_FUNCTIONS.iter().map( |(name, ty)| KCLCompletionItem { label: func_ty_complete_label( @@ -151,7 +151,7 @@ pub fn completion( } } } - kclvm_sema::core::scope::ScopeKind::Root => { + kcl_sema::core::scope::ScopeKind::Root => { completions.extend(BUILTIN_FUNCTIONS.iter().map(|(name, ty)| { KCLCompletionItem { label: func_ty_complete_label(name, &ty.into_func_type()), @@ -257,7 +257,7 @@ fn completion_dot( match node.node { // if the complete trigger character in string, skip it ast::Expr::StringLit(_) | ast::Expr::JoinedString(_) => { - return Some(into_completion_items(&items).into()) + return Some(into_completion_items(&items).into()); } _ => {} } @@ -970,15 +970,15 @@ fn unimport_schemas( mod tests { use crate::{ completion::{ - completion, func_ty_complete_insert_text, func_ty_complete_label, - into_completion_items, KCLCompletionItem, KCLCompletionItemKind, + KCLCompletionItem, KCLCompletionItemKind, completion, func_ty_complete_insert_text, + func_ty_complete_label, into_completion_items, }, tests::{compile_test_file, compile_test_file_and_metadata}, }; - use kclvm_driver::toolchain; - use kclvm_error::Position as KCLPos; - use kclvm_primitives::IndexSet; - use kclvm_sema::builtin::{ + use kcl_driver::toolchain; + use kcl_error::Position as KCLPos; + use kcl_primitives::IndexSet; + use kcl_sema::builtin::{ BUILTIN_FUNCTIONS, MATH_FUNCTION_TYPES, STANDARD_SYSTEM_MODULES, STRING_MEMBER_FUNCTIONS, }; use lsp_types::{CompletionItem, CompletionItemKind, CompletionResponse, InsertTextFormat}; @@ -1644,9 +1644,10 @@ mod tests { match &got { CompletionResponse::Array(arr) => { - assert!(arr - .iter() - .all(|item| item.kind == Some(CompletionItemKind::FUNCTION))) + assert!( + arr.iter() + .all(|item| item.kind == Some(CompletionItemKind::FUNCTION)) + ) } CompletionResponse::List(_) => panic!("test failed"), }; @@ -1722,9 +1723,10 @@ mod tests { let got = completion(Some('.'), &program, &pos, &gs, &tool, None, &schema_map).unwrap(); match got { CompletionResponse::Array(arr) => { - assert!(arr - .iter() - .all(|item| item.kind == Some(CompletionItemKind::FUNCTION))) + assert!( + arr.iter() + .all(|item| item.kind == Some(CompletionItemKind::FUNCTION)) + ) } CompletionResponse::List(_) => panic!("test failed"), }; @@ -2186,14 +2188,6 @@ mod tests { None ); - completion_label_without_system_pkg_test_snapshot!( - import_external_pkg_test, - "src/test_data/completion_test/import/external/external_1/main.k", - 1, - 8, - None - ); - completion_label_without_builtin_func_test_snapshot!( func_return_ty_1, "src/test_data/completion_test/dot/func_return/func_return_1/func_return_1.k", diff --git a/kclvm/tools/src/LSP/src/dispatcher.rs b/crates/tools/src/LSP/src/dispatcher.rs similarity index 100% rename from kclvm/tools/src/LSP/src/dispatcher.rs rename to crates/tools/src/LSP/src/dispatcher.rs index 6fa40d2f0..ad4bb1657 100644 --- a/kclvm/tools/src/LSP/src/dispatcher.rs +++ b/crates/tools/src/LSP/src/dispatcher.rs @@ -1,7 +1,7 @@ use crossbeam_channel::Sender; use lsp_server::{ExtractError, Request}; -use serde::de::DeserializeOwned; use serde::Serialize; +use serde::de::DeserializeOwned; use std::error::Error; use crate::{ diff --git a/kclvm/tools/src/LSP/src/document_symbol.rs b/crates/tools/src/LSP/src/document_symbol.rs similarity index 95% rename from kclvm/tools/src/LSP/src/document_symbol.rs rename to crates/tools/src/LSP/src/document_symbol.rs index b2315ce8b..6623be565 100644 --- a/kclvm/tools/src/LSP/src/document_symbol.rs +++ b/crates/tools/src/LSP/src/document_symbol.rs @@ -1,8 +1,8 @@ -use kclvm_ast::MAIN_PKG; -use kclvm_error::Position; -use kclvm_sema::core::global_state::GlobalState; -use kclvm_sema::core::symbol::KCLSymbol; -use kclvm_sema::core::symbol::SymbolKind as KCLSymbolKind; +use kcl_ast::MAIN_PKG; +use kcl_error::Position; +use kcl_sema::core::global_state::GlobalState; +use kcl_sema::core::symbol::KCLSymbol; +use kcl_sema::core::symbol::SymbolKind as KCLSymbolKind; use lsp_types::Range; use lsp_types::{DocumentSymbol, DocumentSymbolResponse, SymbolKind}; @@ -148,12 +148,12 @@ mod tests { ) -> DocumentSymbol { let range: Range = Range { start: Position { - line: range.0 .0, - character: range.0 .1, + line: range.0.0, + character: range.0.1, }, end: Position { - line: range.1 .0, - character: range.1 .1, + line: range.1.0, + character: range.1.1, }, }; DocumentSymbol { diff --git a/kclvm/tools/src/LSP/src/error.rs b/crates/tools/src/LSP/src/error.rs similarity index 100% rename from kclvm/tools/src/LSP/src/error.rs rename to crates/tools/src/LSP/src/error.rs diff --git a/kclvm/tools/src/LSP/src/find_refs.rs b/crates/tools/src/LSP/src/find_refs.rs similarity index 97% rename from kclvm/tools/src/LSP/src/find_refs.rs rename to crates/tools/src/LSP/src/find_refs.rs index 68d977e9f..038ad38ab 100644 --- a/kclvm/tools/src/LSP/src/find_refs.rs +++ b/crates/tools/src/LSP/src/find_refs.rs @@ -1,6 +1,6 @@ use crate::to_lsp::lsp_location; -use kclvm_error::Position as KCLPos; -use kclvm_sema::core::global_state::GlobalState; +use kcl_error::Position as KCLPos; +use kcl_sema::core::global_state::GlobalState; use lsp_types::Location; use std::collections::HashSet; @@ -48,7 +48,7 @@ mod tests { use std::path::{Path, PathBuf}; use crate::tests::compile_test_file; - use kclvm_error::Position as KCLPos; + use kcl_error::Position as KCLPos; #[macro_export] macro_rules! find_ref_test_snapshot { diff --git a/kclvm/tools/src/LSP/src/formatting.rs b/crates/tools/src/LSP/src/formatting.rs similarity index 98% rename from kclvm/tools/src/LSP/src/formatting.rs rename to crates/tools/src/LSP/src/formatting.rs index 4ba39ac09..82b38107a 100644 --- a/kclvm/tools/src/LSP/src/formatting.rs +++ b/crates/tools/src/LSP/src/formatting.rs @@ -1,4 +1,4 @@ -use kclvm_tools::format::{format_source, FormatOptions}; +use kcl_tools::format::{FormatOptions, format_source}; use lsp_types::{Position, Range, TextEdit}; pub fn format( diff --git a/kclvm/tools/src/LSP/src/from_lsp.rs b/crates/tools/src/LSP/src/from_lsp.rs similarity index 89% rename from kclvm/tools/src/LSP/src/from_lsp.rs rename to crates/tools/src/LSP/src/from_lsp.rs index 5d1e8ecf0..29b66586d 100644 --- a/kclvm/tools/src/LSP/src/from_lsp.rs +++ b/crates/tools/src/LSP/src/from_lsp.rs @@ -1,7 +1,7 @@ use std::ops::Range; -use kclvm_error::Position as KCLPos; -use kclvm_utils::path::PathPrefix; +use kcl_error::Position as KCLPos; +use kcl_utils::path::PathPrefix; use lsp_types::{Position, Url}; use ra_ap_vfs::AbsPathBuf; @@ -18,7 +18,7 @@ pub(crate) fn abs_path(uri: &Url) -> anyhow::Result { // The position in lsp protocol is different with position in ast node whose line number is 1 based. pub(crate) fn kcl_pos(file: &str, pos: Position) -> KCLPos { KCLPos { - filename: kclvm_utils::path::convert_windows_drive_letter(file).adjust_canonicalization(), + filename: kcl_utils::path::convert_windows_drive_letter(file).adjust_canonicalization(), line: (pos.line + 1) as u64, column: Some(pos.character as u64), } @@ -55,7 +55,7 @@ pub(crate) fn file_path_from_url(url: &Url) -> anyhow::Result { .ok() .and_then(|path| { path.to_str() - .map(kclvm_utils::path::convert_windows_drive_letter) + .map(kcl_utils::path::convert_windows_drive_letter) }) .ok_or_else(|| anyhow::anyhow!("can't convert url to file path: {}", url)) } diff --git a/kclvm/tools/src/LSP/src/goto_def.rs b/crates/tools/src/LSP/src/goto_def.rs similarity index 98% rename from kclvm/tools/src/LSP/src/goto_def.rs rename to crates/tools/src/LSP/src/goto_def.rs index f705b6554..ba33057eb 100644 --- a/kclvm/tools/src/LSP/src/goto_def.rs +++ b/crates/tools/src/LSP/src/goto_def.rs @@ -8,10 +8,10 @@ //! + attr type use crate::to_lsp::lsp_location; -use kclvm_error::Position as KCLPos; -use kclvm_primitives::{DefaultHashBuilder, IndexSet}; -use kclvm_sema::core::global_state::GlobalState; -use kclvm_sema::core::symbol::SymbolRef; +use kcl_error::Position as KCLPos; +use kcl_primitives::{DefaultHashBuilder, IndexSet}; +use kcl_sema::core::global_state::GlobalState; +use kcl_sema::core::symbol::SymbolRef; use lsp_types::GotoDefinitionResponse; /// Navigates to the definition of an identifier. @@ -22,7 +22,7 @@ pub fn goto_def(kcl_pos: &KCLPos, gs: &GlobalState) -> Option match gs.get_symbols().get_symbol(def_ref) { Some(def) => match def_ref.get_kind() { - kclvm_sema::core::symbol::SymbolKind::Package => { + kcl_sema::core::symbol::SymbolKind::Package => { let pkg_info = match gs.get_packages().get_package_info(&def.get_name()) { Some(pkg_info) => pkg_info, None => return None, @@ -108,7 +108,7 @@ fn positions_to_goto_def_resp( mod tests { use super::goto_def; use crate::{from_lsp::file_path_from_url, tests::compile_test_file}; - use kclvm_error::Position as KCLPos; + use kcl_error::Position as KCLPos; use std::path::{Path, PathBuf}; #[macro_export] diff --git a/kclvm/tools/src/LSP/src/hover.rs b/crates/tools/src/LSP/src/hover.rs similarity index 94% rename from kclvm/tools/src/LSP/src/hover.rs rename to crates/tools/src/LSP/src/hover.rs index 8c77fd0ac..b542bf873 100644 --- a/kclvm/tools/src/LSP/src/hover.rs +++ b/crates/tools/src/LSP/src/hover.rs @@ -1,8 +1,8 @@ -use kclvm_error::Position as KCLPos; -use kclvm_sema::{ +use kcl_error::Position as KCLPos; +use kcl_sema::{ builtin::BUILTIN_DECORATORS, core::global_state::GlobalState, - ty::{FunctionType, Type, ANY_TYPE_STR}, + ty::{ANY_TYPE_STR, FunctionType, Type}, }; use lsp_types::{Hover, HoverContents, MarkedString}; @@ -22,7 +22,7 @@ pub fn hover(kcl_pos: &KCLPos, gs: &GlobalState) -> Option { match def { Some(def_ref) => match gs.get_symbols().get_symbol(def_ref) { Some(obj) => match def_ref.get_kind() { - kclvm_sema::core::symbol::SymbolKind::Schema => match &obj.get_sema_info().ty { + kcl_sema::core::symbol::SymbolKind::Schema => match &obj.get_sema_info().ty { Some(ty) => { // Build hover content for schema definition // Schema Definition hover @@ -47,7 +47,7 @@ pub fn hover(kcl_pos: &KCLPos, gs: &GlobalState) -> Option { let schema_attrs = obj.get_all_attributes(gs.get_symbols(), module_info); let mut attrs: Vec = vec![]; for schema_attr in schema_attrs { - if let kclvm_sema::core::symbol::SymbolKind::Attribute = + if let kcl_sema::core::symbol::SymbolKind::Attribute = schema_attr.get_kind() { let attr = gs.get_symbols().get_symbol(schema_attr).unwrap(); @@ -92,7 +92,7 @@ pub fn hover(kcl_pos: &KCLPos, gs: &GlobalState) -> Option { } _ => {} }, - kclvm_sema::core::symbol::SymbolKind::Attribute => { + kcl_sema::core::symbol::SymbolKind::Attribute => { let sema_info = obj.get_sema_info(); let attr_symbol = gs.get_symbols().get_attr_symbol(def_ref).unwrap(); let default_value_content = match attr_symbol.get_default_value() { @@ -119,10 +119,10 @@ pub fn hover(kcl_pos: &KCLPos, gs: &GlobalState) -> Option { _ => {} } } - kclvm_sema::core::symbol::SymbolKind::Value - | kclvm_sema::core::symbol::SymbolKind::Function => match &obj.get_sema_info().ty { + kcl_sema::core::symbol::SymbolKind::Value + | kcl_sema::core::symbol::SymbolKind::Function => match &obj.get_sema_info().ty { Some(ty) => match &ty.kind { - kclvm_sema::ty::TypeKind::Function(func_ty) => { + kcl_sema::ty::TypeKind::Function(func_ty) => { docs.append(&mut build_func_hover_content( func_ty.clone(), obj.get_name().clone(), @@ -137,9 +137,9 @@ pub fn hover(kcl_pos: &KCLPos, gs: &GlobalState) -> Option { }, _ => {} }, - kclvm_sema::core::symbol::SymbolKind::Expression => return None, - kclvm_sema::core::symbol::SymbolKind::Comment => return None, - kclvm_sema::core::symbol::SymbolKind::Decorator => { + kcl_sema::core::symbol::SymbolKind::Expression => return None, + kcl_sema::core::symbol::SymbolKind::Comment => return None, + kcl_sema::core::symbol::SymbolKind::Decorator => { match BUILTIN_DECORATORS.get(&obj.get_name()) { Some(ty) => { let mut hover_content = build_func_hover_content( @@ -258,11 +258,11 @@ fn build_func_hover_content( #[cfg(test)] mod tests { - use crate::hover::docs_to_hover; use crate::hover::MarkedStringType; + use crate::hover::docs_to_hover; use std::path::PathBuf; - use kclvm_error::Position as KCLPos; + use kcl_error::Position as KCLPos; use lsp_types::{LanguageString, MarkedString}; use proc_macro_crate::bench_test; @@ -514,7 +514,10 @@ mod tests { ); } if let MarkedString::String(s) = vec[2].clone() { - assert_eq!(s, "Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation."); + assert_eq!( + s, + "Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation." + ); } } _ => unreachable!("test error"), @@ -534,7 +537,10 @@ mod tests { assert_eq!(s.value, "function print() -> NoneType"); } if let MarkedString::String(s) = vec[1].clone() { - assert_eq!(s, "Prints the values to a stream, or to the system stdout by default.\n\nOptional keyword arguments:\n\nsep: string inserted between values, default a space.\n\nend: string appended after the last value, default a newline."); + assert_eq!( + s, + "Prints the values to a stream, or to the system stdout by default.\n\nOptional keyword arguments:\n\nsep: string inserted between values, default a space.\n\nend: string appended after the last value, default a newline." + ); } } _ => unreachable!("test error"), @@ -602,7 +608,10 @@ mod tests { assert_eq!(s.value, "function capitalize() -> str"); } if let MarkedString::String(s) = vec[2].clone() { - assert_eq!(s, "Return a copy of the string with its first character capitalized and the rest lowercased."); + assert_eq!( + s, + "Return a copy of the string with its first character capitalized and the rest lowercased." + ); } } _ => unreachable!("test error"), diff --git a/kclvm/tools/src/LSP/src/inlay_hints.rs b/crates/tools/src/LSP/src/inlay_hints.rs similarity index 97% rename from kclvm/tools/src/LSP/src/inlay_hints.rs rename to crates/tools/src/LSP/src/inlay_hints.rs index 5d2316cbf..91c4471ba 100644 --- a/kclvm/tools/src/LSP/src/inlay_hints.rs +++ b/crates/tools/src/LSP/src/inlay_hints.rs @@ -1,6 +1,6 @@ -use kclvm_primitives::{IndexMap, IndexSet}; -use kclvm_sema::core::global_state::GlobalState; -use kclvm_sema::core::symbol::{SymbolHint, SymbolHintKind}; +use kcl_primitives::{IndexMap, IndexSet}; +use kcl_sema::core::global_state::GlobalState; +use kcl_sema::core::symbol::{SymbolHint, SymbolHintKind}; use lsp_types::{ InlayHint, InlayHintKind, InlayHintLabelPart, Position as LspPosition, Range, TextEdit, }; diff --git a/kclvm/tools/src/LSP/src/lib.rs b/crates/tools/src/LSP/src/lib.rs similarity index 100% rename from kclvm/tools/src/LSP/src/lib.rs rename to crates/tools/src/LSP/src/lib.rs diff --git a/crates/tools/src/LSP/src/main.rs b/crates/tools/src/LSP/src/main.rs new file mode 100644 index 000000000..5106a1fcf --- /dev/null +++ b/crates/tools/src/LSP/src/main.rs @@ -0,0 +1,95 @@ +mod analysis; +mod app; +mod capabilities; +mod compile; +mod completion; +mod dispatcher; +mod document_symbol; +mod error; +mod find_refs; +mod formatting; +mod from_lsp; +mod goto_def; +mod hover; +mod inlay_hints; +mod notification; +mod quick_fix; +mod request; +mod semantic_token; +mod signature_help; +mod state; +mod to_lsp; +mod util; +mod word_index; + +#[cfg(test)] +mod tests; + +use app::{app, main_loop}; + +/// Main entry point for the `kcl-language-server` executable. +fn main() -> Result<(), anyhow::Error> { + let args: Vec = std::env::args().collect(); + let matches = app() + .arg_required_else_help(false) + .try_get_matches_from(args); + match matches { + Ok(arg_matches) => match arg_matches.subcommand() { + Some(("version", _)) => { + println!("{}", kcl_version::get_version_info()); + Ok(()) + } + Some((subcommand, _)) => Err(anyhow::anyhow!("unknown subcommand: {}", subcommand)), + None => { + let status: Result = { + run_server().map_err(|e| anyhow::anyhow!("{}", e))?; + Ok(ExitStatus::Success) + }; + match status.unwrap() { + ExitStatus::Success => {} + ExitStatus::Error => std::process::exit(1), + }; + Ok(()) + } + }, + Err(e) => e.exit(), + } +} + +#[allow(dead_code)] +/// Main entry point for the language server +fn run_server() -> anyhow::Result<()> { + // Setup IO connections + let (connection, io_threads) = lsp_server::Connection::stdio(); + // Wait for a client to connect + let (initialize_id, initialize_params) = connection.initialize_start()?; + + let initialize_params = + util::from_json::("InitializeParams", initialize_params)?; + + let server_capabilities = capabilities::server_capabilities(&initialize_params.capabilities); + + let initialize_result = lsp_types::InitializeResult { + capabilities: server_capabilities, + server_info: Some(lsp_types::ServerInfo { + name: String::from("kcl-language-server"), + version: None, + }), + offset_encoding: None, + }; + + let initialize_result = serde_json::to_value(initialize_result) + .map_err(|_| anyhow::anyhow!("Initialize result error"))?; + + connection.initialize_finish(initialize_id, initialize_result)?; + main_loop(connection, initialize_params)?; + io_threads.join()?; + Ok(()) +} + +#[allow(dead_code)] +#[derive(Copy, Debug, Clone, PartialEq, Eq)] +enum ExitStatus { + Success, + Error, +} diff --git a/kclvm/tools/src/LSP/src/notification.rs b/crates/tools/src/LSP/src/notification.rs similarity index 100% rename from kclvm/tools/src/LSP/src/notification.rs rename to crates/tools/src/LSP/src/notification.rs diff --git a/kclvm/tools/src/LSP/src/quick_fix.rs b/crates/tools/src/LSP/src/quick_fix.rs similarity index 99% rename from kclvm/tools/src/LSP/src/quick_fix.rs rename to crates/tools/src/LSP/src/quick_fix.rs index 0810c04c2..fe8fd1d6f 100644 --- a/kclvm/tools/src/LSP/src/quick_fix.rs +++ b/crates/tools/src/LSP/src/quick_fix.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use kclvm_error::{DiagnosticId, ErrorKind, WarningKind}; +use kcl_error::{DiagnosticId, ErrorKind, WarningKind}; use lsp_types::{ CodeAction, CodeActionKind, CodeActionOrCommand, Diagnostic, NumberOrString, TextEdit, Url, }; @@ -167,7 +167,7 @@ mod tests { use super::quick_fix; use crate::{ - compile::{compile_with_params, Params}, + compile::{Params, compile_with_params}, state::KCLVfs, to_lsp::kcl_diag_to_lsp_diags_by_file, }; diff --git a/kclvm/tools/src/LSP/src/rename.rs b/crates/tools/src/LSP/src/rename.rs similarity index 97% rename from kclvm/tools/src/LSP/src/rename.rs rename to crates/tools/src/LSP/src/rename.rs index 6a0c74fea..e77070fd5 100644 --- a/kclvm/tools/src/LSP/src/rename.rs +++ b/crates/tools/src/LSP/src/rename.rs @@ -1,12 +1,12 @@ use crate::state::KCLVfs; -use crate::word_index::{build_virtual_word_index, VirtualLocation}; +use crate::word_index::{VirtualLocation, build_virtual_word_index}; use crate::{from_lsp::kcl_pos, goto_def::find_def}; -use anyhow::{anyhow, Result}; -use kclvm_ast::ast::{self, Program}; -use kclvm_error::diagnostic; -use kclvm_parser::{load_program, LoadProgramOptions, ParseSessionRef}; -use kclvm_query::{path::parse_attribute_path, selector::parse_symbol_selector_spec}; -use kclvm_sema::{ +use anyhow::{Result, anyhow}; +use kcl_ast::ast::{self, Program}; +use kcl_error::diagnostic; +use kcl_parser::{LoadProgramOptions, ParseSessionRef, load_program}; +use kcl_query::{path::parse_attribute_path, selector::parse_symbol_selector_spec}; +use kcl_sema::{ advanced_resolver::AdvancedResolver, core::global_state::GlobalState, namer::Namer, resolver::resolve_program_with_opts, }; @@ -131,7 +131,7 @@ where ) { if let Some(symbol_ref) = gs .get_symbols() - .get_symbol_by_fully_qualified_name(kclvm_ast::MAIN_PKG) + .get_symbol_by_fully_qualified_name(kcl_ast::MAIN_PKG) { let mut owner_ref = symbol_ref; let mut target = None; @@ -180,7 +180,7 @@ where let prog_scope = resolve_program_with_opts( &mut program, - kclvm_sema::resolver::Options { + kcl_sema::resolver::Options { merge_program: false, type_erasure: false, ..Default::default() @@ -386,8 +386,8 @@ where #[cfg(test)] mod tests { - use kclvm_ast::ast; - use kclvm_error::diagnostic; + use kcl_ast::ast; + use kcl_error::diagnostic; use lsp_types::{Position, Range, TextEdit}; use maplit::hashmap; use std::collections::{HashMap, HashSet}; @@ -813,7 +813,10 @@ a = { d = a.abc e = a["abc"]"# ); - assert_eq!(main_new_content, "import .base\n\na = base.NewPerson {\n age: 1,\n name: {\n first: \"aa\"\n }\n}"); + assert_eq!( + main_new_content, + "import .base\n\na = base.NewPerson {\n age: 1,\n name: {\n first: \"aa\"\n }\n}" + ); // after test, restore the old file content for path in [base_path.clone(), main_path.clone()] { diff --git a/kclvm/tools/src/LSP/src/request.rs b/crates/tools/src/LSP/src/request.rs similarity index 99% rename from kclvm/tools/src/LSP/src/request.rs rename to crates/tools/src/LSP/src/request.rs index 3e43655a8..0d97a399e 100644 --- a/kclvm/tools/src/LSP/src/request.rs +++ b/crates/tools/src/LSP/src/request.rs @@ -1,8 +1,8 @@ use anyhow::anyhow; use crossbeam_channel::Sender; -use kclvm_driver::WorkSpaceKind; -use kclvm_sema::info::is_valid_kcl_name; +use kcl_driver::WorkSpaceKind; +use kcl_sema::info::is_valid_kcl_name; use lsp_types::{Location, SemanticTokensResult, TextEdit}; use ra_ap_vfs::VfsPath; use std::collections::HashMap; @@ -24,7 +24,7 @@ use crate::{ quick_fix, semantic_token::semantic_tokens_full, signature_help::signature_help, - state::{log_message, LanguageServerSnapshot, LanguageServerState, Task}, + state::{LanguageServerSnapshot, LanguageServerState, Task, log_message}, }; impl LanguageServerState { diff --git a/kclvm/tools/src/LSP/src/semantic_token.rs b/crates/tools/src/LSP/src/semantic_token.rs similarity index 99% rename from kclvm/tools/src/LSP/src/semantic_token.rs rename to crates/tools/src/LSP/src/semantic_token.rs index 9a6cbf707..1a7211202 100644 --- a/kclvm/tools/src/LSP/src/semantic_token.rs +++ b/crates/tools/src/LSP/src/semantic_token.rs @@ -1,11 +1,11 @@ use std::vec; -use kclvm_error::Position; -use kclvm_sema::core::{ +use kcl_error::Position; +use kcl_sema::core::{ global_state::GlobalState, symbol::{KCLSymbol, SymbolKind, SymbolRef}, }; -use kclvm_sema::ty::TypeKind; +use kcl_sema::ty::TypeKind; use lsp_types::{SemanticToken, SemanticTokenType, SemanticTokens, SemanticTokensResult}; pub const LEGEND_TYPE: &[SemanticTokenType] = &[ diff --git a/kclvm/tools/src/LSP/src/signature_help.rs b/crates/tools/src/LSP/src/signature_help.rs similarity index 92% rename from kclvm/tools/src/LSP/src/signature_help.rs rename to crates/tools/src/LSP/src/signature_help.rs index a3934db60..64b979fa9 100644 --- a/kclvm/tools/src/LSP/src/signature_help.rs +++ b/crates/tools/src/LSP/src/signature_help.rs @@ -1,10 +1,10 @@ use crate::goto_def::find_def; -use kclvm_error::Position as KCLPos; -use kclvm_sema::core::global_state::GlobalState; -use kclvm_sema::core::scope::Scope; -use kclvm_sema::core::symbol::SymbolKind; -use kclvm_sema::core::symbol::SymbolRef; -use kclvm_sema::ty::FunctionType; +use kcl_error::Position as KCLPos; +use kcl_sema::core::global_state::GlobalState; +use kcl_sema::core::scope::Scope; +use kcl_sema::core::symbol::SymbolKind; +use kcl_sema::core::symbol::SymbolRef; +use kcl_sema::ty::FunctionType; use lsp_types::ParameterInformation; use lsp_types::SignatureHelp; use lsp_types::SignatureInformation; @@ -23,7 +23,7 @@ pub fn signature_help( SymbolKind::Value | SymbolKind::Function => { let symbol = gs.get_symbols().get_symbol(def)?; let ty = &symbol.get_sema_info().ty.clone()?; - if let kclvm_sema::ty::TypeKind::Function(func_ty) = &ty.kind { + if let kcl_sema::ty::TypeKind::Function(func_ty) = &ty.kind { let (label, parameters) = function_signatue_help(&symbol.get_name(), func_ty); let documentation = symbol @@ -51,15 +51,15 @@ pub fn signature_help( // func(arg1) "," => { let scope = gs.look_up_scope(pos)?; - if let kclvm_sema::core::scope::ScopeKind::Local = scope.get_kind() { + if let kcl_sema::core::scope::ScopeKind::Local = scope.get_kind() { let local_scope = gs.get_scopes().try_get_local_scope(&scope)?; - if let kclvm_sema::core::scope::LocalSymbolScopeKind::Callable = + if let kcl_sema::core::scope::LocalSymbolScopeKind::Callable = local_scope.get_kind() { let func_symbol = local_scope.get_owner()?; let symbol = gs.get_symbols().get_symbol(func_symbol)?; let ty = &symbol.get_sema_info().ty.clone()?; - if let kclvm_sema::ty::TypeKind::Function(func_ty) = &ty.kind { + if let kcl_sema::ty::TypeKind::Function(func_ty) = &ty.kind { let (label, parameters) = function_signatue_help(&symbol.get_name(), func_ty); let documentation = symbol @@ -146,7 +146,7 @@ mod tests { use super::signature_help; use crate::tests::compile_test_file; - use kclvm_error::Position as KCLPos; + use kcl_error::Position as KCLPos; #[macro_export] macro_rules! signature_help_test_snapshot { diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__complete_after_compare_expr_1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__complete_after_compare_expr_1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__complete_after_compare_expr_1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__complete_after_compare_expr_1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__complete_unimport_schemas.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__complete_unimport_schemas.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__complete_unimport_schemas.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__complete_unimport_schemas.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_doc_completion.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_doc_completion.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_doc_completion.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_doc_completion.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_return_ty_1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_return_ty_1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_return_ty_1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_return_ty_1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_return_ty_2.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_return_ty_2.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_return_ty_2.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_return_ty_2.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_return_ty_3.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_return_ty_3.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_return_ty_3.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__func_return_ty_3.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__import_external_pkg_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__import_external_pkg_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__import_external_pkg_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__import_external_pkg_test.snap diff --git a/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__import_external_pkg_test.snap.new b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__import_external_pkg_test.snap.new new file mode 100644 index 000000000..cdb091096 --- /dev/null +++ b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__import_external_pkg_test.snap.new @@ -0,0 +1,6 @@ +--- +source: crates/tools/src/LSP/src/completion.rs +assertion_line: 2189 +expression: "format! (\"{:?}\", got_labels)" +--- +[] diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__import_internal_pkg_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__import_internal_pkg_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__import_internal_pkg_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__import_internal_pkg_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__lambda_1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__lambda_1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__lambda_1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__lambda_1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_1_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_1_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_1_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_1_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_2_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_2_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_2_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_2_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_3_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_3_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_3_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_3_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_4_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_4_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_4_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__nested_4_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_in_right.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_in_right.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_in_right.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_in_right.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_newline_completion_0.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_newline_completion_0.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_newline_completion_0.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_newline_completion_0.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_newline_completion_0_1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_newline_completion_0_1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_newline_completion_0_1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_newline_completion_0_1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_newline_completion_1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_newline_completion_1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_newline_completion_1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_newline_completion_1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_0.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_0.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_0.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_0.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_2.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_2.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_2.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_2.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_3.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_3.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_3.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_3.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_4.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_4.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_4.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_attr_ty_4.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_2.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_2.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_2.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_2.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_3.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_3.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_3.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_3.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_4.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_4.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_4.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__completion__tests__schema_def_4.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_from_variable_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_from_variable_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_from_variable_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_from_variable_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_arg_1_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_arg_1_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_arg_1_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_arg_1_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_arg_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_arg_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_arg_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_arg_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_attr_ref_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_attr_ref_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_attr_ref_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_attr_ref_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_attr_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_attr_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_attr_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_attr_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_name_ref_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_name_ref_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_name_ref_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_name_ref_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_name_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_name_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_name_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_schema_name_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_variable_def_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_variable_def_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_variable_def_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_variable_def_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_variable_ref_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_variable_ref_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_variable_ref_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__find_refs__tests__find_refs_variable_ref_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__complex_select_goto_def.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__complex_select_goto_def.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__complex_select_goto_def.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__complex_select_goto_def.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__config_desuger_def_goto_def.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__config_desuger_def_goto_def.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__config_desuger_def_goto_def.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__config_desuger_def_goto_def.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_assign_type_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_assign_type_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_assign_type_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_assign_type_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_2.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_2.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_2.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_2.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_3.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_3.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_3.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_3.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_4.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_4.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_4.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_4.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_5.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_5.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_5.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_5.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_6.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_6.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_6.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_6.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_7.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_7.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_7.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_7.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_8.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_8.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_8.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_attr_in_schema_def_8.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_base_schema_attr_1_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_base_schema_attr_1_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_base_schema_attr_1_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_base_schema_attr_1_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_base_schema_attr_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_base_schema_attr_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_base_schema_attr_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_base_schema_attr_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test2.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test2.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test2.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test2.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test3.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test3.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test3.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test3.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test4.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test4.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test4.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test4.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test5.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test5.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test5.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test5.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test6.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test6.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test6.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test6.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test7.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test7.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test7.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test7.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test8.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test8.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test8.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_dict_to_schema_attr_test8.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_duplicate_var_name_in_schema.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_duplicate_var_name_in_schema.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_duplicate_var_name_in_schema.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_duplicate_var_name_in_schema.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_def_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_def_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_def_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_def_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_names1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_names1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_names1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_names1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_names2.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_names2.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_names2.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_names2.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_names3.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_names3.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_names3.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_identifier_names3.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_import_pkg_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_import_pkg_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_import_pkg_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_import_pkg_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_param_goto_def1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_param_goto_def1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_param_goto_def1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_param_goto_def1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_param_goto_def2.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_param_goto_def2.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_param_goto_def2.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_param_goto_def2.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_param_schema_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_param_schema_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_param_schema_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_param_schema_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_return_schema_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_return_schema_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_return_schema_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_lambda_return_schema_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_local_var_def_test1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_local_var_def_test1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_local_var_def_test1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_local_var_def_test1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_local_var_def_test2.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_local_var_def_test2.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_local_var_def_test2.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_local_var_def_test2.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_local_var_def_test3.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_local_var_def_test3.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_local_var_def_test3.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_local_var_def_test3.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_nested_schema_attr_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_nested_schema_attr_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_nested_schema_attr_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_nested_schema_attr_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_pkg_prefix_def_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_pkg_prefix_def_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_pkg_prefix_def_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_pkg_prefix_def_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_protocol_attr.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_protocol_attr.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_protocol_attr.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_protocol_attr.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_protocol_attr_1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_protocol_attr_1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_protocol_attr_1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_protocol_attr_1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_def_test1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_def_test1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_def_test1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_def_test1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_def_test2.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_def_test2.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_def_test2.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_def_test2.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test2.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test2.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test2.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test2.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test3.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test3.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test3.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test3.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test4.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test4.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test4.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test4.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test5.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test5.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test5.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_attr_ty_def_test5.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_def_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_def_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_def_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_schema_def_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_system_pkg_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_system_pkg_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_system_pkg_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_system_pkg_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_unification_schema_attr_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_unification_schema_attr_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_unification_schema_attr_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_unification_schema_attr_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test2.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test2.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test2.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test2.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test3.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test3.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test3.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test3.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test4.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test4.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test4.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_config_and_config_if_test4.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_dict_comp_test1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_dict_comp_test1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_dict_comp_test1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_dict_comp_test1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_dict_comp_test2.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_dict_comp_test2.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_dict_comp_test2.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__goto_var_def_in_dict_comp_test2.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__lambda_local_var_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__lambda_local_var_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__lambda_local_var_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__lambda_local_var_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__list_if_expr_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__list_if_expr_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__list_if_expr_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__list_if_expr_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__schema_attribute_def_goto_def.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__schema_attribute_def_goto_def.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__schema_attribute_def_goto_def.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__goto_def__tests__schema_attribute_def_goto_def.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__assign_stmt_type_hint.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__assign_stmt_type_hint.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__assign_stmt_type_hint.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__assign_stmt_type_hint.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__config_key_ty.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__config_key_ty.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__config_key_ty.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__config_key_ty.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__config_key_ty_1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__config_key_ty_1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__config_key_ty_1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__config_key_ty_1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__function_call_arg_hint.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__function_call_arg_hint.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__function_call_arg_hint.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__function_call_arg_hint.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__schema_arg_hint.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__schema_arg_hint.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__schema_arg_hint.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__inlay_hints__tests__schema_arg_hint.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__semantic_token__tests__semantic_tokens_full_test.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__semantic_token__tests__semantic_tokens_full_test.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__semantic_token__tests__semantic_tokens_full_test.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__semantic_token__tests__semantic_tokens_full_test.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__builtin_function_signature_help_test_0.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__builtin_function_signature_help_test_0.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__builtin_function_signature_help_test_0.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__builtin_function_signature_help_test_0.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__builtin_function_signature_help_test_1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__builtin_function_signature_help_test_1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__builtin_function_signature_help_test_1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__builtin_function_signature_help_test_1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_0.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_0.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_0.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_0.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_1.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_2.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_2.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_2.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_2.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_3.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_3.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_3.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__lambda_signatue_help_test_3.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__pkg_function_signature_help_test_0.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__pkg_function_signature_help_test_0.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__pkg_function_signature_help_test_0.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__pkg_function_signature_help_test_0.snap diff --git a/kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__pkg_function_signature_help_test_1.snap b/crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__pkg_function_signature_help_test_1.snap similarity index 100% rename from kclvm/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__pkg_function_signature_help_test_1.snap rename to crates/tools/src/LSP/src/snapshots/kcl_language_server__signature_help__tests__pkg_function_signature_help_test_1.snap diff --git a/kclvm/tools/src/LSP/src/state.rs b/crates/tools/src/LSP/src/state.rs similarity index 98% rename from kclvm/tools/src/LSP/src/state.rs rename to crates/tools/src/LSP/src/state.rs index 3b4160681..aac51ab8d 100644 --- a/kclvm/tools/src/LSP/src/state.rs +++ b/crates/tools/src/LSP/src/state.rs @@ -1,21 +1,21 @@ use crate::analysis::{Analysis, AnalysisDatabase, DBState, OpenFileInfo}; -use crate::compile::{compile, Params}; +use crate::compile::{Params, compile}; use crate::from_lsp::file_path_from_url; use crate::to_lsp::{kcl_diag_to_lsp_diags, url_from_path}; use crate::util::{filter_kcl_config_file, get_file_name, to_json}; -use crossbeam_channel::{select, unbounded, Receiver, Sender}; -use kclvm_driver::toolchain::{self, Toolchain}; -use kclvm_driver::{ - lookup_compile_workspace, lookup_compile_workspaces, CompileUnitOptions, WorkSpaceKind, +use crossbeam_channel::{Receiver, Sender, select, unbounded}; +use kcl_driver::toolchain::{self, Toolchain}; +use kcl_driver::{ + CompileUnitOptions, WorkSpaceKind, lookup_compile_workspace, lookup_compile_workspaces, }; -use kclvm_parser::KCLModuleCache; -use kclvm_sema::core::global_state::GlobalState; -use kclvm_sema::resolver::scope::KCLScopeCache; +use kcl_parser::KCLModuleCache; +use kcl_sema::core::global_state::GlobalState; +use kcl_sema::resolver::scope::KCLScopeCache; use lsp_server::RequestId; use lsp_server::{ReqQueue, Request, Response}; use lsp_types::{ - notification::{Notification, PublishDiagnostics}, InitializeParams, PublishDiagnosticsParams, WorkspaceFolder, + notification::{Notification, PublishDiagnostics}, }; use notify::{RecommendedWatcher, RecursiveMode, Watcher}; use parking_lot::RwLock; @@ -25,7 +25,7 @@ use std::path::{Path, PathBuf}; use std::sync::Mutex; use std::thread; use std::time::Duration; -use std::{sync::mpsc, sync::Arc, time::Instant}; +use std::{sync::Arc, sync::mpsc, time::Instant}; pub(crate) type RequestHandler = fn(&mut LanguageServerState, lsp_server::Response); diff --git a/kclvm/tools/src/LSP/src/test_data/code_action/quick_fix/load_pkg_test.k b/crates/tools/src/LSP/src/test_data/code_action/quick_fix/load_pkg_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/code_action/quick_fix/load_pkg_test.k rename to crates/tools/src/LSP/src/test_data/code_action/quick_fix/load_pkg_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/code_action/quick_fix/quick_fix.k b/crates/tools/src/LSP/src/test_data/code_action/quick_fix/quick_fix.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/code_action/quick_fix/quick_fix.k rename to crates/tools/src/LSP/src/test_data/code_action/quick_fix/quick_fix.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/assign/completion.k b/crates/tools/src/LSP/src/test_data/completion_test/assign/completion.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/assign/completion.k rename to crates/tools/src/LSP/src/test_data/completion_test/assign/completion.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/assign/pkg/file1.k b/crates/tools/src/LSP/src/test_data/completion_test/assign/pkg/file1.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/assign/pkg/file1.k rename to crates/tools/src/LSP/src/test_data/completion_test/assign/pkg/file1.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/assign/pkg/file2.k b/crates/tools/src/LSP/src/test_data/completion_test/assign/pkg/file2.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/assign/pkg/file2.k rename to crates/tools/src/LSP/src/test_data/completion_test/assign/pkg/file2.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/assign/pkg/subpkg/file1.k b/crates/tools/src/LSP/src/test_data/completion_test/assign/pkg/subpkg/file1.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/assign/pkg/subpkg/file1.k rename to crates/tools/src/LSP/src/test_data/completion_test/assign/pkg/subpkg/file1.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/check/check.k b/crates/tools/src/LSP/src/test_data/completion_test/check/check.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/check/check.k rename to crates/tools/src/LSP/src/test_data/completion_test/check/check.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/compare/compare.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/compare/compare.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/compare/compare.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/compare/compare.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/completion/completion.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/completion/completion.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/completion/completion.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/completion/completion.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/completion/pkg/file1.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/completion/pkg/file1.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/completion/pkg/file1.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/completion/pkg/file1.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/completion/pkg/file2.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/completion/pkg/file2.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/completion/pkg/file2.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/completion/pkg/file2.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/completion/pkg/subpkg/file1.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/completion/pkg/subpkg/file1.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/completion/pkg/subpkg/file1.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/completion/pkg/subpkg/file1.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/func_return/func_return_1/func_return_1.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/func_return/func_return_1/func_return_1.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/func_return/func_return_1/func_return_1.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/func_return/func_return_1/func_return_1.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/func_return/func_return_2/func_return_2.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/func_return/func_return_2/func_return_2.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/func_return/func_return_2/func_return_2.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/func_return/func_return_2/func_return_2.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/func_return/func_return_3/func_return_3.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/func_return/func_return_3/func_return_3.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/func_return/func_return_3/func_return_3.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/func_return/func_return_3/func_return_3.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/lit_str/lit_str.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/lit_str/lit_str.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/lit_str/lit_str.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/lit_str/lit_str.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/missing_expr/missing_expr.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/missing_expr/missing_expr.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/missing_expr/missing_expr.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/missing_expr/missing_expr.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_1/nested_1.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_1/nested_1.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_1/nested_1.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_1/nested_1.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_2/nested_2.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_2/nested_2.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_2/nested_2.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_2/nested_2.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_3/nested_3.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_3/nested_3.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_3/nested_3.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_3/nested_3.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_4/nested_4.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_4/nested_4.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_4/nested_4.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/nested/nested_4/nested_4.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/schema_attr_ty/schema_attr_ty.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/schema_attr_ty/schema_attr_ty.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/schema_attr_ty/schema_attr_ty.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/schema_attr_ty/schema_attr_ty.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/schema_ty_attr/schema_ty_attr.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/schema_ty_attr/schema_ty_attr.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/schema_ty_attr/schema_ty_attr.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/schema_ty_attr/schema_ty_attr.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/dot/special_expr/compare.k b/crates/tools/src/LSP/src/test_data/completion_test/dot/special_expr/compare.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/dot/special_expr/compare.k rename to crates/tools/src/LSP/src/test_data/completion_test/dot/special_expr/compare.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/import/builtin/builtin_pkg.k b/crates/tools/src/LSP/src/test_data/completion_test/import/builtin/builtin_pkg.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/import/builtin/builtin_pkg.k rename to crates/tools/src/LSP/src/test_data/completion_test/import/builtin/builtin_pkg.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/import/external/external_0/kcl.mod b/crates/tools/src/LSP/src/test_data/completion_test/import/external/external_0/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/import/external/external_0/kcl.mod rename to crates/tools/src/LSP/src/test_data/completion_test/import/external/external_0/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/import/external/external_0/main.k b/crates/tools/src/LSP/src/test_data/completion_test/import/external/external_0/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/import/external/external_0/main.k rename to crates/tools/src/LSP/src/test_data/completion_test/import/external/external_0/main.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/import/external/external_1/kcl.mod b/crates/tools/src/LSP/src/test_data/completion_test/import/external/external_1/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/import/external/external_1/kcl.mod rename to crates/tools/src/LSP/src/test_data/completion_test/import/external/external_1/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/import/external/external_1/main.k b/crates/tools/src/LSP/src/test_data/completion_test/import/external/external_1/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/import/external/external_1/main.k rename to crates/tools/src/LSP/src/test_data/completion_test/import/external/external_1/main.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/import/internal/foo.k b/crates/tools/src/LSP/src/test_data/completion_test/import/internal/foo.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/import/internal/foo.k rename to crates/tools/src/LSP/src/test_data/completion_test/import/internal/foo.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/import/internal/kcl.mod b/crates/tools/src/LSP/src/test_data/completion_test/import/internal/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/import/internal/kcl.mod rename to crates/tools/src/LSP/src/test_data/completion_test/import/internal/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/import/internal/main.k b/crates/tools/src/LSP/src/test_data/completion_test/import/internal/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/import/internal/main.k rename to crates/tools/src/LSP/src/test_data/completion_test/import/internal/main.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/import/internal/tt/tt.k b/crates/tools/src/LSP/src/test_data/completion_test/import/internal/tt/tt.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/import/internal/tt/tt.k rename to crates/tools/src/LSP/src/test_data/completion_test/import/internal/tt/tt.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/import/internal/without_k_file/.gitkeep b/crates/tools/src/LSP/src/test_data/completion_test/import/internal/without_k_file/.gitkeep similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/import/internal/without_k_file/.gitkeep rename to crates/tools/src/LSP/src/test_data/completion_test/import/internal/without_k_file/.gitkeep diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/lambda/lambda_1/lambda_1.k b/crates/tools/src/LSP/src/test_data/completion_test/lambda/lambda_1/lambda_1.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/lambda/lambda_1/lambda_1.k rename to crates/tools/src/LSP/src/test_data/completion_test/lambda/lambda_1/lambda_1.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/newline/docstring_newline.k b/crates/tools/src/LSP/src/test_data/completion_test/newline/docstring_newline.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/newline/docstring_newline.k rename to crates/tools/src/LSP/src/test_data/completion_test/newline/docstring_newline.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/newline/newline_with_version/newline_with_version.k b/crates/tools/src/LSP/src/test_data/completion_test/newline/newline_with_version/newline_with_version.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/newline/newline_with_version/newline_with_version.k rename to crates/tools/src/LSP/src/test_data/completion_test/newline/newline_with_version/newline_with_version.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/newline/schema/schema_0/schema_0.k b/crates/tools/src/LSP/src/test_data/completion_test/newline/schema/schema_0/schema_0.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/newline/schema/schema_0/schema_0.k rename to crates/tools/src/LSP/src/test_data/completion_test/newline/schema/schema_0/schema_0.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/newline/schema/schema_1/schema_1.k b/crates/tools/src/LSP/src/test_data/completion_test/newline/schema/schema_1/schema_1.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/newline/schema/schema_1/schema_1.k rename to crates/tools/src/LSP/src/test_data/completion_test/newline/schema/schema_1/schema_1.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/schema/schema/schema.k b/crates/tools/src/LSP/src/test_data/completion_test/schema/schema/schema.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/schema/schema/schema.k rename to crates/tools/src/LSP/src/test_data/completion_test/schema/schema/schema.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/schema/schema_pos/schema_pos.k b/crates/tools/src/LSP/src/test_data/completion_test/schema/schema_pos/schema_pos.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/schema/schema_pos/schema_pos.k rename to crates/tools/src/LSP/src/test_data/completion_test/schema/schema_pos/schema_pos.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/schema_def/schema_def.k b/crates/tools/src/LSP/src/test_data/completion_test/schema_def/schema_def.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/schema_def/schema_def.k rename to crates/tools/src/LSP/src/test_data/completion_test/schema_def/schema_def.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/schema_doc/schema_doc.k b/crates/tools/src/LSP/src/test_data/completion_test/schema_doc/schema_doc.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/schema_doc/schema_doc.k rename to crates/tools/src/LSP/src/test_data/completion_test/schema_doc/schema_doc.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/unimport/pkg/kcl.mod b/crates/tools/src/LSP/src/test_data/completion_test/unimport/pkg/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/unimport/pkg/kcl.mod rename to crates/tools/src/LSP/src/test_data/completion_test/unimport/pkg/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/unimport/pkg/main.k b/crates/tools/src/LSP/src/test_data/completion_test/unimport/pkg/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/unimport/pkg/main.k rename to crates/tools/src/LSP/src/test_data/completion_test/unimport/pkg/main.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/unimport/unimport/kcl.mod b/crates/tools/src/LSP/src/test_data/completion_test/unimport/unimport/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/unimport/unimport/kcl.mod rename to crates/tools/src/LSP/src/test_data/completion_test/unimport/unimport/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/unimport/unimport/main.k b/crates/tools/src/LSP/src/test_data/completion_test/unimport/unimport/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/unimport/unimport/main.k rename to crates/tools/src/LSP/src/test_data/completion_test/unimport/unimport/main.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/unimport/unimport/subpkg/subpkg.k b/crates/tools/src/LSP/src/test_data/completion_test/unimport/unimport/subpkg/subpkg.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/unimport/unimport/subpkg/subpkg.k rename to crates/tools/src/LSP/src/test_data/completion_test/unimport/unimport/subpkg/subpkg.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/without_dot/completion.k b/crates/tools/src/LSP/src/test_data/completion_test/without_dot/completion.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/without_dot/completion.k rename to crates/tools/src/LSP/src/test_data/completion_test/without_dot/completion.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/without_dot/pkg/file1.k b/crates/tools/src/LSP/src/test_data/completion_test/without_dot/pkg/file1.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/without_dot/pkg/file1.k rename to crates/tools/src/LSP/src/test_data/completion_test/without_dot/pkg/file1.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/without_dot/pkg/file2.k b/crates/tools/src/LSP/src/test_data/completion_test/without_dot/pkg/file2.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/without_dot/pkg/file2.k rename to crates/tools/src/LSP/src/test_data/completion_test/without_dot/pkg/file2.k diff --git a/kclvm/tools/src/LSP/src/test_data/completion_test/without_dot/pkg/subpkg/file1.k b/crates/tools/src/LSP/src/test_data/completion_test/without_dot/pkg/subpkg/file1.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/completion_test/without_dot/pkg/subpkg/file1.k rename to crates/tools/src/LSP/src/test_data/completion_test/without_dot/pkg/subpkg/file1.k diff --git a/kclvm/tools/src/LSP/src/test_data/diagnostics/diagnostics.k b/crates/tools/src/LSP/src/test_data/diagnostics/diagnostics.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/diagnostics/diagnostics.k rename to crates/tools/src/LSP/src/test_data/diagnostics/diagnostics.k diff --git a/kclvm/tools/src/LSP/src/test_data/diagnostics/load_pkg_test.k b/crates/tools/src/LSP/src/test_data/diagnostics/load_pkg_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/diagnostics/load_pkg_test.k rename to crates/tools/src/LSP/src/test_data/diagnostics/load_pkg_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/document_symbol/document_symbol.k b/crates/tools/src/LSP/src/test_data/document_symbol/document_symbol.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/document_symbol/document_symbol.k rename to crates/tools/src/LSP/src/test_data/document_symbol/document_symbol.k diff --git a/kclvm/tools/src/LSP/src/test_data/error_code/aug_assign/aug_assign.k b/crates/tools/src/LSP/src/test_data/error_code/aug_assign/aug_assign.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/error_code/aug_assign/aug_assign.k rename to crates/tools/src/LSP/src/test_data/error_code/aug_assign/aug_assign.k diff --git a/kclvm/tools/src/LSP/src/test_data/find_refs_test/main.k b/crates/tools/src/LSP/src/test_data/find_refs_test/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/find_refs_test/main.k rename to crates/tools/src/LSP/src/test_data/find_refs_test/main.k diff --git a/kclvm/tools/src/LSP/src/test_data/format/format_range.k b/crates/tools/src/LSP/src/test_data/format/format_range.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/format/format_range.k rename to crates/tools/src/LSP/src/test_data/format/format_range.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/complex_select_goto_def/complex_select_goto_def.k b/crates/tools/src/LSP/src/test_data/goto_def_test/complex_select_goto_def/complex_select_goto_def.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/complex_select_goto_def/complex_select_goto_def.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/complex_select_goto_def/complex_select_goto_def.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/config_desuger_def_goto_def/config_desuger_def_goto_def.k b/crates/tools/src/LSP/src/test_data/goto_def_test/config_desuger_def_goto_def/config_desuger_def_goto_def.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/config_desuger_def_goto_def/config_desuger_def_goto_def.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/config_desuger_def_goto_def/config_desuger_def_goto_def.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/dict_to_schema/dict_to_schema.k b/crates/tools/src/LSP/src/test_data/goto_def_test/dict_to_schema/dict_to_schema.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/dict_to_schema/dict_to_schema.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/dict_to_schema/dict_to_schema.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/duplicate_var_name_test/duplicate_var_name.k b/crates/tools/src/LSP/src/test_data/goto_def_test/duplicate_var_name_test/duplicate_var_name.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/duplicate_var_name_test/duplicate_var_name.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/duplicate_var_name_test/duplicate_var_name.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_assign_type_test/goto_assign_type_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_assign_type_test/goto_assign_type_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_assign_type_test/goto_assign_type_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_assign_type_test/goto_assign_type_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_attr_in_schema_def/goto_attr_in_schema_def.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_attr_in_schema_def/goto_attr_in_schema_def.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_attr_in_schema_def/goto_attr_in_schema_def.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_attr_in_schema_def/goto_attr_in_schema_def.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_1_test/goto_base_schema_attr_1_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_1_test/goto_base_schema_attr_1_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_1_test/goto_base_schema_attr_1_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_1_test/goto_base_schema_attr_1_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_1_test/kcl.mod b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_1_test/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_1_test/kcl.mod rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_1_test/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_1_test/types/host.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_1_test/types/host.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_1_test/types/host.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_1_test/types/host.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_test/goto_base_schema_attr_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_test/goto_base_schema_attr_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_test/goto_base_schema_attr_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_base_schema_attr_test/goto_base_schema_attr_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_def.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_def.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_def.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_def.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_identifier_def_test/goto_identifier_def_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_identifier_def_test/goto_identifier_def_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_identifier_def_test/goto_identifier_def_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_identifier_def_test/goto_identifier_def_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_import_file_test/goto_import_file_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_import_file_test/goto_import_file_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_import_file_test/goto_import_file_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_import_file_test/goto_import_file_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_import_pkg_test/goto_import_pkg_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_import_pkg_test/goto_import_pkg_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_import_pkg_test/goto_import_pkg_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_import_pkg_test/goto_import_pkg_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_lambda_param_goto_def/goto_lambda_param_goto_def.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_lambda_param_goto_def/goto_lambda_param_goto_def.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_lambda_param_goto_def/goto_lambda_param_goto_def.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_lambda_param_goto_def/goto_lambda_param_goto_def.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_lambda_param_schema_test/goto_lambda_param_schema_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_lambda_param_schema_test/goto_lambda_param_schema_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_lambda_param_schema_test/goto_lambda_param_schema_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_lambda_param_schema_test/goto_lambda_param_schema_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_lambda_return_schema_test/goto_lambda_return_schema_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_lambda_return_schema_test/goto_lambda_return_schema_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_lambda_return_schema_test/goto_lambda_return_schema_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_lambda_return_schema_test/goto_lambda_return_schema_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_local_var_def_test/goto_local_var_def_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_local_var_def_test/goto_local_var_def_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_local_var_def_test/goto_local_var_def_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_local_var_def_test/goto_local_var_def_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_nested_schema_attr_test/goto_nested_schema_attr_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_nested_schema_attr_test/goto_nested_schema_attr_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_nested_schema_attr_test/goto_nested_schema_attr_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_nested_schema_attr_test/goto_nested_schema_attr_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_pkg_prefix_def_test/goto_pkg_prefix_def_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_pkg_prefix_def_test/goto_pkg_prefix_def_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_pkg_prefix_def_test/goto_pkg_prefix_def_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_pkg_prefix_def_test/goto_pkg_prefix_def_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_protocol/goto_protocol.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_protocol/goto_protocol.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_protocol/goto_protocol.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_protocol/goto_protocol.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_schema_attr_def_test/goto_schema_attr_def_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_schema_attr_def_test/goto_schema_attr_def_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_schema_attr_def_test/goto_schema_attr_def_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_schema_attr_def_test/goto_schema_attr_def_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_schema_attr_ty_def_test/goto_schema_attr_ty_def_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_schema_attr_ty_def_test/goto_schema_attr_ty_def_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_schema_attr_ty_def_test/goto_schema_attr_ty_def_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_schema_attr_ty_def_test/goto_schema_attr_ty_def_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_schema_def_test/goto_schema_def_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_schema_def_test/goto_schema_def_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_schema_def_test/goto_schema_def_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_schema_def_test/goto_schema_def_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_system_pkg_test/goto_system_pkg_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_system_pkg_test/goto_system_pkg_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_system_pkg_test/goto_system_pkg_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_system_pkg_test/goto_system_pkg_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_unification_schema_attr_test/goto_unification_schema_attr_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_unification_schema_attr_test/goto_unification_schema_attr_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_unification_schema_attr_test/goto_unification_schema_attr_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_unification_schema_attr_test/goto_unification_schema_attr_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_var_def_in_config_and_config_if_test/goto_var_def_in_config_and_config_if_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_var_def_in_config_and_config_if_test/goto_var_def_in_config_and_config_if_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_var_def_in_config_and_config_if_test/goto_var_def_in_config_and_config_if_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_var_def_in_config_and_config_if_test/goto_var_def_in_config_and_config_if_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_var_def_in_dict_comp_test/goto_var_def_in_dict_comp_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/goto_var_def_in_dict_comp_test/goto_var_def_in_dict_comp_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/goto_var_def_in_dict_comp_test/goto_var_def_in_dict_comp_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/goto_var_def_in_dict_comp_test/goto_var_def_in_dict_comp_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/kcl.mod b/crates/tools/src/LSP/src/test_data/goto_def_test/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/kcl.mod rename to crates/tools/src/LSP/src/test_data/goto_def_test/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/kcl.yaml b/crates/tools/src/LSP/src/test_data/goto_def_test/kcl.yaml similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/kcl.yaml rename to crates/tools/src/LSP/src/test_data/goto_def_test/kcl.yaml diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/lambda_local_var_test/lambda_local_var_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/lambda_local_var_test/lambda_local_var_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/lambda_local_var_test/lambda_local_var_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/lambda_local_var_test/lambda_local_var_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/list_if_expr_test/list_if_expr_test.k b/crates/tools/src/LSP/src/test_data/goto_def_test/list_if_expr_test/list_if_expr_test.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/list_if_expr_test/list_if_expr_test.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/list_if_expr_test/list_if_expr_test.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/pkg/schema_def.k b/crates/tools/src/LSP/src/test_data/goto_def_test/pkg/schema_def.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/pkg/schema_def.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/pkg/schema_def.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/pkg/schema_def1.k b/crates/tools/src/LSP/src/test_data/goto_def_test/pkg/schema_def1.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/pkg/schema_def1.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/pkg/schema_def1.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/schema_attribute_def_goto_def/schema_attribute_def_goto_def.k b/crates/tools/src/LSP/src/test_data/goto_def_test/schema_attribute_def_goto_def/schema_attribute_def_goto_def.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/schema_attribute_def_goto_def/schema_attribute_def_goto_def.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/schema_attribute_def_goto_def/schema_attribute_def_goto_def.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/system_pkg/goto_sys_pkg.k b/crates/tools/src/LSP/src/test_data/goto_def_test/system_pkg/goto_sys_pkg.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/system_pkg/goto_sys_pkg.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/system_pkg/goto_sys_pkg.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_test/test_goto_identifier_names/test_goto_identifier_names.k b/crates/tools/src/LSP/src/test_data/goto_def_test/test_goto_identifier_names/test_goto_identifier_names.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_test/test_goto_identifier_names/test_goto_identifier_names.k rename to crates/tools/src/LSP/src/test_data/goto_def_test/test_goto_identifier_names/test_goto_identifier_names.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_with_line_test/dep-with-line/kcl.mod b/crates/tools/src/LSP/src/test_data/goto_def_with_line_test/dep-with-line/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_with_line_test/dep-with-line/kcl.mod rename to crates/tools/src/LSP/src/test_data/goto_def_with_line_test/dep-with-line/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_with_line_test/dep-with-line/main.k b/crates/tools/src/LSP/src/test_data/goto_def_with_line_test/dep-with-line/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_with_line_test/dep-with-line/main.k rename to crates/tools/src/LSP/src/test_data/goto_def_with_line_test/dep-with-line/main.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_with_line_test/main_pkg/kcl.mod b/crates/tools/src/LSP/src/test_data/goto_def_with_line_test/main_pkg/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_with_line_test/main_pkg/kcl.mod rename to crates/tools/src/LSP/src/test_data/goto_def_with_line_test/main_pkg/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_with_line_test/main_pkg/main.k b/crates/tools/src/LSP/src/test_data/goto_def_with_line_test/main_pkg/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_def_with_line_test/main_pkg/main.k rename to crates/tools/src/LSP/src/test_data/goto_def_with_line_test/main_pkg/main.k diff --git a/kclvm/tools/src/LSP/src/test_data/goto_import_def_test/kcl.mod b/crates/tools/src/LSP/src/test_data/goto_import_def_test/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_import_def_test/kcl.mod rename to crates/tools/src/LSP/src/test_data/goto_import_def_test/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/goto_import_def_test/main.k b/crates/tools/src/LSP/src/test_data/goto_import_def_test/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/goto_import_def_test/main.k rename to crates/tools/src/LSP/src/test_data/goto_import_def_test/main.k diff --git a/kclvm/tools/src/LSP/src/test_data/hover_test/assign_in_lambda.k b/crates/tools/src/LSP/src/test_data/hover_test/assign_in_lambda.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/hover_test/assign_in_lambda.k rename to crates/tools/src/LSP/src/test_data/hover_test/assign_in_lambda.k diff --git a/kclvm/tools/src/LSP/src/test_data/hover_test/decorator.k b/crates/tools/src/LSP/src/test_data/hover_test/decorator.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/hover_test/decorator.k rename to crates/tools/src/LSP/src/test_data/hover_test/decorator.k diff --git a/kclvm/tools/src/LSP/src/test_data/hover_test/dict_key_in_schema/dict_key_in_schema.k b/crates/tools/src/LSP/src/test_data/hover_test/dict_key_in_schema/dict_key_in_schema.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/hover_test/dict_key_in_schema/dict_key_in_schema.k rename to crates/tools/src/LSP/src/test_data/hover_test/dict_key_in_schema/dict_key_in_schema.k diff --git a/kclvm/tools/src/LSP/src/test_data/hover_test/fib.k b/crates/tools/src/LSP/src/test_data/hover_test/fib.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/hover_test/fib.k rename to crates/tools/src/LSP/src/test_data/hover_test/fib.k diff --git a/kclvm/tools/src/LSP/src/test_data/hover_test/hover.k b/crates/tools/src/LSP/src/test_data/hover_test/hover.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/hover_test/hover.k rename to crates/tools/src/LSP/src/test_data/hover_test/hover.k diff --git a/kclvm/tools/src/LSP/src/test_data/hover_test/import_pkg.k b/crates/tools/src/LSP/src/test_data/hover_test/import_pkg.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/hover_test/import_pkg.k rename to crates/tools/src/LSP/src/test_data/hover_test/import_pkg.k diff --git a/kclvm/tools/src/LSP/src/test_data/hover_test/inherit.k b/crates/tools/src/LSP/src/test_data/hover_test/inherit.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/hover_test/inherit.k rename to crates/tools/src/LSP/src/test_data/hover_test/inherit.k diff --git a/kclvm/tools/src/LSP/src/test_data/hover_test/lambda.k b/crates/tools/src/LSP/src/test_data/hover_test/lambda.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/hover_test/lambda.k rename to crates/tools/src/LSP/src/test_data/hover_test/lambda.k diff --git a/kclvm/tools/src/LSP/src/test_data/hover_test/schema_with_examples.k b/crates/tools/src/LSP/src/test_data/hover_test/schema_with_examples.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/hover_test/schema_with_examples.k rename to crates/tools/src/LSP/src/test_data/hover_test/schema_with_examples.k diff --git a/kclvm/tools/src/LSP/src/test_data/hover_test/ty_in_lambda.k b/crates/tools/src/LSP/src/test_data/hover_test/ty_in_lambda.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/hover_test/ty_in_lambda.k rename to crates/tools/src/LSP/src/test_data/hover_test/ty_in_lambda.k diff --git a/kclvm/tools/src/LSP/src/test_data/inlay_hints/assign_stmt_type_hint/assign_stmt_type_hint.k b/crates/tools/src/LSP/src/test_data/inlay_hints/assign_stmt_type_hint/assign_stmt_type_hint.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/inlay_hints/assign_stmt_type_hint/assign_stmt_type_hint.k rename to crates/tools/src/LSP/src/test_data/inlay_hints/assign_stmt_type_hint/assign_stmt_type_hint.k diff --git a/kclvm/tools/src/LSP/src/test_data/inlay_hints/config_key/config_key.k b/crates/tools/src/LSP/src/test_data/inlay_hints/config_key/config_key.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/inlay_hints/config_key/config_key.k rename to crates/tools/src/LSP/src/test_data/inlay_hints/config_key/config_key.k diff --git a/kclvm/tools/src/LSP/src/test_data/inlay_hints/config_key1/config_key.k b/crates/tools/src/LSP/src/test_data/inlay_hints/config_key1/config_key.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/inlay_hints/config_key1/config_key.k rename to crates/tools/src/LSP/src/test_data/inlay_hints/config_key1/config_key.k diff --git a/kclvm/tools/src/LSP/src/test_data/inlay_hints/function_call/function_call.k b/crates/tools/src/LSP/src/test_data/inlay_hints/function_call/function_call.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/inlay_hints/function_call/function_call.k rename to crates/tools/src/LSP/src/test_data/inlay_hints/function_call/function_call.k diff --git a/kclvm/tools/src/LSP/src/test_data/inlay_hints/schema_args/schema_args_hint.k b/crates/tools/src/LSP/src/test_data/inlay_hints/schema_args/schema_args_hint.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/inlay_hints/schema_args/schema_args_hint.k rename to crates/tools/src/LSP/src/test_data/inlay_hints/schema_args/schema_args_hint.k diff --git a/kclvm/tools/src/LSP/src/test_data/rename_test/base/person.k b/crates/tools/src/LSP/src/test_data/rename_test/base/person.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/rename_test/base/person.k rename to crates/tools/src/LSP/src/test_data/rename_test/base/person.k diff --git a/kclvm/tools/src/LSP/src/test_data/rename_test/config.k b/crates/tools/src/LSP/src/test_data/rename_test/config.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/rename_test/config.k rename to crates/tools/src/LSP/src/test_data/rename_test/config.k diff --git a/kclvm/tools/src/LSP/src/test_data/rename_test/main.k b/crates/tools/src/LSP/src/test_data/rename_test/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/rename_test/main.k rename to crates/tools/src/LSP/src/test_data/rename_test/main.k diff --git a/kclvm/tools/src/LSP/src/test_data/rename_test/pkg/vars.k b/crates/tools/src/LSP/src/test_data/rename_test/pkg/vars.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/rename_test/pkg/vars.k rename to crates/tools/src/LSP/src/test_data/rename_test/pkg/vars.k diff --git a/kclvm/tools/src/LSP/src/test_data/rename_test/rename_on_file/base/person.k b/crates/tools/src/LSP/src/test_data/rename_test/rename_on_file/base/person.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/rename_test/rename_on_file/base/person.k rename to crates/tools/src/LSP/src/test_data/rename_test/rename_on_file/base/person.k diff --git a/kclvm/tools/src/LSP/src/test_data/rename_test/rename_on_file/config.k b/crates/tools/src/LSP/src/test_data/rename_test/rename_on_file/config.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/rename_test/rename_on_file/config.k rename to crates/tools/src/LSP/src/test_data/rename_test/rename_on_file/config.k diff --git a/kclvm/tools/src/LSP/src/test_data/rename_test/rename_on_file/main.k b/crates/tools/src/LSP/src/test_data/rename_test/rename_on_file/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/rename_test/rename_on_file/main.k rename to crates/tools/src/LSP/src/test_data/rename_test/rename_on_file/main.k diff --git a/kclvm/tools/src/LSP/src/test_data/rename_test/rename_on_file/pkg/vars.k b/crates/tools/src/LSP/src/test_data/rename_test/rename_on_file/pkg/vars.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/rename_test/rename_on_file/pkg/vars.k rename to crates/tools/src/LSP/src/test_data/rename_test/rename_on_file/pkg/vars.k diff --git a/kclvm/tools/src/LSP/src/test_data/rename_test/rename_on_file/server.k b/crates/tools/src/LSP/src/test_data/rename_test/rename_on_file/server.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/rename_test/rename_on_file/server.k rename to crates/tools/src/LSP/src/test_data/rename_test/rename_on_file/server.k diff --git a/kclvm/tools/src/LSP/src/test_data/rename_test/server.k b/crates/tools/src/LSP/src/test_data/rename_test/server.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/rename_test/server.k rename to crates/tools/src/LSP/src/test_data/rename_test/server.k diff --git a/kclvm/tools/src/LSP/src/test_data/sema_token/sema_token.k b/crates/tools/src/LSP/src/test_data/sema_token/sema_token.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/sema_token/sema_token.k rename to crates/tools/src/LSP/src/test_data/sema_token/sema_token.k diff --git a/kclvm/tools/src/LSP/src/test_data/signature_help/builtin_function_signature_help/builtin_function_signature_help.k b/crates/tools/src/LSP/src/test_data/signature_help/builtin_function_signature_help/builtin_function_signature_help.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/signature_help/builtin_function_signature_help/builtin_function_signature_help.k rename to crates/tools/src/LSP/src/test_data/signature_help/builtin_function_signature_help/builtin_function_signature_help.k diff --git a/kclvm/tools/src/LSP/src/test_data/signature_help/lambda_signature_help/lambda_signature_help.k b/crates/tools/src/LSP/src/test_data/signature_help/lambda_signature_help/lambda_signature_help.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/signature_help/lambda_signature_help/lambda_signature_help.k rename to crates/tools/src/LSP/src/test_data/signature_help/lambda_signature_help/lambda_signature_help.k diff --git a/kclvm/tools/src/LSP/src/test_data/signature_help/pkg_function_signature_help/pkg_function_signature_help.k b/crates/tools/src/LSP/src/test_data/signature_help/pkg_function_signature_help/pkg_function_signature_help.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/signature_help/pkg_function_signature_help/pkg_function_signature_help.k rename to crates/tools/src/LSP/src/test_data/signature_help/pkg_function_signature_help/pkg_function_signature_help.k diff --git a/kclvm/tools/src/LSP/src/test_data/test_vendor/kcl4_v0.0.1/k4/main.k b/crates/tools/src/LSP/src/test_data/test_vendor/kcl4_v0.0.1/k4/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/test_vendor/kcl4_v0.0.1/k4/main.k rename to crates/tools/src/LSP/src/test_data/test_vendor/kcl4_v0.0.1/k4/main.k diff --git a/kclvm/tools/src/LSP/src/test_data/test_vendor/kcl4_v0.0.1/kcl.mod b/crates/tools/src/LSP/src/test_data/test_vendor/kcl4_v0.0.1/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/test_vendor/kcl4_v0.0.1/kcl.mod rename to crates/tools/src/LSP/src/test_data/test_vendor/kcl4_v0.0.1/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/watcher/modify/kcl.mod b/crates/tools/src/LSP/src/test_data/watcher/modify/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/watcher/modify/kcl.mod rename to crates/tools/src/LSP/src/test_data/watcher/modify/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/watcher/modify/main.k b/crates/tools/src/LSP/src/test_data/watcher/modify/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/watcher/modify/main.k rename to crates/tools/src/LSP/src/test_data/watcher/modify/main.k diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/init/folder/a.k b/crates/tools/src/LSP/src/test_data/workspace/init/folder/a.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/init/folder/a.k rename to crates/tools/src/LSP/src/test_data/workspace/init/folder/a.k diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/init/folder/b.k b/crates/tools/src/LSP/src/test_data/workspace/init/folder/b.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/init/folder/b.k rename to crates/tools/src/LSP/src/test_data/workspace/init/folder/b.k diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/init/folder/sub/c.k b/crates/tools/src/LSP/src/test_data/workspace/init/folder/sub/c.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/init/folder/sub/c.k rename to crates/tools/src/LSP/src/test_data/workspace/init/folder/sub/c.k diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/init/mod/kcl.mod b/crates/tools/src/LSP/src/test_data/workspace/init/mod/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/init/mod/kcl.mod rename to crates/tools/src/LSP/src/test_data/workspace/init/mod/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/init/mod/main.k b/crates/tools/src/LSP/src/test_data/workspace/init/mod/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/init/mod/main.k rename to crates/tools/src/LSP/src/test_data/workspace/init/mod/main.k diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/init/setting/a.k b/crates/tools/src/LSP/src/test_data/workspace/init/setting/a.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/init/setting/a.k rename to crates/tools/src/LSP/src/test_data/workspace/init/setting/a.k diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/init/setting/b.k b/crates/tools/src/LSP/src/test_data/workspace/init/setting/b.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/init/setting/b.k rename to crates/tools/src/LSP/src/test_data/workspace/init/setting/b.k diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/init/setting/kcl.yaml b/crates/tools/src/LSP/src/test_data/workspace/init/setting/kcl.yaml similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/init/setting/kcl.yaml rename to crates/tools/src/LSP/src/test_data/workspace/init/setting/kcl.yaml diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/init/work/a/a.k b/crates/tools/src/LSP/src/test_data/workspace/init/work/a/a.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/init/work/a/a.k rename to crates/tools/src/LSP/src/test_data/workspace/init/work/a/a.k diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/init/work/b/b.k b/crates/tools/src/LSP/src/test_data/workspace/init/work/b/b.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/init/work/b/b.k rename to crates/tools/src/LSP/src/test_data/workspace/init/work/b/b.k diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/init/work/c.k b/crates/tools/src/LSP/src/test_data/workspace/init/work/c.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/init/work/c.k rename to crates/tools/src/LSP/src/test_data/workspace/init/work/c.k diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/init/work/kcl.work b/crates/tools/src/LSP/src/test_data/workspace/init/work/kcl.work similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/init/work/kcl.work rename to crates/tools/src/LSP/src/test_data/workspace/init/work/kcl.work diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/pkg_mod_test/base/base.k b/crates/tools/src/LSP/src/test_data/workspace/pkg_mod_test/base/base.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/pkg_mod_test/base/base.k rename to crates/tools/src/LSP/src/test_data/workspace/pkg_mod_test/base/base.k diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/pkg_mod_test/kcl.mod b/crates/tools/src/LSP/src/test_data/workspace/pkg_mod_test/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/pkg_mod_test/kcl.mod rename to crates/tools/src/LSP/src/test_data/workspace/pkg_mod_test/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/pkg_mod_test/pkg1/a.k b/crates/tools/src/LSP/src/test_data/workspace/pkg_mod_test/pkg1/a.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/pkg_mod_test/pkg1/a.k rename to crates/tools/src/LSP/src/test_data/workspace/pkg_mod_test/pkg1/a.k diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/pkg_mod_test/pkg2/b.k b/crates/tools/src/LSP/src/test_data/workspace/pkg_mod_test/pkg2/b.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/pkg_mod_test/pkg2/b.k rename to crates/tools/src/LSP/src/test_data/workspace/pkg_mod_test/pkg2/b.k diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/pkg_mod_test/test/kcl.mod b/crates/tools/src/LSP/src/test_data/workspace/pkg_mod_test/test/kcl.mod similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/pkg_mod_test/test/kcl.mod rename to crates/tools/src/LSP/src/test_data/workspace/pkg_mod_test/test/kcl.mod diff --git a/kclvm/tools/src/LSP/src/test_data/workspace/pkg_mod_test/test/main.k b/crates/tools/src/LSP/src/test_data/workspace/pkg_mod_test/test/main.k similarity index 100% rename from kclvm/tools/src/LSP/src/test_data/workspace/pkg_mod_test/test/main.k rename to crates/tools/src/LSP/src/test_data/workspace/pkg_mod_test/test/main.k diff --git a/crates/tools/src/LSP/src/tests.rs b/crates/tools/src/LSP/src/tests.rs new file mode 100644 index 000000000..e67a2f00d --- /dev/null +++ b/crates/tools/src/LSP/src/tests.rs @@ -0,0 +1,1948 @@ +use crossbeam_channel::after; +use crossbeam_channel::select; +use kcl_driver::WorkSpaceKind; +use kcl_driver::lookup_compile_workspace; +use kcl_driver::toolchain; +use kcl_driver::toolchain::Metadata; +use kcl_primitives::IndexMap; +use kcl_primitives::IndexSet; +use kcl_sema::core::global_state::GlobalState; +use kcl_sema::ty::SchemaType; +use kcl_utils::path::PathPrefix; + +use kcl_sema::resolver::scope::KCLScopeCache; +use lsp_server::RequestId; +use lsp_server::Response; +use lsp_types::CompletionContext; +use lsp_types::CompletionItem; +use lsp_types::CompletionItemKind; +use lsp_types::CompletionParams; +use lsp_types::CompletionResponse; +use lsp_types::CompletionTriggerKind; +use lsp_types::DocumentFormattingParams; +use lsp_types::DocumentSymbolParams; +use lsp_types::GotoDefinitionParams; +use lsp_types::GotoDefinitionResponse; +use lsp_types::Hover; +use lsp_types::HoverContents; +use lsp_types::HoverParams; +use lsp_types::InitializeParams; +use lsp_types::MarkedString; +use lsp_types::PartialResultParams; +use lsp_types::PublishDiagnosticsParams; +use lsp_types::ReferenceContext; +use lsp_types::ReferenceParams; +use lsp_types::RenameParams; +use lsp_types::SemanticTokensParams; +use lsp_types::TextDocumentIdentifier; +use lsp_types::TextDocumentItem; +use lsp_types::TextDocumentPositionParams; +use lsp_types::TextEdit; +use lsp_types::Url; +use lsp_types::WorkDoneProgressParams; +use lsp_types::WorkspaceEdit; +use lsp_types::WorkspaceFolder; +use lsp_types::notification::Exit; + +use parking_lot::lock_api::RwLock; +use serde::Serialize; +use std::cell::Cell; +use std::cell::RefCell; +use std::collections::HashMap; +use std::collections::HashSet; +use std::env; +use std::path::PathBuf; +use std::process::Command; + +use std::sync::Arc; +use std::thread; +use std::time::Duration; + +use kcl_ast::ast::Program; +use kcl_error::Diagnostic as KCLDiagnostic; +use kcl_parser::KCLModuleCache; + +use lsp_types::Diagnostic; +use lsp_types::DiagnosticRelatedInformation; +use lsp_types::DiagnosticSeverity; +use lsp_types::Location; +use lsp_types::NumberOrString; +use lsp_types::{Position, Range, TextDocumentContentChangeEvent}; + +use proc_macro_crate::bench_test; + +use lsp_server::{Connection, Message, Notification, Request}; + +use crate::compile::compile_with_params; +use crate::from_lsp::file_path_from_url; + +use crate::app::main_loop; +use crate::compile::Params; +use crate::state::KCLGlobalStateCache; +use crate::state::KCLVfs; +use crate::to_lsp::kcl_diag_to_lsp_diags_by_file; +use crate::util::apply_document_changes; +use crate::util::to_json; + +macro_rules! wait_async { + () => { + thread::sleep(Duration::from_millis(100)); + }; + ($time_ms:expr) => { + thread::sleep(Duration::from_millis($time_ms)); + }; +} + +pub(crate) fn compile_test_file( + testfile: &str, +) -> ( + String, + Program, + IndexSet, + GlobalState, + IndexMap>, +) { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let file = path + .join(testfile) + .canonicalize() + .unwrap() + .display() + .to_string() + .adjust_canonicalization(); + + let (diags, compile_res) = compile_with_params(Params { + file: Some(file.clone()), + module_cache: Some(KCLModuleCache::default()), + scope_cache: Some(KCLScopeCache::default()), + vfs: Some(KCLVfs::default()), + gs_cache: Some(KCLGlobalStateCache::default()), + }); + let (program, schema_map, gs) = compile_res.unwrap(); + (file, program, diags, gs, schema_map) +} + +pub(crate) fn compile_test_file_and_metadata( + testfile: &str, +) -> ( + String, + Program, + IndexSet, + GlobalState, + Option, + IndexMap>, +) { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + + let file = path + .join(testfile) + .canonicalize() + .unwrap() + .display() + .to_string() + .adjust_canonicalization(); + + let metadata = lookup_compile_workspace(&toolchain::default(), &file, true).2; + let (diags, compile_res) = compile_with_params(Params { + file: Some(file.clone()), + module_cache: Some(KCLModuleCache::default()), + scope_cache: Some(KCLScopeCache::default()), + vfs: Some(KCLVfs::default()), + gs_cache: Some(KCLGlobalStateCache::default()), + }); + let (program, schema_map, gs) = compile_res.unwrap(); + + (file, program, diags, gs, metadata, schema_map) +} + +type Info = (String, (u32, u32, u32, u32), String); + +fn build_lsp_diag( + pos: (u32, u32, u32, u32), + message: String, + severity: Option, + related_info: Vec, + code: Option, + data: Option, +) -> Diagnostic { + let related_information = if related_info.is_empty() { + None + } else { + Some( + related_info + .iter() + .map(|(file, pos, msg)| DiagnosticRelatedInformation { + location: Location { + uri: Url::from_file_path(file).unwrap(), + range: Range { + start: Position { + line: pos.0, + character: pos.1, + }, + end: Position { + line: pos.2, + character: pos.3, + }, + }, + }, + message: msg.clone(), + }) + .collect(), + ) + }; + Diagnostic { + range: lsp_types::Range { + start: Position { + line: pos.0, + character: pos.1, + }, + end: Position { + line: pos.2, + character: pos.3, + }, + }, + severity, + code, + code_description: None, + source: None, + message, + related_information, + tags: None, + data, + } +} + +fn build_expect_diags() -> Vec { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let mut test_file = path.clone(); + test_file.push("src/test_data/diagnostics/diagnostics.k"); + let file = test_file.to_str().unwrap(); + let expected_diags: Vec = vec![ + build_lsp_diag( + (1, 4, 2, 0), + "expected one of [\"identifier\", \"literal\", \"(\", \"[\", \"{\"] got newline" + .to_string(), + Some(DiagnosticSeverity::ERROR), + vec![], + Some(NumberOrString::String("InvalidSyntax".to_string())), + None, + ), + build_lsp_diag( + (0, 0, 0, 10), + "pkgpath abc not found in the program".to_string(), + Some(DiagnosticSeverity::ERROR), + vec![], + Some(NumberOrString::String("CannotFindModule".to_string())), + None, + ), + build_lsp_diag( + (0, 0, 0, 10), + format!( + "Cannot find the module abc from {}/src/test_data/diagnostics/abc", + path.to_str().unwrap() + ), + Some(DiagnosticSeverity::ERROR), + vec![], + Some(NumberOrString::String("CannotFindModule".to_string())), + None, + ), + build_lsp_diag( + (8, 0, 8, 1), + "Can not change the value of 'd', because it was declared immutable".to_string(), + Some(DiagnosticSeverity::ERROR), + vec![( + file.to_string(), + (7, 0, 7, 1), + "The variable 'd' is declared here".to_string(), + )], + Some(NumberOrString::String("ImmutableError".to_string())), + None, + ), + build_lsp_diag( + (7, 0, 7, 1), + "The variable 'd' is declared here".to_string(), + Some(DiagnosticSeverity::ERROR), + vec![( + file.to_string(), + (8, 0, 8, 1), + "Can not change the value of 'd', because it was declared immutable".to_string(), + )], + Some(NumberOrString::String("ImmutableError".to_string())), + None, + ), + build_lsp_diag( + (2, 0, 2, 1), + "expected str, got int(1)".to_string(), + Some(DiagnosticSeverity::ERROR), + vec![], + Some(NumberOrString::String("TypeError".to_string())), + None, + ), + build_lsp_diag( + (10, 8, 10, 10), + "name 'nu' is not defined, did you mean '[\"number\"]'?".to_string(), + Some(DiagnosticSeverity::ERROR), + vec![], + Some(NumberOrString::String("CompileError".to_string())), + Some(serde_json::json!({ "suggested_replacement": ["number"] })), + ), + build_lsp_diag( + (0, 0, 0, 10), + "Module 'abc' imported but unused".to_string(), + Some(DiagnosticSeverity::WARNING), + vec![], + Some(NumberOrString::String("UnusedImportWarning".to_string())), + None, + ), + ]; + expected_diags +} + +#[test] +#[bench_test] +fn diagnostics_test() { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let mut test_file = path.clone(); + test_file.push("src/test_data/diagnostics/diagnostics.k"); + let file = test_file.to_str().unwrap(); + + let diags = compile_with_params(Params { + file: Some(file.to_string()), + module_cache: None, + scope_cache: None, + vfs: Some(KCLVfs::default()), + gs_cache: Some(KCLGlobalStateCache::default()), + }) + .0; + + let diagnostics = diags + .iter() + .flat_map(|diag| kcl_diag_to_lsp_diags_by_file(diag, file)) + .collect::>(); + + let expected_diags: Vec = build_expect_diags(); + + for (get, expected) in diagnostics.iter().zip(expected_diags.iter()) { + assert_eq!(get, expected) + } +} + +#[test] +#[bench_test] +fn test_apply_document_changes() { + macro_rules! change { + [$($sl:expr, $sc:expr; $el:expr, $ec:expr => $text:expr),+] => { + vec![$(TextDocumentContentChangeEvent { + range: Some(Range { + start: Position { line: $sl, character: $sc }, + end: Position { line: $el, character: $ec }, + }), + range_length: None, + text: String::from($text), + }),+] + }; + } + + let mut text = String::new(); + apply_document_changes(&mut text, vec![]); + assert_eq!(text, ""); + + // Test if full updates work (without a range) + apply_document_changes( + &mut text, + vec![TextDocumentContentChangeEvent { + range: None, + range_length: None, + text: String::from("the"), + }], + ); + + assert_eq!(text, "the"); + apply_document_changes(&mut text, change![0, 3; 0, 3 => " quick"]); + assert_eq!(text, "the quick"); + + apply_document_changes(&mut text, change![0, 0; 0, 4 => "", 0, 5; 0, 5 => " foxes"]); + assert_eq!(text, "quick foxes"); + + apply_document_changes(&mut text, change![0, 11; 0, 11 => "\ndream"]); + assert_eq!(text, "quick foxes\ndream"); + + apply_document_changes(&mut text, change![1, 0; 1, 0 => "have "]); + assert_eq!(text, "quick foxes\nhave dream"); + + apply_document_changes( + &mut text, + change![0, 0; 0, 0 => "the ", 1, 4; 1, 4 => " quiet", 1, 16; 1, 16 => "s\n"], + ); + assert_eq!(text, "the quick foxes\nhave quiet dreams\n"); + + apply_document_changes( + &mut text, + change![0, 15; 0, 15 => "\n", 2, 17; 2, 17 => "\n"], + ); + assert_eq!(text, "the quick foxes\n\nhave quiet dreams\n\n"); + + apply_document_changes( + &mut text, + change![1, 0; 1, 0 => "DREAM", 2, 0; 2, 0 => "they ", 3, 0; 3, 0 => "DON'T THEY?"], + ); + assert_eq!( + text, + "the quick foxes\nDREAM\nthey have quiet dreams\nDON'T THEY?\n" + ); + + apply_document_changes(&mut text, change![0, 10; 1, 5 => "", 2, 0; 2, 12 => ""]); + assert_eq!(text, "the quick \nthey have quiet dreams\n"); + + text = String::from("❤️"); + apply_document_changes(&mut text, change![0, 0; 0, 0 => "a"]); + assert_eq!(text, "a❤️"); + + // todo: Non-ASCII char + // text = String::from("a\nb"); + // apply_document_changes(&mut text, change![0, 1; 1, 0 => "\nțc", 0, 1; 1, 1 => "d"]); + // assert_eq!(text, "adcb"); + + // text = String::from("a\nb"); + // apply_document_changes(&mut text, change![0, 1; 1, 0 => "ț\nc", 0, 2; 0, 2 => "c"]); + // assert_eq!(text, "ațc\ncb"); +} + +#[test] +#[bench_test] +fn file_path_from_url_test() { + if cfg!(windows) { + let url = + Url::parse("file:///c%3A/Users/abc/Desktop/%E4%B8%AD%E6%96%87/ab%20c/abc.k").unwrap(); + let path = file_path_from_url(&url).unwrap(); + assert_eq!(path, "C:\\Users\\abc\\Desktop\\中文\\ab c\\abc.k"); + } else { + let url = Url::parse("file:///Users/abc/Desktop/%E4%B8%AD%E6%96%87/ab%20c/abc.k").unwrap(); + let path = file_path_from_url(&url).unwrap(); + assert_eq!(path, "/Users/abc/Desktop/中文/ab c/abc.k"); + } +} + +// LSP e2e test + +/// A `Project` represents a project that a language server can work with. Call the [`server`] +/// method to instantiate a language server that will serve information about the project. +pub struct Project {} + +impl Project { + /// Instantiates a language server for this project. + pub fn server(self, initialize_params: InitializeParams) -> Server { + Server::new(initialize_params) + } +} + +/// An object that runs the language server main loop and enables sending and receiving messages +/// to and from it. +pub struct Server { + next_request_id: Cell, + worker: Option>, + client: Connection, + messages: RefCell>, +} + +impl Server { + /// Constructs and initializes a new `Server` + pub fn new(initialize_params: InitializeParams) -> Self { + let (connection, client) = Connection::memory(); + + let worker = std::thread::spawn(move || { + main_loop(connection, initialize_params).unwrap(); + }); + + Self { + next_request_id: Cell::new(1), + worker: Some(worker), + client, + messages: RefCell::new(Vec::new()), + } + } + + /// Sends a request to the language server, returning the response + pub fn send_request(&self, params: R::Params) { + let id = self.next_request_id.get(); + self.next_request_id.set(id.wrapping_add(1)); + let r = Request::new(id.into(), R::METHOD.to_string(), params); + self.client.sender.send(r.into()).unwrap(); + } + + /// Sends an LSP notification to the main loop. + pub(crate) fn notification(&self, params: N::Params) + where + N::Params: Serialize, + { + let r = Notification::new(N::METHOD.to_string(), params); + self.send_notification(r); + } + + /// Sends a server notification to the main loop + fn send_notification(&self, not: Notification) { + self.client.sender.send(Message::Notification(not)).unwrap(); + wait_async!(); + } + + /// A function to wait for a specific message to arrive + fn wait_for_message_cond(&self, n: usize, cond: &dyn Fn(&Message) -> bool) { + let mut total = 0; + for msg in self.messages.borrow().iter() { + if cond(msg) { + total += 1 + } + } + while total < n { + let msg = self.recv().expect("no response"); + if cond(&msg) { + total += 1; + } + } + } + + /// Receives a message from the message or timeout. + pub(crate) fn recv(&self) -> Option { + let timeout = Duration::from_secs(5); + let msg = select! { + recv(self.client.receiver) -> msg => msg.ok(), + recv(after(timeout)) -> _ => panic!("timed out"), + }; + if let Some(msg) = &msg { + self.messages.borrow_mut().push(msg.clone()); + } + msg + } + + /// Receives a message from the message, if timeout, return None. + pub(crate) fn recv_without_timeout(&self) -> Option { + let timeout = Duration::from_secs(5); + let msg = select! { + recv(self.client.receiver) -> msg => msg.ok(), + recv(after(timeout)) -> _ => return None, + }; + if let Some(msg) = &msg { + self.messages.borrow_mut().push(msg.clone()); + } + msg + } + + /// Sends a request to the main loop and receives its response + fn send_and_receive(&self, r: Request) -> Response { + let id = r.id.clone(); + self.client.sender.send(r.into()).unwrap(); + while let Some(msg) = self.recv() { + match msg { + Message::Request(req) => { + panic!("did not expect a request as a response to a request: {req:?}") + } + Message::Notification(_) => (), + Message::Response(res) => { + assert_eq!(res.id, id); + return res; + } + } + } + panic!("did not receive a response to our request"); + } + + fn receive_response(&self, id: RequestId) -> Option { + while let Some(msg) = self.recv_without_timeout() { + match msg { + Message::Request(req) => { + panic!("did not expect a request as a response to a request: {req:?}") + } + Message::Notification(_) => (), + Message::Response(res) => { + if res.id == id { + return Some(res); + } + } + } + } + None + } +} + +impl Drop for Server { + fn drop(&mut self) { + // Send the proper shutdown sequence to ensure the main loop terminates properly + self.notification::(()); + + // Cancel the main_loop + if let Some(worker) = self.worker.take() { + worker.join().unwrap(); + } + } +} + +#[test] +fn notification_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let mut path = root.clone(); + + path.push("src/test_data/diagnostics/diagnostics.k"); + + let path = path.to_str().unwrap(); + let src = std::fs::read_to_string(path).unwrap(); + let server = Project {}.server(InitializeParams::default()); + + // Mock open file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: Url::from_file_path(path).unwrap(), + language_id: "KCL".to_string(), + version: 0, + text: src, + }, + }, + ); + + // Wait for first "textDocument/publishDiagnostics" notification + server.wait_for_message_cond(1, &|msg: &Message| match msg { + Message::Notification(not) => not.method == "textDocument/publishDiagnostics", + _ => false, + }); + + let msgs = server.messages.borrow(); + for msg in msgs.iter() { + match msg { + Message::Notification(not) => { + if let Some(uri) = not.params.get("uri") { + if uri.clone() == to_json(Url::from_file_path(path).unwrap()).unwrap() { + assert_eq!( + not.params, + to_json(PublishDiagnosticsParams { + uri: Url::from_file_path(path).unwrap(), + diagnostics: build_expect_diags(), + version: None, + }) + .unwrap() + ); + break; + } + } + } + _ => {} + } + } +} + +#[test] +fn close_file_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let mut path = root.clone(); + + path.push("src/test_data/diagnostics/diagnostics.k"); + + let path = path.to_str().unwrap(); + let src = std::fs::read_to_string(path).unwrap(); + let server = Project {}.server(InitializeParams::default()); + + // Mock open file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: Url::from_file_path(path).unwrap(), + language_id: "KCL".to_string(), + version: 0, + text: src.clone(), + }, + }, + ); + + // Mock close file + server.notification::( + lsp_types::DidCloseTextDocumentParams { + text_document: TextDocumentIdentifier { + uri: Url::from_file_path(path).unwrap(), + }, + }, + ); + + // Mock reopen file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: Url::from_file_path(path).unwrap(), + language_id: "KCL".to_string(), + version: 0, + text: src, + }, + }, + ); +} + +#[test] +fn non_kcl_file_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + + let server = Project {}.server(InitializeParams::default()); + let mut path = root.clone(); + path.push("src/test_data/diagnostics.kcl"); + + // Mock open a Non-KCL file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: Url::from_file_path(path.clone()).unwrap(), + language_id: "KCL".to_string(), + version: 0, + text: "".to_string(), + }, + }, + ); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + + let r: Request = Request::new( + id.into(), + "textDocument/documentSymbol".to_string(), + DocumentSymbolParams { + text_document: TextDocumentIdentifier { + uri: Url::from_file_path(path).unwrap(), + }, + work_done_progress_params: Default::default(), + partial_result_params: Default::default(), + }, + ); + + // Send request and wait for it's response + let res = server.send_and_receive(r); + assert!(res.result.is_some()); +} + +#[test] +fn cancel_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let mut path = root.clone(); + + path.push("src/test_data/goto_def_test/goto_def.k"); + + let path = path.to_str().unwrap(); + let src = std::fs::read_to_string(path).unwrap(); + let server = Project {}.server(InitializeParams::default()); + + // Mock open file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: Url::from_file_path(path).unwrap(), + language_id: "KCL".to_string(), + version: 0, + text: src, + }, + }, + ); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + + // send request + server.send_request::(GotoDefinitionParams { + text_document_position_params: TextDocumentPositionParams { + text_document: TextDocumentIdentifier { + uri: Url::from_file_path(path).unwrap(), + }, + position: Position::new(23, 9), + }, + work_done_progress_params: Default::default(), + partial_result_params: Default::default(), + }); + + // cancel request + server.notification::(lsp_types::CancelParams { + id: NumberOrString::Number(id), + }); + + assert!(server.receive_response(id.into()).is_none()); +} + +#[test] +fn goto_def_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let path = root.clone(); + let path = path + .join("src") + .join("test_data") + .join("goto_def_test") + .join("goto_def.k"); + + let path = path.to_str().unwrap(); + let src = std::fs::read_to_string(path).unwrap(); + let server = Project {}.server(InitializeParams::default()); + + // Mock open file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: Url::from_file_path(path).unwrap(), + language_id: "KCL".to_string(), + version: 0, + text: src, + }, + }, + ); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + + let r: Request = Request::new( + id.into(), + "textDocument/definition".to_string(), + GotoDefinitionParams { + text_document_position_params: TextDocumentPositionParams { + text_document: TextDocumentIdentifier { + uri: Url::from_file_path(path).unwrap(), + }, + position: Position::new(23, 9), + }, + work_done_progress_params: Default::default(), + partial_result_params: Default::default(), + }, + ); + + // Send request and wait for it's response + let res = server.send_and_receive(r); + + assert_eq!( + res.result.unwrap(), + to_json(GotoDefinitionResponse::Scalar(Location { + uri: Url::from_file_path(path).unwrap(), + range: Range { + start: Position::new(20, 7), + end: Position::new(20, 13), + }, + })) + .unwrap() + ); +} + +#[test] +fn complete_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let path = root.clone(); + let path = path + .join("src") + .join("test_data") + .join("completion_test") + .join("dot") + .join("completion") + .join("completion.k"); + + let path = path.to_str().unwrap(); + let src = std::fs::read_to_string(path).unwrap(); + let server = Project {}.server(InitializeParams::default()); + + // Mock open file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: Url::from_file_path(path).unwrap(), + language_id: "KCL".to_string(), + version: 0, + text: src, + }, + }, + ); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + + let r: Request = Request::new( + id.into(), + "textDocument/completion".to_string(), + CompletionParams { + text_document_position: TextDocumentPositionParams { + text_document: TextDocumentIdentifier { + uri: Url::from_file_path(path).unwrap(), + }, + position: Position::new(11, 7), + }, + work_done_progress_params: Default::default(), + partial_result_params: Default::default(), + context: Some(CompletionContext { + trigger_kind: CompletionTriggerKind::TRIGGER_CHARACTER, + trigger_character: Some(".".to_string()), + }), + }, + ); + + // Send request and wait for it's response + let res = server.send_and_receive(r); + + assert_eq!( + res.result.unwrap(), + to_json(CompletionResponse::Array(vec![ + CompletionItem { + label: "name".to_string(), + kind: Some(CompletionItemKind::FIELD), + detail: Some("name: str".to_string()), + ..Default::default() + }, + CompletionItem { + label: "age".to_string(), + kind: Some(CompletionItemKind::FIELD), + detail: Some("age: int".to_string()), + ..Default::default() + } + ])) + .unwrap() + ) +} + +#[test] +fn complete_with_version_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let path = root.clone(); + let path = path + .join("src") + .join("test_data") + .join("completion_test") + .join("newline") + .join("newline_with_version") + .join("newline_with_version.k"); + let path = path.to_str().unwrap(); + let src = std::fs::read_to_string(path).unwrap(); + let server = Project {}.server(InitializeParams::default()); + + // Mock open file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: Url::from_file_path(path).unwrap(), + language_id: "KCL".to_string(), + version: 0, + text: src, + }, + }, + ); + + server.notification::( + lsp_types::DidChangeTextDocumentParams { + text_document: lsp_types::VersionedTextDocumentIdentifier { + uri: Url::from_file_path(path).unwrap(), + version: 1, + }, + content_changes: vec![TextDocumentContentChangeEvent { + range: None, + range_length: None, + text: "schema Name:\n name: str\n\nname1 = \"\"\n\nname: Name{\n \n}" + .to_string(), + }], + }, + ); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + + let r: Request = Request::new( + id.into(), + "textDocument/completion".to_string(), + CompletionParams { + text_document_position: TextDocumentPositionParams { + text_document: TextDocumentIdentifier { + uri: Url::from_file_path(path).unwrap(), + }, + position: Position::new(6, 4), + }, + work_done_progress_params: Default::default(), + partial_result_params: Default::default(), + context: Some(CompletionContext { + trigger_kind: CompletionTriggerKind::TRIGGER_CHARACTER, + trigger_character: Some("\n".to_string()), + }), + }, + ); + + let id = r.id.clone(); + server.client.sender.send(r.into()).unwrap(); + + while let Some(msg) = server.recv() { + match msg { + Message::Request(req) => { + panic!("did not expect a request as a response to a request: {req:?}") + } + Message::Notification(_) => (), + Message::Response(res) => { + assert_eq!(res.id, id); + assert_eq!( + res.result.unwrap(), + to_json(CompletionResponse::Array(vec![CompletionItem { + label: "name".to_string(), + kind: Some(CompletionItemKind::FIELD), + detail: Some("name: str".to_string()), + ..Default::default() + },])) + .unwrap() + ); + break; + } + } + } +} + +#[test] +fn hover_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let path = root + .join("src") + .join("test_data") + .join("hover_test") + .join("hover.k"); + let path = path.to_str().unwrap(); + + let src = std::fs::read_to_string(path).unwrap(); + let server = Project {}.server(InitializeParams::default()); + + // Mock open file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: Url::from_file_path(path).unwrap(), + language_id: "KCL".to_string(), + version: 0, + text: src, + }, + }, + ); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + + let r: Request = Request::new( + id.into(), + "textDocument/hover".to_string(), + HoverParams { + text_document_position_params: TextDocumentPositionParams { + text_document: TextDocumentIdentifier { + uri: Url::from_file_path(path).unwrap(), + }, + position: Position::new(15, 7), + }, + work_done_progress_params: Default::default(), + }, + ); + + // Send request and wait for it's response + let res = server.send_and_receive(r); + + assert_eq!( + res.result.unwrap(), + to_json(Hover { + contents: HoverContents::Array(vec![ + MarkedString::String("__main__".to_string()), + MarkedString::LanguageString(lsp_types::LanguageString { + language: "KCL".to_string(), + value: "schema Person:\n name: str\n age?: int".to_string() + }), + MarkedString::String("hover doc test".to_string()), + ]), + range: None + }) + .unwrap() + ) +} + +#[test] +fn hover_assign_in_lambda_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let mut path = root.clone(); + + path.push("src/test_data/hover_test/assign_in_lambda.k"); + + let path = path.to_str().unwrap(); + let src = std::fs::read_to_string(path).unwrap(); + let server = Project {}.server(InitializeParams::default()); + + // Mock open file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: Url::from_file_path(path).unwrap(), + language_id: "KCL".to_string(), + version: 0, + text: src, + }, + }, + ); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + + let r: Request = Request::new( + id.into(), + "textDocument/hover".to_string(), + HoverParams { + text_document_position_params: TextDocumentPositionParams { + text_document: TextDocumentIdentifier { + uri: Url::from_file_path(path).unwrap(), + }, + position: Position::new(4, 7), + }, + work_done_progress_params: Default::default(), + }, + ); + + // Send request and wait for it's response + let res = server.send_and_receive(r); + + assert_eq!( + res.result.unwrap(), + to_json(Hover { + contents: HoverContents::Scalar(MarkedString::LanguageString( + lsp_types::LanguageString { + language: "KCL".to_string(), + value: "images: [str]".to_string() + } + )), + range: None + }) + .unwrap() + ) +} + +#[test] +fn formatting_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let mut path = root.clone(); + + path.push("src/test_data/format/format_range.k"); + + let path = path.to_str().unwrap(); + let src = std::fs::read_to_string(path).unwrap(); + let server = Project {}.server(InitializeParams::default()); + + // Mock open file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: Url::from_file_path(path).unwrap(), + language_id: "KCL".to_string(), + version: 0, + text: src, + }, + }, + ); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + + let r: Request = Request::new( + id.into(), + "textDocument/formatting".to_string(), + DocumentFormattingParams { + text_document: TextDocumentIdentifier { + uri: Url::from_file_path(path).unwrap(), + }, + options: Default::default(), + work_done_progress_params: Default::default(), + }, + ); + + // Send request and wait for it's response + let res = server.send_and_receive(r); + + assert_eq!( + res.result.unwrap(), + to_json(Some(vec![TextEdit { + range: Range::new( + Position::new(0, 0), + Position::new(i32::MAX as u32, i32::MAX as u32), + ), + new_text: "a = 1\n\nb = 2\n\nc = 3\n\nd = 4\n".to_string() + }])) + .unwrap() + ) +} + +#[test] +fn formatting_unsaved_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let mut path = root.clone(); + + path.push("src/test_data/format/format_range.k"); + + let path = path.to_str().unwrap(); + let src = std::fs::read_to_string(path).unwrap(); + let server = Project {}.server(InitializeParams::default()); + + let uri = Url::from_file_path(path).unwrap(); + + // Mock open file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: uri.clone(), + language_id: "KCL".to_string(), + version: 0, + text: src, + }, + }, + ); + + // Mock edit file + server.notification::( + lsp_types::DidChangeTextDocumentParams { + text_document: lsp_types::VersionedTextDocumentIdentifier { + uri: uri.clone(), + version: 1, + }, + content_changes: vec![lsp_types::TextDocumentContentChangeEvent { + range: Some(lsp_types::Range::new( + lsp_types::Position::new(0, 0), + lsp_types::Position::new(0, 0), + )), + range_length: Some(0), + text: String::from("unsaved = 0\n"), + }], + }, + ); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + + let r: Request = Request::new( + id.into(), + "textDocument/formatting".to_string(), + DocumentFormattingParams { + text_document: TextDocumentIdentifier { + uri: Url::from_file_path(path).unwrap(), + }, + options: Default::default(), + work_done_progress_params: Default::default(), + }, + ); + + // Send request and wait for it's response + let res = server.send_and_receive(r); + + assert_eq!( + res.result.unwrap(), + to_json(Some(vec![TextEdit { + range: Range::new( + Position::new(0, 0), + Position::new(i32::MAX as u32, i32::MAX as u32), + ), + new_text: "unsaved = 0\n\na = 1\n\nb = 2\n\nc = 3\n\nd = 4\n".to_string() + }])) + .unwrap() + ) +} + +// TODO: wait for fix `kcl mod metadata` to read only. Otherwise it will lead to an infinite loop +#[allow(dead_code)] +// #[test] +fn mod_file_watcher_test() { + let path = PathBuf::from(".") + .join("src") + .join("test_data") + .join("watcher") + .join("modify") + .canonicalize() + .unwrap(); + + let mod_file_path = path.join("kcl.mod"); + let main_path = path.join("main.k"); + + let mod_src_bac = std::fs::read_to_string(mod_file_path.clone()).unwrap(); + let main_src = std::fs::read_to_string(main_path.clone()).unwrap(); + + let initialize_params = InitializeParams { + workspace_folders: Some(vec![WorkspaceFolder { + uri: Url::from_file_path(path.clone()).unwrap(), + name: "test".to_string(), + }]), + ..Default::default() + }; + let server = Project {}.server(initialize_params); + + // Mock open file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: Url::from_file_path(main_path.clone()).unwrap(), + language_id: "KCL".to_string(), + version: 0, + text: main_src, + }, + }, + ); + + let _ = Command::new("kcl") + .arg("mod") + .arg("add") + .arg("helloworld") + .current_dir(path) + .output() + .unwrap(); + + // wait for download dependence + wait_async!(2000); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + + let r: Request = Request::new( + id.into(), + "textDocument/hover".to_string(), + HoverParams { + text_document_position_params: TextDocumentPositionParams { + text_document: TextDocumentIdentifier { + uri: Url::from_file_path(main_path).unwrap(), + }, + position: Position::new(0, 8), + }, + work_done_progress_params: Default::default(), + }, + ); + + // Send request and wait for it's response + let res = server.send_and_receive(r); + + std::fs::write(mod_file_path, mod_src_bac).unwrap(); + assert_eq!( + res.result.unwrap(), + to_json(Hover { + contents: HoverContents::Scalar(MarkedString::LanguageString( + lsp_types::LanguageString { + language: "KCL".to_owned(), + value: "helloworld: ".to_string(), + } + )), + range: None + }) + .unwrap() + ) +} + +#[test] +fn lsp_version_test() { + let args = vec!["kcl-language-server".to_string(), "version".to_string()]; + let matches = crate::app::app() + .arg_required_else_help(false) + .try_get_matches_from(args); + match matches { + Ok(arg_match) => match arg_match.subcommand() { + Some(("version", _)) => {} + _ => panic!("test failed"), + }, + Err(_) => panic!("test failed"), + } +} + +#[test] +fn lsp_run_test() { + let args = vec!["kcl-language-server".to_string()]; + let matches = crate::app::app() + .arg_required_else_help(false) + .try_get_matches_from(args); + match matches { + Ok(arg_match) => match arg_match.subcommand() { + None => {} + _ => panic!("test failed"), + }, + Err(_) => panic!("test failed"), + } +} + +#[test] +fn lsp_invalid_subcommand_test() { + let args = vec!["kcl-language-server".to_string(), "invalid".to_string()]; + let matches = crate::app::app() + .arg_required_else_help(false) + .try_get_matches_from(args); + match matches { + Ok(_) => panic!("test failed"), + Err(e) => match e.kind() { + clap::error::ErrorKind::InvalidSubcommand => {} + _ => panic!("test failed"), + }, + } +} + +#[test] +fn find_refs_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("test_data") + .join("find_refs_test"); + let mut path = root.clone(); + path.push("main.k"); + + let path = path.to_str().unwrap(); + let src = std::fs::read_to_string(path).unwrap(); + let initialize_params = InitializeParams { + workspace_folders: Some(vec![WorkspaceFolder { + uri: Url::from_file_path(root.clone()).unwrap(), + name: "test".to_string(), + }]), + ..Default::default() + }; + let server = Project {}.server(initialize_params); + + // Wait for async build word_index_map + wait_async!(); + + let url = Url::from_file_path(path).unwrap(); + + // Mock open file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: url.clone(), + language_id: "KCL".to_string(), + version: 0, + text: src, + }, + }, + ); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + + let r: Request = Request::new( + id.into(), + "textDocument/references".to_string(), + ReferenceParams { + text_document_position: TextDocumentPositionParams { + text_document: TextDocumentIdentifier { uri: url.clone() }, + position: Position::new(0, 1), + }, + work_done_progress_params: Default::default(), + partial_result_params: Default::default(), + context: ReferenceContext { + include_declaration: true, + }, + }, + ); + + // Send request and wait for it's response + let res = server.send_and_receive(r); + + assert_eq!( + res.result.unwrap(), + to_json(vec![ + Location { + uri: url.clone(), + range: Range { + start: Position::new(0, 0), + end: Position::new(0, 1), + }, + }, + Location { + uri: url.clone(), + range: Range { + start: Position::new(1, 4), + end: Position::new(1, 5), + }, + }, + Location { + uri: url.clone(), + range: Range { + start: Position::new(2, 4), + end: Position::new(2, 5), + }, + }, + Location { + uri: url.clone(), + range: Range { + start: Position::new(12, 14), + end: Position::new(12, 15), + }, + }, + ]) + .unwrap() + ); +} + +#[test] +fn find_refs_with_file_change_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("test_data") + .join("find_refs_test"); + let mut path = root.clone(); + path.push("main.k"); + + let path = path.to_str().unwrap(); + let src = std::fs::read_to_string(path).unwrap(); + let initialize_params = InitializeParams { + workspace_folders: Some(vec![WorkspaceFolder { + uri: Url::from_file_path(root.clone()).unwrap(), + name: "test".to_string(), + }]), + ..Default::default() + }; + let server = Project {}.server(initialize_params); + + // Wait for async build word_index_map + wait_async!(); + + let url = Url::from_file_path(path).unwrap(); + + // Mock open file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: url.clone(), + language_id: "KCL".to_string(), + version: 0, + text: src, + }, + }, + ); + + // Mock change file content + server.notification::( + lsp_types::DidChangeTextDocumentParams { + text_document: lsp_types::VersionedTextDocumentIdentifier { + uri: url.clone(), + version: 1, + }, + content_changes: vec![lsp_types::TextDocumentContentChangeEvent { + range: None, + range_length: None, + text: r#"a = "demo" + +schema Name: + name: str + +schema Person: + n: Name + +p2 = Person { + n: Name{ + name: a + } +}"# + .to_string(), + }], + }, + ); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + // Mock trigger find references + let r: Request = Request::new( + id.into(), + "textDocument/references".to_string(), + ReferenceParams { + text_document_position: TextDocumentPositionParams { + text_document: TextDocumentIdentifier { uri: url.clone() }, + position: Position::new(0, 1), + }, + work_done_progress_params: Default::default(), + partial_result_params: Default::default(), + context: ReferenceContext { + include_declaration: true, + }, + }, + ); + + // Send request and wait for it's response + let res = server.send_and_receive(r); + assert_eq!( + res.result.unwrap(), + to_json(vec![ + Location { + uri: url.clone(), + range: Range { + start: Position::new(0, 0), + end: Position::new(0, 1), + }, + }, + Location { + uri: url.clone(), + range: Range { + start: Position::new(10, 14), + end: Position::new(10, 15), + }, + }, + ]) + .unwrap() + ); +} + +#[test] +fn rename_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("test_data") + .join("rename_test"); + let path = root.clone(); + let main_path = root.clone(); + let path = path.join("pkg").join("vars.k"); + let main_path = main_path.join("main.k"); + + let path = path.to_str().unwrap(); + let src = std::fs::read_to_string(path).unwrap(); + let initialize_params = InitializeParams { + workspace_folders: Some(vec![WorkspaceFolder { + uri: Url::from_file_path(root.clone()).unwrap(), + name: "test".to_string(), + }]), + ..Default::default() + }; + let server = Project {}.server(initialize_params); + + wait_async!(); + + let url = Url::from_file_path(path).unwrap(); + let main_url = Url::from_file_path(main_path).unwrap(); + + // Mock open file + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: url.clone(), + language_id: "KCL".to_string(), + version: 0, + text: src, + }, + }, + ); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + + let new_name = String::from("Person2"); + let r: Request = Request::new( + id.into(), + "textDocument/rename".to_string(), + RenameParams { + text_document_position: TextDocumentPositionParams { + text_document: TextDocumentIdentifier { uri: url.clone() }, + position: Position::new(0, 7), + }, + new_name: new_name.clone(), + work_done_progress_params: Default::default(), + }, + ); + + // Send request and wait for it's response + let res = server.send_and_receive(r); + let expect = WorkspaceEdit { + changes: Some(HashMap::from_iter(vec![ + ( + url.clone(), + vec![ + TextEdit { + range: Range { + start: Position::new(0, 7), + end: Position::new(0, 13), + }, + new_text: new_name.clone(), + }, + TextEdit { + range: Range { + start: Position::new(4, 7), + end: Position::new(4, 13), + }, + new_text: new_name.clone(), + }, + TextEdit { + range: Range { + start: Position::new(9, 8), + end: Position::new(9, 14), + }, + new_text: new_name.clone(), + }, + ], + ), + ( + main_url.clone(), + vec![TextEdit { + range: Range { + start: Position::new(2, 11), + end: Position::new(2, 17), + }, + new_text: new_name.clone(), + }], + ), + ])), + ..Default::default() + }; + assert_eq!(res.result.unwrap(), to_json(expect).unwrap()); +} + +#[test] +fn kcl_workspace_init_kclwork_test() { + let tool: crate::state::KCLToolChain = Arc::new(RwLock::new(toolchain::default())); + let tool = Arc::clone(&tool); + + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("test_data") + .join("workspace") + .join("init"); + + let mut work = root.clone(); + work.push("work"); + + let (workspaces, failed) = + kcl_driver::lookup_compile_workspaces(&*tool.read(), work.to_str().unwrap(), true); + + let mut expected = HashSet::new(); + + expected.insert(WorkSpaceKind::Folder( + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("test_data") + .join("workspace") + .join("init") + .join("work") + .join("a"), + )); + + expected.insert(WorkSpaceKind::Folder( + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("test_data") + .join("workspace") + .join("init") + .join("work") + .join("b"), + )); + + expected.insert(WorkSpaceKind::File( + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("test_data") + .join("workspace") + .join("init") + .join("work") + .join("c.k"), + )); + + assert_eq!(expected, workspaces.keys().cloned().collect()); + + assert!(failed.is_some()); + assert!(failed.unwrap().is_empty()); +} + +#[test] +fn kcl_workspace_init_kclmod_test() { + let tool: crate::state::KCLToolChain = Arc::new(RwLock::new(toolchain::default())); + let tool = Arc::clone(&tool); + + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("test_data") + .join("workspace") + .join("init"); + + let mut work = root.clone(); + work.push("mod"); + + let mut main = work.clone(); + main.push("main.k"); + + let (workspaces, failed) = + kcl_driver::lookup_compile_workspaces(&*tool.read(), work.to_str().unwrap(), true); + + let mut expected = HashSet::new(); + + expected.insert(WorkSpaceKind::ModFile( + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("test_data") + .join("workspace") + .join("init") + .join("mod") + .join("kcl.mod"), + )); + + assert_eq!(expected, workspaces.keys().cloned().collect()); + assert_eq!( + vec![main.to_str().unwrap().to_string()], + workspaces.values().next().unwrap().0 + ); + assert!(failed.is_none()); +} + +#[test] +fn kcl_workspace_init_settings_file_test() { + let tool: crate::state::KCLToolChain = Arc::new(RwLock::new(toolchain::default())); + let tool = Arc::clone(&tool); + + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("test_data") + .join("workspace") + .join("init"); + + let mut work = root.clone(); + work.push("setting"); + + let mut a = work.clone(); + a.push("a.k"); + + let (workspaces, failed) = + kcl_driver::lookup_compile_workspaces(&*tool.read(), work.to_str().unwrap(), true); + + let mut expected = HashSet::new(); + + expected.insert(WorkSpaceKind::SettingFile( + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("test_data") + .join("workspace") + .join("init") + .join("setting") + .join("kcl.yaml"), + )); + + assert_eq!(expected, workspaces.keys().cloned().collect()); + assert!(failed.is_none()); + assert_eq!( + vec![a.file_name().unwrap().to_str().unwrap().to_string()], + workspaces.values().next().unwrap().0 + ); +} + +#[test] +fn kcl_workspace_init_folder_test() { + let tool: crate::state::KCLToolChain = Arc::new(RwLock::new(toolchain::default())); + let tool = Arc::clone(&tool); + + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("test_data") + .join("workspace") + .join("init"); + + let mut work = root.clone(); + work.push("folder"); + + let (workspaces, failed) = + kcl_driver::lookup_compile_workspaces(&*tool.read(), work.to_str().unwrap(), true); + + let mut expected = HashSet::new(); + + expected.insert(WorkSpaceKind::Folder( + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("test_data") + .join("workspace") + .join("init") + .join("folder"), + )); + + assert_eq!(expected, workspaces.keys().cloned().collect()); + + assert!(failed.is_none()); +} + +#[test] +fn init_workspace_sema_token_test() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("src") + .join("test_data") + .join("workspace") + .join("init") + .join("folder"); + + let mut a_path = root.clone(); + a_path.push("a.k"); + + let mut c_path = root.clone(); + c_path.push("sub"); + c_path.push("c.k"); + + let a_path = a_path.to_str().unwrap(); + let c_path = c_path.to_str().unwrap(); + let a_src = std::fs::read_to_string(a_path).unwrap(); + let c_src = std::fs::read_to_string(c_path).unwrap(); + let initialize_params = InitializeParams { + workspace_folders: Some(vec![WorkspaceFolder { + uri: Url::from_file_path(root.clone()).unwrap(), + name: "test".to_string(), + }]), + ..Default::default() + }; + let server = Project {}.server(initialize_params); + + let a_url = Url::from_file_path(a_path).unwrap(); + let c_url = Url::from_file_path(c_path).unwrap(); + + // Mock open file in init workspace + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: a_url.clone(), + language_id: "KCL".to_string(), + version: 0, + text: a_src, + }, + }, + ); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + + let r: Request = Request::new( + id.into(), + "textDocument/semanticTokens/full".to_string(), + SemanticTokensParams { + text_document: TextDocumentIdentifier { uri: a_url }, + work_done_progress_params: WorkDoneProgressParams { + work_done_token: None, + }, + partial_result_params: PartialResultParams { + partial_result_token: None, + }, + }, + ); + + let res = server.send_and_receive(r); + assert!(res.result.is_some()); + + // Mock open file not in init workspace + server.notification::( + lsp_types::DidOpenTextDocumentParams { + text_document: TextDocumentItem { + uri: c_url.clone(), + language_id: "KCL".to_string(), + version: 0, + text: c_src, + }, + }, + ); + + let id = server.next_request_id.get(); + server.next_request_id.set(id.wrapping_add(1)); + + let r: Request = Request::new( + id.into(), + "textDocument/semanticTokens/full".to_string(), + SemanticTokensParams { + text_document: TextDocumentIdentifier { uri: c_url }, + work_done_progress_params: WorkDoneProgressParams { + work_done_token: None, + }, + partial_result_params: PartialResultParams { + partial_result_token: None, + }, + }, + ); + + let res = server.send_and_receive(r); + assert!(res.result.is_some()); +} + +#[test] +fn pkg_mod_test() { + let (_file, _program, diags, _gs, _) = + compile_test_file("src/test_data/workspace/pkg_mod_test/test/main.k"); + assert_eq!(diags.iter().filter(|diag| diag.is_error()).count(), 0); +} + +#[test] +fn aug_assign_without_define() { + let (_file, _program, diags, _gs, _) = + compile_test_file("src/test_data/error_code/aug_assign/aug_assign.k"); + assert_eq!(diags.len(), 1); +} diff --git a/kclvm/tools/src/LSP/src/to_lsp.rs b/crates/tools/src/LSP/src/to_lsp.rs similarity index 97% rename from kclvm/tools/src/LSP/src/to_lsp.rs rename to crates/tools/src/LSP/src/to_lsp.rs index b95615f77..16a1af6dc 100644 --- a/kclvm/tools/src/LSP/src/to_lsp.rs +++ b/crates/tools/src/LSP/src/to_lsp.rs @@ -1,10 +1,10 @@ use im_rc::HashMap; -use kclvm_error::Diagnostic as KCLDiagnostic; -use kclvm_error::DiagnosticId; -use kclvm_error::Level; -use kclvm_error::Message; -use kclvm_error::Position as KCLPos; -use kclvm_utils::path::PathPrefix; +use kcl_error::Diagnostic as KCLDiagnostic; +use kcl_error::DiagnosticId; +use kcl_error::Level; +use kcl_error::Message; +use kcl_error::Position as KCLPos; +use kcl_utils::path::PathPrefix; use lsp_types::*; use serde_json::json; diff --git a/crates/tools/src/LSP/src/util.rs b/crates/tools/src/LSP/src/util.rs new file mode 100644 index 000000000..8678a68eb --- /dev/null +++ b/crates/tools/src/LSP/src/util.rs @@ -0,0 +1,667 @@ +use kcl_ast::ast::{ + ConfigEntry, Expr, Identifier, MemberOrIndex, Node, NodeRef, PosTuple, Program, SchemaStmt, + Stmt, Type, +}; +use kcl_ast::node_ref; +use kcl_ast::pos::ContainsPos; + +use kcl_error::Position as KCLPos; +use kcl_parser::entry::get_dir_files; + +use crate::from_lsp; +use crate::state::KCLVfs; +use lsp_types::Url; +use parking_lot::RwLockReadGuard; +use ra_ap_vfs::{FileId, Vfs}; +use serde::{Serialize, de::DeserializeOwned}; + +use std::fs; +use std::path::{Path, PathBuf}; + +/// Deserializes a `T` from a json value. +pub(crate) fn from_json( + what: &'static str, + json: serde_json::Value, +) -> anyhow::Result { + T::deserialize(&json) + .map_err(|e| anyhow::anyhow!("could not deserialize {}: {}: {}", what, e, json)) +} + +/// Converts the `T` to a json value +pub(crate) fn to_json(value: T) -> anyhow::Result { + serde_json::to_value(value).map_err(|e| anyhow::anyhow!("could not serialize to json: {}", e)) +} + +/// Get the filename from the given VFS using the file id. +pub(crate) fn get_file_name(vfs: RwLockReadGuard, file_id: FileId) -> anyhow::Result { + if let Some(path) = vfs.file_path(file_id).as_path() { + Ok(path + .as_ref() + .to_str() + .ok_or(anyhow::anyhow!("Failed to get file file"))? + .to_string()) + } else { + Err(anyhow::anyhow!( + "{} isn't on the file system.", + vfs.file_path(file_id) + )) + } +} + +/// Update text with TextDocumentContentChangeEvent param +pub(crate) fn apply_document_changes( + old_text: &mut String, + content_changes: Vec, +) { + for change in content_changes { + match change.range { + Some(range) => { + let range = from_lsp::text_range(old_text, range); + old_text.replace_range(range, &change.text); + } + None => { + *old_text = change.text; + } + } + } +} + +pub(crate) fn load_files_code_from_vfs( + files: &[&str], + vfs: &KCLVfs, +) -> anyhow::Result> { + let mut res = vec![]; + let vfs = &mut vfs.read(); + for file in files { + let url = Url::from_file_path(file) + .map_err(|_| anyhow::anyhow!("can't convert file to url: {}", file))?; + let path = from_lsp::abs_path(&url)?; + match vfs.file_id(&path.clone().into()) { + Some(id) => { + // Load code from vfs if exist + res.push(String::from_utf8(vfs.file_contents(id).to_vec()).unwrap()); + } + None => { + // In order to ensure that k_file corresponds to k_code, load the code from the file system if not exist + let p: &Path = path.as_ref(); + if p.is_file() { + res.push( + fs::read_to_string(path) + .map_err(|_| anyhow::anyhow!("can't convert file to url: {}", file))?, + ); + } else if p.is_dir() { + let k_files = get_dir_files(p.to_str().unwrap(), false) + .map_err(|_| anyhow::anyhow!("can't get dir files: {} ", file))?; + for k_file in k_files { + let k_file_path = Path::new(k_file.as_str()); + res.push( + fs::read_to_string(k_file_path).map_err(|_| { + anyhow::anyhow!("can't convert file to url: {}", file) + })?, + ); + } + } + } + } + } + Ok(res) +} + +pub(crate) fn filter_kcl_config_file(paths: &[PathBuf]) -> Vec { + paths + .iter() + .filter(|p| { + p.file_name().map(|n| n.to_str().unwrap()) == Some(kcl_config::modfile::KCL_MOD_FILE) + || p.file_name().map(|n| n.to_str().unwrap()) + == Some(kcl_config::settings::DEFAULT_SETTING_FILE) + }) + .map(|p| p.clone()) + .collect() +} + +macro_rules! walk_if_contains { + ($expr: expr, $pos: expr, $schema_def: expr) => { + if $expr.contains_pos($pos) { + return inner_most_expr(&$expr, &$pos, $schema_def); + } + }; +} + +macro_rules! walk_if_contains_with_new_expr { + ($expr: expr, $pos: expr, $schema_def: expr, $kind: expr) => { + if $expr.contains_pos($pos) { + walk_if_contains!( + Node::node_with_pos( + $kind($expr.node.clone()), + ( + $expr.filename.clone(), + $expr.line, + $expr.column, + $expr.end_line, + $expr.end_column, + ), + ), + $pos, + $schema_def + ); + } + }; +} + +macro_rules! walk_option_if_contains { + ($opt: expr, $pos: expr, $schema_def: expr) => { + if let Some(expr) = &$opt { + walk_if_contains!(expr, $pos, $schema_def) + } + }; +} + +macro_rules! walk_list_if_contains { + ($list: expr, $pos: expr, $schema_def: expr) => { + for elem in &$list { + walk_if_contains!(elem, $pos, $schema_def) + } + }; +} + +fn transfer_ident_names(names: Vec, pos: &PosTuple) -> Vec> { + let mut new_names = vec![]; + let mut col = pos.2; + for name in &names { + let mut name_pos = pos.clone(); + name_pos.2 = col; + name_pos.4 = col + name.len() as u64; + new_names.push(Node::node_with_pos(name.clone(), name_pos)); + col = col + name.len() as u64 + ".".len() as u64; + } + new_names +} + +/// Recursively finds the inner most expr and its schema_def expr if in a schema expr(e.g., schema_attr and schema_expr) +/// in a stmt according to the position. +pub(crate) fn inner_most_expr_in_stmt( + stmt: &Stmt, + pos: &KCLPos, + schema_def: Option>, +) -> (Option>, Option>) { + match stmt { + Stmt::Assign(assign_stmt) => { + if let Some(ty) = &assign_stmt.ty { + if ty.contains_pos(pos) { + return (build_identifier_from_ty_string(ty, pos), schema_def); + } + } + walk_if_contains!(assign_stmt.value, pos, schema_def); + + for expr in &assign_stmt.targets { + walk_if_contains_with_new_expr!(expr, pos, schema_def, Expr::Target); + } + (None, schema_def) + } + Stmt::TypeAlias(type_alias_stmt) => { + walk_if_contains_with_new_expr!( + type_alias_stmt.type_name, + pos, + schema_def, + Expr::Identifier + ); + (None, schema_def) + } + Stmt::Expr(expr_stmt) => { + walk_list_if_contains!(expr_stmt.exprs, pos, schema_def); + (None, schema_def) + } + Stmt::Unification(unification_stmt) => { + walk_if_contains_with_new_expr!( + unification_stmt.target, + pos, + schema_def, + Expr::Identifier + ); + + walk_if_contains_with_new_expr!(unification_stmt.value, pos, schema_def, Expr::Schema); + + (None, schema_def) + } + Stmt::AugAssign(aug_assign_stmt) => { + walk_if_contains!(aug_assign_stmt.value, pos, schema_def); + walk_if_contains_with_new_expr!(aug_assign_stmt.target, pos, schema_def, Expr::Target); + (None, schema_def) + } + Stmt::Assert(assert_stmt) => { + walk_if_contains!(assert_stmt.test, pos, schema_def); + walk_option_if_contains!(assert_stmt.if_cond, pos, schema_def); + walk_option_if_contains!(assert_stmt.msg, pos, schema_def); + (None, schema_def) + } + Stmt::If(if_stmt) => { + walk_if_contains!(if_stmt.cond, pos, schema_def); + for stmt in &if_stmt.body { + if stmt.contains_pos(pos) { + return inner_most_expr_in_stmt(&stmt.node, pos, schema_def); + } + } + for stmt in &if_stmt.orelse { + if stmt.contains_pos(pos) { + return inner_most_expr_in_stmt(&stmt.node, pos, schema_def); + } + } + (None, schema_def) + } + Stmt::Schema(schema_stmt) => { + walk_if_contains!( + Node::node_with_pos( + Expr::Identifier(Identifier { + names: transfer_ident_names( + vec![schema_stmt.name.node.clone()], + &( + schema_stmt.name.filename.clone(), + schema_stmt.name.line, + schema_stmt.name.column, + schema_stmt.name.end_line, + schema_stmt.name.end_column, + ), + ), + pkgpath: "".to_string(), + ctx: kcl_ast::ast::ExprContext::Load, + }), + ( + schema_stmt.name.filename.clone(), + schema_stmt.name.line, + schema_stmt.name.column, + schema_stmt.name.end_line, + schema_stmt.name.end_column, + ), + ), + pos, + schema_def + ); + if let Some(parent_id) = &schema_stmt.parent_name { + walk_if_contains_with_new_expr!(parent_id, pos, schema_def, Expr::Identifier); + } + if let Some(host) = &schema_stmt.for_host_name { + walk_if_contains_with_new_expr!(host, pos, schema_def, Expr::Identifier); + } + for mixin in &schema_stmt.mixins { + walk_if_contains_with_new_expr!(mixin, pos, schema_def, Expr::Identifier); + } + for stmt in &schema_stmt.body { + if stmt.contains_pos(pos) { + return inner_most_expr_in_stmt(&stmt.node, pos, schema_def); + } + } + for decorator in &schema_stmt.decorators { + walk_if_contains_with_new_expr!(decorator, pos, schema_def, Expr::Call); + } + for check in &schema_stmt.checks { + walk_if_contains_with_new_expr!(check, pos, schema_def, Expr::Check); + } + (None, schema_def) + } + Stmt::SchemaAttr(schema_attr_expr) => { + walk_if_contains!( + Node::node_with_pos( + Expr::Identifier(Identifier { + names: vec![*schema_attr_expr.name.clone()], + pkgpath: "".to_string(), + ctx: kcl_ast::ast::ExprContext::Load, + }), + ( + schema_attr_expr.name.filename.clone(), + schema_attr_expr.name.line, + schema_attr_expr.name.column, + schema_attr_expr.name.end_line, + schema_attr_expr.name.end_column, + ), + ), + pos, + schema_def + ); + if schema_attr_expr.ty.contains_pos(pos) { + return ( + build_identifier_from_ty_string(&schema_attr_expr.ty, pos), + schema_def, + ); + } + walk_option_if_contains!(schema_attr_expr.value, pos, schema_def); + for decorator in &schema_attr_expr.decorators { + walk_if_contains_with_new_expr!(decorator, pos, schema_def, Expr::Call); + } + (None, schema_def) + } + Stmt::Rule(rule_stmt) => { + for parent_id in &rule_stmt.parent_rules { + walk_if_contains_with_new_expr!(parent_id, pos, schema_def, Expr::Identifier); + } + for decorator in &rule_stmt.decorators { + walk_if_contains_with_new_expr!(decorator, pos, schema_def, Expr::Call); + } + for check in &rule_stmt.checks { + walk_if_contains_with_new_expr!(check, pos, schema_def, Expr::Check); + } + (None, schema_def) + } + Stmt::Import(_) => (None, schema_def), + } +} + +/// Recursively finds the inner most expr and its schema_def expr if in a schema expr(e.g., schema_attr in schema_expr) +/// in a expr according to the position. +pub(crate) fn inner_most_expr( + expr: &Node, + pos: &KCLPos, + schema_def: Option>, +) -> (Option>, Option>) { + if !expr.contains_pos(pos) { + return (None, None); + } + match &expr.node { + Expr::Identifier(_) => (Some(expr.clone()), schema_def), + Expr::Target(target) => { + for path in &target.paths { + if let MemberOrIndex::Index(index) = path { + if index.contains_pos(pos) { + return (Some(*index.clone()), schema_def); + } + } + } + (Some(expr.clone()), schema_def) + } + Expr::Selector(select_expr) => { + walk_if_contains!(select_expr.value, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::Schema(schema_expr) => { + walk_if_contains_with_new_expr!(schema_expr.name, pos, schema_def, Expr::Identifier); + walk_list_if_contains!(schema_expr.args, pos, schema_def); + + for kwargs in &schema_expr.kwargs { + walk_if_contains_with_new_expr!(kwargs, pos, schema_def, Expr::Keyword); + } + if schema_expr.config.contains_pos(pos) { + return inner_most_expr(&schema_expr.config, pos, Some(expr.clone())); + } + (Some(expr.clone()), schema_def) + } + Expr::Config(config_expr) => { + for item in &config_expr.items { + if item.contains_pos(pos) { + return inner_most_expr_in_config_entry(item, pos, schema_def); + } + } + (Some(expr.clone()), schema_def) + } + Expr::Unary(unary_expr) => { + walk_if_contains!(unary_expr.operand, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::Binary(binary_expr) => { + walk_if_contains!(binary_expr.left, pos, schema_def); + walk_if_contains!(binary_expr.right, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::If(if_expr) => { + walk_if_contains!(if_expr.body, pos, schema_def); + walk_if_contains!(if_expr.cond, pos, schema_def); + walk_if_contains!(if_expr.orelse, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::Call(call_expr) => { + walk_list_if_contains!(call_expr.args, pos, schema_def); + for keyword in &call_expr.keywords { + walk_if_contains_with_new_expr!(keyword, pos, schema_def, Expr::Keyword); + } + walk_if_contains!(call_expr.func, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::Paren(paren_expr) => { + walk_if_contains!(paren_expr.expr, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::Quant(quant_expr) => { + walk_if_contains!(quant_expr.target, pos, schema_def); + for var in &quant_expr.variables { + walk_if_contains_with_new_expr!(var, pos, schema_def, Expr::Identifier); + } + walk_if_contains!(quant_expr.test, pos, schema_def); + walk_option_if_contains!(quant_expr.if_cond, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::List(list_expr) => { + walk_list_if_contains!(list_expr.elts, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::ListIfItem(list_if_item_expr) => { + walk_if_contains!(list_if_item_expr.if_cond, pos, schema_def); + walk_list_if_contains!(list_if_item_expr.exprs, pos, schema_def); + walk_option_if_contains!(list_if_item_expr.orelse, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::ListComp(list_comp_expr) => { + walk_if_contains!(list_comp_expr.elt, pos, schema_def); + for comp_clause in &list_comp_expr.generators { + walk_if_contains_with_new_expr!(comp_clause, pos, schema_def, Expr::CompClause); + } + (Some(expr.clone()), schema_def) + } + Expr::Starred(starred_exor) => { + walk_if_contains!(starred_exor.value, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::DictComp(dict_comp) => { + walk_option_if_contains!(dict_comp.entry.key, pos, schema_def); + walk_if_contains!(dict_comp.entry.value, pos, schema_def); + + for generator in &dict_comp.generators { + if generator.contains_pos(pos) { + walk_if_contains_with_new_expr!(generator, pos, schema_def, Expr::CompClause); + } + } + (Some(expr.clone()), schema_def) + } + Expr::ConfigIfEntry(config_if_entry_expr) => { + walk_if_contains!(config_if_entry_expr.if_cond, pos, schema_def); + for item in &config_if_entry_expr.items { + if item.contains_pos(pos) { + return inner_most_expr_in_config_entry(item, pos, schema_def); + } + } + walk_option_if_contains!(config_if_entry_expr.orelse, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::CompClause(comp_clause) => { + for target in &comp_clause.targets { + walk_if_contains_with_new_expr!(target, pos, schema_def, Expr::Identifier); + } + walk_if_contains!(comp_clause.iter, pos, schema_def); + walk_list_if_contains!(comp_clause.ifs, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::Check(check_expr) => { + walk_if_contains!(check_expr.test, pos, schema_def); + walk_option_if_contains!(check_expr.if_cond, pos, schema_def); + walk_option_if_contains!(check_expr.msg, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::Lambda(lambda_expr) => { + if let Some(args) = &lambda_expr.args { + walk_if_contains_with_new_expr!(args, pos, schema_def, Expr::Arguments); + } + for stmt in &lambda_expr.body { + if stmt.contains_pos(pos) { + return inner_most_expr_in_stmt(&stmt.node, pos, schema_def); + } + } + + (Some(expr.clone()), schema_def) + } + Expr::Subscript(subscript_expr) => { + walk_if_contains!(subscript_expr.value, pos, schema_def); + walk_option_if_contains!(subscript_expr.index, pos, schema_def); + walk_option_if_contains!(subscript_expr.lower, pos, schema_def); + walk_option_if_contains!(subscript_expr.upper, pos, schema_def); + walk_option_if_contains!(subscript_expr.step, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::Keyword(keyword) => { + walk_if_contains_with_new_expr!(keyword.arg, pos, schema_def, Expr::Identifier); + walk_option_if_contains!(keyword.value, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::Arguments(argument) => { + for arg in &argument.args { + walk_if_contains_with_new_expr!(arg, pos, schema_def, Expr::Identifier); + } + for default in &argument.defaults { + walk_option_if_contains!(default, pos, schema_def); + } + for ty in argument.ty_list.iter().flatten() { + if ty.contains_pos(pos) { + return ( + Some(build_identifier_from_string(&node_ref!( + ty.node.to_string(), + ty.pos() + ))), + schema_def, + ); + } + } + (Some(expr.clone()), schema_def) + } + Expr::Compare(compare_expr) => { + walk_if_contains!(compare_expr.left, pos, schema_def); + walk_list_if_contains!(compare_expr.comparators, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::NumberLit(_) => (Some(expr.clone()), schema_def), + Expr::StringLit(_) => (Some(expr.clone()), schema_def), + Expr::NameConstantLit(_) => (Some(expr.clone()), schema_def), + Expr::JoinedString(joined_string) => { + walk_list_if_contains!(joined_string.values, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::FormattedValue(formatted_value) => { + walk_if_contains!(formatted_value.value, pos, schema_def); + (Some(expr.clone()), schema_def) + } + Expr::Missing(_) => (Some(expr.clone()), schema_def), + } +} + +fn inner_most_expr_in_config_entry( + config_entry: &Node, + pos: &KCLPos, + schema_def: Option>, +) -> (Option>, Option>) { + if let Some(key) = &config_entry.node.key { + if key.contains_pos(pos) { + return inner_most_expr(key, pos, schema_def); + } + } + if config_entry.node.value.contains_pos(pos) { + inner_most_expr(&config_entry.node.value, pos, None) + } else { + (None, schema_def) + } +} + +pub(crate) fn is_in_docstring( + program: &Program, + pos: &KCLPos, +) -> Option<(NodeRef, SchemaStmt)> { + match program.pos_to_stmt(pos) { + Some(node) => match node.node.clone() { + Stmt::Schema(schema) => match &schema.doc { + Some(doc) => { + if doc.contains_pos(pos) { + Some((doc.clone(), schema)) + } else { + None + } + } + None => None, + }, + _ => None, + }, + None => None, + } +} + +/// Build a temp identifier expr with string +fn build_identifier_from_string(s: &NodeRef) -> Node { + Node::node_with_pos( + Expr::Identifier(Identifier { + names: transfer_ident_names( + vec![s.node.clone()], + &( + s.filename.clone(), + s.line, + s.column, + s.end_line, + s.end_column, + ), + ), + pkgpath: "".to_string(), + ctx: kcl_ast::ast::ExprContext::Load, + }), + ( + s.filename.clone(), + s.line, + s.column, + s.end_line, + s.end_column, + ), + ) +} + +/// Build a temp identifier expr with string +fn build_identifier_from_ty_string(ty: &NodeRef, pos: &KCLPos) -> Option> { + if !ty.contains_pos(pos) { + return None; + } + match &ty.node { + Type::Any => None, + Type::Named(id) => Some(Node::node_with_pos( + Expr::Identifier(id.clone()), + ( + ty.filename.clone(), + ty.line, + ty.column, + ty.end_line, + ty.end_column, + ), + )), + Type::Basic(_) => None, + Type::List(list_ty) => { + if let Some(inner) = &list_ty.inner_type { + if inner.contains_pos(pos) { + return build_identifier_from_ty_string(inner, pos); + } + } + None + } + Type::Dict(dict_ty) => { + if let Some(key_ty) = &dict_ty.key_type { + if key_ty.contains_pos(pos) { + return build_identifier_from_ty_string(key_ty, pos); + } + } + if let Some(value_ty) = &dict_ty.value_type { + if value_ty.contains_pos(pos) { + return build_identifier_from_ty_string(value_ty, pos); + } + } + None + } + Type::Union(union_ty) => { + for ty in &union_ty.type_elements { + if ty.contains_pos(pos) { + return build_identifier_from_ty_string(ty, pos); + } + } + None + } + Type::Literal(_) => None, + Type::Function(_) => None, + } +} diff --git a/kclvm/tools/src/LSP/src/word_index.rs b/crates/tools/src/LSP/src/word_index.rs similarity index 99% rename from kclvm/tools/src/LSP/src/word_index.rs rename to crates/tools/src/LSP/src/word_index.rs index 26c36e7e8..838a97b7e 100644 --- a/kclvm/tools/src/LSP/src/word_index.rs +++ b/crates/tools/src/LSP/src/word_index.rs @@ -1,4 +1,4 @@ -use kclvm_span::symbol::reserved; +use kcl_span::symbol::reserved; use lsp_types::{Position, Range}; use std::collections::HashMap; @@ -136,7 +136,7 @@ fn build_virtual_word_index_with_file_content( #[cfg(test)] mod tests { - use super::{line_to_words, Word}; + use super::{Word, line_to_words}; use std::collections::HashMap; #[test] diff --git a/kclvm/tools/src/fix/LICENSE b/crates/tools/src/fix/LICENSE similarity index 100% rename from kclvm/tools/src/fix/LICENSE rename to crates/tools/src/fix/LICENSE diff --git a/crates/tools/src/fix/mod.rs b/crates/tools/src/fix/mod.rs new file mode 100644 index 000000000..30a9797a0 --- /dev/null +++ b/crates/tools/src/fix/mod.rs @@ -0,0 +1,171 @@ +mod replace; +#[cfg(test)] +mod tests; +use anyhow::{Error, ensure}; +use kcl_error::{Diagnostic, diagnostic::Range as KCLRange}; +use std::collections::HashMap; +use std::fs; +use std::ops::Range; + +/// A structure for handling code fixes. +pub struct CodeFix { + data: replace::Data, +} + +impl CodeFix { + pub fn new(s: &str) -> CodeFix { + CodeFix { + data: replace::Data::new(s.as_bytes()), + } + } + + pub fn apply(&mut self, suggestion: &Suggestion) -> Result<(), Error> { + let snippet = &suggestion.replacement.snippet; + self.data.replace_range( + snippet.range.start, + snippet.range.end.saturating_sub(1), + suggestion.replacement.replacement.as_bytes(), + )?; + Ok(()) + } + + pub fn finish(&self) -> Result { + Ok(String::from_utf8(self.data.to_vec())?) + } +} + +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +/// An error/warning and possible solutions for fixing it +pub struct Suggestion { + pub message: String, + pub replacement: Replacement, +} + +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +pub struct Replacement { + pub snippet: Snippet, + pub replacement: String, +} + +#[derive(Debug, Clone, Hash, PartialEq, Eq)] +pub struct Snippet { + pub file_name: String, + pub range: Range, +} + +pub fn diag_to_suggestion( + diag: Diagnostic, + files: &mut HashMap, +) -> anyhow::Result> { + let mut suggestions = vec![]; + + for msg in &diag.messages { + let replacements = msg + .suggested_replacement + .clone() + .unwrap_or_else(|| vec!["".to_string()]); + let replacement_str = replacements.first().cloned().unwrap_or_default(); + + let file_name = msg.range.0.filename.clone(); + let src = match files.get(&file_name) { + Some(src) => src.clone(), + None => { + let src = fs::read_to_string(&file_name).expect("Unable to read file"); + files.insert(file_name.clone(), src.clone()); + src + } + }; + + suggestions.push(Suggestion { + message: msg.message.clone(), + replacement: Replacement { + snippet: Snippet { + file_name, + range: text_range(src.as_str(), &msg.range)?, + }, + replacement: replacement_str, + }, + }); + } + Ok(suggestions) +} + +fn is_newline_at_index(s: &str, index: usize) -> bool { + let length = s.len(); + + if index >= length { + return false; + } + + let bytes = s.as_bytes(); + + if bytes[index] == b'\n' { + return true; + } + #[cfg(target_os = "windows")] + if bytes[index] == b'\r' && index + 1 < length && bytes[index + 1] == b'\n' { + return true; + } + + false +} + +pub(crate) fn text_range(text: &str, range: &KCLRange) -> anyhow::Result, Error> { + let mut lines_length = vec![]; + let lines_text: Vec<&str> = text.split('\n').collect(); + let mut pre_total_length = 0; + + for line in &lines_text { + lines_length.push(pre_total_length); + pre_total_length += line.len() + "\n".len(); + } + + ensure!( + (range.0.line as usize) <= lines_length.len() + && (range.1.line as usize) <= lines_length.len() + ); + + // The KCL diagnostic line is 1-based and the column is 0-based. + let start = + lines_length.get(range.0.line as usize - 1).unwrap() + range.0.column.unwrap_or(0) as usize; + let mut end = + lines_length.get(range.1.line as usize - 1).unwrap() + range.1.column.unwrap_or(0) as usize; + + if is_newline_at_index(text, end) { + if cfg!(windows) { + end += "\r\n".len() + } else { + end += "\n".len() + } + } + + Ok(Range { start, end }) +} + +pub fn fix(diags: Vec) -> Result<(), Error> { + let mut suggestions = vec![]; + let mut source_code = HashMap::new(); + for diag in diags { + suggestions.extend(diag_to_suggestion(diag, &mut source_code)?) + } + + let mut files = HashMap::new(); + for suggestion in suggestions { + let file = suggestion.replacement.snippet.file_name.clone(); + files.entry(file).or_insert_with(Vec::new).push(suggestion); + } + + for (source_file, suggestions) in &files { + println!("fix file: {:?}", source_file); + let source = fs::read_to_string(source_file)?; + let mut fix = CodeFix::new(&source); + for suggestion in suggestions.iter() { + if let Err(e) = fix.apply(suggestion) { + eprintln!("Failed to apply suggestion to {}: {}", source_file, e); + } + } + let fixes = fix.finish()?; + fs::write(source_file, fixes)?; + } + Ok(()) +} diff --git a/kclvm/tools/src/fix/replace.rs b/crates/tools/src/fix/replace.rs similarity index 97% rename from kclvm/tools/src/fix/replace.rs rename to crates/tools/src/fix/replace.rs index 4bc4d5c31..70a644760 100644 --- a/kclvm/tools/src/fix/replace.rs +++ b/crates/tools/src/fix/replace.rs @@ -5,7 +5,7 @@ //! replacement of parts of its content, with the ability to prevent changing //! the same parts multiple times. -use anyhow::{anyhow, ensure, Error}; +use anyhow::{Error, anyhow, ensure}; use std::rc::Rc; #[derive(Debug, Clone, PartialEq, Eq)] @@ -57,9 +57,9 @@ impl Data { } self.parts.iter().fold(Vec::new(), |mut acc, d| { - match d.data { + match &d.data { State::Initial => acc.extend_from_slice(&self.original[d.start..=d.end]), - State::Replaced(ref d) | State::Inserted(ref d) => acc.extend_from_slice(d), + State::Replaced(d) | State::Inserted(d) => acc.extend_from_slice(&d), }; acc }) @@ -124,7 +124,7 @@ impl Data { // can replace the exact same range with the exact same content // multiple times and we'll process and allow it. if part_to_split.start == from && part_to_split.end == up_to_and_including { - if let State::Replaced(ref replacement) = part_to_split.data { + if let State::Replaced(replacement) = &part_to_split.data { if &**replacement == data { return Ok(()); } diff --git a/kclvm/tools/src/fix/test_data/fix_import.k b/crates/tools/src/fix/test_data/fix_import.k similarity index 100% rename from kclvm/tools/src/fix/test_data/fix_import.k rename to crates/tools/src/fix/test_data/fix_import.k diff --git a/kclvm/tools/src/fix/test_data/unused_import.k b/crates/tools/src/fix/test_data/unused_import.k similarity index 100% rename from kclvm/tools/src/fix/test_data/unused_import.k rename to crates/tools/src/fix/test_data/unused_import.k diff --git a/kclvm/tools/src/fix/tests.rs b/crates/tools/src/fix/tests.rs similarity index 100% rename from kclvm/tools/src/fix/tests.rs rename to crates/tools/src/fix/tests.rs diff --git a/crates/tools/src/format/mod.rs b/crates/tools/src/format/mod.rs new file mode 100644 index 000000000..7a7439559 --- /dev/null +++ b/crates/tools/src/format/mod.rs @@ -0,0 +1,94 @@ +//! [kcl_tools::format] module mainly contains some functions of language formatting, +//! the main API function is `format`, which accepts a path to be formatted and +//! formatted options. +//! +//! The basic principle is to call the [kcl_parser::parse_file] function to parse the +//! AST Module, and then use the AST printer [kcl_tools::printer::print_ast_module] +//! to print it as source code string. +use anyhow::Result; +use kcl_ast_pretty::print_ast_module; +use kcl_parser::get_kcl_files; +use std::path::Path; + +use kcl_parser::{parse_file_force_errors, parse_single_file}; + +#[cfg(test)] +mod tests; + +/// FormatOptions contains two options: +/// - is_stdout: whether to output the formatted result to stdout. +/// - recursively: whether to recursively traverse a folder and format all KCL files in it. +/// - omit_errors: whether to omit the parse errors when format the KCL code. +#[derive(Debug, Default)] +pub struct FormatOptions { + pub is_stdout: bool, + pub recursively: bool, + pub omit_errors: bool, +} + +/// Formats kcl file or directory path contains kcl files and +/// returns the changed file paths. +/// +/// # Examples +/// +/// ```no_run +/// use kcl_tools::format::{format, FormatOptions}; +/// +/// // Format a single file. +/// format("path_to_a_single_file.k", &FormatOptions::default()).unwrap(); +/// // Format a folder contains kcl files +/// format("path_to_a_folder", &FormatOptions::default()).unwrap(); +/// ``` +pub fn format>(path: P, opts: &FormatOptions) -> Result> { + let mut changed_paths: Vec = vec![]; + let path_ref = path.as_ref(); + if path_ref.is_dir() { + for file in &get_kcl_files(path, opts.recursively)? { + if format_file(file, opts)? { + changed_paths.push(file.clone()) + } + } + } else if path_ref.is_file() { + let file = path_ref.to_str().unwrap().to_string(); + if format_file(&file, opts)? { + changed_paths.push(file) + } + } + if opts.is_stdout { + let n = changed_paths.len(); + println!( + "KCL format done and {} {} formatted:", + n, + if n <= 1 { "file was" } else { "files were" } + ); + for p in &changed_paths { + println!("{}", p); + } + } + Ok(changed_paths) +} + +/// Formats a file and returns whether the file has been formatted and modified. +pub fn format_file(file: &str, opts: &FormatOptions) -> Result { + let src = std::fs::read_to_string(file)?; + let (source, is_formatted) = format_source(file, &src, opts)?; + if opts.is_stdout { + println!("{}", source); + } else { + std::fs::write(file, &source)? + } + Ok(is_formatted) +} + +/// Formats a code source and returns the formatted source and +/// whether the source is changed. +pub fn format_source(file: &str, src: &str, opts: &FormatOptions) -> Result<(String, bool)> { + let module = if opts.omit_errors { + parse_single_file(file, Some(src.to_string()))?.module + } else { + parse_file_force_errors(file, Some(src.to_string()))? + }; + let formatted_src = print_ast_module(&module); + let is_formatted = src != formatted_src; + Ok((formatted_src, is_formatted)) +} diff --git a/kclvm/tools/src/format/test_data/fail_format_data/syntax_err.k b/crates/tools/src/format/test_data/fail_format_data/syntax_err.k similarity index 100% rename from kclvm/tools/src/format/test_data/fail_format_data/syntax_err.k rename to crates/tools/src/format/test_data/fail_format_data/syntax_err.k diff --git a/kclvm/tools/src/format/test_data/format_data/assert.golden b/crates/tools/src/format/test_data/format_data/assert.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/assert.golden rename to crates/tools/src/format/test_data/format_data/assert.golden diff --git a/kclvm/tools/src/format/test_data/format_data/assert.input b/crates/tools/src/format/test_data/format_data/assert.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/assert.input rename to crates/tools/src/format/test_data/format_data/assert.input diff --git a/kclvm/tools/src/format/test_data/format_data/blankline.golden b/crates/tools/src/format/test_data/format_data/blankline.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/blankline.golden rename to crates/tools/src/format/test_data/format_data/blankline.golden diff --git a/kclvm/tools/src/format/test_data/format_data/blankline.input b/crates/tools/src/format/test_data/format_data/blankline.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/blankline.input rename to crates/tools/src/format/test_data/format_data/blankline.input diff --git a/kclvm/tools/src/format/test_data/format_data/breakline.golden b/crates/tools/src/format/test_data/format_data/breakline.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/breakline.golden rename to crates/tools/src/format/test_data/format_data/breakline.golden diff --git a/kclvm/tools/src/format/test_data/format_data/breakline.input b/crates/tools/src/format/test_data/format_data/breakline.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/breakline.input rename to crates/tools/src/format/test_data/format_data/breakline.input diff --git a/kclvm/tools/src/format/test_data/format_data/check.golden b/crates/tools/src/format/test_data/format_data/check.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/check.golden rename to crates/tools/src/format/test_data/format_data/check.golden diff --git a/kclvm/tools/src/format/test_data/format_data/check.input b/crates/tools/src/format/test_data/format_data/check.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/check.input rename to crates/tools/src/format/test_data/format_data/check.input diff --git a/kclvm/tools/src/format/test_data/format_data/codelayout.golden b/crates/tools/src/format/test_data/format_data/codelayout.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/codelayout.golden rename to crates/tools/src/format/test_data/format_data/codelayout.golden diff --git a/kclvm/tools/src/format/test_data/format_data/codelayout.input b/crates/tools/src/format/test_data/format_data/codelayout.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/codelayout.input rename to crates/tools/src/format/test_data/format_data/codelayout.input diff --git a/kclvm/tools/src/format/test_data/format_data/collection_if.golden b/crates/tools/src/format/test_data/format_data/collection_if.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/collection_if.golden rename to crates/tools/src/format/test_data/format_data/collection_if.golden diff --git a/kclvm/tools/src/format/test_data/format_data/collection_if.input b/crates/tools/src/format/test_data/format_data/collection_if.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/collection_if.input rename to crates/tools/src/format/test_data/format_data/collection_if.input diff --git a/kclvm/tools/src/format/test_data/format_data/comment.golden b/crates/tools/src/format/test_data/format_data/comment.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/comment.golden rename to crates/tools/src/format/test_data/format_data/comment.golden diff --git a/kclvm/tools/src/format/test_data/format_data/comment.input b/crates/tools/src/format/test_data/format_data/comment.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/comment.input rename to crates/tools/src/format/test_data/format_data/comment.input diff --git a/kclvm/tools/src/format/test_data/format_data/comp_for.golden b/crates/tools/src/format/test_data/format_data/comp_for.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/comp_for.golden rename to crates/tools/src/format/test_data/format_data/comp_for.golden diff --git a/kclvm/tools/src/format/test_data/format_data/comp_for.input b/crates/tools/src/format/test_data/format_data/comp_for.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/comp_for.input rename to crates/tools/src/format/test_data/format_data/comp_for.input diff --git a/kclvm/tools/src/format/test_data/format_data/different_stmts_line_breaks.golden b/crates/tools/src/format/test_data/format_data/different_stmts_line_breaks.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/different_stmts_line_breaks.golden rename to crates/tools/src/format/test_data/format_data/different_stmts_line_breaks.golden diff --git a/kclvm/tools/src/format/test_data/format_data/different_stmts_line_breaks.input b/crates/tools/src/format/test_data/format_data/different_stmts_line_breaks.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/different_stmts_line_breaks.input rename to crates/tools/src/format/test_data/format_data/different_stmts_line_breaks.input diff --git a/kclvm/tools/src/format/test_data/format_data/empty.golden b/crates/tools/src/format/test_data/format_data/empty.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/empty.golden rename to crates/tools/src/format/test_data/format_data/empty.golden diff --git a/kclvm/tools/src/format/test_data/format_data/empty.input b/crates/tools/src/format/test_data/format_data/empty.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/empty.input rename to crates/tools/src/format/test_data/format_data/empty.input diff --git a/kclvm/tools/src/format/test_data/format_data/import.golden b/crates/tools/src/format/test_data/format_data/import.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/import.golden rename to crates/tools/src/format/test_data/format_data/import.golden diff --git a/kclvm/tools/src/format/test_data/format_data/import.input b/crates/tools/src/format/test_data/format_data/import.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/import.input rename to crates/tools/src/format/test_data/format_data/import.input diff --git a/kclvm/tools/src/format/test_data/format_data/import_only.golden b/crates/tools/src/format/test_data/format_data/import_only.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/import_only.golden rename to crates/tools/src/format/test_data/format_data/import_only.golden diff --git a/kclvm/tools/src/format/test_data/format_data/import_only.input b/crates/tools/src/format/test_data/format_data/import_only.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/import_only.input rename to crates/tools/src/format/test_data/format_data/import_only.input diff --git a/kclvm/tools/src/format/test_data/format_data/indent.golden b/crates/tools/src/format/test_data/format_data/indent.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/indent.golden rename to crates/tools/src/format/test_data/format_data/indent.golden diff --git a/kclvm/tools/src/format/test_data/format_data/indent.input b/crates/tools/src/format/test_data/format_data/indent.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/indent.input rename to crates/tools/src/format/test_data/format_data/indent.input diff --git a/kclvm/tools/src/format/test_data/format_data/inline_comment.golden b/crates/tools/src/format/test_data/format_data/inline_comment.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/inline_comment.golden rename to crates/tools/src/format/test_data/format_data/inline_comment.golden diff --git a/kclvm/tools/src/format/test_data/format_data/inline_comment.input b/crates/tools/src/format/test_data/format_data/inline_comment.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/inline_comment.input rename to crates/tools/src/format/test_data/format_data/inline_comment.input diff --git a/kclvm/tools/src/format/test_data/format_data/lambda.golden b/crates/tools/src/format/test_data/format_data/lambda.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/lambda.golden rename to crates/tools/src/format/test_data/format_data/lambda.golden diff --git a/kclvm/tools/src/format/test_data/format_data/lambda.input b/crates/tools/src/format/test_data/format_data/lambda.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/lambda.input rename to crates/tools/src/format/test_data/format_data/lambda.input diff --git a/kclvm/tools/src/format/test_data/format_data/layout_import_stmt.golden b/crates/tools/src/format/test_data/format_data/layout_import_stmt.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/layout_import_stmt.golden rename to crates/tools/src/format/test_data/format_data/layout_import_stmt.golden diff --git a/kclvm/tools/src/format/test_data/format_data/layout_import_stmt.input b/crates/tools/src/format/test_data/format_data/layout_import_stmt.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/layout_import_stmt.input rename to crates/tools/src/format/test_data/format_data/layout_import_stmt.input diff --git a/kclvm/tools/src/format/test_data/format_data/list_dict_schema_expr.golden b/crates/tools/src/format/test_data/format_data/list_dict_schema_expr.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/list_dict_schema_expr.golden rename to crates/tools/src/format/test_data/format_data/list_dict_schema_expr.golden diff --git a/kclvm/tools/src/format/test_data/format_data/list_dict_schema_expr.input b/crates/tools/src/format/test_data/format_data/list_dict_schema_expr.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/list_dict_schema_expr.input rename to crates/tools/src/format/test_data/format_data/list_dict_schema_expr.input diff --git a/kclvm/tools/src/format/test_data/format_data/quant.golden b/crates/tools/src/format/test_data/format_data/quant.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/quant.golden rename to crates/tools/src/format/test_data/format_data/quant.golden diff --git a/kclvm/tools/src/format/test_data/format_data/quant.input b/crates/tools/src/format/test_data/format_data/quant.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/quant.input rename to crates/tools/src/format/test_data/format_data/quant.input diff --git a/kclvm/tools/src/format/test_data/format_data/schema.golden b/crates/tools/src/format/test_data/format_data/schema.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/schema.golden rename to crates/tools/src/format/test_data/format_data/schema.golden diff --git a/kclvm/tools/src/format/test_data/format_data/schema.input b/crates/tools/src/format/test_data/format_data/schema.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/schema.input rename to crates/tools/src/format/test_data/format_data/schema.input diff --git a/kclvm/tools/src/format/test_data/format_data/string.golden b/crates/tools/src/format/test_data/format_data/string.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/string.golden rename to crates/tools/src/format/test_data/format_data/string.golden diff --git a/kclvm/tools/src/format/test_data/format_data/string.input b/crates/tools/src/format/test_data/format_data/string.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/string.input rename to crates/tools/src/format/test_data/format_data/string.input diff --git a/kclvm/tools/src/format/test_data/format_data/trailing_comment_collection.golden b/crates/tools/src/format/test_data/format_data/trailing_comment_collection.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/trailing_comment_collection.golden rename to crates/tools/src/format/test_data/format_data/trailing_comment_collection.golden diff --git a/kclvm/tools/src/format/test_data/format_data/trailing_comment_collection.input b/crates/tools/src/format/test_data/format_data/trailing_comment_collection.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/trailing_comment_collection.input rename to crates/tools/src/format/test_data/format_data/trailing_comment_collection.input diff --git a/kclvm/tools/src/format/test_data/format_data/type_alias.golden b/crates/tools/src/format/test_data/format_data/type_alias.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/type_alias.golden rename to crates/tools/src/format/test_data/format_data/type_alias.golden diff --git a/kclvm/tools/src/format/test_data/format_data/type_alias.input b/crates/tools/src/format/test_data/format_data/type_alias.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/type_alias.input rename to crates/tools/src/format/test_data/format_data/type_alias.input diff --git a/kclvm/tools/src/format/test_data/format_data/unary.golden b/crates/tools/src/format/test_data/format_data/unary.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/unary.golden rename to crates/tools/src/format/test_data/format_data/unary.golden diff --git a/kclvm/tools/src/format/test_data/format_data/unary.input b/crates/tools/src/format/test_data/format_data/unary.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/unary.input rename to crates/tools/src/format/test_data/format_data/unary.input diff --git a/kclvm/tools/src/format/test_data/format_data/union_types.golden b/crates/tools/src/format/test_data/format_data/union_types.golden similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/union_types.golden rename to crates/tools/src/format/test_data/format_data/union_types.golden diff --git a/kclvm/tools/src/format/test_data/format_data/union_types.input b/crates/tools/src/format/test_data/format_data/union_types.input similarity index 100% rename from kclvm/tools/src/format/test_data/format_data/union_types.input rename to crates/tools/src/format/test_data/format_data/union_types.input diff --git a/kclvm/tools/src/format/test_data/format_path_data/folder/first.k b/crates/tools/src/format/test_data/format_path_data/folder/first.k similarity index 100% rename from kclvm/tools/src/format/test_data/format_path_data/folder/first.k rename to crates/tools/src/format/test_data/format_path_data/folder/first.k diff --git a/kclvm/tools/src/format/test_data/format_path_data/folder/second.k b/crates/tools/src/format/test_data/format_path_data/folder/second.k similarity index 100% rename from kclvm/tools/src/format/test_data/format_path_data/folder/second.k rename to crates/tools/src/format/test_data/format_path_data/folder/second.k diff --git a/kclvm/tools/src/format/test_data/format_path_data/if.k b/crates/tools/src/format/test_data/format_path_data/if.k similarity index 100% rename from kclvm/tools/src/format/test_data/format_path_data/if.k rename to crates/tools/src/format/test_data/format_path_data/if.k diff --git a/kclvm/tools/src/format/test_data/format_path_data/internal_pkg/test.k b/crates/tools/src/format/test_data/format_path_data/internal_pkg/test.k similarity index 100% rename from kclvm/tools/src/format/test_data/format_path_data/internal_pkg/test.k rename to crates/tools/src/format/test_data/format_path_data/internal_pkg/test.k diff --git a/kclvm/tools/src/format/test_data/format_path_data/single_file.k b/crates/tools/src/format/test_data/format_path_data/single_file.k similarity index 100% rename from kclvm/tools/src/format/test_data/format_path_data/single_file.k rename to crates/tools/src/format/test_data/format_path_data/single_file.k diff --git a/crates/tools/src/format/tests.rs b/crates/tools/src/format/tests.rs new file mode 100644 index 000000000..c17378a8c --- /dev/null +++ b/crates/tools/src/format/tests.rs @@ -0,0 +1,238 @@ +use super::*; +use kcl_parser::parse_file_force_errors; +use pretty_assertions::assert_eq; +use walkdir::WalkDir; + +const FILE_INPUT_SUFFIX: &str = ".input"; +const FILE_OUTPUT_SUFFIX: &str = ".golden"; +const TEST_CASES: &[&str; 23] = &[ + "assert", + "check", + "blankline", + "breakline", + "codelayout", + "collection_if", + "comment", + "comp_for", + "empty", + "import", + "import_only", + "indent", + "inline_comment", + "lambda", + "quant", + "schema", + "string", + "type_alias", + "unary", + "union_types", + "layout_import_stmt", + "different_stmts_line_breaks", + "trailing_comment_collection", + // "list_dict_schema_expr", +]; + +fn read_data(data_name: &str) -> (String, String) { + let src = std::fs::read_to_string(format!( + "./src/format/test_data/format_data/{}{}", + data_name, FILE_INPUT_SUFFIX + )) + .unwrap(); + + ( + format_source("", &src, &Default::default()).unwrap().0, + std::fs::read_to_string(format!( + "./src/format/test_data/format_data/{}{}", + data_name, FILE_OUTPUT_SUFFIX + )) + .unwrap(), + ) +} + +#[test] +fn test_format_source() { + for case in TEST_CASES { + let (data_input, data_output) = read_data(case); + #[cfg(target_os = "windows")] + let data_output = data_output.replace("\r\n", "\n"); + assert_eq!(data_input, data_output, "Test failed on {}", case); + } +} + +#[test] +fn test_format_single_file() { + assert!( + format( + "./src/format/test_data/format_path_data/single_file.k", + &FormatOptions::default() + ) + .is_ok() + ); +} + +#[test] +fn test_format_folder() { + assert!( + format( + "./src/format/test_data/format_path_data/folder", + &FormatOptions::default() + ) + .is_ok() + ); +} + +#[test] +fn test_format_with_stdout_option() { + let opts = FormatOptions { + is_stdout: true, + recursively: false, + omit_errors: false, + }; + let changed_files = format("./src/format/test_data/format_path_data/if.k", &opts).unwrap(); + assert_eq!(changed_files.len(), 1); + let changed_files = format("./src/format/test_data/format_path_data/", &opts).unwrap(); + assert_eq!(changed_files.len(), 1); + let opts = FormatOptions { + is_stdout: true, + recursively: true, + omit_errors: false, + }; + let changed_files = format("./src/format/test_data/format_path_data/", &opts).unwrap(); + assert_eq!(changed_files.len(), 2); +} + +#[test] +fn test_format_with_omit_error_option() { + let opts = FormatOptions { + is_stdout: false, + recursively: false, + omit_errors: true, + }; + let cases = [ + ( + r#"x = { +a: { +b: 1 +c: 2 +} +d: 3 +} +"#, + r#"x = { + a: { + b: 1 + c: 2 + } + d: 3 +} +"#, + ), + ( + r#"x = { +a: { + b: 1 + c: 2 +} +} +"#, + r#"x = { + a: { + b: 1 + c: 2 + } +} +"#, + ), + ( + r#"x = { + a: 1 + b: 2 + c: 3 +} +"#, + r#"x = { + a: 1 + b: 2 + c: 3 +} +"#, + ), + ( + r#"x = { + a: 1 + b: 2 + c: 3 +} +"#, + r#"x = { + a: 1 + b: 2 + c: 3 +} +"#, + ), + ]; + for (code, expected_code) in cases { + let (actual_code, _) = format_source("error_indent.k", code, &opts).unwrap(); + assert_eq!(actual_code, expected_code); + } +} + +#[test] +fn test_format_integration_konfig() -> Result<()> { + let konfig_path = Path::new(".") + .canonicalize()? + .parent() + .unwrap() + .parent() + .unwrap() + .join("test") + .join("integration") + .join("konfig"); + let files = get_files(konfig_path, true, true, ".k"); + for file in &files { + // Skip test and hidden files. + if file.ends_with("_test.k") || file.starts_with('_') { + continue; + } + assert!( + parse_file_force_errors(file, None).is_ok(), + "file {} test format failed", + file + ); + let src = std::fs::read_to_string(file)?; + let (formatted_src, _) = format_source("", &src, &Default::default())?; + let parse_result = parse_file_force_errors("test.k", Some(formatted_src.clone() + "\n")); + assert!( + parse_result.is_ok(), + "file {} test format failed, the formatted source is\n{}\n the parse error is\n{}", + file, + formatted_src, + parse_result.err().unwrap(), + ); + } + Ok(()) +} + +/// Get kcl files from path. +fn get_files>( + path: P, + recursively: bool, + sorted: bool, + suffix: &str, +) -> Vec { + let mut files = vec![]; + for entry in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) { + let path = entry.path(); + if path.is_file() { + let file = path.to_str().unwrap(); + if file.ends_with(suffix) && (recursively || entry.depth() == 1) { + files.push(file.to_string()) + } + } + } + if sorted { + files.sort(); + } + files +} diff --git a/kclvm/tools/src/lib.rs b/crates/tools/src/lib.rs similarity index 100% rename from kclvm/tools/src/lib.rs rename to crates/tools/src/lib.rs diff --git a/crates/tools/src/lint/mod.rs b/crates/tools/src/lint/mod.rs new file mode 100644 index 000000000..f5df4c335 --- /dev/null +++ b/crates/tools/src/lint/mod.rs @@ -0,0 +1,97 @@ +use std::sync::Arc; + +use kcl_error::{Diagnostic, Handler}; +use kcl_parser::{LoadProgramOptions, ParseSession, load_program}; +use kcl_primitives::IndexSet; +use kcl_runtime::PanicInfo; +use kcl_sema::resolver::resolve_program_with_opts; +#[cfg(test)] +mod tests; + +/// KCL Lint tools API, check a set of files, skips execute, divides and returns diagnostics into error and warning +/// +/// # Parameters +/// +/// `file`: [&str] +/// The File that need to be check +/// +/// `opts`: Option +/// The compilation parameters of KCL, same as the compilation process +/// +/// # Returns +/// +/// result: (IndexSet, IndexSet) +/// Error and warning diagenostics. +/// +/// # Examples +/// +/// ```no_run +/// use kcl_tools::lint::lint_files; +/// let (errors, warnings) = lint_files(&["test.k"], None); +/// ``` +/// +/// - test.k +/// +/// ```kcl +/// import math +/// schema Person: +/// age: int +/// ``` +/// +/// - return +/// ```no_check +/// error: [] +/// warning: [ +/// Diagnostic { +/// level: Warning +/// messages: [Message { +/// range: ( +/// Position { +/// filename: test.k, +/// line: 1, +/// column: None, +/// }, +/// Position { +/// filename: test.k, +/// line: 1, +/// column: None, +/// }, +/// ), +/// style: Style::Line, +/// message: "Module 'math' imported but unused", +/// note: Some("Consider removing this statement".to_string()), +/// }], +/// code: Some, +/// } +/// ] +/// ``` +pub fn lint_files( + files: &[&str], + opts: Option, +) -> (IndexSet, IndexSet) { + // Parse AST program. + let sess = Arc::new(ParseSession::default()); + let mut opts = opts.unwrap_or_default(); + opts.load_plugins = true; + let mut program = match load_program(sess.clone(), files, Some(opts), None) { + Ok(p) => p.program, + Err(err_str) => { + return Handler::default() + .add_panic_info(&PanicInfo::from(err_str.to_string())) + .classification(); + } + }; + sess.append_diagnostic( + resolve_program_with_opts( + &mut program, + kcl_sema::resolver::Options { + merge_program: false, + ..Default::default() + }, + None, + ) + .handler + .diagnostics, + ) + .classification() +} diff --git a/kclvm/tools/src/lint/test_data/import_test/a.k b/crates/tools/src/lint/test_data/import_test/a.k similarity index 100% rename from kclvm/tools/src/lint/test_data/import_test/a.k rename to crates/tools/src/lint/test_data/import_test/a.k diff --git a/kclvm/tools/src/lint/test_data/import_test/b.k b/crates/tools/src/lint/test_data/import_test/b.k similarity index 100% rename from kclvm/tools/src/lint/test_data/import_test/b.k rename to crates/tools/src/lint/test_data/import_test/b.k diff --git a/kclvm/tools/src/lint/test_data/lint.k b/crates/tools/src/lint/test_data/lint.k similarity index 100% rename from kclvm/tools/src/lint/test_data/lint.k rename to crates/tools/src/lint/test_data/lint.k diff --git a/kclvm/tools/src/lint/test_data/unused_check_for_each_file/a.k b/crates/tools/src/lint/test_data/unused_check_for_each_file/a.k similarity index 100% rename from kclvm/tools/src/lint/test_data/unused_check_for_each_file/a.k rename to crates/tools/src/lint/test_data/unused_check_for_each_file/a.k diff --git a/kclvm/tools/src/lint/test_data/unused_check_for_each_file/b.k b/crates/tools/src/lint/test_data/unused_check_for_each_file/b.k similarity index 100% rename from kclvm/tools/src/lint/test_data/unused_check_for_each_file/b.k rename to crates/tools/src/lint/test_data/unused_check_for_each_file/b.k diff --git a/kclvm/tools/src/lint/tests.rs b/crates/tools/src/lint/tests.rs similarity index 100% rename from kclvm/tools/src/lint/tests.rs rename to crates/tools/src/lint/tests.rs diff --git a/crates/tools/src/testing/mod.rs b/crates/tools/src/testing/mod.rs new file mode 100644 index 000000000..313efbbb1 --- /dev/null +++ b/crates/tools/src/testing/mod.rs @@ -0,0 +1,58 @@ +//! [kcl_tools::testing] module mainly contains some functions of language testing tool. +//! +//! The basic principle of the testing tool is to search for test files in the KCL package +//! that have the suffix "_test.k" and do not start with "_". These test files will be regard +//! as test suites. Within these files, any lambda literals starting with "test_" will be +//! considered as test cases, but these lambda functions should not have any parameters. +//! To perform the testing, the tool compiles the test suite file and its dependencies into an +//! [kcl_runner::Artifact], which is regard as a new compilation entry point. Then, +//! it executes each test case separately and collects information about the test cases, +//! such as the execution time and whether the test passes or fails. +pub use crate::testing::suite::{TestSuite, load_test_suites}; +use anyhow::{Error, Result}; +use kcl_primitives::IndexMap; +use kcl_runner::ExecProgramArgs; +use std::time::Duration; + +mod suite; + +#[cfg(test)] +mod tests; + +/// Trait for running tests. +pub trait TestRun { + type Options; + type Result; + + /// Run the test with the given options and return the result. + fn run(&self, opts: &Self::Options) -> Result; +} + +/// Represents the result of a test. +#[derive(Debug, Default)] +pub struct TestResult { + /// This field stores test case information in an [IndexMap], where the key is a [String] and the value is a [TestCaseInfo] struct. + pub info: IndexMap, +} + +/// Represents information about a test case. +#[derive(Debug, Default)] +pub struct TestCaseInfo { + /// This field stores the log message of the test. + pub log_message: String, + /// This field stores the error associated with the test case, if any. + pub error: Option, + /// This field stores the duration of the test case. + pub duration: Duration, +} + +/// Represents options for running tests. +#[derive(Debug, Default, Clone)] +pub struct TestOptions { + /// This field stores the execution program arguments. + pub exec_args: ExecProgramArgs, + /// This field stores a regular expression for filtering tests to run. + pub run_regexp: String, + /// This field determines whether the test run should stop on the first failure. + pub fail_fast: bool, +} diff --git a/kclvm/tools/src/testing/suite.rs b/crates/tools/src/testing/suite.rs similarity index 81% rename from kclvm/tools/src/testing/suite.rs rename to crates/tools/src/testing/suite.rs index 87bfcdca1..f2cba5cd3 100644 --- a/kclvm/tools/src/testing/suite.rs +++ b/crates/tools/src/testing/suite.rs @@ -1,18 +1,14 @@ use std::{fs::remove_file, path::Path}; use crate::testing::{TestCaseInfo, TestOptions, TestResult, TestRun}; -use anyhow::{anyhow, Result}; -use kclvm_ast::ast; -use kclvm_driver::get_pkg_list; -use kclvm_parser::get_kcl_files; -use kclvm_parser::{parse_file_force_errors, ParseSessionRef}; -use kclvm_primitives::{DefaultHashBuilder, IndexMap}; -#[cfg(feature = "llvm")] -use kclvm_runner::build_program; -use kclvm_runner::exec_program; -#[cfg(feature = "llvm")] -use kclvm_runner::runner::ProgramRunner; -use kclvm_runner::{Artifact, ExecProgramArgs, KCL_FAST_EVAL_ENV_VAR}; +use anyhow::{Result, anyhow}; +use kcl_ast::ast; +use kcl_driver::get_pkg_list; +use kcl_parser::get_kcl_files; +use kcl_parser::{ParseSessionRef, parse_file_force_errors}; +use kcl_primitives::{DefaultHashBuilder, IndexMap}; +use kcl_runner::ExecProgramArgs; +use kcl_runner::exec_program; use std::time::Instant; /// File suffix for test files. @@ -62,21 +58,6 @@ impl TestRun for TestSuite { disable_yaml_result: true, ..opts.exec_args.clone() }; - let is_fast_eval_mode = std::env::var(KCL_FAST_EVAL_ENV_VAR).is_ok(); - // Build the program - let artifact: Option = if is_fast_eval_mode { - None - } else { - #[cfg(feature = "llvm")] - let artifact = Some(build_program::( - ParseSessionRef::default(), - &args, - None, - )?); - #[cfg(not(feature = "llvm"))] - let artifact = None; - artifact - }; // Save the user argument options. let user_args = args.args; // Test every case in the suite. @@ -88,16 +69,7 @@ impl TestRun for TestSuite { args.args.append(&mut user_args.clone()); let start = Instant::now(); // Check if is the fast eval mode. - let exec_result = if let Some(_artifact) = &artifact { - #[cfg(feature = "llvm")] - let exec_result = _artifact.run(&args)?; - #[cfg(not(feature = "llvm"))] - let exec_result = exec_program(ParseSessionRef::default(), &args)?; - exec_result - } else { - args.fast_eval = true; - exec_program(ParseSessionRef::default(), &args)? - }; + let exec_result = exec_program(ParseSessionRef::default(), &args)?; // Check if there was an error. let error = if exec_result.err_message.is_empty() { None diff --git a/kclvm/tools/src/testing/test_data/module/kcl.mod b/crates/tools/src/testing/test_data/module/kcl.mod similarity index 100% rename from kclvm/tools/src/testing/test_data/module/kcl.mod rename to crates/tools/src/testing/test_data/module/kcl.mod diff --git a/kclvm/tools/src/testing/test_data/module/pkg/func.k b/crates/tools/src/testing/test_data/module/pkg/func.k similarity index 100% rename from kclvm/tools/src/testing/test_data/module/pkg/func.k rename to crates/tools/src/testing/test_data/module/pkg/func.k diff --git a/kclvm/tools/src/testing/test_data/module/pkg/func_test.k b/crates/tools/src/testing/test_data/module/pkg/func_test.k similarity index 100% rename from kclvm/tools/src/testing/test_data/module/pkg/func_test.k rename to crates/tools/src/testing/test_data/module/pkg/func_test.k diff --git a/crates/tools/src/testing/tests.rs b/crates/tools/src/testing/tests.rs new file mode 100644 index 000000000..0486a054f --- /dev/null +++ b/crates/tools/src/testing/tests.rs @@ -0,0 +1,51 @@ +use kcl_ast::ast::Argument; +use kcl_runner::ExecProgramArgs; + +use crate::testing::TestRun; + +use super::{TestOptions, load_test_suites}; +use std::path::Path; + +#[test] +fn test_load_test_suites_and_run() { + let opts = TestOptions { + exec_args: ExecProgramArgs { + args: vec![Argument { + name: "a".to_string(), + value: "\"a\"".to_string(), + }], + ..Default::default() + }, + ..Default::default() + }; + let suites = load_test_suites( + Path::new(".") + .join("src") + .join("testing") + .join("test_data") + .join("module") + .join("pkg") + .to_str() + .unwrap(), + &opts, + ) + .unwrap(); + assert_eq!(suites.len(), 1); + assert_eq!(suites[0].cases.len(), 3); + let test_result = suites[0].run(&opts).unwrap(); + assert_eq!(test_result.info.len(), 3); + assert!(test_result.info[0].error.is_none()); + assert!( + test_result.info[1] + .error + .as_ref() + .unwrap() + .to_string() + .contains("Error"), + ); + assert!( + test_result.info[2].error.is_none(), + "{:?}", + test_result.info[2].error + ); +} diff --git a/kclvm/tools/src/util/loader.rs b/crates/tools/src/util/loader.rs similarity index 93% rename from kclvm/tools/src/util/loader.rs rename to crates/tools/src/util/loader.rs index a0fc6c6a8..0a7eac608 100644 --- a/kclvm/tools/src/util/loader.rs +++ b/crates/tools/src/util/loader.rs @@ -1,9 +1,9 @@ use std::{fs, path::PathBuf}; -use anyhow::{bail, Context, Result}; -use compiler_base_span::{span::new_byte_pos, BytePos, FilePathMapping, SourceMap}; +use anyhow::{Context, Result, bail}; +use compiler_base_span::{BytePos, FilePathMapping, SourceMap, span::new_byte_pos}; use json_spanned_value::{self as jsv, spanned}; -use kclvm_ast::ast::PosTuple; +use kcl_ast::ast::PosTuple; use located_yaml::YamlLoader; pub(crate) trait Loader { @@ -66,7 +66,7 @@ impl DataLoader { pub fn byte_pos_to_pos_in_sourcemap(&self, lo: BytePos, hi: BytePos) -> PosTuple { let lo = self.sm.lookup_char_pos(lo); let hi = self.sm.lookup_char_pos(hi); - let filename = kclvm_utils::path::convert_windows_drive_letter(&format!( + let filename = kcl_utils::path::convert_windows_drive_letter(&format!( "{}", lo.file.name.prefer_remapped() )); @@ -80,7 +80,7 @@ impl DataLoader { } pub fn file_name(&self) -> String { - kclvm_utils::path::convert_windows_drive_letter(&format!( + kcl_utils::path::convert_windows_drive_letter(&format!( "{}", self.sm .lookup_char_pos(new_byte_pos(0)) diff --git a/kclvm/tools/src/util/mod.rs b/crates/tools/src/util/mod.rs similarity index 100% rename from kclvm/tools/src/util/mod.rs rename to crates/tools/src/util/mod.rs diff --git a/kclvm/tools/src/util/test_datas/test.json b/crates/tools/src/util/test_datas/test.json similarity index 100% rename from kclvm/tools/src/util/test_datas/test.json rename to crates/tools/src/util/test_datas/test.json diff --git a/kclvm/tools/src/util/test_datas/test.yaml b/crates/tools/src/util/test_datas/test.yaml similarity index 100% rename from kclvm/tools/src/util/test_datas/test.yaml rename to crates/tools/src/util/test_datas/test.yaml diff --git a/kclvm/tools/src/util/test_datas/test_invalid.json b/crates/tools/src/util/test_datas/test_invalid.json similarity index 100% rename from kclvm/tools/src/util/test_datas/test_invalid.json rename to crates/tools/src/util/test_datas/test_invalid.json diff --git a/kclvm/tools/src/util/test_datas/test_invalid.yaml b/crates/tools/src/util/test_datas/test_invalid.yaml similarity index 100% rename from kclvm/tools/src/util/test_datas/test_invalid.yaml rename to crates/tools/src/util/test_datas/test_invalid.yaml diff --git a/crates/tools/src/util/tests.rs b/crates/tools/src/util/tests.rs new file mode 100644 index 000000000..b274811ef --- /dev/null +++ b/crates/tools/src/util/tests.rs @@ -0,0 +1,263 @@ +use std::path::PathBuf; + +use anyhow::{Context, Result}; + +const CARGO_DIR: &str = env!("CARGO_MANIFEST_DIR"); +const REL_PATH: &str = "src/util/test_datas"; +const FILE_TEST_CASES: &[&str] = &["test"]; + +const FILE_EXTENSIONS: &[&str] = &[".json", ".yaml"]; + +const JSON_STR_TEST_CASES: &[&str] = &[r#"{ + "name": "John Doe", + "age": 43, + "address": { + "street": "10 Downing Street", + "city": "London" + }, + "phones": [ + "+44 1234567", + "+44 2345678" + ] +} +"#]; + +const YAML_STR_TEST_CASES: &[&str] = &[r#"languages: + - Ruby + - Perl + - Python +websites: + YAML: yaml.org + Ruby: ruby-lang.org + Python: python.org + Perl: use.perl.org +"#]; + +fn construct_full_path(path: &str) -> Result { + let mut cargo_file_path = PathBuf::from(CARGO_DIR); + cargo_file_path.push(REL_PATH); + cargo_file_path.push(path); + Ok(cargo_file_path + .to_str() + .with_context(|| format!("No such file or directory '{}'", path))? + .to_string()) +} + +mod test_loader { + mod test_data_loader { + use regex::Regex; + + use crate::util::{ + loader::{DataLoader, Loader, LoaderKind}, + tests::{ + FILE_EXTENSIONS, FILE_TEST_CASES, JSON_STR_TEST_CASES, YAML_STR_TEST_CASES, + construct_full_path, + }, + }; + + fn data_loader_from_file(loader_kind: LoaderKind, file_path: &str) -> DataLoader { + let test_case_path = construct_full_path(file_path).unwrap(); + + DataLoader::new_with_file_path(loader_kind, &test_case_path).unwrap() + } + + fn data_loader_from_str(loader_kind: LoaderKind, s: &str) -> DataLoader { + DataLoader::new_with_str(loader_kind, s).unwrap() + } + + #[test] + fn test_new_with_file_path_json() { + for test_case in FILE_TEST_CASES { + let json_loader = data_loader_from_file( + LoaderKind::JSON, + &format!("{}{}", test_case, FILE_EXTENSIONS[0]), + ); + + #[cfg(not(target_os = "windows"))] + let got_data = json_loader.get_data(); + #[cfg(target_os = "windows")] + let got_data = json_loader.get_data().replace("\r\n", "\n"); + + assert_eq!( + got_data, + r#"{ + "name": "John Doe", + "age": 43, + "address": { + "street": "10 Downing Street", + "city": "London" + }, + "phones": [ + "+44 1234567", + "+44 2345678" + ] +} +"# + ); + } + } + + #[test] + fn test_new_with_str_json() { + for test_case in JSON_STR_TEST_CASES { + let json_loader = data_loader_from_str(LoaderKind::JSON, test_case); + assert_eq!(json_loader.get_data(), *test_case); + } + } + + #[test] + fn test_new_with_file_path_yaml() { + for test_case in FILE_TEST_CASES { + let yaml_loader = data_loader_from_file( + LoaderKind::YAML, + &format!("{}{}", test_case, FILE_EXTENSIONS[1]), + ); + + #[cfg(not(target_os = "windows"))] + let got_data = yaml_loader.get_data(); + #[cfg(target_os = "windows")] + let got_data = yaml_loader.get_data().replace("\r\n", "\n"); + + assert_eq!( + got_data, + r#"languages: + - Ruby + - Perl + - Python +websites: + YAML: yaml.org + Ruby: ruby-lang.org + Python: python.org + Perl: use.perl.org +"# + ); + } + } + + #[test] + fn test_new_with_str_yaml() { + for test_case in YAML_STR_TEST_CASES { + let yaml_loader = data_loader_from_str(LoaderKind::JSON, test_case); + assert_eq!(yaml_loader.get_data(), *test_case); + } + } + + #[test] + fn test_load() { + let yaml_loader = data_loader_from_file( + LoaderKind::YAML, + &format!("{}{}", FILE_TEST_CASES[0], FILE_EXTENSIONS[1]), + ); + + let got_yaml = + >::load(&yaml_loader).unwrap(); + let expect_yaml: serde_yaml_ng::Value = + serde_yaml_ng::from_str(yaml_loader.get_data()).unwrap(); + + assert_eq!(got_yaml, expect_yaml); + + let json_loader = data_loader_from_file( + LoaderKind::JSON, + &format!("{}{}", FILE_TEST_CASES[0], FILE_EXTENSIONS[0]), + ); + + let got_json = >::load(&json_loader).unwrap(); + let expect_json: serde_json::Value = + serde_json::from_str(json_loader.get_data()).unwrap(); + + assert_eq!(got_json, expect_json); + } + + #[test] + fn test_load_invalid() { + let yaml_loader = data_loader_from_file( + LoaderKind::YAML, + &format!("{}{}", FILE_TEST_CASES[0], FILE_EXTENSIONS[1]), + ); + + match >::load(&yaml_loader) { + Ok(_) => { + panic!("unreachable") + } + Err(err) => { + assert_eq!(format!("{:?}", err), "Failed to String to Json Value"); + } + } + + let json_loader = data_loader_from_file( + LoaderKind::JSON, + &format!("{}{}", FILE_TEST_CASES[0], FILE_EXTENSIONS[0]), + ); + + match >::load(&json_loader) { + Ok(_) => { + panic!("unreachable") + } + Err(err) => { + assert_eq!(format!("{:?}", err), "Failed to String to Yaml Value"); + } + } + } + + #[test] + fn new_with_file_path_invalid() { + match DataLoader::new_with_file_path(LoaderKind::JSON, "invalid file path") { + Ok(_) => { + panic!("unreachable") + } + Err(err) => { + assert!( + Regex::new(r"^Failed to Load 'invalid file path'\n\nCaused by:.*") + .unwrap() + .is_match(&format!("{:?}", err)) + ); + } + }; + } + + #[test] + fn test_invalid_file() { + let invalid_json_file_path = construct_full_path("test_invalid.json").unwrap(); + let json_loader = + DataLoader::new_with_file_path(LoaderKind::JSON, &invalid_json_file_path).unwrap(); + + match >::load(&json_loader) { + Ok(_) => { + panic!("unreachable") + } + Err(err) => { + #[cfg(not(target_os = "windows"))] + let got_err = format!("{:?}", err); + #[cfg(target_os = "windows")] + let got_err = format!("{:?}", err).replace("\r\n", "\n"); + + assert_eq!( + got_err, + "Failed to String 'languages:\n - Ruby\n - Perl\n - Python \nwebsites:\n YAML: yaml.org \n Ruby: ruby-lang.org \n Python: python.org \n Perl: use.perl.org' to Json\n\nCaused by:\n expected value at line 1 column 1" + ); + } + } + + let invalid_yaml_file_path = construct_full_path("test_invalid.yaml").unwrap(); + let yaml_loader = + DataLoader::new_with_file_path(LoaderKind::YAML, &invalid_yaml_file_path).unwrap(); + + match >::load(&yaml_loader) { + Ok(_) => { + panic!("unreachable") + } + Err(err) => { + #[cfg(not(target_os = "windows"))] + let got_err = format!("{:?}", err); + #[cfg(target_os = "windows")] + let got_err = format!("{:?}", err).replace("\r\n", "\n"); + + assert_eq!( + got_err, + "Failed to String '\"name\": \"John Doe\",\ninvalid\n' to Yaml\n\nCaused by:\n did not find expected key at line 1 column 19, while parsing a block mapping" + ); + } + } + } + } +} diff --git a/kclvm/tools/src/vet/expr_builder.rs b/crates/tools/src/vet/expr_builder.rs similarity index 99% rename from kclvm/tools/src/vet/expr_builder.rs rename to crates/tools/src/vet/expr_builder.rs index 020394297..ff4b0d9c1 100644 --- a/kclvm/tools/src/vet/expr_builder.rs +++ b/crates/tools/src/vet/expr_builder.rs @@ -1,5 +1,5 @@ use compiler_base_span::span::new_byte_pos; -use kclvm_ast::{ +use kcl_ast::{ ast::{ ConfigEntry, ConfigEntryOperation, ConfigExpr, Expr, ExprContext, Identifier, ListExpr, NameConstant, NameConstantLit, Node, NodeRef, NumberLit, NumberLitValue, SchemaExpr, @@ -9,7 +9,7 @@ use kclvm_ast::{ use serde_json::json; use crate::util::loader::{DataLoader, Loader, LoaderKind}; -use anyhow::{bail, Context, Result}; +use anyhow::{Context, Result, bail}; const FAIL_LOAD_VALIDATED_ERR_MSG: &str = "Failed to load the validated file"; diff --git a/kclvm/tools/src/vet/mod.rs b/crates/tools/src/vet/mod.rs similarity index 100% rename from kclvm/tools/src/vet/mod.rs rename to crates/tools/src/vet/mod.rs diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-2.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-2.snap new file mode 100644 index 000000000..276260423 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-2.snap @@ -0,0 +1,159 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "/simple.k.json", + "line": 1, + "node": { + "args": [], + "config": { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "/simple.k.json", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "/simple.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 9, + "end_line": 3, + "filename": "/simple.k.json", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"age\"", + "type": "StringLit", + "value": "age" + } + }, + "operation": "Union", + "value": { + "column": 11, + "end_column": 13, + "end_line": 3, + "filename": "/simple.k.json", + "line": 3, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 18 + } + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "/simple.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 13, + "end_line": 4, + "filename": "/simple.k.json", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"message\"", + "type": "StringLit", + "value": "message" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 30, + "end_line": 4, + "filename": "/simple.k.json", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"This is Alice\"", + "type": "StringLit", + "value": "This is Alice" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "/simple.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 2, + "filename": "/simple.k.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"name\"", + "type": "StringLit", + "value": "name" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 19, + "end_line": 2, + "filename": "/simple.k.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"Alice\"", + "type": "StringLit", + "value": "Alice" + } + } + } + } + ], + "type": "Config" + } + }, + "kwargs": [], + "name": { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "/simple.k.json", + "line": 1, + "node": { + "ctx": "Load", + "names": [ + { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "/simple.k.json", + "line": 1, + "node": "simple" + } + ], + "pkgpath": "" + } + }, + "type": "Schema" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-3.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-3.snap new file mode 100644 index 000000000..1a9c6167f --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-3.snap @@ -0,0 +1,19 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 1, + "filename": "/plain_value.k.json", + "line": 1, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 1 + } + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-4.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-4.snap new file mode 100644 index 000000000..c27fe784d --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-4.snap @@ -0,0 +1,172 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 7, + "filename": "/list.k.json", + "line": 1, + "node": { + "ctx": "Load", + "elts": [ + { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "/list.k.json", + "line": 2, + "node": { + "args": [], + "config": { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "/list.k.json", + "line": 2, + "node": { + "items": [ + { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "/list.k.json", + "line": 2, + "node": { + "key": { + "column": 8, + "end_column": 13, + "end_line": 4, + "filename": "/list.k.json", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"age\"", + "type": "StringLit", + "value": "age" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 17, + "end_line": 4, + "filename": "/list.k.json", + "line": 4, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 18 + } + } + } + } + }, + { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "/list.k.json", + "line": 2, + "node": { + "key": { + "column": 8, + "end_column": 17, + "end_line": 5, + "filename": "/list.k.json", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"message\"", + "type": "StringLit", + "value": "message" + } + }, + "operation": "Union", + "value": { + "column": 19, + "end_column": 34, + "end_line": 5, + "filename": "/list.k.json", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"This is Alice\"", + "type": "StringLit", + "value": "This is Alice" + } + } + } + }, + { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "/list.k.json", + "line": 2, + "node": { + "key": { + "column": 8, + "end_column": 14, + "end_line": 3, + "filename": "/list.k.json", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"name\"", + "type": "StringLit", + "value": "name" + } + }, + "operation": "Union", + "value": { + "column": 16, + "end_column": 23, + "end_line": 3, + "filename": "/list.k.json", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"Alice\"", + "type": "StringLit", + "value": "Alice" + } + } + } + } + ], + "type": "Config" + } + }, + "kwargs": [], + "name": { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "/list.k.json", + "line": 2, + "node": { + "ctx": "Load", + "names": [ + { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "/list.k.json", + "line": 2, + "node": "list" + } + ], + "pkgpath": "" + } + }, + "type": "Schema" + } + } + ], + "type": "List" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-5.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-5.snap new file mode 100644 index 000000000..b6c41e2e0 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-5.snap @@ -0,0 +1,420 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "args": [], + "config": { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 9, + "end_line": 3, + "filename": "/complex.k.json", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"age\"", + "type": "StringLit", + "value": "age" + } + }, + "operation": "Union", + "value": { + "column": 11, + "end_column": 13, + "end_line": 3, + "filename": "/complex.k.json", + "line": 3, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 18 + } + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 5, + "filename": "/complex.k.json", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"data\"", + "type": "StringLit", + "value": "data" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 5, + "end_line": 8, + "filename": "/complex.k.json", + "line": 5, + "node": { + "items": [ + { + "column": 12, + "end_column": 5, + "end_line": 8, + "filename": "/complex.k.json", + "line": 5, + "node": { + "key": { + "column": 8, + "end_column": 12, + "end_line": 6, + "filename": "/complex.k.json", + "line": 6, + "node": { + "is_long_string": false, + "raw_value": "\"id\"", + "type": "StringLit", + "value": "id" + } + }, + "operation": "Union", + "value": { + "column": 14, + "end_column": 15, + "end_line": 6, + "filename": "/complex.k.json", + "line": 6, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 1 + } + } + } + } + }, + { + "column": 12, + "end_column": 5, + "end_line": 8, + "filename": "/complex.k.json", + "line": 5, + "node": { + "key": { + "column": 8, + "end_column": 15, + "end_line": 7, + "filename": "/complex.k.json", + "line": 7, + "node": { + "is_long_string": false, + "raw_value": "\"value\"", + "type": "StringLit", + "value": "value" + } + }, + "operation": "Union", + "value": { + "column": 17, + "end_column": 25, + "end_line": 7, + "filename": "/complex.k.json", + "line": 7, + "node": { + "is_long_string": false, + "raw_value": "\"value1\"", + "type": "StringLit", + "value": "value1" + } + } + } + } + ], + "type": "Config" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 8, + "end_line": 12, + "filename": "/complex.k.json", + "line": 12, + "node": { + "is_long_string": false, + "raw_value": "\"hc\"", + "type": "StringLit", + "value": "hc" + } + }, + "operation": "Union", + "value": { + "column": 10, + "end_column": 19, + "end_line": 12, + "filename": "/complex.k.json", + "line": 12, + "node": { + "ctx": "Load", + "elts": [ + { + "column": 11, + "end_column": 12, + "end_line": 12, + "filename": "/complex.k.json", + "line": 12, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 1 + } + } + }, + { + "column": 14, + "end_column": 15, + "end_line": 12, + "filename": "/complex.k.json", + "line": 12, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 2 + } + } + }, + { + "column": 17, + "end_column": 18, + "end_line": 12, + "filename": "/complex.k.json", + "line": 12, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 3 + } + } + } + ], + "type": "List" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 12, + "end_line": 9, + "filename": "/complex.k.json", + "line": 9, + "node": { + "is_long_string": false, + "raw_value": "\"labels\"", + "type": "StringLit", + "value": "labels" + } + }, + "operation": "Union", + "value": { + "column": 14, + "end_column": 5, + "end_line": 11, + "filename": "/complex.k.json", + "line": 9, + "node": { + "items": [ + { + "column": 14, + "end_column": 5, + "end_line": 11, + "filename": "/complex.k.json", + "line": 9, + "node": { + "key": { + "column": 8, + "end_column": 13, + "end_line": 10, + "filename": "/complex.k.json", + "line": 10, + "node": { + "is_long_string": false, + "raw_value": "\"key\"", + "type": "StringLit", + "value": "key" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 22, + "end_line": 10, + "filename": "/complex.k.json", + "line": 10, + "node": { + "is_long_string": false, + "raw_value": "\"value\"", + "type": "StringLit", + "value": "value" + } + } + } + } + ], + "type": "Config" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 13, + "end_line": 4, + "filename": "/complex.k.json", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"message\"", + "type": "StringLit", + "value": "message" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 30, + "end_line": 4, + "filename": "/complex.k.json", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"This is Alice\"", + "type": "StringLit", + "value": "This is Alice" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 2, + "filename": "/complex.k.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"name\"", + "type": "StringLit", + "value": "name" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 19, + "end_line": 2, + "filename": "/complex.k.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"Alice\"", + "type": "StringLit", + "value": "Alice" + } + } + } + } + ], + "type": "Config" + } + }, + "kwargs": [], + "name": { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "ctx": "Load", + "names": [ + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": "complex" + } + ], + "pkgpath": "" + } + }, + "type": "Schema" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-6.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-6.snap new file mode 100644 index 000000000..6f2a8bf5a --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-6.snap @@ -0,0 +1,83 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_null.json", + "line": 1, + "node": { + "args": [], + "config": { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_null.json", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_null.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 16, + "end_line": 2, + "filename": "/only_with_null.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"null_value\"", + "type": "StringLit", + "value": "null_value" + } + }, + "operation": "Union", + "value": { + "column": 18, + "end_column": 22, + "end_line": 2, + "filename": "/only_with_null.json", + "line": 2, + "node": { + "type": "NameConstantLit", + "value": "None" + } + } + } + } + ], + "type": "Config" + } + }, + "kwargs": [], + "name": { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_null.json", + "line": 1, + "node": { + "ctx": "Load", + "names": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_null.json", + "line": 1, + "node": "only_with_null" + } + ], + "pkgpath": "" + } + }, + "type": "Schema" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-7.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-7.snap new file mode 100644 index 000000000..a452af8d1 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-7.snap @@ -0,0 +1,83 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_bool.json", + "line": 1, + "node": { + "args": [], + "config": { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_bool.json", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_bool.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 2, + "filename": "/only_with_bool.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"flag\"", + "type": "StringLit", + "value": "flag" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 16, + "end_line": 2, + "filename": "/only_with_bool.json", + "line": 2, + "node": { + "type": "NameConstantLit", + "value": "True" + } + } + } + } + ], + "type": "Config" + } + }, + "kwargs": [], + "name": { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_bool.json", + "line": 1, + "node": { + "ctx": "Load", + "names": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_bool.json", + "line": 1, + "node": "only_with_bool" + } + ], + "pkgpath": "" + } + }, + "type": "Schema" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-8.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-8.snap new file mode 100644 index 000000000..552fb701a --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath-8.snap @@ -0,0 +1,87 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_float.json", + "line": 1, + "node": { + "args": [], + "config": { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_float.json", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_float.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 17, + "end_line": 2, + "filename": "/only_with_float.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"float_value\"", + "type": "StringLit", + "value": "float_value" + } + }, + "operation": "Union", + "value": { + "column": 19, + "end_column": 23, + "end_line": 2, + "filename": "/only_with_float.json", + "line": 2, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Float", + "value": 0.33 + } + } + } + } + } + ], + "type": "Config" + } + }, + "kwargs": [], + "name": { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_float.json", + "line": 1, + "node": { + "ctx": "Load", + "names": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_float.json", + "line": 1, + "node": "only_with_float" + } + ], + "pkgpath": "" + } + }, + "type": "Schema" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath.snap new file mode 100644 index 000000000..5a64eed61 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_filepath.snap @@ -0,0 +1,292 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "/test.k.json", + "line": 1, + "node": { + "args": [], + "config": { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "/test.k.json", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "/test.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 13, + "end_line": 4, + "filename": "/test.k.json", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"address\"", + "type": "StringLit", + "value": "address" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 5, + "end_line": 7, + "filename": "/test.k.json", + "line": 4, + "node": { + "items": [ + { + "column": 15, + "end_column": 5, + "end_line": 7, + "filename": "/test.k.json", + "line": 4, + "node": { + "key": { + "column": 8, + "end_column": 14, + "end_line": 6, + "filename": "/test.k.json", + "line": 6, + "node": { + "is_long_string": false, + "raw_value": "\"city\"", + "type": "StringLit", + "value": "city" + } + }, + "operation": "Union", + "value": { + "column": 16, + "end_column": 24, + "end_line": 6, + "filename": "/test.k.json", + "line": 6, + "node": { + "is_long_string": false, + "raw_value": "\"London\"", + "type": "StringLit", + "value": "London" + } + } + } + }, + { + "column": 15, + "end_column": 5, + "end_line": 7, + "filename": "/test.k.json", + "line": 4, + "node": { + "key": { + "column": 8, + "end_column": 16, + "end_line": 5, + "filename": "/test.k.json", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"street\"", + "type": "StringLit", + "value": "street" + } + }, + "operation": "Union", + "value": { + "column": 18, + "end_column": 37, + "end_line": 5, + "filename": "/test.k.json", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"10 Downing Street\"", + "type": "StringLit", + "value": "10 Downing Street" + } + } + } + } + ], + "type": "Config" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "/test.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 9, + "end_line": 3, + "filename": "/test.k.json", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"age\"", + "type": "StringLit", + "value": "age" + } + }, + "operation": "Union", + "value": { + "column": 11, + "end_column": 13, + "end_line": 3, + "filename": "/test.k.json", + "line": 3, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 43 + } + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "/test.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 2, + "filename": "/test.k.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"name\"", + "type": "StringLit", + "value": "name" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 22, + "end_line": 2, + "filename": "/test.k.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"John Doe\"", + "type": "StringLit", + "value": "John Doe" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "/test.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 12, + "end_line": 8, + "filename": "/test.k.json", + "line": 8, + "node": { + "is_long_string": false, + "raw_value": "\"phones\"", + "type": "StringLit", + "value": "phones" + } + }, + "operation": "Union", + "value": { + "column": 14, + "end_column": 5, + "end_line": 11, + "filename": "/test.k.json", + "line": 8, + "node": { + "ctx": "Load", + "elts": [ + { + "column": 8, + "end_column": 21, + "end_line": 9, + "filename": "/test.k.json", + "line": 9, + "node": { + "is_long_string": false, + "raw_value": "\"+44 1234567\"", + "type": "StringLit", + "value": "+44 1234567" + } + }, + { + "column": 8, + "end_column": 21, + "end_line": 10, + "filename": "/test.k.json", + "line": 10, + "node": { + "is_long_string": false, + "raw_value": "\"+44 2345678\"", + "type": "StringLit", + "value": "+44 2345678" + } + } + ], + "type": "List" + } + } + } + } + ], + "type": "Config" + } + }, + "kwargs": [], + "name": { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "/test.k.json", + "line": 1, + "node": { + "ctx": "Load", + "names": [ + { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "/test.k.json", + "line": 1, + "node": "test" + } + ], + "pkgpath": "" + } + }, + "type": "Schema" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-2.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-2.snap new file mode 100644 index 000000000..4afb6daca --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-2.snap @@ -0,0 +1,159 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "", + "line": 1, + "node": { + "args": [], + "config": { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 9, + "end_line": 3, + "filename": "", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"age\"", + "type": "StringLit", + "value": "age" + } + }, + "operation": "Union", + "value": { + "column": 11, + "end_column": 13, + "end_line": 3, + "filename": "", + "line": 3, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 18 + } + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 13, + "end_line": 4, + "filename": "", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"message\"", + "type": "StringLit", + "value": "message" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 30, + "end_line": 4, + "filename": "", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"This is Alice\"", + "type": "StringLit", + "value": "This is Alice" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 2, + "filename": "", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"name\"", + "type": "StringLit", + "value": "name" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 19, + "end_line": 2, + "filename": "", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"Alice\"", + "type": "StringLit", + "value": "Alice" + } + } + } + } + ], + "type": "Config" + } + }, + "kwargs": [], + "name": { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "", + "line": 1, + "node": { + "ctx": "Load", + "names": [ + { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "", + "line": 1, + "node": "simple" + } + ], + "pkgpath": "" + } + }, + "type": "Schema" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-3.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-3.snap new file mode 100644 index 000000000..002a817a5 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-3.snap @@ -0,0 +1,19 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 1, + "filename": "", + "line": 1, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 1 + } + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-4.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-4.snap new file mode 100644 index 000000000..e07fb4161 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-4.snap @@ -0,0 +1,172 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 7, + "filename": "", + "line": 1, + "node": { + "ctx": "Load", + "elts": [ + { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "", + "line": 2, + "node": { + "args": [], + "config": { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "", + "line": 2, + "node": { + "items": [ + { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "", + "line": 2, + "node": { + "key": { + "column": 8, + "end_column": 13, + "end_line": 4, + "filename": "", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"age\"", + "type": "StringLit", + "value": "age" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 17, + "end_line": 4, + "filename": "", + "line": 4, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 18 + } + } + } + } + }, + { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "", + "line": 2, + "node": { + "key": { + "column": 8, + "end_column": 17, + "end_line": 5, + "filename": "", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"message\"", + "type": "StringLit", + "value": "message" + } + }, + "operation": "Union", + "value": { + "column": 19, + "end_column": 34, + "end_line": 5, + "filename": "", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"This is Alice\"", + "type": "StringLit", + "value": "This is Alice" + } + } + } + }, + { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "", + "line": 2, + "node": { + "key": { + "column": 8, + "end_column": 14, + "end_line": 3, + "filename": "", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"name\"", + "type": "StringLit", + "value": "name" + } + }, + "operation": "Union", + "value": { + "column": 16, + "end_column": 23, + "end_line": 3, + "filename": "", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"Alice\"", + "type": "StringLit", + "value": "Alice" + } + } + } + } + ], + "type": "Config" + } + }, + "kwargs": [], + "name": { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "", + "line": 2, + "node": { + "ctx": "Load", + "names": [ + { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "", + "line": 2, + "node": "list" + } + ], + "pkgpath": "" + } + }, + "type": "Schema" + } + } + ], + "type": "List" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-5.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-5.snap new file mode 100644 index 000000000..ee96408ea --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-5.snap @@ -0,0 +1,420 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "", + "line": 1, + "node": { + "args": [], + "config": { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 9, + "end_line": 3, + "filename": "", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"age\"", + "type": "StringLit", + "value": "age" + } + }, + "operation": "Union", + "value": { + "column": 11, + "end_column": 13, + "end_line": 3, + "filename": "", + "line": 3, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 18 + } + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 5, + "filename": "", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"data\"", + "type": "StringLit", + "value": "data" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 5, + "end_line": 8, + "filename": "", + "line": 5, + "node": { + "items": [ + { + "column": 12, + "end_column": 5, + "end_line": 8, + "filename": "", + "line": 5, + "node": { + "key": { + "column": 8, + "end_column": 12, + "end_line": 6, + "filename": "", + "line": 6, + "node": { + "is_long_string": false, + "raw_value": "\"id\"", + "type": "StringLit", + "value": "id" + } + }, + "operation": "Union", + "value": { + "column": 14, + "end_column": 15, + "end_line": 6, + "filename": "", + "line": 6, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 1 + } + } + } + } + }, + { + "column": 12, + "end_column": 5, + "end_line": 8, + "filename": "", + "line": 5, + "node": { + "key": { + "column": 8, + "end_column": 15, + "end_line": 7, + "filename": "", + "line": 7, + "node": { + "is_long_string": false, + "raw_value": "\"value\"", + "type": "StringLit", + "value": "value" + } + }, + "operation": "Union", + "value": { + "column": 17, + "end_column": 25, + "end_line": 7, + "filename": "", + "line": 7, + "node": { + "is_long_string": false, + "raw_value": "\"value1\"", + "type": "StringLit", + "value": "value1" + } + } + } + } + ], + "type": "Config" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 8, + "end_line": 12, + "filename": "", + "line": 12, + "node": { + "is_long_string": false, + "raw_value": "\"hc\"", + "type": "StringLit", + "value": "hc" + } + }, + "operation": "Union", + "value": { + "column": 10, + "end_column": 19, + "end_line": 12, + "filename": "", + "line": 12, + "node": { + "ctx": "Load", + "elts": [ + { + "column": 11, + "end_column": 12, + "end_line": 12, + "filename": "", + "line": 12, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 1 + } + } + }, + { + "column": 14, + "end_column": 15, + "end_line": 12, + "filename": "", + "line": 12, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 2 + } + } + }, + { + "column": 17, + "end_column": 18, + "end_line": 12, + "filename": "", + "line": 12, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 3 + } + } + } + ], + "type": "List" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 12, + "end_line": 9, + "filename": "", + "line": 9, + "node": { + "is_long_string": false, + "raw_value": "\"labels\"", + "type": "StringLit", + "value": "labels" + } + }, + "operation": "Union", + "value": { + "column": 14, + "end_column": 5, + "end_line": 11, + "filename": "", + "line": 9, + "node": { + "items": [ + { + "column": 14, + "end_column": 5, + "end_line": 11, + "filename": "", + "line": 9, + "node": { + "key": { + "column": 8, + "end_column": 13, + "end_line": 10, + "filename": "", + "line": 10, + "node": { + "is_long_string": false, + "raw_value": "\"key\"", + "type": "StringLit", + "value": "key" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 22, + "end_line": 10, + "filename": "", + "line": 10, + "node": { + "is_long_string": false, + "raw_value": "\"value\"", + "type": "StringLit", + "value": "value" + } + } + } + } + ], + "type": "Config" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 13, + "end_line": 4, + "filename": "", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"message\"", + "type": "StringLit", + "value": "message" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 30, + "end_line": 4, + "filename": "", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"This is Alice\"", + "type": "StringLit", + "value": "This is Alice" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 2, + "filename": "", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"name\"", + "type": "StringLit", + "value": "name" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 19, + "end_line": 2, + "filename": "", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"Alice\"", + "type": "StringLit", + "value": "Alice" + } + } + } + } + ], + "type": "Config" + } + }, + "kwargs": [], + "name": { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "", + "line": 1, + "node": { + "ctx": "Load", + "names": [ + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "", + "line": 1, + "node": "complex" + } + ], + "pkgpath": "" + } + }, + "type": "Schema" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-6.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-6.snap new file mode 100644 index 000000000..7cc395311 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-6.snap @@ -0,0 +1,83 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": { + "args": [], + "config": { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 16, + "end_line": 2, + "filename": "", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"null_value\"", + "type": "StringLit", + "value": "null_value" + } + }, + "operation": "Union", + "value": { + "column": 18, + "end_column": 22, + "end_line": 2, + "filename": "", + "line": 2, + "node": { + "type": "NameConstantLit", + "value": "None" + } + } + } + } + ], + "type": "Config" + } + }, + "kwargs": [], + "name": { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": { + "ctx": "Load", + "names": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": "only_with_null" + } + ], + "pkgpath": "" + } + }, + "type": "Schema" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-7.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-7.snap new file mode 100644 index 000000000..87a5db0a0 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-7.snap @@ -0,0 +1,83 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": { + "args": [], + "config": { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 2, + "filename": "", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"flag\"", + "type": "StringLit", + "value": "flag" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 16, + "end_line": 2, + "filename": "", + "line": 2, + "node": { + "type": "NameConstantLit", + "value": "True" + } + } + } + } + ], + "type": "Config" + } + }, + "kwargs": [], + "name": { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": { + "ctx": "Load", + "names": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": "only_with_bool" + } + ], + "pkgpath": "" + } + }, + "type": "Schema" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-8.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-8.snap new file mode 100644 index 000000000..b0663955c --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str-8.snap @@ -0,0 +1,87 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": { + "args": [], + "config": { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 17, + "end_line": 2, + "filename": "", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"float_value\"", + "type": "StringLit", + "value": "float_value" + } + }, + "operation": "Union", + "value": { + "column": 19, + "end_column": 23, + "end_line": 2, + "filename": "", + "line": 2, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Float", + "value": 0.33 + } + } + } + } + } + ], + "type": "Config" + } + }, + "kwargs": [], + "name": { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": { + "ctx": "Load", + "names": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "", + "line": 1, + "node": "only_with_float" + } + ], + "pkgpath": "" + } + }, + "type": "Schema" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str.snap new file mode 100644 index 000000000..ad82e2a72 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_json_with_str.snap @@ -0,0 +1,292 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "", + "line": 1, + "node": { + "args": [], + "config": { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 13, + "end_line": 4, + "filename": "", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"address\"", + "type": "StringLit", + "value": "address" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 5, + "end_line": 7, + "filename": "", + "line": 4, + "node": { + "items": [ + { + "column": 15, + "end_column": 5, + "end_line": 7, + "filename": "", + "line": 4, + "node": { + "key": { + "column": 8, + "end_column": 14, + "end_line": 6, + "filename": "", + "line": 6, + "node": { + "is_long_string": false, + "raw_value": "\"city\"", + "type": "StringLit", + "value": "city" + } + }, + "operation": "Union", + "value": { + "column": 16, + "end_column": 24, + "end_line": 6, + "filename": "", + "line": 6, + "node": { + "is_long_string": false, + "raw_value": "\"London\"", + "type": "StringLit", + "value": "London" + } + } + } + }, + { + "column": 15, + "end_column": 5, + "end_line": 7, + "filename": "", + "line": 4, + "node": { + "key": { + "column": 8, + "end_column": 16, + "end_line": 5, + "filename": "", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"street\"", + "type": "StringLit", + "value": "street" + } + }, + "operation": "Union", + "value": { + "column": 18, + "end_column": 37, + "end_line": 5, + "filename": "", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"10 Downing Street\"", + "type": "StringLit", + "value": "10 Downing Street" + } + } + } + } + ], + "type": "Config" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 9, + "end_line": 3, + "filename": "", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"age\"", + "type": "StringLit", + "value": "age" + } + }, + "operation": "Union", + "value": { + "column": 11, + "end_column": 13, + "end_line": 3, + "filename": "", + "line": 3, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 43 + } + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 2, + "filename": "", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"name\"", + "type": "StringLit", + "value": "name" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 22, + "end_line": 2, + "filename": "", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"John Doe\"", + "type": "StringLit", + "value": "John Doe" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 12, + "end_line": 8, + "filename": "", + "line": 8, + "node": { + "is_long_string": false, + "raw_value": "\"phones\"", + "type": "StringLit", + "value": "phones" + } + }, + "operation": "Union", + "value": { + "column": 14, + "end_column": 5, + "end_line": 11, + "filename": "", + "line": 8, + "node": { + "ctx": "Load", + "elts": [ + { + "column": 8, + "end_column": 21, + "end_line": 9, + "filename": "", + "line": 9, + "node": { + "is_long_string": false, + "raw_value": "\"+44 1234567\"", + "type": "StringLit", + "value": "+44 1234567" + } + }, + { + "column": 8, + "end_column": 21, + "end_line": 10, + "filename": "", + "line": 10, + "node": { + "is_long_string": false, + "raw_value": "\"+44 2345678\"", + "type": "StringLit", + "value": "+44 2345678" + } + } + ], + "type": "List" + } + } + } + } + ], + "type": "Config" + } + }, + "kwargs": [], + "name": { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "", + "line": 1, + "node": { + "ctx": "Load", + "names": [ + { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "", + "line": 1, + "node": "test" + } + ], + "pkgpath": "" + } + }, + "type": "Schema" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-2.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-2.snap new file mode 100644 index 000000000..af912f504 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-2.snap @@ -0,0 +1,126 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "/simple.k.json", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "/simple.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 9, + "end_line": 3, + "filename": "/simple.k.json", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"age\"", + "type": "StringLit", + "value": "age" + } + }, + "operation": "Union", + "value": { + "column": 11, + "end_column": 13, + "end_line": 3, + "filename": "/simple.k.json", + "line": 3, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 18 + } + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "/simple.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 13, + "end_line": 4, + "filename": "/simple.k.json", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"message\"", + "type": "StringLit", + "value": "message" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 30, + "end_line": 4, + "filename": "/simple.k.json", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"This is Alice\"", + "type": "StringLit", + "value": "This is Alice" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 5, + "filename": "/simple.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 2, + "filename": "/simple.k.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"name\"", + "type": "StringLit", + "value": "name" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 19, + "end_line": 2, + "filename": "/simple.k.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"Alice\"", + "type": "StringLit", + "value": "Alice" + } + } + } + } + ], + "type": "Config" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-3.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-3.snap new file mode 100644 index 000000000..1a9c6167f --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-3.snap @@ -0,0 +1,19 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 1, + "filename": "/plain_value.k.json", + "line": 1, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 1 + } + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-4.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-4.snap new file mode 100644 index 000000000..9a726a513 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-4.snap @@ -0,0 +1,139 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 7, + "filename": "/list.k.json", + "line": 1, + "node": { + "ctx": "Load", + "elts": [ + { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "/list.k.json", + "line": 2, + "node": { + "items": [ + { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "/list.k.json", + "line": 2, + "node": { + "key": { + "column": 8, + "end_column": 13, + "end_line": 4, + "filename": "/list.k.json", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"age\"", + "type": "StringLit", + "value": "age" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 17, + "end_line": 4, + "filename": "/list.k.json", + "line": 4, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 18 + } + } + } + } + }, + { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "/list.k.json", + "line": 2, + "node": { + "key": { + "column": 8, + "end_column": 17, + "end_line": 5, + "filename": "/list.k.json", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"message\"", + "type": "StringLit", + "value": "message" + } + }, + "operation": "Union", + "value": { + "column": 19, + "end_column": 34, + "end_line": 5, + "filename": "/list.k.json", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"This is Alice\"", + "type": "StringLit", + "value": "This is Alice" + } + } + } + }, + { + "column": 4, + "end_column": 5, + "end_line": 6, + "filename": "/list.k.json", + "line": 2, + "node": { + "key": { + "column": 8, + "end_column": 14, + "end_line": 3, + "filename": "/list.k.json", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"name\"", + "type": "StringLit", + "value": "name" + } + }, + "operation": "Union", + "value": { + "column": 16, + "end_column": 23, + "end_line": 3, + "filename": "/list.k.json", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"Alice\"", + "type": "StringLit", + "value": "Alice" + } + } + } + } + ], + "type": "Config" + } + } + ], + "type": "List" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-5.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-5.snap new file mode 100644 index 000000000..dd655f06b --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-5.snap @@ -0,0 +1,387 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 9, + "end_line": 3, + "filename": "/complex.k.json", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"age\"", + "type": "StringLit", + "value": "age" + } + }, + "operation": "Union", + "value": { + "column": 11, + "end_column": 13, + "end_line": 3, + "filename": "/complex.k.json", + "line": 3, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 18 + } + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 5, + "filename": "/complex.k.json", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"data\"", + "type": "StringLit", + "value": "data" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 5, + "end_line": 8, + "filename": "/complex.k.json", + "line": 5, + "node": { + "items": [ + { + "column": 12, + "end_column": 5, + "end_line": 8, + "filename": "/complex.k.json", + "line": 5, + "node": { + "key": { + "column": 8, + "end_column": 12, + "end_line": 6, + "filename": "/complex.k.json", + "line": 6, + "node": { + "is_long_string": false, + "raw_value": "\"id\"", + "type": "StringLit", + "value": "id" + } + }, + "operation": "Union", + "value": { + "column": 14, + "end_column": 15, + "end_line": 6, + "filename": "/complex.k.json", + "line": 6, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 1 + } + } + } + } + }, + { + "column": 12, + "end_column": 5, + "end_line": 8, + "filename": "/complex.k.json", + "line": 5, + "node": { + "key": { + "column": 8, + "end_column": 15, + "end_line": 7, + "filename": "/complex.k.json", + "line": 7, + "node": { + "is_long_string": false, + "raw_value": "\"value\"", + "type": "StringLit", + "value": "value" + } + }, + "operation": "Union", + "value": { + "column": 17, + "end_column": 25, + "end_line": 7, + "filename": "/complex.k.json", + "line": 7, + "node": { + "is_long_string": false, + "raw_value": "\"value1\"", + "type": "StringLit", + "value": "value1" + } + } + } + } + ], + "type": "Config" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 8, + "end_line": 12, + "filename": "/complex.k.json", + "line": 12, + "node": { + "is_long_string": false, + "raw_value": "\"hc\"", + "type": "StringLit", + "value": "hc" + } + }, + "operation": "Union", + "value": { + "column": 10, + "end_column": 19, + "end_line": 12, + "filename": "/complex.k.json", + "line": 12, + "node": { + "ctx": "Load", + "elts": [ + { + "column": 11, + "end_column": 12, + "end_line": 12, + "filename": "/complex.k.json", + "line": 12, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 1 + } + } + }, + { + "column": 14, + "end_column": 15, + "end_line": 12, + "filename": "/complex.k.json", + "line": 12, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 2 + } + } + }, + { + "column": 17, + "end_column": 18, + "end_line": 12, + "filename": "/complex.k.json", + "line": 12, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 3 + } + } + } + ], + "type": "List" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 12, + "end_line": 9, + "filename": "/complex.k.json", + "line": 9, + "node": { + "is_long_string": false, + "raw_value": "\"labels\"", + "type": "StringLit", + "value": "labels" + } + }, + "operation": "Union", + "value": { + "column": 14, + "end_column": 5, + "end_line": 11, + "filename": "/complex.k.json", + "line": 9, + "node": { + "items": [ + { + "column": 14, + "end_column": 5, + "end_line": 11, + "filename": "/complex.k.json", + "line": 9, + "node": { + "key": { + "column": 8, + "end_column": 13, + "end_line": 10, + "filename": "/complex.k.json", + "line": 10, + "node": { + "is_long_string": false, + "raw_value": "\"key\"", + "type": "StringLit", + "value": "key" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 22, + "end_line": 10, + "filename": "/complex.k.json", + "line": 10, + "node": { + "is_long_string": false, + "raw_value": "\"value\"", + "type": "StringLit", + "value": "value" + } + } + } + } + ], + "type": "Config" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 13, + "end_line": 4, + "filename": "/complex.k.json", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"message\"", + "type": "StringLit", + "value": "message" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 30, + "end_line": 4, + "filename": "/complex.k.json", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"This is Alice\"", + "type": "StringLit", + "value": "This is Alice" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 13, + "filename": "/complex.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 2, + "filename": "/complex.k.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"name\"", + "type": "StringLit", + "value": "name" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 19, + "end_line": 2, + "filename": "/complex.k.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"Alice\"", + "type": "StringLit", + "value": "Alice" + } + } + } + } + ], + "type": "Config" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-6.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-6.snap new file mode 100644 index 000000000..b792a40c3 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-6.snap @@ -0,0 +1,50 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_null.json", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_null.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 16, + "end_line": 2, + "filename": "/only_with_null.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"null_value\"", + "type": "StringLit", + "value": "null_value" + } + }, + "operation": "Union", + "value": { + "column": 18, + "end_column": 22, + "end_line": 2, + "filename": "/only_with_null.json", + "line": 2, + "node": { + "type": "NameConstantLit", + "value": "None" + } + } + } + } + ], + "type": "Config" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-7.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-7.snap new file mode 100644 index 000000000..00e93e237 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-7.snap @@ -0,0 +1,50 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_bool.json", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_bool.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 2, + "filename": "/only_with_bool.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"flag\"", + "type": "StringLit", + "value": "flag" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 16, + "end_line": 2, + "filename": "/only_with_bool.json", + "line": 2, + "node": { + "type": "NameConstantLit", + "value": "True" + } + } + } + } + ], + "type": "Config" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-8.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-8.snap new file mode 100644 index 000000000..099a3bc6b --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-8.snap @@ -0,0 +1,54 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_float.json", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 3, + "filename": "/only_with_float.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 17, + "end_line": 2, + "filename": "/only_with_float.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"float_value\"", + "type": "StringLit", + "value": "float_value" + } + }, + "operation": "Union", + "value": { + "column": 19, + "end_column": 23, + "end_line": 2, + "filename": "/only_with_float.json", + "line": 2, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Float", + "value": 0.33 + } + } + } + } + } + ], + "type": "Config" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name.snap new file mode 100644 index 000000000..d4eaf4dda --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name.snap @@ -0,0 +1,259 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_json_str +--- +{ + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "/test.k.json", + "line": 1, + "node": { + "items": [ + { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "/test.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 13, + "end_line": 4, + "filename": "/test.k.json", + "line": 4, + "node": { + "is_long_string": false, + "raw_value": "\"address\"", + "type": "StringLit", + "value": "address" + } + }, + "operation": "Union", + "value": { + "column": 15, + "end_column": 5, + "end_line": 7, + "filename": "/test.k.json", + "line": 4, + "node": { + "items": [ + { + "column": 15, + "end_column": 5, + "end_line": 7, + "filename": "/test.k.json", + "line": 4, + "node": { + "key": { + "column": 8, + "end_column": 14, + "end_line": 6, + "filename": "/test.k.json", + "line": 6, + "node": { + "is_long_string": false, + "raw_value": "\"city\"", + "type": "StringLit", + "value": "city" + } + }, + "operation": "Union", + "value": { + "column": 16, + "end_column": 24, + "end_line": 6, + "filename": "/test.k.json", + "line": 6, + "node": { + "is_long_string": false, + "raw_value": "\"London\"", + "type": "StringLit", + "value": "London" + } + } + } + }, + { + "column": 15, + "end_column": 5, + "end_line": 7, + "filename": "/test.k.json", + "line": 4, + "node": { + "key": { + "column": 8, + "end_column": 16, + "end_line": 5, + "filename": "/test.k.json", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"street\"", + "type": "StringLit", + "value": "street" + } + }, + "operation": "Union", + "value": { + "column": 18, + "end_column": 37, + "end_line": 5, + "filename": "/test.k.json", + "line": 5, + "node": { + "is_long_string": false, + "raw_value": "\"10 Downing Street\"", + "type": "StringLit", + "value": "10 Downing Street" + } + } + } + } + ], + "type": "Config" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "/test.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 9, + "end_line": 3, + "filename": "/test.k.json", + "line": 3, + "node": { + "is_long_string": false, + "raw_value": "\"age\"", + "type": "StringLit", + "value": "age" + } + }, + "operation": "Union", + "value": { + "column": 11, + "end_column": 13, + "end_line": 3, + "filename": "/test.k.json", + "line": 3, + "node": { + "binary_suffix": null, + "type": "NumberLit", + "value": { + "type": "Int", + "value": 43 + } + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "/test.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 10, + "end_line": 2, + "filename": "/test.k.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"name\"", + "type": "StringLit", + "value": "name" + } + }, + "operation": "Union", + "value": { + "column": 12, + "end_column": 22, + "end_line": 2, + "filename": "/test.k.json", + "line": 2, + "node": { + "is_long_string": false, + "raw_value": "\"John Doe\"", + "type": "StringLit", + "value": "John Doe" + } + } + } + }, + { + "column": 0, + "end_column": 1, + "end_line": 12, + "filename": "/test.k.json", + "line": 1, + "node": { + "key": { + "column": 4, + "end_column": 12, + "end_line": 8, + "filename": "/test.k.json", + "line": 8, + "node": { + "is_long_string": false, + "raw_value": "\"phones\"", + "type": "StringLit", + "value": "phones" + } + }, + "operation": "Union", + "value": { + "column": 14, + "end_column": 5, + "end_line": 11, + "filename": "/test.k.json", + "line": 8, + "node": { + "ctx": "Load", + "elts": [ + { + "column": 8, + "end_column": 21, + "end_line": 9, + "filename": "/test.k.json", + "line": 9, + "node": { + "is_long_string": false, + "raw_value": "\"+44 1234567\"", + "type": "StringLit", + "value": "+44 1234567" + } + }, + { + "column": 8, + "end_column": 21, + "end_line": 10, + "filename": "/test.k.json", + "line": 10, + "node": { + "is_long_string": false, + "raw_value": "\"+44 2345678\"", + "type": "StringLit", + "value": "+44 2345678" + } + } + ], + "type": "List" + } + } + } + } + ], + "type": "Config" + } +} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-2.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-2.snap new file mode 100644 index 000000000..1299e4510 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-2.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"name\"","value":"name"},"filename":"/simple.k.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Alice,\"","value":"Alice,"},"filename":"/simple.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"age\"","value":"age"},"filename":"/simple.k.yaml","line":2,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"18,\"","value":"18,"},"filename":"/simple.k.yaml","line":2,"column":5,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"message\"","value":"message"},"filename":"/simple.k.yaml","line":3,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"This is Alice\"","value":"This is Alice"},"filename":"/simple.k.yaml","line":3,"column":9,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}]},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-3.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-3.snap new file mode 100644 index 000000000..3e65e93b2 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-3.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":1}},"filename":"/plain_value.k.yaml","line":1,"column":0,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-4.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-4.snap new file mode 100644 index 000000000..08c0b77ea --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-4.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"List","elts":[{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"name\"","value":"name"},"filename":"/list.k.yaml","line":1,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Alice\"","value":"Alice"},"filename":"/list.k.yaml","line":1,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"age\"","value":"age"},"filename":"/list.k.yaml","line":2,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":18}},"filename":"/list.k.yaml","line":2,"column":7,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"message\"","value":"message"},"filename":"/list.k.yaml","line":3,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"This is Alice\"","value":"This is Alice"},"filename":"/list.k.yaml","line":3,"column":11,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0}]},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0}],"ctx":"Load"},"filename":"/list.k.yaml","line":1,"column":0,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-5.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-5.snap new file mode 100644 index 000000000..ad635d7ab --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-5.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"name\"","value":"name"},"filename":"/complex.k.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Alice\"","value":"Alice"},"filename":"/complex.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"age\"","value":"age"},"filename":"/complex.k.yaml","line":2,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":18}},"filename":"/complex.k.yaml","line":2,"column":5,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"message\"","value":"message"},"filename":"/complex.k.yaml","line":3,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"This is Alice\"","value":"This is Alice"},"filename":"/complex.k.yaml","line":3,"column":9,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"data\"","value":"data"},"filename":"/complex.k.yaml","line":4,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"id\"","value":"id"},"filename":"/complex.k.yaml","line":5,"column":4,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":1}},"filename":"/complex.k.yaml","line":5,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":5,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"value\"","value":"value"},"filename":"/complex.k.yaml","line":6,"column":4,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"value1\"","value":"value1"},"filename":"/complex.k.yaml","line":6,"column":11,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":5,"column":6,"end_line":0,"end_column":0}]},"filename":"/complex.k.yaml","line":5,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"labels\"","value":"labels"},"filename":"/complex.k.yaml","line":7,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"key\"","value":"key"},"filename":"/complex.k.yaml","line":8,"column":4,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"value\"","value":"value"},"filename":"/complex.k.yaml","line":8,"column":9,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":8,"column":7,"end_line":0,"end_column":0}]},"filename":"/complex.k.yaml","line":8,"column":7,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"hc\"","value":"hc"},"filename":"/complex.k.yaml","line":9,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"List","elts":[{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":1}},"filename":"/complex.k.yaml","line":10,"column":6,"end_line":0,"end_column":0},{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":2}},"filename":"/complex.k.yaml","line":11,"column":6,"end_line":0,"end_column":0},{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":3}},"filename":"/complex.k.yaml","line":12,"column":6,"end_line":0,"end_column":0}],"ctx":"Load"},"filename":"/complex.k.yaml","line":10,"column":4,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}]},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-6.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-6.snap new file mode 100644 index 000000000..d6231cc6e --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-6.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"null_val\"","value":"null_val"},"filename":"/only_with_null.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NameConstantLit","value":"None"},"filename":"/only_with_null.yaml","line":1,"column":10,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/only_with_null.yaml","line":1,"column":8,"end_line":0,"end_column":0}]},"filename":"/only_with_null.yaml","line":1,"column":8,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-7.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-7.snap new file mode 100644 index 000000000..2fd867f08 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-7.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"bool_val\"","value":"bool_val"},"filename":"/only_with_bool.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NameConstantLit","value":"True"},"filename":"/only_with_bool.yaml","line":1,"column":10,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/only_with_bool.yaml","line":1,"column":8,"end_line":0,"end_column":0}]},"filename":"/only_with_bool.yaml","line":1,"column":8,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-8.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-8.snap new file mode 100644 index 000000000..44d949e57 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-8.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"float_val\"","value":"float_val"},"filename":"/only_with_float.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Float","value":0.33}},"filename":"/only_with_float.yaml","line":1,"column":11,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/only_with_float.yaml","line":1,"column":9,"end_line":0,"end_column":0}]},"filename":"/only_with_float.yaml","line":1,"column":9,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name.snap new file mode 100644 index 000000000..79feaa6ca --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"languages\"","value":"languages"},"filename":"/test.k.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"List","elts":[{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Ruby\"","value":"Ruby"},"filename":"/test.k.yaml","line":2,"column":4,"end_line":0,"end_column":0},{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Perl\"","value":"Perl"},"filename":"/test.k.yaml","line":3,"column":4,"end_line":0,"end_column":0},{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Python\"","value":"Python"},"filename":"/test.k.yaml","line":4,"column":4,"end_line":0,"end_column":0}],"ctx":"Load"},"filename":"/test.k.yaml","line":2,"column":2,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"websites\"","value":"websites"},"filename":"/test.k.yaml","line":5,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"YAML\"","value":"YAML"},"filename":"/test.k.yaml","line":6,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"yaml.org\"","value":"yaml.org"},"filename":"/test.k.yaml","line":6,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Ruby\"","value":"Ruby"},"filename":"/test.k.yaml","line":7,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"ruby-lang.org\"","value":"ruby-lang.org"},"filename":"/test.k.yaml","line":7,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Python\"","value":"Python"},"filename":"/test.k.yaml","line":8,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"python.org\"","value":"python.org"},"filename":"/test.k.yaml","line":8,"column":10,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Perl\"","value":"Perl"},"filename":"/test.k.yaml","line":9,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"use.perl.org\"","value":"use.perl.org"},"filename":"/test.k.yaml","line":9,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0}]},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0}]},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-2.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-2.snap new file mode 100644 index 000000000..5970fb67c --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-2.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"Schema","name":{"node":{"names":[{"node":"simple","filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}],"pkgpath":"","ctx":"Load"},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},"args":[],"kwargs":[],"config":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"name\"","value":"name"},"filename":"/simple.k.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Alice,\"","value":"Alice,"},"filename":"/simple.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"age\"","value":"age"},"filename":"/simple.k.yaml","line":2,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"18,\"","value":"18,"},"filename":"/simple.k.yaml","line":2,"column":5,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"message\"","value":"message"},"filename":"/simple.k.yaml","line":3,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"This is Alice\"","value":"This is Alice"},"filename":"/simple.k.yaml","line":3,"column":9,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}]},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-3.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-3.snap new file mode 100644 index 000000000..3e65e93b2 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-3.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":1}},"filename":"/plain_value.k.yaml","line":1,"column":0,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-4.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-4.snap new file mode 100644 index 000000000..d3437377a --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-4.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"List","elts":[{"node":{"type":"Schema","name":{"node":{"names":[{"node":"list","filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0}],"pkgpath":"","ctx":"Load"},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},"args":[],"kwargs":[],"config":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"name\"","value":"name"},"filename":"/list.k.yaml","line":1,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Alice\"","value":"Alice"},"filename":"/list.k.yaml","line":1,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"age\"","value":"age"},"filename":"/list.k.yaml","line":2,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":18}},"filename":"/list.k.yaml","line":2,"column":7,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"message\"","value":"message"},"filename":"/list.k.yaml","line":3,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"This is Alice\"","value":"This is Alice"},"filename":"/list.k.yaml","line":3,"column":11,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0}]},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0}},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0}],"ctx":"Load"},"filename":"/list.k.yaml","line":1,"column":0,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-5.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-5.snap new file mode 100644 index 000000000..62538b643 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-5.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"Schema","name":{"node":{"names":[{"node":"complex","filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}],"pkgpath":"","ctx":"Load"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},"args":[],"kwargs":[],"config":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"name\"","value":"name"},"filename":"/complex.k.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Alice\"","value":"Alice"},"filename":"/complex.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"age\"","value":"age"},"filename":"/complex.k.yaml","line":2,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":18}},"filename":"/complex.k.yaml","line":2,"column":5,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"message\"","value":"message"},"filename":"/complex.k.yaml","line":3,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"This is Alice\"","value":"This is Alice"},"filename":"/complex.k.yaml","line":3,"column":9,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"data\"","value":"data"},"filename":"/complex.k.yaml","line":4,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"id\"","value":"id"},"filename":"/complex.k.yaml","line":5,"column":4,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":1}},"filename":"/complex.k.yaml","line":5,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":5,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"value\"","value":"value"},"filename":"/complex.k.yaml","line":6,"column":4,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"value1\"","value":"value1"},"filename":"/complex.k.yaml","line":6,"column":11,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":5,"column":6,"end_line":0,"end_column":0}]},"filename":"/complex.k.yaml","line":5,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"labels\"","value":"labels"},"filename":"/complex.k.yaml","line":7,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"key\"","value":"key"},"filename":"/complex.k.yaml","line":8,"column":4,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"value\"","value":"value"},"filename":"/complex.k.yaml","line":8,"column":9,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":8,"column":7,"end_line":0,"end_column":0}]},"filename":"/complex.k.yaml","line":8,"column":7,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"hc\"","value":"hc"},"filename":"/complex.k.yaml","line":9,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"List","elts":[{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":1}},"filename":"/complex.k.yaml","line":10,"column":6,"end_line":0,"end_column":0},{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":2}},"filename":"/complex.k.yaml","line":11,"column":6,"end_line":0,"end_column":0},{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":3}},"filename":"/complex.k.yaml","line":12,"column":6,"end_line":0,"end_column":0}],"ctx":"Load"},"filename":"/complex.k.yaml","line":10,"column":4,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}]},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-6.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-6.snap new file mode 100644 index 000000000..198e4c02d --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-6.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"Schema","name":{"node":{"names":[{"node":"only_with_null","filename":"/only_with_null.yaml","line":1,"column":8,"end_line":0,"end_column":0}],"pkgpath":"","ctx":"Load"},"filename":"/only_with_null.yaml","line":1,"column":8,"end_line":0,"end_column":0},"args":[],"kwargs":[],"config":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"null_val\"","value":"null_val"},"filename":"/only_with_null.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NameConstantLit","value":"None"},"filename":"/only_with_null.yaml","line":1,"column":10,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/only_with_null.yaml","line":1,"column":8,"end_line":0,"end_column":0}]},"filename":"/only_with_null.yaml","line":1,"column":8,"end_line":0,"end_column":0}},"filename":"/only_with_null.yaml","line":1,"column":8,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-7.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-7.snap new file mode 100644 index 000000000..00f47666c --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-7.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"Schema","name":{"node":{"names":[{"node":"only_with_bool","filename":"/only_with_bool.yaml","line":1,"column":8,"end_line":0,"end_column":0}],"pkgpath":"","ctx":"Load"},"filename":"/only_with_bool.yaml","line":1,"column":8,"end_line":0,"end_column":0},"args":[],"kwargs":[],"config":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"bool_val\"","value":"bool_val"},"filename":"/only_with_bool.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NameConstantLit","value":"True"},"filename":"/only_with_bool.yaml","line":1,"column":10,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/only_with_bool.yaml","line":1,"column":8,"end_line":0,"end_column":0}]},"filename":"/only_with_bool.yaml","line":1,"column":8,"end_line":0,"end_column":0}},"filename":"/only_with_bool.yaml","line":1,"column":8,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-8.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-8.snap new file mode 100644 index 000000000..1e59767f1 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml-8.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"Schema","name":{"node":{"names":[{"node":"only_with_float","filename":"/only_with_float.yaml","line":1,"column":9,"end_line":0,"end_column":0}],"pkgpath":"","ctx":"Load"},"filename":"/only_with_float.yaml","line":1,"column":9,"end_line":0,"end_column":0},"args":[],"kwargs":[],"config":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"float_val\"","value":"float_val"},"filename":"/only_with_float.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Float","value":0.33}},"filename":"/only_with_float.yaml","line":1,"column":11,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/only_with_float.yaml","line":1,"column":9,"end_line":0,"end_column":0}]},"filename":"/only_with_float.yaml","line":1,"column":9,"end_line":0,"end_column":0}},"filename":"/only_with_float.yaml","line":1,"column":9,"end_line":0,"end_column":0} diff --git a/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml.snap b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml.snap new file mode 100644 index 000000000..aa5562a82 --- /dev/null +++ b/crates/tools/src/vet/snapshots/kcl_tools__vet__tests__test_expr_builder__build_yaml.snap @@ -0,0 +1,5 @@ +--- +source: crates/tools/src/vet/tests.rs +expression: got_ast_yaml_str +--- +{"node":{"type":"Schema","name":{"node":{"names":[{"node":"test","filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0}],"pkgpath":"","ctx":"Load"},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0},"args":[],"kwargs":[],"config":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"languages\"","value":"languages"},"filename":"/test.k.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"List","elts":[{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Ruby\"","value":"Ruby"},"filename":"/test.k.yaml","line":2,"column":4,"end_line":0,"end_column":0},{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Perl\"","value":"Perl"},"filename":"/test.k.yaml","line":3,"column":4,"end_line":0,"end_column":0},{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Python\"","value":"Python"},"filename":"/test.k.yaml","line":4,"column":4,"end_line":0,"end_column":0}],"ctx":"Load"},"filename":"/test.k.yaml","line":2,"column":2,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"websites\"","value":"websites"},"filename":"/test.k.yaml","line":5,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"YAML\"","value":"YAML"},"filename":"/test.k.yaml","line":6,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"yaml.org\"","value":"yaml.org"},"filename":"/test.k.yaml","line":6,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Ruby\"","value":"Ruby"},"filename":"/test.k.yaml","line":7,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"ruby-lang.org\"","value":"ruby-lang.org"},"filename":"/test.k.yaml","line":7,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Python\"","value":"Python"},"filename":"/test.k.yaml","line":8,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"python.org\"","value":"python.org"},"filename":"/test.k.yaml","line":8,"column":10,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Perl\"","value":"Perl"},"filename":"/test.k.yaml","line":9,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"use.perl.org\"","value":"use.perl.org"},"filename":"/test.k.yaml","line":9,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0}]},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0}]},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0}},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/test_datas/invalid/test_invalid.json b/crates/tools/src/vet/test_datas/invalid/test_invalid.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid/test_invalid.json rename to crates/tools/src/vet/test_datas/invalid/test_invalid.json diff --git a/kclvm/tools/src/vet/test_datas/invalid/test_invalid.yaml b/crates/tools/src/vet/test_datas/invalid/test_invalid.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid/test_invalid.yaml rename to crates/tools/src/vet/test_datas/invalid/test_invalid.yaml diff --git a/kclvm/tools/src/vet/test_datas/invalid/unsupported/json_with_u64.ast.json b/crates/tools/src/vet/test_datas/invalid/unsupported/json_with_u64.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid/unsupported/json_with_u64.ast.json rename to crates/tools/src/vet/test_datas/invalid/unsupported/json_with_u64.ast.json diff --git a/kclvm/tools/src/vet/test_datas/invalid/unsupported/json_with_u64.json b/crates/tools/src/vet/test_datas/invalid/unsupported/json_with_u64.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid/unsupported/json_with_u64.json rename to crates/tools/src/vet/test_datas/invalid/unsupported/json_with_u64.json diff --git a/kclvm/tools/src/vet/test_datas/invalid/unsupported/yaml_with_u64.ast.yaml b/crates/tools/src/vet/test_datas/invalid/unsupported/yaml_with_u64.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid/unsupported/yaml_with_u64.ast.yaml rename to crates/tools/src/vet/test_datas/invalid/unsupported/yaml_with_u64.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/invalid/unsupported/yaml_with_u64.yaml b/crates/tools/src/vet/test_datas/invalid/unsupported/yaml_with_u64.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid/unsupported/yaml_with_u64.yaml rename to crates/tools/src/vet/test_datas/invalid/unsupported/yaml_with_u64.yaml diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/complex.k b/crates/tools/src/vet/test_datas/invalid_validate_cases/complex.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/complex.k rename to crates/tools/src/vet/test_datas/invalid_validate_cases/complex.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/complex.k.json b/crates/tools/src/vet/test_datas/invalid_validate_cases/complex.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/complex.k.json rename to crates/tools/src/vet/test_datas/invalid_validate_cases/complex.k.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/complex.k.stderr.json b/crates/tools/src/vet/test_datas/invalid_validate_cases/complex.k.stderr.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/complex.k.stderr.json rename to crates/tools/src/vet/test_datas/invalid_validate_cases/complex.k.stderr.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/complex.k.yaml b/crates/tools/src/vet/test_datas/invalid_validate_cases/complex.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/complex.k.yaml rename to crates/tools/src/vet/test_datas/invalid_validate_cases/complex.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/list.k b/crates/tools/src/vet/test_datas/invalid_validate_cases/list.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/list.k rename to crates/tools/src/vet/test_datas/invalid_validate_cases/list.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/list.k.json b/crates/tools/src/vet/test_datas/invalid_validate_cases/list.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/list.k.json rename to crates/tools/src/vet/test_datas/invalid_validate_cases/list.k.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/list.k.stderr.json b/crates/tools/src/vet/test_datas/invalid_validate_cases/list.k.stderr.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/list.k.stderr.json rename to crates/tools/src/vet/test_datas/invalid_validate_cases/list.k.stderr.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/list.k.yaml b/crates/tools/src/vet/test_datas/invalid_validate_cases/list.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/list.k.yaml rename to crates/tools/src/vet/test_datas/invalid_validate_cases/list.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k b/crates/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k rename to crates/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k.json b/crates/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k.json rename to crates/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k.stderr.json b/crates/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k.stderr.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k.stderr.json rename to crates/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k.stderr.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k.yaml b/crates/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k.yaml rename to crates/tools/src/vet/test_datas/invalid_validate_cases/plain_value.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/simple.k b/crates/tools/src/vet/test_datas/invalid_validate_cases/simple.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/simple.k rename to crates/tools/src/vet/test_datas/invalid_validate_cases/simple.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/simple.k.json b/crates/tools/src/vet/test_datas/invalid_validate_cases/simple.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/simple.k.json rename to crates/tools/src/vet/test_datas/invalid_validate_cases/simple.k.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/simple.k.stderr.json b/crates/tools/src/vet/test_datas/invalid_validate_cases/simple.k.stderr.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/simple.k.stderr.json rename to crates/tools/src/vet/test_datas/invalid_validate_cases/simple.k.stderr.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/simple.k.yaml b/crates/tools/src/vet/test_datas/invalid_validate_cases/simple.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/simple.k.yaml rename to crates/tools/src/vet/test_datas/invalid_validate_cases/simple.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/test.k b/crates/tools/src/vet/test_datas/invalid_validate_cases/test.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/test.k rename to crates/tools/src/vet/test_datas/invalid_validate_cases/test.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/test.k.json b/crates/tools/src/vet/test_datas/invalid_validate_cases/test.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/test.k.json rename to crates/tools/src/vet/test_datas/invalid_validate_cases/test.k.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/test.k.stderr.json b/crates/tools/src/vet/test_datas/invalid_validate_cases/test.k.stderr.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/test.k.stderr.json rename to crates/tools/src/vet/test_datas/invalid_validate_cases/test.k.stderr.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_validate_cases/test.k.yaml b/crates/tools/src/vet/test_datas/invalid_validate_cases/test.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_validate_cases/test.k.yaml rename to crates/tools/src/vet/test_datas/invalid_validate_cases/test.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/complex.k b/crates/tools/src/vet/test_datas/invalid_vet_cases_json/complex.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/complex.k rename to crates/tools/src/vet/test_datas/invalid_vet_cases_json/complex.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/complex.k.json b/crates/tools/src/vet/test_datas/invalid_vet_cases_json/complex.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/complex.k.json rename to crates/tools/src/vet/test_datas/invalid_vet_cases_json/complex.k.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/dep/kcl.mod b/crates/tools/src/vet/test_datas/invalid_vet_cases_json/dep/kcl.mod similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/dep/kcl.mod rename to crates/tools/src/vet/test_datas/invalid_vet_cases_json/dep/kcl.mod diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/dep/main.k b/crates/tools/src/vet/test_datas/invalid_vet_cases_json/dep/main.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/dep/main.k rename to crates/tools/src/vet/test_datas/invalid_vet_cases_json/dep/main.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/list.k b/crates/tools/src/vet/test_datas/invalid_vet_cases_json/list.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/list.k rename to crates/tools/src/vet/test_datas/invalid_vet_cases_json/list.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/list.k.json b/crates/tools/src/vet/test_datas/invalid_vet_cases_json/list.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/list.k.json rename to crates/tools/src/vet/test_datas/invalid_vet_cases_json/list.k.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/plain_value.k b/crates/tools/src/vet/test_datas/invalid_vet_cases_json/plain_value.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/plain_value.k rename to crates/tools/src/vet/test_datas/invalid_vet_cases_json/plain_value.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/plain_value.k.json b/crates/tools/src/vet/test_datas/invalid_vet_cases_json/plain_value.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/plain_value.k.json rename to crates/tools/src/vet/test_datas/invalid_vet_cases_json/plain_value.k.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/simple.k b/crates/tools/src/vet/test_datas/invalid_vet_cases_json/simple.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/simple.k rename to crates/tools/src/vet/test_datas/invalid_vet_cases_json/simple.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/simple.k.json b/crates/tools/src/vet/test_datas/invalid_vet_cases_json/simple.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/simple.k.json rename to crates/tools/src/vet/test_datas/invalid_vet_cases_json/simple.k.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/test.k b/crates/tools/src/vet/test_datas/invalid_vet_cases_json/test.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/test.k rename to crates/tools/src/vet/test_datas/invalid_vet_cases_json/test.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/test.k.json b/crates/tools/src/vet/test_datas/invalid_vet_cases_json/test.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/test.k.json rename to crates/tools/src/vet/test_datas/invalid_vet_cases_json/test.k.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/with_import.k b/crates/tools/src/vet/test_datas/invalid_vet_cases_json/with_import.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/with_import.k rename to crates/tools/src/vet/test_datas/invalid_vet_cases_json/with_import.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/with_import.k.json b/crates/tools/src/vet/test_datas/invalid_vet_cases_json/with_import.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_json/with_import.k.json rename to crates/tools/src/vet/test_datas/invalid_vet_cases_json/with_import.k.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/complex.k b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/complex.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/complex.k rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/complex.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/complex.k.stderr.json b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/complex.k.stderr.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/complex.k.stderr.json rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/complex.k.stderr.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/complex.k.yaml b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/complex.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/complex.k.yaml rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/complex.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/dep/kcl.mod b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/dep/kcl.mod similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/dep/kcl.mod rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/dep/kcl.mod diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/dep/main.k b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/dep/main.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/dep/main.k rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/dep/main.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/list.k b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/list.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/list.k rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/list.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/list.k.stderr.json b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/list.k.stderr.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/list.k.stderr.json rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/list.k.stderr.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/list.k.yaml b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/list.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/list.k.yaml rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/list.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/plain_value.k b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/plain_value.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/plain_value.k rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/plain_value.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/plain_value.k.stderr.json b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/plain_value.k.stderr.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/plain_value.k.stderr.json rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/plain_value.k.stderr.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/plain_value.k.yaml b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/plain_value.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/plain_value.k.yaml rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/plain_value.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/simple.k b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/simple.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/simple.k rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/simple.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/simple.k.stderr.json b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/simple.k.stderr.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/simple.k.stderr.json rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/simple.k.stderr.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/simple.k.yaml b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/simple.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/simple.k.yaml rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/simple.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/test.k b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/test.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/test.k rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/test.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/test.k.stderr.json b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/test.k.stderr.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/test.k.stderr.json rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/test.k.stderr.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/test.k.yaml b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/test.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/test.k.yaml rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/test.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/with_import.k b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/with_import.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/with_import.k rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/with_import.k diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/with_import.k.stderr.json b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/with_import.k.stderr.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/with_import.k.stderr.json rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/with_import.k.stderr.json diff --git a/kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/with_import.k.yaml b/crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/with_import.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/invalid_vet_cases_yaml/with_import.k.yaml rename to crates/tools/src/vet/test_datas/invalid_vet_cases_yaml/with_import.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/json/complex.k.ast.json b/crates/tools/src/vet/test_datas/json/complex.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/complex.k.ast.json rename to crates/tools/src/vet/test_datas/json/complex.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/complex.k.json b/crates/tools/src/vet/test_datas/json/complex.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/complex.k.json rename to crates/tools/src/vet/test_datas/json/complex.k.json diff --git a/kclvm/tools/src/vet/test_datas/json/list.k.ast.json b/crates/tools/src/vet/test_datas/json/list.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/list.k.ast.json rename to crates/tools/src/vet/test_datas/json/list.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/list.k.json b/crates/tools/src/vet/test_datas/json/list.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/list.k.json rename to crates/tools/src/vet/test_datas/json/list.k.json diff --git a/kclvm/tools/src/vet/test_datas/json/no_schema_name/complex.k.ast.json b/crates/tools/src/vet/test_datas/json/no_schema_name/complex.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/no_schema_name/complex.k.ast.json rename to crates/tools/src/vet/test_datas/json/no_schema_name/complex.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/no_schema_name/list.k.ast.json b/crates/tools/src/vet/test_datas/json/no_schema_name/list.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/no_schema_name/list.k.ast.json rename to crates/tools/src/vet/test_datas/json/no_schema_name/list.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/no_schema_name/only_with_bool.ast.json b/crates/tools/src/vet/test_datas/json/no_schema_name/only_with_bool.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/no_schema_name/only_with_bool.ast.json rename to crates/tools/src/vet/test_datas/json/no_schema_name/only_with_bool.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/no_schema_name/only_with_float.ast.json b/crates/tools/src/vet/test_datas/json/no_schema_name/only_with_float.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/no_schema_name/only_with_float.ast.json rename to crates/tools/src/vet/test_datas/json/no_schema_name/only_with_float.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/no_schema_name/only_with_null.ast.json b/crates/tools/src/vet/test_datas/json/no_schema_name/only_with_null.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/no_schema_name/only_with_null.ast.json rename to crates/tools/src/vet/test_datas/json/no_schema_name/only_with_null.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/no_schema_name/plain_value.k.ast.json b/crates/tools/src/vet/test_datas/json/no_schema_name/plain_value.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/no_schema_name/plain_value.k.ast.json rename to crates/tools/src/vet/test_datas/json/no_schema_name/plain_value.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/no_schema_name/simple.k.ast.json b/crates/tools/src/vet/test_datas/json/no_schema_name/simple.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/no_schema_name/simple.k.ast.json rename to crates/tools/src/vet/test_datas/json/no_schema_name/simple.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/no_schema_name/test.k.ast.json b/crates/tools/src/vet/test_datas/json/no_schema_name/test.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/no_schema_name/test.k.ast.json rename to crates/tools/src/vet/test_datas/json/no_schema_name/test.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/only_with_bool.ast.json b/crates/tools/src/vet/test_datas/json/only_with_bool.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/only_with_bool.ast.json rename to crates/tools/src/vet/test_datas/json/only_with_bool.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/only_with_bool.json b/crates/tools/src/vet/test_datas/json/only_with_bool.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/only_with_bool.json rename to crates/tools/src/vet/test_datas/json/only_with_bool.json diff --git a/kclvm/tools/src/vet/test_datas/json/only_with_float.ast.json b/crates/tools/src/vet/test_datas/json/only_with_float.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/only_with_float.ast.json rename to crates/tools/src/vet/test_datas/json/only_with_float.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/only_with_float.json b/crates/tools/src/vet/test_datas/json/only_with_float.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/only_with_float.json rename to crates/tools/src/vet/test_datas/json/only_with_float.json diff --git a/kclvm/tools/src/vet/test_datas/json/only_with_null.ast.json b/crates/tools/src/vet/test_datas/json/only_with_null.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/only_with_null.ast.json rename to crates/tools/src/vet/test_datas/json/only_with_null.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/only_with_null.json b/crates/tools/src/vet/test_datas/json/only_with_null.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/only_with_null.json rename to crates/tools/src/vet/test_datas/json/only_with_null.json diff --git a/kclvm/tools/src/vet/test_datas/json/plain_value.k.ast.json b/crates/tools/src/vet/test_datas/json/plain_value.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/plain_value.k.ast.json rename to crates/tools/src/vet/test_datas/json/plain_value.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/plain_value.k.json b/crates/tools/src/vet/test_datas/json/plain_value.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/plain_value.k.json rename to crates/tools/src/vet/test_datas/json/plain_value.k.json diff --git a/kclvm/tools/src/vet/test_datas/json/simple.k.ast.json b/crates/tools/src/vet/test_datas/json/simple.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/simple.k.ast.json rename to crates/tools/src/vet/test_datas/json/simple.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/simple.k.json b/crates/tools/src/vet/test_datas/json/simple.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/simple.k.json rename to crates/tools/src/vet/test_datas/json/simple.k.json diff --git a/kclvm/tools/src/vet/test_datas/json/test.k.ast.json b/crates/tools/src/vet/test_datas/json/test.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/test.k.ast.json rename to crates/tools/src/vet/test_datas/json/test.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json/test.k.json b/crates/tools/src/vet/test_datas/json/test.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json/test.k.json rename to crates/tools/src/vet/test_datas/json/test.k.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/complex.k.ast.json b/crates/tools/src/vet/test_datas/json_str/complex.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/complex.k.ast.json rename to crates/tools/src/vet/test_datas/json_str/complex.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/complex.k.json b/crates/tools/src/vet/test_datas/json_str/complex.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/complex.k.json rename to crates/tools/src/vet/test_datas/json_str/complex.k.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/list.k.ast.json b/crates/tools/src/vet/test_datas/json_str/list.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/list.k.ast.json rename to crates/tools/src/vet/test_datas/json_str/list.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/list.k.json b/crates/tools/src/vet/test_datas/json_str/list.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/list.k.json rename to crates/tools/src/vet/test_datas/json_str/list.k.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/only_with_bool.ast.json b/crates/tools/src/vet/test_datas/json_str/only_with_bool.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/only_with_bool.ast.json rename to crates/tools/src/vet/test_datas/json_str/only_with_bool.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/only_with_bool.json b/crates/tools/src/vet/test_datas/json_str/only_with_bool.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/only_with_bool.json rename to crates/tools/src/vet/test_datas/json_str/only_with_bool.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/only_with_float.ast.json b/crates/tools/src/vet/test_datas/json_str/only_with_float.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/only_with_float.ast.json rename to crates/tools/src/vet/test_datas/json_str/only_with_float.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/only_with_float.json b/crates/tools/src/vet/test_datas/json_str/only_with_float.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/only_with_float.json rename to crates/tools/src/vet/test_datas/json_str/only_with_float.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/only_with_null.ast.json b/crates/tools/src/vet/test_datas/json_str/only_with_null.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/only_with_null.ast.json rename to crates/tools/src/vet/test_datas/json_str/only_with_null.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/only_with_null.json b/crates/tools/src/vet/test_datas/json_str/only_with_null.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/only_with_null.json rename to crates/tools/src/vet/test_datas/json_str/only_with_null.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/plain_value.k.ast.json b/crates/tools/src/vet/test_datas/json_str/plain_value.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/plain_value.k.ast.json rename to crates/tools/src/vet/test_datas/json_str/plain_value.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/plain_value.k.json b/crates/tools/src/vet/test_datas/json_str/plain_value.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/plain_value.k.json rename to crates/tools/src/vet/test_datas/json_str/plain_value.k.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/simple.k.ast.json b/crates/tools/src/vet/test_datas/json_str/simple.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/simple.k.ast.json rename to crates/tools/src/vet/test_datas/json_str/simple.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/simple.k.json b/crates/tools/src/vet/test_datas/json_str/simple.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/simple.k.json rename to crates/tools/src/vet/test_datas/json_str/simple.k.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/test.k.ast.json b/crates/tools/src/vet/test_datas/json_str/test.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/test.k.ast.json rename to crates/tools/src/vet/test_datas/json_str/test.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str/test.k.json b/crates/tools/src/vet/test_datas/json_str/test.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str/test.k.json rename to crates/tools/src/vet/test_datas/json_str/test.k.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/complex.k.ast.json b/crates/tools/src/vet/test_datas/json_str_win/complex.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/complex.k.ast.json rename to crates/tools/src/vet/test_datas/json_str_win/complex.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/complex.k.json b/crates/tools/src/vet/test_datas/json_str_win/complex.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/complex.k.json rename to crates/tools/src/vet/test_datas/json_str_win/complex.k.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/list.k.ast.json b/crates/tools/src/vet/test_datas/json_str_win/list.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/list.k.ast.json rename to crates/tools/src/vet/test_datas/json_str_win/list.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/list.k.json b/crates/tools/src/vet/test_datas/json_str_win/list.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/list.k.json rename to crates/tools/src/vet/test_datas/json_str_win/list.k.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/only_with_bool.ast.json b/crates/tools/src/vet/test_datas/json_str_win/only_with_bool.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/only_with_bool.ast.json rename to crates/tools/src/vet/test_datas/json_str_win/only_with_bool.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/only_with_bool.json b/crates/tools/src/vet/test_datas/json_str_win/only_with_bool.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/only_with_bool.json rename to crates/tools/src/vet/test_datas/json_str_win/only_with_bool.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/only_with_float.ast.json b/crates/tools/src/vet/test_datas/json_str_win/only_with_float.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/only_with_float.ast.json rename to crates/tools/src/vet/test_datas/json_str_win/only_with_float.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/only_with_float.json b/crates/tools/src/vet/test_datas/json_str_win/only_with_float.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/only_with_float.json rename to crates/tools/src/vet/test_datas/json_str_win/only_with_float.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/only_with_null.ast.json b/crates/tools/src/vet/test_datas/json_str_win/only_with_null.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/only_with_null.ast.json rename to crates/tools/src/vet/test_datas/json_str_win/only_with_null.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/only_with_null.json b/crates/tools/src/vet/test_datas/json_str_win/only_with_null.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/only_with_null.json rename to crates/tools/src/vet/test_datas/json_str_win/only_with_null.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/plain_value.k.ast.json b/crates/tools/src/vet/test_datas/json_str_win/plain_value.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/plain_value.k.ast.json rename to crates/tools/src/vet/test_datas/json_str_win/plain_value.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/plain_value.k.json b/crates/tools/src/vet/test_datas/json_str_win/plain_value.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/plain_value.k.json rename to crates/tools/src/vet/test_datas/json_str_win/plain_value.k.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/simple.k.ast.json b/crates/tools/src/vet/test_datas/json_str_win/simple.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/simple.k.ast.json rename to crates/tools/src/vet/test_datas/json_str_win/simple.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/simple.k.json b/crates/tools/src/vet/test_datas/json_str_win/simple.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/simple.k.json rename to crates/tools/src/vet/test_datas/json_str_win/simple.k.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/test.k.ast.json b/crates/tools/src/vet/test_datas/json_str_win/test.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/test.k.ast.json rename to crates/tools/src/vet/test_datas/json_str_win/test.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_str_win/test.k.json b/crates/tools/src/vet/test_datas/json_str_win/test.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_str_win/test.k.json rename to crates/tools/src/vet/test_datas/json_str_win/test.k.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/complex.k.ast.json b/crates/tools/src/vet/test_datas/json_win/complex.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/complex.k.ast.json rename to crates/tools/src/vet/test_datas/json_win/complex.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/list.k.ast.json b/crates/tools/src/vet/test_datas/json_win/list.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/list.k.ast.json rename to crates/tools/src/vet/test_datas/json_win/list.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/no_schema_name/complex.k.ast.json b/crates/tools/src/vet/test_datas/json_win/no_schema_name/complex.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/no_schema_name/complex.k.ast.json rename to crates/tools/src/vet/test_datas/json_win/no_schema_name/complex.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/no_schema_name/list.k.ast.json b/crates/tools/src/vet/test_datas/json_win/no_schema_name/list.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/no_schema_name/list.k.ast.json rename to crates/tools/src/vet/test_datas/json_win/no_schema_name/list.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/no_schema_name/only_with_bool.ast.json b/crates/tools/src/vet/test_datas/json_win/no_schema_name/only_with_bool.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/no_schema_name/only_with_bool.ast.json rename to crates/tools/src/vet/test_datas/json_win/no_schema_name/only_with_bool.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/no_schema_name/only_with_float.ast.json b/crates/tools/src/vet/test_datas/json_win/no_schema_name/only_with_float.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/no_schema_name/only_with_float.ast.json rename to crates/tools/src/vet/test_datas/json_win/no_schema_name/only_with_float.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/no_schema_name/only_with_null.ast.json b/crates/tools/src/vet/test_datas/json_win/no_schema_name/only_with_null.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/no_schema_name/only_with_null.ast.json rename to crates/tools/src/vet/test_datas/json_win/no_schema_name/only_with_null.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/no_schema_name/plain_value.k.ast.json b/crates/tools/src/vet/test_datas/json_win/no_schema_name/plain_value.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/no_schema_name/plain_value.k.ast.json rename to crates/tools/src/vet/test_datas/json_win/no_schema_name/plain_value.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/no_schema_name/simple.k.ast.json b/crates/tools/src/vet/test_datas/json_win/no_schema_name/simple.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/no_schema_name/simple.k.ast.json rename to crates/tools/src/vet/test_datas/json_win/no_schema_name/simple.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/no_schema_name/test.k.ast.json b/crates/tools/src/vet/test_datas/json_win/no_schema_name/test.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/no_schema_name/test.k.ast.json rename to crates/tools/src/vet/test_datas/json_win/no_schema_name/test.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/only_with_bool.ast.json b/crates/tools/src/vet/test_datas/json_win/only_with_bool.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/only_with_bool.ast.json rename to crates/tools/src/vet/test_datas/json_win/only_with_bool.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/only_with_float.ast.json b/crates/tools/src/vet/test_datas/json_win/only_with_float.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/only_with_float.ast.json rename to crates/tools/src/vet/test_datas/json_win/only_with_float.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/only_with_null.ast.json b/crates/tools/src/vet/test_datas/json_win/only_with_null.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/only_with_null.ast.json rename to crates/tools/src/vet/test_datas/json_win/only_with_null.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/plain_value.k.ast.json b/crates/tools/src/vet/test_datas/json_win/plain_value.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/plain_value.k.ast.json rename to crates/tools/src/vet/test_datas/json_win/plain_value.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/simple.k.ast.json b/crates/tools/src/vet/test_datas/json_win/simple.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/simple.k.ast.json rename to crates/tools/src/vet/test_datas/json_win/simple.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/json_win/test.k.ast.json b/crates/tools/src/vet/test_datas/json_win/test.k.ast.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/json_win/test.k.ast.json rename to crates/tools/src/vet/test_datas/json_win/test.k.ast.json diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/complex.k b/crates/tools/src/vet/test_datas/validate_cases/complex.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/complex.k rename to crates/tools/src/vet/test_datas/validate_cases/complex.k diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/complex.k.json b/crates/tools/src/vet/test_datas/validate_cases/complex.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/complex.k.json rename to crates/tools/src/vet/test_datas/validate_cases/complex.k.json diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/complex.k.yaml b/crates/tools/src/vet/test_datas/validate_cases/complex.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/complex.k.yaml rename to crates/tools/src/vet/test_datas/validate_cases/complex.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/dep/kcl.mod b/crates/tools/src/vet/test_datas/validate_cases/dep/kcl.mod similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/dep/kcl.mod rename to crates/tools/src/vet/test_datas/validate_cases/dep/kcl.mod diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/dep/main.k b/crates/tools/src/vet/test_datas/validate_cases/dep/main.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/dep/main.k rename to crates/tools/src/vet/test_datas/validate_cases/dep/main.k diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/list.k b/crates/tools/src/vet/test_datas/validate_cases/list.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/list.k rename to crates/tools/src/vet/test_datas/validate_cases/list.k diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/list.k.json b/crates/tools/src/vet/test_datas/validate_cases/list.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/list.k.json rename to crates/tools/src/vet/test_datas/validate_cases/list.k.json diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/list.k.yaml b/crates/tools/src/vet/test_datas/validate_cases/list.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/list.k.yaml rename to crates/tools/src/vet/test_datas/validate_cases/list.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/plain_value.k b/crates/tools/src/vet/test_datas/validate_cases/plain_value.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/plain_value.k rename to crates/tools/src/vet/test_datas/validate_cases/plain_value.k diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/plain_value.k.json b/crates/tools/src/vet/test_datas/validate_cases/plain_value.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/plain_value.k.json rename to crates/tools/src/vet/test_datas/validate_cases/plain_value.k.json diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/plain_value.k.yaml b/crates/tools/src/vet/test_datas/validate_cases/plain_value.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/plain_value.k.yaml rename to crates/tools/src/vet/test_datas/validate_cases/plain_value.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/simple.k b/crates/tools/src/vet/test_datas/validate_cases/simple.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/simple.k rename to crates/tools/src/vet/test_datas/validate_cases/simple.k diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/simple.k.json b/crates/tools/src/vet/test_datas/validate_cases/simple.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/simple.k.json rename to crates/tools/src/vet/test_datas/validate_cases/simple.k.json diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/simple.k.yaml b/crates/tools/src/vet/test_datas/validate_cases/simple.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/simple.k.yaml rename to crates/tools/src/vet/test_datas/validate_cases/simple.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/test.k b/crates/tools/src/vet/test_datas/validate_cases/test.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/test.k rename to crates/tools/src/vet/test_datas/validate_cases/test.k diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/test.k.json b/crates/tools/src/vet/test_datas/validate_cases/test.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/test.k.json rename to crates/tools/src/vet/test_datas/validate_cases/test.k.json diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/test.k.yaml b/crates/tools/src/vet/test_datas/validate_cases/test.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/test.k.yaml rename to crates/tools/src/vet/test_datas/validate_cases/test.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/with_import.k b/crates/tools/src/vet/test_datas/validate_cases/with_import.k similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/with_import.k rename to crates/tools/src/vet/test_datas/validate_cases/with_import.k diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/with_import.k.json b/crates/tools/src/vet/test_datas/validate_cases/with_import.k.json similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/with_import.k.json rename to crates/tools/src/vet/test_datas/validate_cases/with_import.k.json diff --git a/kclvm/tools/src/vet/test_datas/validate_cases/with_import.k.yaml b/crates/tools/src/vet/test_datas/validate_cases/with_import.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/validate_cases/with_import.k.yaml rename to crates/tools/src/vet/test_datas/validate_cases/with_import.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/complex.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml/complex.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/complex.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/complex.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/complex.k.yaml b/crates/tools/src/vet/test_datas/yaml/complex.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/complex.k.yaml rename to crates/tools/src/vet/test_datas/yaml/complex.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/list.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml/list.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/list.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/list.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/list.k.yaml b/crates/tools/src/vet/test_datas/yaml/list.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/list.k.yaml rename to crates/tools/src/vet/test_datas/yaml/list.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/no_schema_name/complex.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml/no_schema_name/complex.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/no_schema_name/complex.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/no_schema_name/complex.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/no_schema_name/list.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml/no_schema_name/list.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/no_schema_name/list.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/no_schema_name/list.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/no_schema_name/only_with_bool.ast.yaml b/crates/tools/src/vet/test_datas/yaml/no_schema_name/only_with_bool.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/no_schema_name/only_with_bool.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/no_schema_name/only_with_bool.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/no_schema_name/only_with_float.ast.yaml b/crates/tools/src/vet/test_datas/yaml/no_schema_name/only_with_float.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/no_schema_name/only_with_float.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/no_schema_name/only_with_float.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/no_schema_name/only_with_null.ast.yaml b/crates/tools/src/vet/test_datas/yaml/no_schema_name/only_with_null.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/no_schema_name/only_with_null.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/no_schema_name/only_with_null.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/no_schema_name/plain_value.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml/no_schema_name/plain_value.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/no_schema_name/plain_value.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/no_schema_name/plain_value.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/no_schema_name/simple.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml/no_schema_name/simple.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/no_schema_name/simple.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/no_schema_name/simple.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/no_schema_name/test.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml/no_schema_name/test.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/no_schema_name/test.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/no_schema_name/test.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/only_with_bool.ast.yaml b/crates/tools/src/vet/test_datas/yaml/only_with_bool.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/only_with_bool.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/only_with_bool.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/only_with_bool.yaml b/crates/tools/src/vet/test_datas/yaml/only_with_bool.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/only_with_bool.yaml rename to crates/tools/src/vet/test_datas/yaml/only_with_bool.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/only_with_float.ast.yaml b/crates/tools/src/vet/test_datas/yaml/only_with_float.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/only_with_float.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/only_with_float.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/only_with_float.yaml b/crates/tools/src/vet/test_datas/yaml/only_with_float.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/only_with_float.yaml rename to crates/tools/src/vet/test_datas/yaml/only_with_float.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/only_with_null.ast.yaml b/crates/tools/src/vet/test_datas/yaml/only_with_null.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/only_with_null.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/only_with_null.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/only_with_null.yaml b/crates/tools/src/vet/test_datas/yaml/only_with_null.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/only_with_null.yaml rename to crates/tools/src/vet/test_datas/yaml/only_with_null.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/plain_value.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml/plain_value.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/plain_value.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/plain_value.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/plain_value.k.yaml b/crates/tools/src/vet/test_datas/yaml/plain_value.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/plain_value.k.yaml rename to crates/tools/src/vet/test_datas/yaml/plain_value.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/simple.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml/simple.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/simple.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/simple.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/simple.k.yaml b/crates/tools/src/vet/test_datas/yaml/simple.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/simple.k.yaml rename to crates/tools/src/vet/test_datas/yaml/simple.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/test.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml/test.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/test.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml/test.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml/test.k.yaml b/crates/tools/src/vet/test_datas/yaml/test.k.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml/test.k.yaml rename to crates/tools/src/vet/test_datas/yaml/test.k.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/complex.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/complex.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/complex.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/complex.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/list.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/list.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/list.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/list.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/complex.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/no_schema_name/complex.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/complex.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/no_schema_name/complex.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/list.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/no_schema_name/list.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/list.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/no_schema_name/list.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/only_with_bool.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/no_schema_name/only_with_bool.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/only_with_bool.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/no_schema_name/only_with_bool.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/only_with_float.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/no_schema_name/only_with_float.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/only_with_float.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/no_schema_name/only_with_float.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/only_with_null.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/no_schema_name/only_with_null.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/only_with_null.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/no_schema_name/only_with_null.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/plain_value.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/no_schema_name/plain_value.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/plain_value.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/no_schema_name/plain_value.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/simple.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/no_schema_name/simple.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/simple.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/no_schema_name/simple.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/test.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/no_schema_name/test.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/no_schema_name/test.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/no_schema_name/test.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/only_with_bool.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/only_with_bool.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/only_with_bool.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/only_with_bool.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/only_with_float.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/only_with_float.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/only_with_float.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/only_with_float.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/only_with_null.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/only_with_null.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/only_with_null.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/only_with_null.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/plain_value.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/plain_value.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/plain_value.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/plain_value.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/simple.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/simple.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/simple.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/simple.k.ast.yaml diff --git a/kclvm/tools/src/vet/test_datas/yaml_win/test.k.ast.yaml b/crates/tools/src/vet/test_datas/yaml_win/test.k.ast.yaml similarity index 100% rename from kclvm/tools/src/vet/test_datas/yaml_win/test.k.ast.yaml rename to crates/tools/src/vet/test_datas/yaml_win/test.k.ast.yaml diff --git a/crates/tools/src/vet/tests.rs b/crates/tools/src/vet/tests.rs new file mode 100644 index 000000000..11f8e5d2c --- /dev/null +++ b/crates/tools/src/vet/tests.rs @@ -0,0 +1,647 @@ +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Result}; + +use crate::util::loader::LoaderKind; + +const CARGO_DIR: &str = env!("CARGO_MANIFEST_DIR"); +pub(crate) fn rel_path() -> String { + Path::new("src") + .join("vet") + .join("test_datas") + .display() + .to_string() +} + +const TEST_CASES: &[&str] = &[ + "test.k", + "simple.k", + "plain_value.k", + "list.k", + "complex.k", + "only_with_null", + "only_with_bool", + "only_with_float", +]; + +const SCHEMA_NAMES: &[&str] = &[ + "test", + "simple", + "plain_value", + "list", + "complex", + "only_with_null", + "only_with_bool", + "only_with_float", +]; + +const FILE_EXTENSIONS: &[&str] = &["json", "yaml", "ast.json", "ast.yaml", "k"]; + +const LOADER_KIND: [&LoaderKind; 2] = [&LoaderKind::JSON, &LoaderKind::YAML]; + +const INVALID_FILE_RESULT: &[&str] = &[ + "Failed to Load JSON\n\nCaused by:\n 0: Failed to String 'languages:\n - Ruby\n ' to Json\n 1: expected value at line 1 column 1", + "Failed to Load YAML\n\nCaused by:\n 0: Failed to String '{\n \"name\": \"John Doe\",\n \"city\": \"London\"\n invalid\n \n ' to Yaml\n 1: while parsing a flow mapping, did not find expected ',' or '}' at line 4 column 1", +]; + +fn construct_full_path(path: &str) -> Result { + let mut cargo_file_path = PathBuf::from(CARGO_DIR); + cargo_file_path.push(&rel_path()); + cargo_file_path.push(path); + Ok(cargo_file_path + .to_str() + .with_context(|| format!("No such file or directory '{}'", path))? + .to_string()) +} + +mod test_expr_builder { + use regex::Regex; + + use crate::{ + util::loader::LoaderKind, + vet::{ + expr_builder::ExprBuilder, + tests::{ + FILE_EXTENSIONS, INVALID_FILE_RESULT, LOADER_KIND, SCHEMA_NAMES, TEST_CASES, + construct_full_path, deal_windows_filepath, + }, + }, + }; + use std::panic; + #[cfg(not(target_os = "windows"))] + use std::{fs, path::Path}; + + #[test] + #[cfg(not(target_os = "windows"))] + fn test_build_with_json_no_schema_name() { + for test_name in TEST_CASES { + let file_path = construct_full_path(&format!( + "{}.{}", + Path::new(FILE_EXTENSIONS[0]).join(test_name).display(), + FILE_EXTENSIONS[0] + )) + .unwrap(); + let expr_builder = + ExprBuilder::new_with_file_path(*LOADER_KIND[0], file_path.clone()).unwrap(); + let expr_ast = expr_builder.build(None).unwrap(); + let got_ast_json = serde_json::to_value(&expr_ast).unwrap(); + + let got_ast_json_str = serde_json::to_string_pretty(&got_ast_json) + .unwrap() + .replace( + &deal_windows_filepath(construct_full_path("json").unwrap(), |s| { + s.replace('\\', "\\\\") + }), + "", + ); + + insta::assert_snapshot!(got_ast_json_str); + } + } + + #[test] + fn test_build_with_yaml_no_schema_name() { + for test_name in TEST_CASES { + let file_path = construct_full_path(&format!( + "{}/{}.{}", + FILE_EXTENSIONS[1], test_name, FILE_EXTENSIONS[1] + )) + .unwrap(); + let expr_builder = + ExprBuilder::new_with_file_path(*LOADER_KIND[1], file_path.clone()).unwrap(); + let expr_ast = expr_builder.build(None).unwrap(); + let got_ast_yaml = serde_yaml_ng::to_value(&expr_ast).unwrap(); + + let got_ast_yaml_str = serde_json::to_string(&got_ast_yaml).unwrap().replace( + &deal_windows_filepath(construct_full_path("yaml").unwrap(), |s| { + s.replace('\\', "\\\\") + }), + "", + ); + + insta::assert_snapshot!(got_ast_yaml_str) + } + } + + #[test] + #[cfg(not(target_os = "windows"))] + /// Test `expr_builder.build()` with input json files. + fn test_build_json_with_filepath() { + for i in 0..TEST_CASES.len() { + let file_path = + construct_full_path(&format!("{1}/{0}.{1}", TEST_CASES[i], FILE_EXTENSIONS[0])) + .unwrap(); + let expr_builder = ExprBuilder::new_with_file_path(*LOADER_KIND[0], file_path).unwrap(); + let expr_ast = expr_builder + .build(Some(SCHEMA_NAMES[i].to_string())) + .unwrap(); + let got_ast_json = serde_json::to_value(&expr_ast).unwrap(); + + let got_ast_json_str = serde_json::to_string_pretty(&got_ast_json) + .unwrap() + .replace( + &deal_windows_filepath(construct_full_path("json").unwrap(), |s| { + s.replace('\\', "\\\\") + }), + "", + ); + + insta::assert_snapshot!(got_ast_json_str); + } + } + + #[test] + #[cfg(not(target_os = "windows"))] + /// Test `expr_builder.build()` with input json files. + fn test_build_json_with_str() { + for i in 0..TEST_CASES.len() { + let file_path = + construct_full_path(&format!("{1}/{0}.{1}", TEST_CASES[i], FILE_EXTENSIONS[0])) + .unwrap(); + + let content = fs::read_to_string(file_path).unwrap(); + + let expr_builder = ExprBuilder::new_with_str(*LOADER_KIND[0], content).unwrap(); + let expr_ast = expr_builder + .build(Some(SCHEMA_NAMES[i].to_string())) + .unwrap(); + let got_ast_json = serde_json::to_value(&expr_ast).unwrap(); + + let got_ast_json_str = serde_json::to_string_pretty(&got_ast_json) + .unwrap() + .replace( + &deal_windows_filepath(construct_full_path("json").unwrap(), |s| { + s.replace('\\', "\\\\") + }), + "", + ); + + insta::assert_snapshot!(got_ast_json_str); + } + } + + #[test] + /// Test `expr_builder.build()` with input yaml files. + fn test_build_yaml() { + for i in 0..TEST_CASES.len() { + let file_path = + construct_full_path(&format!("{1}/{0}.{1}", TEST_CASES[i], FILE_EXTENSIONS[1])) + .unwrap(); + let expr_builder = ExprBuilder::new_with_file_path(*LOADER_KIND[1], file_path).unwrap(); + let expr_ast = expr_builder + .build(Some(SCHEMA_NAMES[i].to_string())) + .unwrap(); + let got_ast_yaml = serde_yaml_ng::to_value(&expr_ast).unwrap(); + + let got_ast_yaml_str = serde_json::to_string(&got_ast_yaml).unwrap().replace( + &deal_windows_filepath(construct_full_path("yaml").unwrap(), |s| { + s.replace('\\', "\\\\") + }), + "", + ); + + insta::assert_snapshot!(got_ast_yaml_str); + } + } + + #[test] + /// Test `expr_builder.build()` with input invalid json/yaml files. + fn test_build_with_invalid() { + for i in 0..2 { + let file_path = construct_full_path(&format!( + "invalid/{}.{}", + "test_invalid", FILE_EXTENSIONS[i] + )) + .unwrap(); + let expr_builder = ExprBuilder::new_with_file_path(*LOADER_KIND[i], file_path).unwrap(); + match expr_builder.build(None) { + Ok(_) => { + panic!("This test case should be failed.") + } + Err(err) => { + #[cfg(not(target_os = "windows"))] + let got_err = format!("{:?}", err); + #[cfg(target_os = "windows")] + let got_err = format!("{:?}", err).replace("\r\n", "\n"); + + assert_eq!(got_err, INVALID_FILE_RESULT[i]); + } + }; + } + } + + #[test] + /// Test `expr_builder.build()` with files that do not exist. + fn test_build_with_noexist_file() { + for i in 0..2 { + let file_path = construct_full_path(&format!( + "json/{}.{}", + "test_json_not_exist", FILE_EXTENSIONS[i] + )) + .unwrap(); + match ExprBuilder::new_with_file_path(*LOADER_KIND[i], file_path.clone()) { + Ok(_) => { + panic!("This test case should be failed.") + } + Err(err) => { + assert!( + Regex::new( + r"^Failed to Load '.*'\n\nCaused by:\n 0: Failed to Load '.*'\n .*" + ) + .unwrap() + .is_match(&format!("{:?}", err)) + ) + } + }; + } + } + + #[test] + /// Test `expr_builder.build()` with yaml files and json data loader. + fn test_build_with_yaml_file_with_json_kind() { + let file_path = construct_full_path(&format!("yaml/{}", "test.k.yaml")).unwrap(); + let expr_builder = ExprBuilder::new_with_file_path(LoaderKind::JSON, file_path).unwrap(); + + match expr_builder.build(None) { + Ok(_) => { + panic!("This test case should be failed.") + } + Err(err) => { + #[cfg(not(target_os = "windows"))] + let got_err = format!("{:?}", err); + #[cfg(target_os = "windows")] + let got_err = format!("{:?}", err).replace("\r\n", "\n"); + + assert_eq!( + got_err, + "Failed to Load JSON\n\nCaused by:\n 0: Failed to String 'languages:\n - Ruby\n - Perl\n - Python \n websites:\n YAML: yaml.org \n Ruby: ruby-lang.org \n Python: python.org \n Perl: use.perl.org\n ' to Json\n 1: expected value at line 1 column 1" + ) + } + } + } + + #[test] + fn test_unsupported_u64_json() { + // unsupported u64 json + let file_path = construct_full_path("invalid/unsupported/json_with_u64.json").unwrap(); + let expr_builder = ExprBuilder::new_with_file_path(*LOADER_KIND[0], file_path).unwrap(); + match expr_builder.build(None) { + Ok(_) => { + panic!("unreachable") + } + Err(err) => { + assert_eq!( + format!("{:?}", err), + "Failed to Load JSON\n\nCaused by:\n 0: Failed to load the validated file\n 1: Failed to load the validated file, Unsupported Unsigned 64" + ); + } + }; + } + + #[test] + fn test_unsupported_u64_yaml() { + // unsupported u64 yaml + let file_path = construct_full_path("invalid/unsupported/yaml_with_u64.yaml").unwrap(); + let expr_builder = ExprBuilder::new_with_file_path(*LOADER_KIND[1], file_path).unwrap(); + match expr_builder.build(None) { + Ok(_) => { + panic!("unreachable") + } + Err(err) => { + assert_eq!( + format!("{:?}", err), + "Failed to Load YAML\n\nCaused by:\n 0: Failed to load the validated file\n 1: Failed to load the validated file, Unsupported Number Type" + ); + } + }; + } +} + +mod test_validater { + use std::{ + fs, panic, + path::{Path, PathBuf}, + }; + + use crate::{ + util::loader::LoaderKind, + vet::{ + tests::deal_windows_filepath, + validator::{ValidateOption, validate}, + }, + }; + + use super::{LOADER_KIND, construct_full_path}; + + const KCL_TEST_CASES: &[&str] = &[ + "test.k", + "simple.k", + "list.k", + "plain_value.k", + "complex.k", + "with_import.k", + ]; + const KCL_TEST_CASES_WITH_CODE: &[&str] = + &["test.k", "simple.k", "list.k", "plain_value.k", "complex.k"]; + const VALIDATED_FILE_TYPE: &[&str] = &["json", "yaml"]; + + #[test] + fn test_validator() { + test_validate(); + println!("test_validate - PASS"); + test_invalid_validate_only_code(); + println!("test_invalid_validate_only_code - PASS"); + test_validate_with_invalid_kcl_path(); + println!("test_validate_with_invalid_kcl_path - PASS"); + test_validate_with_invalid_file_path(); + println!("test_validate_with_invalid_file_path - PASS"); + test_validate_with_invalid_file_type(); + println!("test_validate_with_invalid_file_type - PASS"); + test_invalid_validate_with_json_pos(); + println!("test_invalid_validate_with_json_pos - PASS"); + test_invalid_validate_with_yaml_pos(); + println!("test_invalid_validate_with_yaml_pos - PASS"); + } + + fn test_validate() { + for (i, file_suffix) in VALIDATED_FILE_TYPE.iter().enumerate() { + for case in KCL_TEST_CASES { + let validated_file_path = construct_full_path(&format!( + "{}.{}", + Path::new("validate_cases").join(case).display(), + file_suffix + )) + .unwrap(); + + let kcl_file_path = construct_full_path( + &Path::new("validate_cases").join(case).display().to_string(), + ) + .unwrap(); + + let opt = ValidateOption::new( + None, + "value".to_string(), + validated_file_path.clone(), + *LOADER_KIND[i], + Some(kcl_file_path.to_string()), + None, + Default::default(), + ); + + match validate(opt) { + Ok(res) => assert!(res), + Err(err) => unreachable!("{:?}", err), + } + } + } + } + + fn test_invalid_validate_with_json_pos() { + let root_path = PathBuf::from(construct_full_path("invalid_vet_cases_json").unwrap()) + .canonicalize() + .unwrap(); + for (i, _) in VALIDATED_FILE_TYPE.iter().enumerate() { + for case in KCL_TEST_CASES { + let validated_file_path = construct_full_path(&format!( + "{}.{}", + Path::new("invalid_vet_cases_json").join(case).display(), + "json" + )) + .unwrap(); + + let kcl_code = fs::read_to_string( + construct_full_path( + &Path::new("invalid_vet_cases_json") + .join(case) + .display() + .to_string(), + ) + .unwrap(), + ) + .expect("Something went wrong reading the file"); + + let kcl_path = construct_full_path( + &Path::new("invalid_vet_cases_json") + .join(case) + .display() + .to_string(), + ) + .unwrap(); + + let opt = ValidateOption::new( + None, + "value".to_string(), + validated_file_path.clone(), + *LOADER_KIND[i], + Some(kcl_path), + Some(kcl_code), + Default::default(), + ); + + let result = validate(opt).unwrap_err(); + println!("{}", result); + assert!( + result.to_string().replace('\\', "").contains( + &deal_windows_filepath(root_path.join(case).display().to_string(), |s| { + s.replace('\\', "\\\\") + }) + .replace('\\', "") + ), + "{result}" + ); + } + } + } + + fn test_invalid_validate_with_yaml_pos() { + let root_path = PathBuf::from(construct_full_path("invalid_vet_cases_yaml").unwrap()) + .canonicalize() + .unwrap(); + for case in KCL_TEST_CASES { + let validated_file_path = construct_full_path(&format!( + "{}.{}", + Path::new("invalid_vet_cases_yaml").join(case).display(), + "yaml" + )) + .unwrap(); + + let kcl_code = fs::read_to_string( + construct_full_path( + &Path::new("invalid_vet_cases_yaml") + .join(case) + .display() + .to_string(), + ) + .unwrap(), + ) + .expect("Something went wrong reading the file"); + + let kcl_path = construct_full_path( + &Path::new("invalid_vet_cases_yaml") + .join(case) + .display() + .to_string(), + ) + .unwrap(); + + let opt = ValidateOption::new( + None, + "value".to_string(), + validated_file_path.clone(), + LoaderKind::YAML, + Some(kcl_path), + Some(kcl_code), + Default::default(), + ); + + let result = validate(opt).unwrap_err(); + println!("{}", result); + assert!( + result.to_string().replace('\\', "").contains( + &deal_windows_filepath(root_path.join(case).display().to_string(), |s| { + s.replace('\\', "\\\\") + }) + .replace('\\', "") + ), + "{result}" + ); + } + } + + #[test] + fn test_invalid_validate_only_code() { + for (i, file_suffix) in VALIDATED_FILE_TYPE.iter().enumerate() { + for case in KCL_TEST_CASES_WITH_CODE { + let validated_file_path = construct_full_path(&format!( + "{}.{}", + Path::new("invalid_validate_cases").join(case).display(), + file_suffix + )) + .unwrap(); + + let kcl_code = fs::read_to_string( + construct_full_path( + &Path::new("invalid_validate_cases") + .join(case) + .display() + .to_string(), + ) + .unwrap(), + ) + .expect("Something went wrong reading the file"); + + let opt = ValidateOption::new( + None, + "value".to_string(), + validated_file_path.clone(), + *LOADER_KIND[i], + None, + Some(kcl_code), + Default::default(), + ); + + let result = validate(opt).unwrap_err(); + assert!(result.to_string().contains("Error"), "{result}"); + } + } + } + + fn test_validate_with_invalid_kcl_path() { + let opt = ValidateOption::new( + None, + "value".to_string(), + "The validated file path is invalid".to_string(), + LoaderKind::JSON, + None, + None, + Default::default(), + ); + + match validate(opt) { + Ok(_) => { + panic!("unreachable") + } + Err(err) => { + assert_eq!( + err.to_string(), + "Cannot find the kcl file, please check the file path validationTempKCLCode.k" + ); + } + } + } + + fn test_validate_with_invalid_file_path() { + let kcl_code = fs::read_to_string( + construct_full_path(&format!("{}/{}", "validate_cases", "test.k")).unwrap(), + ) + .expect("Something went wrong reading the file"); + + let opt = ValidateOption::new( + None, + "value".to_string(), + "invalid/file/path".to_string(), + LoaderKind::JSON, + None, + Some(kcl_code), + Default::default(), + ); + + match validate(opt) { + Ok(_) => { + panic!("unreachable") + } + Err(err) => { + assert_eq!(err.to_string(), "Failed to Load 'invalid/file/path'") + } + } + } + + fn test_validate_with_invalid_file_type() { + let kcl_code = fs::read_to_string( + construct_full_path(&format!("{}/{}", "validate_cases", "test.k")).unwrap(), + ) + .expect("Something went wrong reading the file"); + + let validated_file_path = + construct_full_path(&format!("{}/{}", "validate_cases", "test.k.yaml")).unwrap(); + + let opt = ValidateOption::new( + None, + "value".to_string(), + validated_file_path, + LoaderKind::JSON, + None, + Some(kcl_code), + Default::default(), + ); + + match validate(opt) { + Ok(_) => { + panic!("unreachable") + } + Err(err) => { + assert_eq!(err.to_string(), "Failed to Load JSON") + } + } + } +} + +/// Deal with windows filepath +#[allow(unused)] +fn deal_windows_filepath(filepath: String, transform: F) -> String +where + F: FnOnce(String) -> String, +{ + #[cfg(not(target_os = "windows"))] + return filepath; + #[cfg(target_os = "windows")] + { + use kcl_utils::path::PathPrefix; + let path = PathBuf::from(filepath) + .canonicalize() + .unwrap() + .display() + .to_string(); + return transform(Path::new(&path).adjust_canonicalization()); + } +} diff --git a/kclvm/tools/src/vet/validator.rs b/crates/tools/src/vet/validator.rs similarity index 90% rename from kclvm/tools/src/vet/validator.rs rename to crates/tools/src/vet/validator.rs index f8c61402a..b1d2cc530 100644 --- a/kclvm/tools/src/vet/validator.rs +++ b/crates/tools/src/vet/validator.rs @@ -7,12 +7,12 @@ //! - Validation rules for validating file contents are defined in KCL statment. //! - Convert the json or yaml file to be verified into a KCL assign expression. //! - Combine KCL statment and KCL expression into a KCL program, -//! and the KCL program is checked by the KCLVM compiler. +//! and the KCL program is checked by the KCL compiler. //! //! For example. //! //! 1. If the json file to be verified is as follows: -//! (kclvm/tools/src/vet/test_datas/validate_cases/test.json) +//! (kcl/tools/src/vet/test_datas/validate_cases/test.json) //! //! ```ignore //! { @@ -23,7 +23,7 @@ //! ``` //! //! 2. You can define KCL like below and define validation rules in check block. -//! (kclvm/tools/src/vet/test_datas/validate_cases/test.k) +//! (kcl/tools/src/vet/test_datas/validate_cases/test.k) //! //! ```ignore //! schema User: @@ -46,7 +46,7 @@ //! } //! ``` //! -//! 4. Finally, a KCL program like the following will be handed over to KCLVM to compile and check for problems. +//! 4. Finally, a KCL program like the following will be handed over to KCL to compile and check for problems. //! //! ```ignore //! value = User { @@ -70,12 +70,12 @@ use std::collections::HashMap; use super::expr_builder::ExprBuilder; pub use crate::util::loader::LoaderKind; use anyhow::Result; -use kclvm_ast::{ +use kcl_ast::{ ast::{AssignStmt, Expr, Node, NodeRef, Program, SchemaStmt, Stmt, Target}, node_ref, }; -use kclvm_parser::{LoadProgramOptions, ParseSessionRef}; -use kclvm_runner::{execute, ExecProgramArgs, MapErrorResult}; +use kcl_parser::{LoadProgramOptions, ParseSessionRef}; +use kcl_runner::{ExecProgramArgs, MapErrorResult, execute}; const TMP_FILE: &str = "validationTempKCLCode.k"; @@ -91,7 +91,7 @@ const TMP_FILE: &str = "validationTempKCLCode.k"; /// # Examples /// /// 1. If you want to verify the following json file. -/// (kclvm/tools/src/vet/test_datas/validate_cases/test.json) +/// (kcl/tools/src/vet/test_datas/validate_cases/test.json) /// ```ignore /// { /// "name": "Alice", @@ -101,7 +101,7 @@ const TMP_FILE: &str = "validationTempKCLCode.k"; /// ``` /// /// 2. First, you can create a KCL schema and write validation rules. -/// (kclvm/tools/src/vet/test_datas/validate_cases/test.k) +/// (kcl/tools/src/vet/test_datas/validate_cases/test.k) /// ```ignore /// schema User: /// name: str @@ -115,10 +115,10 @@ const TMP_FILE: &str = "validationTempKCLCode.k"; /// /// 3. Second, you can call this method as follows to validate the content of the json file with the kcl file. /// ``` -/// use kclvm_tools::vet::validator::validate; +/// use kcl_tools::vet::validator::validate; /// use std::path::PathBuf; -/// use kclvm_tools::util::loader::LoaderKind; -/// use kclvm_tools::vet::validator::ValidateOption; +/// use kcl_tools::util::loader::LoaderKind; +/// use kcl_tools::vet::validator::ValidateOption; /// // First get the file path of the file to be verified. /// let mut validated_file_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); /// validated_file_path.push("src/vet/test_datas/validate_cases/test.json"); @@ -162,7 +162,7 @@ const TMP_FILE: &str = "validationTempKCLCode.k"; /// "rust_line": 2203, /// "rust_col": 9, /// "kcl_pkgpath": "__main__", -/// "kcl_file": "kclvm/tools/src/vet/test_datas/invalid_validate_cases/test.json", +/// "kcl_file": "kcl/tools/src/vet/test_datas/invalid_validate_cases/test.json", /// "kcl_line": 7, /// "kcl_col": 0, /// "kcl_arg_msg": "Check failed on the condition", @@ -180,7 +180,7 @@ pub fn validate(val_opt: ValidateOption) -> Result { let k_code = val_opt.kcl_code.map_or_else(Vec::new, |code| vec![code]); let sess = ParseSessionRef::default(); - let compile_res = kclvm_parser::load_program( + let compile_res = kcl_parser::load_program( sess, [k_path] .iter() @@ -209,7 +209,7 @@ pub fn validate(val_opt: ValidateOption) -> Result { let assign_stmt = build_assign(&val_opt.attribute_name, validated_expr); - match compile_res.program.pkgs.get(kclvm_ast::MAIN_PKG) { + match compile_res.program.pkgs.get(kcl_ast::MAIN_PKG) { Some(pkg) => { if let Some(module) = pkg.first() { let mut m = compile_res @@ -251,7 +251,7 @@ fn build_assign(attr_name: &str, node: NodeRef) -> NodeRef { fn filter_schema_stmt_from_prog(prog: &Program) -> Vec { let mut result = vec![]; for (pkg_name, modules) in &prog.pkgs { - if pkg_name != kclvm_ast::MAIN_PKG { + if pkg_name != kcl_ast::MAIN_PKG { continue; } for module in modules { diff --git a/crates/utils/Cargo.toml b/crates/utils/Cargo.toml new file mode 100644 index 000000000..753c6f36d --- /dev/null +++ b/crates/utils/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "kcl-utils" +version.workspace = true +edition.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +anyhow = "1" +regex = "1.3" + + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +fslock = "0.2.1" diff --git a/kclvm/utils/src/fslock.rs b/crates/utils/src/fslock.rs similarity index 100% rename from kclvm/utils/src/fslock.rs rename to crates/utils/src/fslock.rs diff --git a/kclvm/utils/src/lib.rs b/crates/utils/src/lib.rs similarity index 100% rename from kclvm/utils/src/lib.rs rename to crates/utils/src/lib.rs diff --git a/crates/utils/src/path.rs b/crates/utils/src/path.rs new file mode 100644 index 000000000..21e57dcd3 --- /dev/null +++ b/crates/utils/src/path.rs @@ -0,0 +1,151 @@ +//! This file primarily offers utils for working with file paths, +//! enabling them to be automatically formatted according to the OS. + +use std::path::Path; + +/// Util methods for file path prefixes +pub trait PathPrefix { + /// In the Windows system, the file path returned by method [`canonicalize()`], + /// in rust [`PathBuf`] or [`Path`], will include the '\\?\' character, + /// which is prepared for the Windows API. + /// + /// Paths containing "\\?\" may sometimes result in the file being unable to be found. + /// As such, [`adjust_canonicalization()`] is required to remove this '\\?\'. + /// On non-Windows systems, this method does not make any modifications to the file path. + /// + /// For more information about "\\?\", + /// see https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#short-vs-long-names + fn adjust_canonicalization(&self) -> String; +} + +impl

, -) -> Result { - // Parse program. - let opts = args.get_load_program_options(); - let kcl_paths_str = args - .k_filename_list - .iter() - .map(|s| s.as_str()) - .collect::>(); - let mut program = - load_program(sess.clone(), kcl_paths_str.as_slice(), Some(opts), None)?.program; - // Resolve program. - let scope = resolve_program(&mut program); - // Emit parse and resolve errors if exists. - emit_compile_diag_to_string(sess, &scope, false)?; - // When set the common package cache path, lock the package to prevent the - // data competition during compilation of different modules. - if let Ok(cache_path) = std::env::var(KCL_CACHE_PATH_ENV_VAR) { - build_with_lock(args, program, scope, &cache_path, output) - } else { - let temp_dir = std::env::temp_dir(); - build_with_lock(args, program, scope, &temp_dir.to_string_lossy(), output) - } -} - -fn build_with_lock>( - args: &ExecProgramArgs, - program: Program, - scope: ProgramScope, - cache_path: &str, - output: Option

, -) -> Result { - let lock_file = Path::new(&cache_path) - .join(format!("pkg.lock")) - .display() - .to_string(); - let mut lock_file = open_lock_file(&lock_file)?; - lock_file.lock()?; - let artifact = build(args, program, scope, output); - lock_file.unlock()?; - artifact -} - -fn build>( - args: &ExecProgramArgs, - program: Program, - scope: ProgramScope, - output: Option

, -) -> Result { - // Create a temp entry file and the temp dir will be delete automatically. - let temp_dir = tempdir()?; - let temp_dir_path = temp_dir.path().to_str().ok_or(anyhow!( - "Internal error: {}: No such file or directory", - temp_dir.path().display() - ))?; - let temp_entry_file = temp_file(temp_dir_path)?; - - // Link libs into one library. - let lib_suffix = Command::get_lib_suffix(); - // Temporary output of linker - let temp_out_lib_file = if let Some(output) = output { - output - .as_ref() - .to_str() - .ok_or(anyhow!("build output path is not found"))? - .to_string() - } else { - format!("{}{}", temp_entry_file, lib_suffix) - }; - // Generate native libs. - let lib_paths = assembler::KclvmAssembler::new( - program, - scope, - temp_entry_file.clone(), - KclvmLibAssembler::LLVM, - args.get_package_maps_from_external_pkg(), - ) - .gen_libs(args)?; - let lib_path = linker::KclvmLinker::link_all_libs(lib_paths, temp_out_lib_file)?; - - // Return the library artifact. - Artifact::from_path(lib_path) -} - -/// Clean all the tmp files generated during lib generating and linking. -#[inline] -#[cfg(feature = "llvm")] -fn clean_tmp_files(temp_entry_file: &String, lib_suffix: &String) -> Result<()> { - let temp_entry_lib_file = format!("{}{}", temp_entry_file, lib_suffix); - remove_file(&temp_entry_lib_file) -} - -#[inline] -#[cfg(feature = "llvm")] -fn remove_file(file: &str) -> Result<()> { - if Path::new(&file).exists() { - std::fs::remove_file(file)?; - } - Ok(()) -} - -/// Returns a temporary file name consisting of timestamp and process id. -fn temp_file(dir: &str) -> Result { - let timestamp = chrono::Local::now() - .timestamp_nanos_opt() - .unwrap_or_default(); - let id = std::process::id(); - let file = format!("{}_{}", id, timestamp); - std::fs::create_dir_all(dir)?; - Ok(Path::new(dir) - .join(file) - .to_str() - .ok_or(anyhow::anyhow!("{dir} not found"))? - .to_string()) -} - -// [`emit_compile_diag_to_string`] will emit compile diagnostics to string, including parsing and resolving diagnostics. -fn emit_compile_diag_to_string( - sess: ParseSessionRef, - scope: &ProgramScope, - include_warnings: bool, -) -> Result<()> { - let mut res_str = sess.1.write().emit_to_string()?; - let sema_err = scope.emit_diagnostics_to_string(sess.0.clone(), include_warnings); - if let Err(err) = &sema_err { - #[cfg(not(target_os = "windows"))] - res_str.push('\n'); - #[cfg(target_os = "windows")] - res_str.push_str("\r\n"); - res_str.push_str(err); - } - - res_str - .is_empty() - .then(|| Ok(())) - .unwrap_or_else(|| bail!(res_str)) -} diff --git a/kclvm/runner/src/runner.rs b/kclvm/runner/src/runner.rs deleted file mode 100644 index cfa1449c7..000000000 --- a/kclvm/runner/src/runner.rs +++ /dev/null @@ -1,640 +0,0 @@ -use anyhow::{anyhow, Result}; -use kclvm_evaluator::Evaluator; -use std::collections::HashMap; -use std::{cell::RefCell, rc::Rc}; - -use kclvm_ast::ast; -use kclvm_config::{ - modfile::get_vendor_home, - settings::{SettingsFile, SettingsPathBuf}, -}; -use kclvm_error::{Diagnostic, Handler}; -#[cfg(not(target_arch = "wasm32"))] -use kclvm_runtime::kclvm_plugin_init; -#[cfg(feature = "llvm")] -use kclvm_runtime::FFIRunOptions; -use kclvm_runtime::{Context, PanicInfo, RuntimePanicRecord}; -#[cfg(target_arch = "wasm32")] -use once_cell::sync::Lazy; -use serde::{Deserialize, Serialize}; -use std::ffi::OsStr; -use std::os::raw::c_char; - -const RESULT_SIZE: usize = 2048 * 2048; -const KCL_DEBUG_ERROR_ENV_VAR: &str = "KCL_DEBUG_ERROR"; - -#[allow(non_camel_case_types)] -pub type kclvm_char_t = c_char; -#[allow(non_camel_case_types)] -pub type kclvm_size_t = i32; -#[allow(non_camel_case_types)] -pub type kclvm_context_t = std::ffi::c_void; -#[allow(non_camel_case_types)] -pub type kclvm_value_ref_t = std::ffi::c_void; - -/// ExecProgramArgs denotes the configuration required to execute the KCL program. -#[derive(Serialize, Deserialize, Debug, Default, Clone)] -pub struct ExecProgramArgs { - pub work_dir: Option, - pub k_filename_list: Vec, - /// -E key=value - pub external_pkgs: Vec, - pub k_code_list: Vec, - /// -D key=value - pub args: Vec, - /// -O override_spec - pub overrides: Vec, - /// -S path_selector - pub path_selector: Vec, - pub disable_yaml_result: bool, - /// Whether to apply overrides on the source code. - pub print_override_ast: bool, - /// -r --strict-range-check - pub strict_range_check: bool, - /// -n --disable-none - pub disable_none: bool, - /// -v --verbose - pub verbose: i32, - /// -d --debug - pub debug: i32, - /// yaml/json: sort keys - pub sort_keys: bool, - /// Show hidden attributes - pub show_hidden: bool, - /// Whether including schema type in JSON/YAML result - pub include_schema_type_path: bool, - /// Whether to compile only. - pub compile_only: bool, - /// plugin_agent is the address of plugin. - #[serde(skip)] - pub plugin_agent: u64, - /// fast_eval denotes directly executing at the AST level to obtain - /// the result without any form of compilation. - #[serde(skip)] - pub fast_eval: bool, -} - -impl ExecProgramArgs { - /// [`get_package_maps_from_external_pkg`] gets the package name to package path mapping. - pub fn get_package_maps_from_external_pkg(&self) -> HashMap { - let mut package_maps = HashMap::new(); - for external_pkg in &self.external_pkgs { - package_maps.insert(external_pkg.pkg_name.clone(), external_pkg.pkg_path.clone()); - } - package_maps - } - - /// [`set_external_pkg_from_package_maps`] sets the package name to package path mapping. - pub fn set_external_pkg_from_package_maps(&mut self, package_maps: HashMap) { - self.external_pkgs = package_maps - .iter() - .map(|(pkg_name, pkg_path)| ast::ExternalPkg { - pkg_name: pkg_name.clone(), - pkg_path: pkg_path.clone(), - }) - .collect(); - } -} - -/// ExecProgramResult denotes the running result of the KCL program. -#[derive(Serialize, Deserialize, Debug, Default, Clone)] -pub struct ExecProgramResult { - pub json_result: String, - pub yaml_result: String, - pub log_message: String, - pub err_message: String, -} - -pub trait MapErrorResult { - /// Map execute error message into the [`Result::Err`] - fn map_err_to_result(self) -> Result - where - Self: Sized; -} - -impl MapErrorResult for ExecProgramResult { - /// Map execute error message into the [`Result::Err`] - fn map_err_to_result(self) -> Result - where - Self: Sized, - { - if self.err_message.is_empty() { - Ok(self) - } else { - Err(anyhow!(self.err_message)) - } - } -} - -impl MapErrorResult for Result { - /// Map execute error message into the [`Result::Err`] - fn map_err_to_result(self) -> Result - where - Self: Sized, - { - match self { - Ok(result) => result.map_err_to_result(), - Err(err) => Err(err), - } - } -} - -impl ExecProgramArgs { - /// Deserialize an instance of type [ExecProgramArgs] from a string of JSON text. - pub fn from_str(s: &str) -> Self { - if s.trim().is_empty() { - return Default::default(); - } - serde_json::from_str::(s).expect(s) - } - - /// Serialize the [ExecProgramArgs] structure as a String of JSON. - pub fn to_json(&self) -> String { - serde_json::ser::to_string(self).unwrap() - } - - /// Get the input file list. - pub fn get_files(&self) -> Vec<&str> { - self.k_filename_list.iter().map(|s| s.as_str()).collect() - } - - /// Get the [`kclvm_parser::LoadProgramOptions`] from the [`kclvm_runner::ExecProgramArgs`] - pub fn get_load_program_options(&self) -> kclvm_parser::LoadProgramOptions { - kclvm_parser::LoadProgramOptions { - work_dir: self.work_dir.clone().unwrap_or_default(), - vendor_dirs: vec![get_vendor_home()], - package_maps: self.get_package_maps_from_external_pkg(), - k_code_list: self.k_code_list.clone(), - load_plugins: self.plugin_agent > 0, - ..Default::default() - } - } -} - -impl TryFrom for ExecProgramArgs { - type Error = anyhow::Error; - fn try_from(settings: SettingsFile) -> Result { - let mut args = Self::default(); - if let Some(cli_configs) = settings.kcl_cli_configs { - args.k_filename_list = cli_configs.files.unwrap_or_default(); - if args.k_filename_list.is_empty() { - args.k_filename_list = cli_configs.file.unwrap_or_default(); - } - args.strict_range_check = cli_configs.strict_range_check.unwrap_or_default(); - args.disable_none = cli_configs.disable_none.unwrap_or_default(); - args.verbose = cli_configs.verbose.unwrap_or_default() as i32; - args.debug = cli_configs.debug.unwrap_or_default() as i32; - args.sort_keys = cli_configs.sort_keys.unwrap_or_default(); - args.show_hidden = cli_configs.show_hidden.unwrap_or_default(); - args.fast_eval = cli_configs.fast_eval.unwrap_or_default(); - args.include_schema_type_path = - cli_configs.include_schema_type_path.unwrap_or_default(); - for override_str in cli_configs.overrides.unwrap_or_default() { - args.overrides.push(override_str); - } - args.path_selector = cli_configs.path_selector.unwrap_or_default(); - args.set_external_pkg_from_package_maps( - cli_configs.package_maps.unwrap_or(HashMap::default()), - ) - } - if let Some(options) = settings.kcl_options { - args.args = options - .iter() - .map(|o| ast::Argument { - name: o.key.to_string(), - value: o.value.to_string(), - }) - .collect(); - } - Ok(args) - } -} - -impl TryFrom for ExecProgramArgs { - type Error = anyhow::Error; - fn try_from(s: SettingsPathBuf) -> Result { - let mut args: ExecProgramArgs = s.settings().clone().try_into()?; - args.work_dir = s.path().clone().map(|p| p.to_string_lossy().to_string()); - Ok(args) - } -} - -#[derive(Debug, Default)] -pub struct RunnerOptions { - pub plugin_agent_ptr: u64, -} - -#[cfg(feature = "llvm")] -/// A public struct named [Artifact] which wraps around the native library [libloading::Library]. -pub struct Artifact(libloading::Library, String); -#[cfg(not(feature = "llvm"))] -pub struct Artifact(String); - -pub trait ProgramRunner { - /// Run with the arguments [ExecProgramArgs] and return the program execute result that - /// contains the planning result and the evaluation errors if any. - fn run(&self, args: &ExecProgramArgs) -> Result; -} - -impl ProgramRunner for Artifact { - fn run(&self, args: &ExecProgramArgs) -> Result { - #[cfg(feature = "llvm")] - unsafe { - LibRunner::lib_kclvm_plugin_init(&self.0, args.plugin_agent)?; - LibRunner::lib_kcl_run(&self.0, args) - } - #[cfg(not(feature = "llvm"))] - { - let _ = args; - Err(anyhow::anyhow!("error: llvm feature is not enabled. Note: Set KCL_FAST_EVAL=1 or rebuild the crate with the llvm feature.")) - } - } -} - -#[cfg(feature = "llvm")] -impl Artifact { - #[inline] - pub fn from_path>(path: P) -> Result { - let path = path.as_ref().to_str().unwrap().to_string(); - let lib = unsafe { libloading::Library::new(&path)? }; - Ok(Self(lib, path)) - } - - #[inline] - pub fn get_path(&self) -> &String { - &self.1 - } -} - -#[cfg(not(feature = "llvm"))] -impl Artifact { - #[inline] - pub fn from_path>(path: P) -> Result { - let path = path.as_ref().to_str().unwrap().to_string(); - Ok(Self(path)) - } - - #[inline] - pub fn get_path(&self) -> &String { - &self.0 - } -} - -#[cfg(feature = "llvm")] -pub struct LibRunner { - opts: RunnerOptions, -} - -#[cfg(feature = "llvm")] -impl LibRunner { - /// New a runner using the lib path and options. - pub fn new(opts: Option) -> Self { - Self { - opts: opts.unwrap_or_default(), - } - } - - /// Run kcl library with exec arguments. - pub fn run(&self, lib_path: &str, args: &ExecProgramArgs) -> Result { - unsafe { - let lib = libloading::Library::new(std::path::PathBuf::from(lib_path).canonicalize()?)?; - Self::lib_kclvm_plugin_init(&lib, self.opts.plugin_agent_ptr)?; - Self::lib_kcl_run(&lib, args) - } - } -} - -#[cfg(feature = "llvm")] -impl LibRunner { - unsafe fn lib_kclvm_plugin_init( - lib: &libloading::Library, - plugin_method_ptr: u64, - ) -> Result<()> { - // get kclvm_plugin_init - let kclvm_plugin_init: libloading::Symbol< - unsafe extern "C-unwind" fn( - fn_ptr: extern "C-unwind" fn( - method: *const c_char, - args_json: *const c_char, - kwargs_json: *const c_char, - ) -> *const c_char, - ), - > = lib.get(b"kclvm_plugin_init")?; - - // get plugin_method - let plugin_method_ptr = plugin_method_ptr; - let plugin_method_ptr = (plugin_method_ptr as *const u64) as *const () - as *const extern "C-unwind" fn( - method: *const c_char, - args: *const c_char, - kwargs: *const c_char, - ) -> *const c_char; - let plugin_method: extern "C-unwind" fn( - method: *const c_char, - args: *const c_char, - kwargs: *const c_char, - ) -> *const c_char = std::mem::transmute(plugin_method_ptr); - - // register plugin agent - kclvm_plugin_init(plugin_method); - Ok(()) - } - - unsafe fn lib_kcl_run( - lib: &libloading::Library, - args: &ExecProgramArgs, - ) -> Result { - let kcl_run: libloading::Symbol< - unsafe extern "C-unwind" fn( - kclvm_main_ptr: u64, // main.k => kclvm_main - option_len: kclvm_size_t, - option_keys: *const *const kclvm_char_t, - option_values: *const *const kclvm_char_t, - opts: FFIRunOptions, - path_selector: *const *const kclvm_char_t, - json_result_buffer_len: *mut kclvm_size_t, - json_result_buffer: *mut kclvm_char_t, - yaml_result_buffer_len: *mut kclvm_size_t, - yaml_result_buffer: *mut kclvm_char_t, - err_buffer_len: *mut kclvm_size_t, - err_buffer: *mut kclvm_char_t, - log_buffer_len: *mut kclvm_size_t, - log_buffer: *mut kclvm_char_t, - ) -> kclvm_size_t, - > = lib.get(b"_kcl_run")?; - - // The lib main function - let kclvm_main: libloading::Symbol = lib.get(b"kclvm_main")?; - let kclvm_main_ptr = kclvm_main.into_raw().into_raw() as u64; - - // CLI configs option len - let option_len = args.args.len() as kclvm_size_t; - // CLI configs option keys - let cstr_argv: Vec<_> = args - .args - .iter() - .map(|arg| std::ffi::CString::new(arg.name.as_str()).unwrap()) - .collect(); - let mut p_argv: Vec<_> = cstr_argv - .iter() // do NOT into_iter() - .map(|arg| arg.as_ptr()) - .collect(); - p_argv.push(std::ptr::null()); - let option_keys = p_argv.as_ptr(); - // CLI configs option values - let cstr_argv: Vec<_> = args - .args - .iter() - .map(|arg| std::ffi::CString::new(arg.value.as_str()).unwrap()) - .collect(); - let mut p_argv: Vec<_> = cstr_argv - .iter() // do NOT into_iter() - .map(|arg| arg.as_ptr()) - .collect(); - p_argv.push(std::ptr::null()); - let option_values = p_argv.as_ptr(); - // path selectors - let cstr_argv: Vec<_> = args - .path_selector - .iter() - .map(|arg| std::ffi::CString::new(arg.as_str()).unwrap()) - .collect(); - let mut p_argv: Vec<_> = cstr_argv - .iter() // do NOT into_iter() - .map(|arg| arg.as_ptr()) - .collect(); - p_argv.push(std::ptr::null()); - let path_selector = p_argv.as_ptr(); - - let opts = FFIRunOptions { - strict_range_check: args.strict_range_check as i32, - disable_none: args.disable_none as i32, - disable_schema_check: 0, - disable_empty_list: 0, - sort_keys: args.sort_keys as i32, - show_hidden: args.show_hidden as i32, - debug_mode: args.debug, - include_schema_type_path: args.include_schema_type_path as i32, - }; - let mut json_buffer = Buffer::make(); - let mut yaml_buffer = Buffer::make(); - let mut log_buffer = Buffer::make(); - let mut err_buffer = Buffer::make(); - // Input the main function, options and return the exec result - // including JSON and YAML result, log message and error message. - kcl_run( - kclvm_main_ptr, - option_len, - option_keys, - option_values, - opts, - path_selector, - json_buffer.mut_len(), - json_buffer.mut_ptr(), - yaml_buffer.mut_len(), - yaml_buffer.mut_ptr(), - err_buffer.mut_len(), - err_buffer.mut_ptr(), - log_buffer.mut_len(), - log_buffer.mut_ptr(), - ); - // Convert runtime result to ExecProgramResult - let mut result = ExecProgramResult { - yaml_result: yaml_buffer.to_string()?, - json_result: json_buffer.to_string()?, - log_message: log_buffer.to_string()?, - err_message: err_buffer.to_string()?, - }; - // Wrap runtime JSON Panic error string into diagnostic style string. - if !result.err_message.is_empty() && std::env::var(KCL_DEBUG_ERROR_ENV_VAR).is_err() { - result.err_message = match Handler::default() - .add_diagnostic(>::into(PanicInfo::from( - result.err_message.as_str(), - ))) - .emit_to_string() - { - Ok(msg) => msg, - Err(err) => err.to_string(), - }; - } - Ok(result) - } -} - -thread_local! { - pub static KCL_RUNTIME_PANIC_RECORD: RefCell = RefCell::new(RuntimePanicRecord::default()) -} - -#[cfg(target_arch = "wasm32")] -static ONCE_PANIC_HOOK: Lazy<()> = Lazy::new(|| { - std::panic::set_hook(Box::new(|info: &std::panic::PanicHookInfo| { - KCL_RUNTIME_PANIC_RECORD.with(|record| { - let mut record = record.borrow_mut(); - record.kcl_panic_info = true; - record.message = if let Some(s) = info.payload().downcast_ref::<&str>() { - s.to_string() - } else if let Some(s) = info.payload().downcast_ref::<&String>() { - (*s).clone() - } else if let Some(s) = info.payload().downcast_ref::() { - (*s).clone() - } else { - "unknown runtime error".to_string() - }; - if let Some(location) = info.location() { - record.rust_file = location.file().to_string(); - record.rust_line = location.line() as i32; - record.rust_col = location.column() as i32; - } - }) - })); -}); - -pub struct FastRunner { - opts: RunnerOptions, -} - -impl FastRunner { - /// New a runner using the lib path and options. - pub fn new(opts: Option) -> Self { - Self { - opts: opts.unwrap_or_default(), - } - } - - /// Run kcl library with exec arguments. - pub fn run(&self, program: &ast::Program, args: &ExecProgramArgs) -> Result { - let ctx = Rc::new(RefCell::new(args_to_ctx(program, args))); - let evaluator = Evaluator::new_with_runtime_ctx(program, ctx.clone()); - #[cfg(target_arch = "wasm32")] - // Ensure the panic hook is set (this will only happen once) for the WASM target, - // because it is single threaded. - Lazy::force(&ONCE_PANIC_HOOK); - #[cfg(not(target_arch = "wasm32"))] - let prev_hook = std::panic::take_hook(); - #[cfg(not(target_arch = "wasm32"))] - std::panic::set_hook(Box::new(|info: &std::panic::PanicHookInfo| { - KCL_RUNTIME_PANIC_RECORD.with(|record| { - let mut record = record.borrow_mut(); - record.kcl_panic_info = true; - record.message = if let Some(s) = info.payload().downcast_ref::<&str>() { - s.to_string() - } else if let Some(s) = info.payload().downcast_ref::<&String>() { - (*s).clone() - } else if let Some(s) = info.payload().downcast_ref::() { - (*s).clone() - } else { - "unknown runtime error".to_string() - }; - if let Some(location) = info.location() { - record.rust_file = location.file().to_string(); - record.rust_line = location.line() as i32; - record.rust_col = location.column() as i32; - } - }) - })); - let evaluator_result = std::panic::catch_unwind(|| { - if self.opts.plugin_agent_ptr > 0 { - #[cfg(not(target_arch = "wasm32"))] - unsafe { - let plugin_method: extern "C-unwind" fn( - method: *const c_char, - args: *const c_char, - kwargs: *const c_char, - ) -> *const c_char = std::mem::transmute(self.opts.plugin_agent_ptr); - kclvm_plugin_init(plugin_method); - } - } - evaluator.run() - }); - #[cfg(not(target_arch = "wasm32"))] - std::panic::set_hook(prev_hook); - KCL_RUNTIME_PANIC_RECORD.with(|record| { - let record = record.borrow(); - ctx.borrow_mut().set_panic_info(&record); - }); - let mut result = ExecProgramResult { - log_message: ctx.borrow().log_message.clone(), - ..Default::default() - }; - let is_err = evaluator_result.is_err(); - match evaluator_result { - Ok(r) => match r { - Ok((json, yaml)) => { - result.json_result = json; - result.yaml_result = yaml; - } - Err(err) => { - result.err_message = err.to_string(); - } - }, - Err(err) => { - result.err_message = if is_err { - ctx.borrow() - .get_panic_info_json_string() - .unwrap_or_default() - } else { - kclvm_error::err_to_str(err) - }; - } - } - // Wrap runtime JSON Panic error string into diagnostic style string. - if !result.err_message.is_empty() && std::env::var(KCL_DEBUG_ERROR_ENV_VAR).is_err() { - result.err_message = match Handler::default() - .add_diagnostic(>::into(PanicInfo::from( - result.err_message.as_str(), - ))) - .emit_to_string() - { - Ok(msg) => msg, - Err(err) => err.to_string(), - }; - } - // Free all value references at runtime. This is because the runtime context marks - // all KCL objects and holds their copies, so it is necessary to actively GC them. - ctx.borrow().gc(); - Ok(result) - } -} - -pub(crate) fn args_to_ctx(program: &ast::Program, args: &ExecProgramArgs) -> Context { - let mut ctx = Context::new(); - ctx.cfg.strict_range_check = args.strict_range_check; - ctx.cfg.debug_mode = args.debug != 0; - ctx.plan_opts.disable_none = args.disable_none; - ctx.plan_opts.show_hidden = args.show_hidden; - ctx.plan_opts.sort_keys = args.sort_keys; - ctx.plan_opts.include_schema_type_path = args.include_schema_type_path; - ctx.plan_opts.query_paths = args.path_selector.clone(); - for arg in &args.args { - ctx.builtin_option_init(&arg.name, &arg.value); - } - ctx.set_kcl_workdir(&args.work_dir.clone().unwrap_or_default()); - ctx.set_kcl_module_path(&program.root); - ctx -} - -#[repr(C)] -pub struct Buffer(Vec, i32); - -impl Buffer { - #[inline] - pub fn make() -> Self { - let buffer = vec![0u8; RESULT_SIZE]; - Self(buffer, RESULT_SIZE as i32 - 1) - } - - #[inline] - pub fn to_string(&self) -> anyhow::Result { - Ok(String::from_utf8(self.0[0..self.1 as usize].to_vec())?) - } - - #[inline] - pub fn mut_ptr(&mut self) -> *mut c_char { - self.0.as_mut_ptr() as *mut c_char - } - - #[inline] - pub fn mut_len(&mut self) -> &mut i32 { - &mut self.1 - } -} diff --git a/kclvm/runner/src/test_datas/settings_file/settings.json b/kclvm/runner/src/test_datas/settings_file/settings.json deleted file mode 100644 index b3567f2ea..000000000 --- a/kclvm/runner/src/test_datas/settings_file/settings.json +++ /dev/null @@ -1 +0,0 @@ -{"work_dir":null,"k_filename_list":["../main.k","./before/base.k","./main.k","./sub/sub.k"],"external_pkgs":[],"k_code_list":[],"args":[{"name":"app-name","value":"\"kclvm\""},{"name":"image","value":"\"kclvm:v0.0.1\""}],"overrides":[],"path_selector":[],"disable_yaml_result":false,"print_override_ast":false,"strict_range_check":false,"disable_none":false,"verbose":0,"debug":0,"sort_keys":false,"show_hidden":false,"include_schema_type_path":false,"compile_only":false} \ No newline at end of file diff --git a/kclvm/runner/src/test_datas/settings_file/settings.yaml b/kclvm/runner/src/test_datas/settings_file/settings.yaml deleted file mode 100644 index 8b7a8a399..000000000 --- a/kclvm/runner/src/test_datas/settings_file/settings.yaml +++ /dev/null @@ -1,14 +0,0 @@ -kcl_cli_configs: - files: - - ../main.k - - ./before/base.k - - ./main.k - - ./sub/sub.k - disable_none: false - strict_range_check: false - debug: false -kcl_options: - - key: app-name - value: kclvm - - key: image - value: kclvm:v0.0.1 diff --git a/kclvm/runner/src/tests.rs b/kclvm/runner/src/tests.rs deleted file mode 100644 index d04f55d6d..000000000 --- a/kclvm/runner/src/tests.rs +++ /dev/null @@ -1,737 +0,0 @@ -#[cfg(feature = "llvm")] -use crate::assembler::clean_path; -#[cfg(feature = "llvm")] -use crate::assembler::KclvmAssembler; -#[cfg(feature = "llvm")] -use crate::assembler::KclvmLibAssembler; -#[cfg(feature = "llvm")] -use crate::assembler::LibAssembler; -use crate::exec_program; -#[cfg(feature = "llvm")] -use crate::temp_file; -use crate::{execute, runner::ExecProgramArgs}; -#[cfg(feature = "llvm")] -use anyhow::Context; -use anyhow::Result; -use kclvm_ast::ast::{Module, Program}; -#[cfg(feature = "llvm")] -use kclvm_compiler::codegen::OBJECT_FILE_SUFFIX; -use kclvm_config::settings::load_file; -use kclvm_parser::load_program; -use kclvm_parser::ParseSession; -#[cfg(feature = "llvm")] -use kclvm_sema::resolver::resolve_program; -use kclvm_utils::path::PathPrefix; -use serde_json::Value; -#[cfg(feature = "llvm")] -use std::fs::create_dir_all; -use std::path::{Path, PathBuf}; -use std::sync::Arc; -use std::sync::RwLock; -use std::{ - collections::HashMap, - fs::{self, File}, -}; -#[cfg(feature = "llvm")] -use tempfile::tempdir; -use uuid::Uuid; -use walkdir::WalkDir; - -#[cfg(feature = "llvm")] -const MULTI_FILE_TEST_CASES: &[&str; 5] = &[ - "no_kcl_mod_file", - "relative_import", - "relative_import_as", - "import_regular_module", - "import_regular_module_as", -]; - -const TEST_CASES: &[&str; 5] = &[ - "init_check_order_0", - "init_check_order_1", - "normal_2", - "type_annotation_not_full_2", - "multi_vars_0", -]; - -fn exec_data_path() -> String { - Path::new("src").join("exec_data").display().to_string() -} - -fn exec_err_data_path() -> String { - Path::new("src").join("exec_err_data").display().to_string() -} - -fn custom_manifests_data_path() -> String { - Path::new("src") - .join("custom_manifests_data") - .display() - .to_string() -} - -#[cfg(feature = "llvm")] -fn multi_file_test_cases() -> Vec { - let mut test_cases: Vec = MULTI_FILE_TEST_CASES - .iter() - .map(|case| { - Path::new("multi_file_compilation") - .join(case) - .display() - .to_string() - }) - .collect(); - - test_cases.push( - Path::new("multi_file_compilation") - .join("import_abs_path") - .join("app-main") - .display() - .to_string(), - ); - test_cases.push( - Path::new("..") - .join("..") - .join("..") - .join("..") - .join("test") - .join("integration") - .join("konfig") - .join("base") - .join("examples") - .join("job-example") - .join("dev") - .display() - .to_string(), - ); - - test_cases -} - -fn exec_prog_args_test_case() -> Vec { - vec![Path::new("exec_prog_args") - .join("default.json") - .display() - .to_string()] -} - -fn settings_file_test_case() -> Vec<(String, String)> { - vec![( - Path::new("settings_file") - .join("settings.yaml") - .display() - .to_string(), - Path::new("settings_file") - .join("settings.json") - .display() - .to_string(), - )] -} - -const EXPECTED_JSON_FILE_NAME: &str = "stdout.golden.json"; - -fn test_case_path() -> String { - Path::new("src").join("test_datas").display().to_string() -} - -const KCL_FILE_NAME: &str = "main.k"; -const MAIN_PKG_NAME: &str = "__main__"; -#[cfg(feature = "llvm")] -const CARGO_PATH: &str = env!("CARGO_MANIFEST_DIR"); - -#[derive(serde::Deserialize, serde::Serialize)] -struct SimplePanicInfo { - line: i32, - col: i32, - message: String, -} - -#[cfg(feature = "llvm")] -fn gen_full_path(rel_path: String) -> Result { - let mut cargo_file_path = PathBuf::from(CARGO_PATH); - cargo_file_path.push(&rel_path); - let full_path = cargo_file_path - .to_str() - .with_context(|| format!("No such file or directory '{}'", rel_path))?; - Ok(full_path.to_string()) -} - -/// Load test kcl file to ast.Program -fn load_test_program(filename: String) -> Program { - let module = kclvm_parser::parse_file_force_errors(&filename, None).unwrap(); - construct_program(module) -} - -#[cfg(feature = "llvm")] -fn parse_program(test_kcl_case_path: &str) -> Program { - let args = ExecProgramArgs::default(); - let opts = args.get_load_program_options(); - load_program( - Arc::new(ParseSession::default()), - &[test_kcl_case_path], - Some(opts), - None, - ) - .unwrap() - .program -} - -/// Construct ast.Program by ast.Module and default configuration. -/// Default configuration: -/// module.pkg = "__main__" -/// Program.root = "__main__" -fn construct_program(module: Module) -> Program { - let mut pkgs_ast = HashMap::new(); - pkgs_ast.insert(MAIN_PKG_NAME.to_string(), vec![module.filename.clone()]); - let mut modules = HashMap::new(); - modules.insert(module.filename.clone(), Arc::new(RwLock::new(module))); - Program { - root: MAIN_PKG_NAME.to_string(), - pkgs: pkgs_ast, - modules, - pkgs_not_imported: HashMap::new(), - modules_not_imported: HashMap::new(), - } -} - -#[cfg(feature = "llvm")] -fn construct_pkg_lib_path( - prog: &Program, - assembler: &KclvmAssembler, - main_path: &str, - suffix: String, -) -> Vec { - let cache_dir = assembler.construct_cache_dir(&prog.root); - let mut result = vec![]; - for (pkgpath, _) in &prog.pkgs { - if pkgpath == "__main__" { - result.push(PathBuf::from(format!("{}{}", main_path, suffix))); - } else { - result.push(cache_dir.join(format!("{}{}", pkgpath.clone(), suffix))); - } - } - result -} - -/// Load the expect result from stdout.golden.json -fn load_expect_file(filename: String) -> String { - let f = File::open(filename).unwrap(); - let v: serde_json::Value = serde_json::from_reader(f).unwrap(); - v.to_string() -} - -/// Format str by json str -fn format_str_by_json(str: String) -> String { - let v: serde_json::Value = serde_json::from_str(&str).unwrap(); - v.to_string() -} - -fn execute_for_test(kcl_path: &String) -> String { - let args = ExecProgramArgs::default(); - // Parse kcl file - let program = load_test_program(kcl_path.to_string()); - // Generate libs, link libs and execute. - execute(Arc::new(ParseSession::default()), program, &args) - .unwrap() - .json_result -} - -#[cfg(feature = "llvm")] -fn gen_assembler(entry_file: &str, test_kcl_case_path: &str) -> KclvmAssembler { - let mut prog = parse_program(test_kcl_case_path); - let scope = resolve_program(&mut prog); - KclvmAssembler::new( - prog.clone(), - scope, - entry_file.to_string(), - KclvmLibAssembler::LLVM, - HashMap::new(), - ) -} - -#[cfg(feature = "llvm")] -fn gen_libs_for_test(entry_file: &str, test_kcl_case_path: &str) { - let assembler = gen_assembler(entry_file, test_kcl_case_path); - - let expected_pkg_paths = construct_pkg_lib_path( - &parse_program(test_kcl_case_path), - &assembler, - PathBuf::from(entry_file).to_str().unwrap(), - OBJECT_FILE_SUFFIX.to_string(), - ); - - let lib_paths = assembler.gen_libs(&ExecProgramArgs::default()).unwrap(); - - assert_eq!(lib_paths.len(), expected_pkg_paths.len()); - - for pkg_path in &expected_pkg_paths { - assert_eq!(pkg_path.exists(), true); - } - - let tmp_main_lib_path = - fs::canonicalize(format!("{}{}", entry_file, OBJECT_FILE_SUFFIX)).unwrap(); - assert_eq!(tmp_main_lib_path.exists(), true); - - clean_path(tmp_main_lib_path.to_str().unwrap()).unwrap(); - assert_eq!(tmp_main_lib_path.exists(), false); -} - -#[cfg(feature = "llvm")] -fn assemble_lib_for_test( - entry_file: &str, - test_kcl_case_path: &str, - assembler: &KclvmLibAssembler, -) -> String { - // default args and configuration - let mut args = ExecProgramArgs::default(); - - args.k_filename_list.push(test_kcl_case_path.to_string()); - let files = args.get_files(); - let opts = args.get_load_program_options(); - let sess = Arc::new(ParseSession::default()); - // parse and resolve kcl - let mut program = load_program(sess, &files, Some(opts), None) - .unwrap() - .program; - - let scope = resolve_program(&mut program); - - // tmp file - let temp_entry_file_path = &format!("{}{}", entry_file, OBJECT_FILE_SUFFIX); - - // Assemble object files - assembler - .assemble( - &program, - scope.import_names, - entry_file, - temp_entry_file_path, - &ExecProgramArgs::default(), - ) - .unwrap() -} - -fn test_kclvm_runner_execute() { - for case in TEST_CASES { - let kcl_path = &Path::new(&test_case_path()) - .join(case) - .join(KCL_FILE_NAME) - .display() - .to_string(); - let expected_path = &Path::new(&test_case_path()) - .join(case) - .join(EXPECTED_JSON_FILE_NAME) - .display() - .to_string(); - let result = execute_for_test(kcl_path); - let expected_result = load_expect_file(expected_path.to_string()); - assert_eq!(expected_result, format_str_by_json(result)); - } -} - -#[test] -#[cfg(feature = "llvm")] -fn test_assemble_lib_llvm() { - for case in TEST_CASES { - let temp_dir = tempdir().unwrap(); - let temp_dir_path = temp_dir.path().to_str().unwrap(); - let temp_entry_file = temp_file(temp_dir_path).unwrap(); - let kcl_path = &Path::new(&test_case_path()) - .join(case) - .join(KCL_FILE_NAME) - .display() - .to_string(); - let assembler = &KclvmLibAssembler::LLVM; - - let lib_file = assemble_lib_for_test( - &format!("{}{}", temp_entry_file, "4assemble_lib"), - kcl_path, - assembler, - ); - - let lib_path = std::path::Path::new(&lib_file); - assert_eq!(lib_path.exists(), true); - clean_path(&lib_file).unwrap(); - assert_eq!(lib_path.exists(), false); - } -} - -#[test] -#[cfg(feature = "llvm")] -fn test_gen_libs() { - for case in multi_file_test_cases() { - let temp_dir = tempdir().unwrap(); - let temp_dir_path = temp_dir.path().to_str().unwrap(); - let temp_entry_file = temp_file(temp_dir_path).unwrap(); - - let kcl_path = gen_full_path( - Path::new(&test_case_path()) - .join(case) - .join(KCL_FILE_NAME) - .display() - .to_string(), - ) - .unwrap(); - gen_libs_for_test(&format!("{}{}", temp_entry_file, "4gen_libs"), &kcl_path); - } -} - -#[test] -#[cfg(feature = "llvm")] -fn test_clean_path_for_genlibs() { - let mut prog = parse_program( - &Path::new(".") - .join("src") - .join("test_datas") - .join("multi_file_compilation") - .join("import_abs_path") - .join("app-main") - .join("main.k") - .display() - .to_string(), - ); - let scope = resolve_program(&mut prog); - let assembler = KclvmAssembler::new( - prog, - scope, - String::new(), - KclvmLibAssembler::LLVM, - HashMap::new(), - ); - - let temp_dir = tempdir().unwrap(); - let temp_dir_path = temp_dir.path().to_str().unwrap(); - let tmp_file_path = &temp_file(temp_dir_path).unwrap(); - - create_dir_all(tmp_file_path).unwrap(); - - let file_name = &Path::new(tmp_file_path).join("test").display().to_string(); - let file_suffix = ".o"; - - File::create(file_name).unwrap(); - let path = std::path::Path::new(file_name); - assert_eq!(path.exists(), true); - - assembler - .clean_path_for_genlibs(file_name, file_suffix) - .unwrap(); - assert_eq!(path.exists(), false); - - let test1 = &format!("{}{}", file_name, ".test1.o"); - let test2 = &format!("{}{}", file_name, ".test2.o"); - File::create(test1).unwrap(); - File::create(test2).unwrap(); - let path1 = std::path::Path::new(test1); - - let path2 = std::path::Path::new(test2); - assert_eq!(path1.exists(), true); - assert_eq!(path2.exists(), true); - - assembler - .clean_path_for_genlibs(file_name, file_suffix) - .unwrap(); - assert_eq!(path1.exists(), false); - assert_eq!(path2.exists(), false); -} - -#[test] -fn test_to_json_program_arg() { - for case in exec_prog_args_test_case() { - let test_case_json_file = &Path::new(&test_case_path()) - .join(case) - .display() - .to_string(); - let expected_json_str = fs::read_to_string(test_case_json_file).unwrap(); - let exec_prog_args = ExecProgramArgs::default(); - assert_eq!(expected_json_str.trim(), exec_prog_args.to_json().trim()); - } -} - -#[test] -fn test_from_str_program_arg() { - for case in exec_prog_args_test_case() { - let test_case_json_file = &Path::new(&test_case_path()) - .join(case) - .display() - .to_string(); - let expected_json_str = fs::read_to_string(test_case_json_file).unwrap(); - let exec_prog_args = ExecProgramArgs::from_str(&expected_json_str); - assert_eq!(expected_json_str.trim(), exec_prog_args.to_json().trim()); - } -} - -#[test] -fn test_from_setting_file_program_arg() { - for (case_yaml, case_json) in settings_file_test_case() { - let test_case_yaml_file = &Path::new(&test_case_path()) - .join(case_yaml) - .display() - .to_string(); - let settings_file = load_file(test_case_yaml_file).unwrap(); - - let test_case_json_file = &Path::new(&test_case_path()) - .join(case_json) - .display() - .to_string(); - let expected_json_str = fs::read_to_string(test_case_json_file).unwrap(); - - let exec_prog_args = ExecProgramArgs::try_from(settings_file).unwrap(); - assert_eq!(expected_json_str.trim(), exec_prog_args.to_json().trim()); - } -} - -fn test_exec_file() { - let result = std::panic::catch_unwind(|| { - for file in get_files(exec_data_path(), false, true, ".k") { - exec(&file).unwrap(); - println!("{} - PASS", file); - } - }); - assert!(result.is_ok()); -} - -fn test_custom_manifests_output() { - exec_with_result_at(&custom_manifests_data_path()); -} - -fn test_exec_with_err_result() { - exec_with_err_result_at(&exec_err_data_path()); -} - -fn clean_dir(path: String) { - if let Ok(_) = fs::remove_dir_all(path) {} -} - -#[test] -fn test_exec() { - clean_dir( - Path::new(".") - .join("src") - .join("exec_data") - .join(".kclvm") - .display() - .to_string(), - ); - - clean_dir( - Path::new(".") - .join("src") - .join("exec_err_data") - .join(".kclvm") - .display() - .to_string(), - ); - - test_exec_file(); - println!("test_exec_file - PASS"); - - test_kclvm_runner_execute(); - println!("test_kclvm_runner_execute - PASS"); - - test_custom_manifests_output(); - println!("test_custom_manifests_output - PASS"); - - test_exec_with_err_result(); - println!("test_exec_with_err_result - PASS"); - - test_indent_error(); - println!("test_indent_error - PASS"); - - test_compile_with_file_pattern(); - println!("test_compile_with_file_pattern - PASS"); - - test_uuid(); - println!("test_uuid - PASS"); -} - -fn test_indent_error() { - let test_path = PathBuf::from("./src/test_indent_error"); - let kcl_files = get_files(test_path.clone(), false, true, ".k"); - let output_files = get_files(test_path, false, true, ".stderr"); - - for (kcl_file, err_file) in kcl_files.iter().zip(&output_files) { - let mut args = ExecProgramArgs::default(); - args.k_filename_list.push(kcl_file.to_string()); - let res = exec_program(Arc::new(ParseSession::default()), &args); - assert!(res.is_err()); - if let Err(err_msg) = res { - let expect_err = fs::read_to_string(err_file).expect("Failed to read file"); - assert!(err_msg.to_string().contains(&expect_err)); - } - } -} - -fn exec(file: &str) -> Result { - let mut args = ExecProgramArgs::default(); - args.k_filename_list.push(file.to_string()); - let opts = args.get_load_program_options(); - let sess = Arc::new(ParseSession::default()); - // Load AST program - let program = load_program(sess.clone(), &[file], Some(opts), None) - .unwrap() - .program; - // Resolve ATS, generate libs, link libs and execute. - match execute(sess, program, &args) { - Ok(result) => { - if result.err_message.is_empty() { - Ok(result.json_result) - } else { - Err(result.err_message) - } - } - Err(err) => Err(err.to_string()), - } -} - -/// Run all kcl files at path and compare the exec result with the expect output. -fn exec_with_result_at(path: &str) { - let kcl_files = get_files(path, false, true, ".k"); - let output_files = get_files(path, false, true, ".stdout.golden"); - for (kcl_file, output_file) in kcl_files.iter().zip(&output_files) { - let mut args = ExecProgramArgs::default(); - args.k_filename_list.push(kcl_file.to_string()); - let result = exec_program(Arc::new(ParseSession::default()), &args).unwrap(); - - #[cfg(not(target_os = "windows"))] - let newline = "\n"; - #[cfg(target_os = "windows")] - let newline = "\r\n"; - - let expected = std::fs::read_to_string(output_file) - .unwrap() - .strip_suffix(newline) - .unwrap() - .to_string(); - - #[cfg(target_os = "windows")] - let expected = expected.replace("\r\n", "\n"); - - assert_eq!( - result.yaml_result, expected, - "test case {} {} failed", - path, kcl_file - ); - } -} - -/// Run all kcl files at path and compare the exec error result with the expect error output. -fn exec_with_err_result_at(path: &str) { - let kcl_files = get_files(path, false, true, ".k"); - let output_files = get_files(path, false, true, ".stderr.json"); - - let prev_hook = std::panic::take_hook(); - // disable print panic info - std::panic::set_hook(Box::new(|_| {})); - let result = std::panic::catch_unwind(|| { - for (kcl_file, _) in kcl_files.iter().zip(&output_files) { - let mut args = ExecProgramArgs::default(); - args.k_filename_list.push(kcl_file.to_string()); - let result = exec_program(Arc::new(ParseSession::default()), &args); - if let Ok(result) = result { - assert!(!result.err_message.is_empty(), "{}", result.err_message); - } else { - assert!(result.is_err()); - } - } - }); - assert!(result.is_ok()); - std::panic::set_hook(prev_hook); -} - -/// Get kcl files from path. -fn get_files>( - path: P, - recursively: bool, - sorted: bool, - suffix: &str, -) -> Vec { - let mut files = vec![]; - for entry in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) { - let path = entry.path(); - if path.is_file() { - let file = path.to_str().unwrap(); - if file.ends_with(suffix) && (recursively || entry.depth() == 1) { - files.push(file.to_string()) - } - } - } - if sorted { - files.sort(); - } - files -} - -fn test_compile_with_file_pattern() { - let test_path = PathBuf::from("./src/test_file_pattern/**/main.k"); - let mut args = ExecProgramArgs::default(); - args.k_filename_list.push(test_path.display().to_string()); - let res = exec_program(Arc::new(ParseSession::default()), &args); - assert!(res.is_ok()); - assert_eq!( - res.as_ref().unwrap().yaml_result, - "k3: Hello World!\nk1: Hello World!\nk2: Hello World!" - ); - assert_eq!( - res.as_ref().unwrap().json_result, - "{\"k3\": \"Hello World!\", \"k1\": \"Hello World!\", \"k2\": \"Hello World!\"}" - ); -} - -fn test_uuid() { - let res = exec( - &PathBuf::from(".") - .join("src") - .join("test_uuid") - .join("main.k") - .canonicalize() - .unwrap() - .display() - .to_string(), - ); - - let v: Value = serde_json::from_str(res.clone().unwrap().as_str()).unwrap(); - assert!(v["a"].as_str().is_some()); - if let Some(uuid_str) = v["a"].as_str() { - assert!(Uuid::parse_str(uuid_str).is_ok()); - } -} - -#[test] -fn test_compile_with_symbolic_link() { - let main_test_path = PathBuf::from("./src/test_symbolic_link/test_pkg/bbb/main.k"); - let mut args = ExecProgramArgs::default(); - args.k_filename_list - .push(main_test_path.display().to_string()); - let res = exec_program(Arc::new(ParseSession::default()), &args); - assert!(res.is_ok()); - assert_eq!( - res.as_ref().unwrap().yaml_result, - "The_first_kcl_program: Hello World!\nb: 1" - ); - assert_eq!( - res.as_ref().unwrap().json_result, - "{\"The_first_kcl_program\": \"Hello World!\", \"b\": 1}" - ); -} - -#[test] -fn test_kcl_issue_1799() { - let main_test_path = PathBuf::from("./src/test_issues/github.com/kcl-lang/kcl/1799/main.k"); - let mut args = ExecProgramArgs::default(); - args.k_filename_list - .push(main_test_path.display().to_string()); - args.work_dir = Some(".".to_string()); - let res = exec_program(Arc::new(ParseSession::default()), &args); - assert!(res.is_ok()); - assert_eq!( - res.as_ref().unwrap().yaml_result, - format!( - "a: {}", - main_test_path - .parent() - .unwrap() - .canonicalize() - .unwrap() - .adjust_canonicalization() - ) - ); -} diff --git a/kclvm/runtime/Cargo.lock b/kclvm/runtime/Cargo.lock deleted file mode 100644 index 05641b334..000000000 --- a/kclvm/runtime/Cargo.lock +++ /dev/null @@ -1,630 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "ahash" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" -dependencies = [ - "getrandom", - "once_cell", - "version_check", -] - -[[package]] -name = "aho-corasick" -version = "0.7.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" -dependencies = [ - "memchr", -] - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "base64" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" - -[[package]] -name = "bit-set" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e11e16035ea35e4e5997b393eacbf6f63983188f7a2ad25bfb13465f5ad59de" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bstr" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" -dependencies = [ - "lazy_static", - "memchr", - "regex-automata", -] - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "chrono" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" -dependencies = [ - "libc", - "num-integer", - "num-traits", - "time", - "winapi", -] - -[[package]] -name = "cpufeatures" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95059428f66df56b63431fdb4e1947ed2190586af5c5a8a8b71122bdf5a7f469" -dependencies = [ - "libc", -] - -[[package]] -name = "digest" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" -dependencies = [ - "generic-array", -] - -[[package]] -name = "either" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" - -[[package]] -name = "fancy-regex" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d6b8560a05112eb52f04b00e5d3790c0dd75d9d980eb8a122fb23b92a623ccf" -dependencies = [ - "bit-set", - "regex", -] - -[[package]] -name = "generic-array" -version = "0.14.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "501466ecc8a30d1d3b7fc9229b122b2ce8ed6e9d9223f1138d4babb253e51817" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - -[[package]] -name = "hashbrown" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" - -[[package]] -name = "indexmap" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" -dependencies = [ - "autocfg", - "hashbrown", -] - -[[package]] -name = "itertools" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" - -[[package]] -name = "json_minimal" -version = "0.1.3" - -[[package]] -name = "kclvm-runtime" -version = "0.1.0" -dependencies = [ - "ahash", - "base64", - "bstr", - "chrono", - "fancy-regex", - "indexmap", - "itertools", - "json_minimal", - "kclvm_runtime_internal_macros", - "libc", - "md5", - "num-integer", - "phf", - "regex", - "serde", - "serde_json", - "serde_yaml", - "sha1", - "sha2", - "unic-ucd-bidi", - "unic-ucd-category", - "unicode-casing", -] - -[[package]] -name = "kclvm_runtime_internal_macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.112" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b03d17f364a3a042d5e5d46b053bbbf82c92c9430c592dd4c064dc6ee997125" - -[[package]] -name = "linked-hash-map" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3" - -[[package]] -name = "matches" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" - -[[package]] -name = "md5" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" - -[[package]] -name = "memchr" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" - -[[package]] -name = "num-integer" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db" -dependencies = [ - "autocfg", - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" -dependencies = [ - "autocfg", -] - -[[package]] -name = "once_cell" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56" - -[[package]] -name = "opaque-debug" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" - -[[package]] -name = "phf" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2ac8b67553a7ca9457ce0e526948cad581819238f4a9d1ea74545851fa24f37" -dependencies = [ - "phf_macros", - "phf_shared", - "proc-macro-hack", -] - -[[package]] -name = "phf_generator" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43f3220d96e0080cc9ea234978ccd80d904eafb17be31bb0f76daaea6493082" -dependencies = [ - "phf_shared", - "rand", -] - -[[package]] -name = "phf_macros" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b706f5936eb50ed880ae3009395b43ed19db5bff2ebd459c95e7bf013a89ab86" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro-hack", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "phf_shared" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a68318426de33640f02be62b4ae8eb1261be2efbc337b60c54d845bf4484e0d9" -dependencies = [ - "siphasher", -] - -[[package]] -name = "ppv-lite86" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed0cfbc8191465bed66e1718596ee0b0b35d5ee1f41c5df2189d0fe8bde535ba" - -[[package]] -name = "proc-macro-hack" -version = "0.5.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" - -[[package]] -name = "proc-macro2" -version = "1.0.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "quote" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "864d3e96a899863136fc6e99f3d7cae289dafe43bf2c5ac19b70df7210c0a145" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rand" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e7573632e6454cf6b99d7aac4ccca54be06da05aca2ef7423d22d27d4d4bcd8" -dependencies = [ - "libc", - "rand_chacha", - "rand_core", - "rand_hc", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" -dependencies = [ - "getrandom", -] - -[[package]] -name = "rand_hc" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d51e9f596de227fda2ea6c84607f5558e196eeaf43c986b724ba4fb8fdf497e7" -dependencies = [ - "rand_core", -] - -[[package]] -name = "regex" -version = "1.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83f127d94bdbcda4c8cc2e50f6f84f4b611f69c902699ca385a39c3a75f9ff1" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" - -[[package]] -name = "regex-syntax" -version = "0.6.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49b3de9ec5dc0a3417da371aab17d729997c15010e7fd24ff707773a33bddb64" - -[[package]] -name = "ryu" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" - -[[package]] -name = "serde" -version = "1.0.131" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4ad69dfbd3e45369132cc64e6748c2d65cdfb001a2b1c232d128b4ad60561c1" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.131" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b710a83c4e0dff6a3d511946b95274ad9ca9e5d3ae497b63fda866ac955358d2" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.73" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcbd0344bc6533bc7ec56df11d42fb70f1b912351c0825ccb7211b59d8af7cf5" -dependencies = [ - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_yaml" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a521f2940385c165a24ee286aa8599633d162077a54bdcae2a6fd5a7bfa7a0" -dependencies = [ - "indexmap", - "ryu", - "serde", - "yaml-rust", -] - -[[package]] -name = "sha1" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2579985fda508104f7587689507983eadd6a6e84dd35d6d115361f530916fa0d" - -[[package]] -name = "sha2" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b69f9a4c9740d74c5baa3fd2e547f9525fa8088a8a958e0ca2409a514e33f5fa" -dependencies = [ - "block-buffer", - "cfg-if", - "cpufeatures", - "digest", - "opaque-debug", -] - -[[package]] -name = "siphasher" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "533494a8f9b724d33625ab53c6c4800f7cc445895924a8ef649222dcb76e938b" - -[[package]] -name = "syn" -version = "1.0.86" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a65b3f4ffa0092e9887669db0eae07941f023991ab58ea44da8fe8e2d511c6b" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "time" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" -dependencies = [ - "libc", - "wasi", - "winapi", -] - -[[package]] -name = "typenum" -version = "1.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b63708a265f51345575b27fe43f9500ad611579e764c79edbc2037b1121959ec" - -[[package]] -name = "unic-char-property" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" -dependencies = [ - "unic-char-range", -] - -[[package]] -name = "unic-char-range" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" - -[[package]] -name = "unic-common" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" - -[[package]] -name = "unic-ucd-bidi" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1d568b51222484e1f8209ce48caa6b430bf352962b877d592c29ab31fb53d8c" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-category" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b8d4591f5fcfe1bd4453baaf803c40e1b1e69ff8455c47620440b46efef91c0" -dependencies = [ - "matches", - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-version" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" -dependencies = [ - "unic-common", -] - -[[package]] -name = "unicode-casing" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "623f59e6af2a98bdafeb93fa277ac8e1e40440973001ca15cf4ae1541cd16d56" - -[[package]] -name = "unicode-xid" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" - -[[package]] -name = "version_check" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" - -[[package]] -name = "wasi" -version = "0.10.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "yaml-rust" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" -dependencies = [ - "linked-hash-map", -] diff --git a/kclvm/runtime/Cargo.toml b/kclvm/runtime/Cargo.toml deleted file mode 100644 index 83f9191d4..000000000 --- a/kclvm/runtime/Cargo.toml +++ /dev/null @@ -1,45 +0,0 @@ -[package] -name = "kclvm-runtime" -version = "0.11.2" -edition = "2021" - -[dependencies] -kclvm-primitives = { path = "../primitives" } -kclvm_runtime_internal_macros = { path = "./internal_macros" } -serde_json = "1.0.132" -serde = { version = "1", features = ["derive"] } -serde_yaml_ng = "0.10.0" -lazy_static = "1.4.0" -generational-arena = "0.2.9" -base64 = "0.13.0" -base32 = "0.4.0" -cidr = "0.3.1" -libc = "0.2.112" -itertools = "0.10.3" -unic-ucd-bidi = "0.9" -unic-ucd-category = "0.9" -unicode-casing = "0.1" -bstr = "0.2.16" -regex = "1.5.5" -md5 = "0.7.0" -sha2 = "0.9.8" -sha1 = "0.6.0" -chrono = "0.4.19" -phf = { version = "0.9", features = ["macros"] } -fancy-regex = "0.7.1" -num-integer = "0.1.44" -glob = "0.3.0" -uuid = { version = "1.7.0", features = ["serde", "v4"] } -handlebars = "5.1.2" -walkdir = "2.5.0" -anyhow = "1" -blake3 = "1.5.4" -encoding_rs = "0.8.35" - -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] -hostname = "0.4.0" -dns-lookup = "2.0.4" - -[[bin]] -name = "gen-api-spec" -path = "scripts/gen-api-spec.rs" diff --git a/kclvm/runtime/Makefile b/kclvm/runtime/Makefile deleted file mode 100644 index c1c27b8be..000000000 --- a/kclvm/runtime/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -default: - make gen-api-spec - -gen-api-spec: - mkdir -p target - - cargo clean -q - - KCLVM_RUNTIME_GEN_API_SPEC= cargo build -r > ./src/_kclvm_api_spec.rs.tmp - - echo "// Copyright The KCL Authors. All rights reserved.\n" > ./src/_kclvm_api_spec.rs - echo "// Auto generated by command, DONOT EDIT!!!\n" >> ./src/_kclvm_api_spec.rs - cat ./src/_kclvm_api_spec.rs.tmp >> ./src/_kclvm_api_spec.rs - rm ./src/_kclvm_api_spec.rs.tmp - - cargo run -r --bin gen-api-spec diff --git a/kclvm/runtime/internal_macros/Cargo.lock b/kclvm/runtime/internal_macros/Cargo.lock deleted file mode 100644 index a60b6e922..000000000 --- a/kclvm/runtime/internal_macros/Cargo.lock +++ /dev/null @@ -1,47 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "kclvm_runtime_internal_macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "proc-macro2" -version = "1.0.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "quote" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "864d3e96a899863136fc6e99f3d7cae289dafe43bf2c5ac19b70df7210c0a145" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "syn" -version = "1.0.86" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a65b3f4ffa0092e9887669db0eae07941f023991ab58ea44da8fe8e2d511c6b" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "unicode-xid" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" diff --git a/kclvm/runtime/internal_macros/Cargo.toml b/kclvm/runtime/internal_macros/Cargo.toml deleted file mode 100644 index 3db5e19ac..000000000 --- a/kclvm/runtime/internal_macros/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "kclvm_runtime_internal_macros" -version = "0.5.0" -edition = "2021" - -[dependencies] -syn = { version = "1.0", features = ["full"] } -proc-macro2 = "1.0" -quote = "1.0" - -[lib] -proc-macro = true - -[features] -default = [] diff --git a/kclvm/runtime/internal_macros/src/lib.rs b/kclvm/runtime/internal_macros/src/lib.rs deleted file mode 100644 index 2a7ea763b..000000000 --- a/kclvm/runtime/internal_macros/src/lib.rs +++ /dev/null @@ -1,220 +0,0 @@ -use proc_macro::TokenStream; -use quote::quote; -use syn::{parse_macro_input, FnArg}; - -// ---------------------------------------------------------------------------- - -#[proc_macro_attribute] -pub fn runtime_fn(_attr: TokenStream, item: TokenStream) -> TokenStream { - let parsed_fn = parse_macro_input!(item as syn::ItemFn); - - if std::env::var("KCLVM_RUNTIME_GEN_API_SPEC").is_ok() { - print_api_spec(&parsed_fn); - } - - let x = quote! { - #parsed_fn - }; - x.into() -} - -// ---------------------------------------------------------------------------- -#[allow(clippy::upper_case_acronyms)] -#[derive(Debug)] -enum TargetName { - C, - LLVM, -} - -fn print_api_spec(fn_item: &syn::ItemFn) { - let fn_name = get_fn_name(fn_item); - let fn_c_sig = get_fn_sig(fn_item, &TargetName::C); - let fn_llvm_sig = get_fn_sig(fn_item, &TargetName::LLVM); - - // skip _fn_name() - if !fn_name.starts_with('_') { - println!("// api-spec: {}", fn_name); - println!("// api-spec(c): {};", fn_c_sig); - println!("// api-spec(llvm): {};", fn_llvm_sig); - println!(); - } -} - -// ---------------------------------------------------------------------------- - -fn get_fn_name(fn_item: &syn::ItemFn) -> String { - fn_item.sig.ident.to_string() -} - -fn get_fn_sig(fn_item: &syn::ItemFn, target: &TargetName) -> String { - let fn_name = get_fn_name(fn_item); - let args_type = get_fn_args_type(fn_item, target); - let output_type = get_fn_output_type(fn_item, target); - - match target { - TargetName::C => format!("{} {}({})", output_type, fn_name, args_type), - TargetName::LLVM => format!("declare {} @{}({})", output_type, fn_name, args_type), - } -} - -fn get_fn_output_type(fn_item: &syn::ItemFn, target: &TargetName) -> String { - match target { - TargetName::C => match &fn_item.sig.output { - syn::ReturnType::Type(_, ty) => build_c_type(ty), - syn::ReturnType::Default => "void".to_string(), - }, - TargetName::LLVM => match &fn_item.sig.output { - syn::ReturnType::Type(_, ty) => build_llvm_type(ty), - syn::ReturnType::Default => "void".to_string(), - }, - } -} - -// ---------------------------------------------------------------------------- - -fn get_fn_args_type(fn_item: &syn::ItemFn, target: &TargetName) -> String { - let fn_name = get_fn_name(fn_item); - let inputs = &fn_item.sig.inputs; - - let mut result = String::new(); - for (i, arg) in inputs.iter().enumerate() { - let arg_name = get_fn_arg_name(arg, target); - let arg_typ = get_fn_arg_type(arg, target); - - if arg_name.is_empty() { - panic!("{}", format!("{}, arg{}: invalid arg type", fn_name, i)); - } - if arg_typ.is_empty() { - panic!("{}", format!("{}, arg{}: invalid arg type", fn_name, i)); - } - - if i > 0 { - result.push_str(", "); - } - result.push_str(format!("{} {}", arg_typ, arg_name).as_str()); - } - - result -} - -// ---------------------------------------------------------------------------- - -fn get_fn_arg_name(arg: &FnArg, target: &TargetName) -> String { - match arg { - syn::FnArg::Typed(ty) => { - let syn::PatType { pat, .. } = ty; - match &**pat { - syn::Pat::Ident(x) => match target { - TargetName::C => x.ident.to_string(), - TargetName::LLVM => format!("%{}", x.ident), - }, - _ => panic!("unsupported type: {}", quote!(#ty)), - } - } - _ => panic!("unsupported arg: {}", quote!(#arg)), - } -} - -fn get_fn_arg_type(arg: &FnArg, target: &TargetName) -> String { - match arg { - syn::FnArg::Typed(ty) => { - let syn::PatType { ty, .. } = ty; - match target { - TargetName::C => build_c_type(ty), - TargetName::LLVM => build_llvm_type(ty), - } - } - _ => panic!("unsupported fn arg: {}", quote!(#arg)), - } -} - -// ---------------------------------------------------------------------------- - -fn build_c_type(ty: &syn::Type) -> String { - match ty { - syn::Type::Path(ty_path) => { - let ty_name = ty_path.path.segments[0].ident.to_string(); - - match ty_name.as_str() { - "c_void" => "void".to_string(), - "c_char" => "char".to_string(), - - "bool" => "uint8_t".to_string(), - - "i8" => "int8_t".to_string(), - "u8" => "uint8_t".to_string(), - - "i16" => "int16_t".to_string(), - "u16" => "uint16_t".to_string(), - - "i32" => "int32_t".to_string(), - "u32" => "uint32_t".to_string(), - - "i64" => "int64_t".to_string(), - "u64" => "uint64_t".to_string(), - "i128" | "u128" => "".to_string(), - - "f32" => "float".to_string(), - "f64" => "double".to_string(), - - _ => ty_name, - } - } - syn::Type::Ptr(ty_ptr) => { - let base_ty = &ty_ptr.elem; - let base_constr = build_c_type(base_ty); - format!("{}*", base_constr) - } - syn::Type::Reference(ty_ref) => { - let base_ty = &ty_ref.elem; - let base_constr = build_c_type(base_ty); - format!("{}*", base_constr) - } - syn::Type::BareFn(_) => "void*".to_string(), - syn::Type::Never(_) => "void".to_string(), - _ => panic!("unsupported type: {}", quote!(#ty)), - } -} - -fn build_llvm_type(ty: &syn::Type) -> String { - match ty { - syn::Type::Path(ty_path) => { - let ty_name = ty_path.path.segments[0].ident.to_string(); - - match ty_name.as_str() { - "c_void" => "void".to_string(), - "c_char" => "i8".to_string(), - - "bool" => "i8".to_string(), - - "i8" | "u8" => "i8".to_string(), - "i16" | "u16" => "i16".to_string(), - "i32" | "u32" => "i32".to_string(), - "i64" | "u64" => "i64".to_string(), - "i128" | "u128" => "i128".to_string(), - - "f32" => "float".to_string(), - "f64" => "double".to_string(), - - _ => format!("%{}", ty_name), - } - } - syn::Type::Ptr(ty_ptr) => { - let base_ty = &ty_ptr.elem; - let base_constr = build_llvm_type(base_ty); - format!("{}*", base_constr) - } - syn::Type::Reference(ty_ref) => { - let base_ty = &ty_ref.elem; - let base_constr = build_llvm_type(base_ty); - format!("{}*", base_constr) - } - syn::Type::BareFn(_) => "i8*".to_string(), - syn::Type::Never(_) => "void".to_string(), - _ => panic!("unsupported type: {}", quote!(#ty)), - } -} - -// ---------------------------------------------------------------------------- -// END -// ---------------------------------------------------------------------------- diff --git a/kclvm/runtime/src/_kcl_run.rs b/kclvm/runtime/src/_kcl_run.rs deleted file mode 100644 index 729a51cbc..000000000 --- a/kclvm/runtime/src/_kcl_run.rs +++ /dev/null @@ -1,186 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. -#![allow(clippy::missing_safety_doc)] - -use std::os::raw::c_char; - -use crate::*; - -use self::eval::LazyEvalScope; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_context_t = Context; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_eval_scope_t = LazyEvalScope; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_kind_t = Kind; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_type_t = Type; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_value_ref_t = ValueRef; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_iterator_t = ValueIterator; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_char_t = c_char; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_size_t = i32; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_bool_t = i8; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_int_t = i64; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_float_t = f64; - -#[derive(Debug, Default, Clone)] -pub struct RuntimePanicRecord { - pub kcl_panic_info: bool, - pub message: String, - pub rust_file: String, - pub rust_line: i32, - pub rust_col: i32, -} - -#[derive(Debug, Default, Clone, Copy)] -#[repr(C)] -pub struct FFIRunOptions { - pub strict_range_check: i32, - pub disable_none: i32, - pub disable_schema_check: i32, - pub debug_mode: i32, - pub show_hidden: i32, - pub sort_keys: i32, - pub include_schema_type_path: i32, - pub disable_empty_list: i32, -} - -thread_local! { - static KCL_RUNTIME_PANIC_RECORD: std::cell::RefCell = std::cell::RefCell::new(RuntimePanicRecord::default()) -} - -fn new_ctx_with_opts(opts: FFIRunOptions, path_selector: &[String]) -> Context { - let mut ctx = Context::new(); - // Config - ctx.cfg.strict_range_check = opts.strict_range_check != 0; - ctx.cfg.disable_schema_check = opts.disable_schema_check != 0; - ctx.cfg.debug_mode = opts.debug_mode != 0; - // Plan options - ctx.plan_opts.disable_none = opts.disable_none != 0; - ctx.plan_opts.show_hidden = opts.show_hidden != 0; - ctx.plan_opts.sort_keys = opts.sort_keys != 0; - ctx.plan_opts.include_schema_type_path = opts.include_schema_type_path != 0; - ctx.plan_opts.disable_empty_list = opts.disable_empty_list != 0; - ctx.plan_opts.query_paths = path_selector.to_vec(); - ctx -} - -#[no_mangle] -#[runtime_fn] -#[allow(clippy::too_many_arguments)] -pub unsafe extern "C-unwind" fn _kcl_run( - kclvm_main_ptr: u64, // main.k => kclvm_main - option_len: kclvm_size_t, - option_keys: *const *const kclvm_char_t, - option_values: *const *const kclvm_char_t, - opts: FFIRunOptions, - path_selector: *const *const kclvm_char_t, - json_result_buffer_len: *mut kclvm_size_t, - json_result_buffer: *mut kclvm_char_t, - yaml_result_buffer_len: *mut kclvm_size_t, - yaml_result_buffer: *mut kclvm_char_t, - err_buffer_len: *mut kclvm_size_t, - err_buffer: *mut kclvm_char_t, - log_buffer_len: *mut kclvm_size_t, - log_buffer: *mut kclvm_char_t, -) -> kclvm_size_t { - // Init runtime context with options - let ctx = Box::new(new_ctx_with_opts(opts, &c2str_vec(path_selector))).into_raw(); - let scope = kclvm_scope_new(); - let option_keys = std::slice::from_raw_parts(option_keys, option_len as usize); - let option_values = std::slice::from_raw_parts(option_values, option_len as usize); - for i in 0..(option_len as usize) { - kclvm_builtin_option_init(ctx, option_keys[i], option_values[i]); - } - let prev_hook = std::panic::take_hook(); - std::panic::set_hook(Box::new(|info: &std::panic::PanicHookInfo| { - KCL_RUNTIME_PANIC_RECORD.with(|record| { - let mut record = record.borrow_mut(); - record.kcl_panic_info = true; - - record.message = if let Some(s) = info.payload().downcast_ref::<&str>() { - s.to_string() - } else if let Some(s) = info.payload().downcast_ref::<&String>() { - (*s).clone() - } else if let Some(s) = info.payload().downcast_ref::() { - (*s).clone() - } else { - "".to_string() - }; - if let Some(location) = info.location() { - record.rust_file = location.file().to_string(); - record.rust_line = location.line() as i32; - record.rust_col = location.column() as i32; - } - }) - })); - let result = std::panic::catch_unwind(|| _kcl_run_in_closure(ctx, scope, kclvm_main_ptr)); - std::panic::set_hook(prev_hook); - KCL_RUNTIME_PANIC_RECORD.with(|record| { - let record = record.borrow(); - let ctx = mut_ptr_as_ref(ctx); - ctx.set_panic_info(&record); - }); - // Get the runtime context. - let ctx_ref = ptr_as_ref(ctx); - // Copy planned result and log message - copy_str_to( - &ctx_ref.json_result, - json_result_buffer, - json_result_buffer_len, - ); - copy_str_to( - &ctx_ref.yaml_result, - yaml_result_buffer, - yaml_result_buffer_len, - ); - copy_str_to(&ctx_ref.log_message, log_buffer, log_buffer_len); - // Copy JSON panic info message pointer - let json_panic_info = if result.is_err() { - ctx_ref.get_panic_info_json_string().unwrap_or_default() - } else { - "".to_string() - }; - copy_str_to(&json_panic_info, err_buffer, err_buffer_len); - // Delete the context - kclvm_context_delete(ctx); - // Delete the scope - kclvm_scope_delete(scope); - result.is_err() as kclvm_size_t -} - -unsafe fn _kcl_run_in_closure( - ctx: *mut Context, - scope: *mut LazyEvalScope, - kclvm_main_ptr: u64, // main.k => kclvm_main -) { - let kclvm_main = (&kclvm_main_ptr as *const u64) as *const () - as *const extern "C-unwind" fn( - ctx: *mut kclvm_context_t, - scope: *mut kclvm_eval_scope_t, - ) -> *mut kclvm_value_ref_t; - - unsafe { - if kclvm_main.is_null() { - panic!("kcl program main function not found"); - } - (*kclvm_main)(ctx, scope); - } -} diff --git a/kclvm/runtime/src/_kclvm.bc b/kclvm/runtime/src/_kclvm.bc deleted file mode 100644 index b604c8633..000000000 Binary files a/kclvm/runtime/src/_kclvm.bc and /dev/null differ diff --git a/kclvm/runtime/src/_kclvm.h b/kclvm/runtime/src/_kclvm.h deleted file mode 100644 index 95fd4b1bb..000000000 --- a/kclvm/runtime/src/_kclvm.h +++ /dev/null @@ -1,738 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. - -// Auto generated, DONOT EDIT!!! - -#pragma once - -#ifndef _kclvm_h_ -#define _kclvm_h_ - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// please keep same as 'kclvm/runtime/src/kind/mod.rs#Kind' - -enum kclvm_kind_t { - Invalid = 0, - Undefined = 1, - None = 2, - Bool = 3, - Int = 4, - Float = 5, - Str = 6, - List = 7, - Dict = 8, - Schema = 9, - Error = 10, - Any = 11, - Union = 12, - BoolLit = 13, - IntLit = 14, - FloatLit = 15, - StrLit = 16, - Func = 17, - Max = 18, -}; - -typedef int8_t kclvm_bool_t; - -typedef struct kclvm_buffer_t kclvm_buffer_t; - -typedef char kclvm_char_t; - -typedef struct kclvm_context_t kclvm_context_t; - -typedef struct kclvm_decorator_value_t kclvm_decorator_value_t; - -typedef struct kclvm_eval_scope_t kclvm_eval_scope_t; - -typedef double kclvm_float_t; - -typedef int64_t kclvm_int_t; - -typedef struct kclvm_iterator_t kclvm_iterator_t; - -typedef enum kclvm_kind_t kclvm_kind_t; - -typedef int32_t kclvm_size_t; - -typedef struct kclvm_type_t kclvm_type_t; - -typedef struct kclvm_value_ref_t kclvm_value_ref_t; - -typedef struct kclvm_value_t kclvm_value_t; - -void kclvm_assert(kclvm_context_t* ctx, kclvm_value_ref_t* value, kclvm_value_ref_t* msg); - -kclvm_value_ref_t* kclvm_base32_decode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_base32_encode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_base64_decode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_base64_encode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_abs(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_all_true(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_any_true(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_bin(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_bool(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_dict(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_float(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_hex(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_int(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_isnullish(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_isunique(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_len(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_list(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_max(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_min(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_multiplyof(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_oct(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_option(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -void kclvm_builtin_option_init(kclvm_context_t* ctx, char* key, char* value); - -kclvm_value_ref_t* kclvm_builtin_option_reset(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_ord(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_pow(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_print(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_range(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_round(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_sorted(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_str(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_capitalize(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_chars(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_count(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_endswith(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_find(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_format(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_index(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_isalnum(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_isalpha(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_isdigit(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_islower(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_isspace(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_istitle(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_isupper(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_join(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_lower(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_lstrip(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_removeprefix(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_removesuffix(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_replace(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_rfind(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_rindex(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_rsplit(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_rstrip(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_split(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_splitlines(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_startswith(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_strip(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_title(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_str_upper(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_builtin_sum(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_typeof(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_builtin_zip(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -void kclvm_config_attr_map(kclvm_value_ref_t* value, kclvm_char_t* name, kclvm_char_t* type_str); - -void kclvm_context_delete(kclvm_context_t* p); - -char* kclvm_context_invoke(kclvm_context_t* p, char* method, char* args, char* kwargs); - -kclvm_context_t* kclvm_context_new(); - -kclvm_bool_t kclvm_context_pkgpath_is_imported(kclvm_context_t* ctx, kclvm_char_t* pkgpath); - -void kclvm_context_set_debug_mode(kclvm_context_t* p, kclvm_bool_t v); - -void kclvm_context_set_disable_none(kclvm_context_t* p, kclvm_bool_t v); - -void kclvm_context_set_disable_schema_check(kclvm_context_t* p, kclvm_bool_t v); - -void kclvm_context_set_import_names(kclvm_context_t* p, kclvm_value_ref_t* import_names); - -void kclvm_context_set_kcl_filename(kclvm_context_t* ctx, char* filename); - -void kclvm_context_set_kcl_line_col(kclvm_context_t* ctx, int32_t line, int32_t col); - -void kclvm_context_set_kcl_location(kclvm_context_t* p, char* filename, int32_t line, int32_t col); - -void kclvm_context_set_kcl_modpath(kclvm_context_t* p, char* module_path); - -void kclvm_context_set_kcl_pkgpath(kclvm_context_t* p, char* pkgpath); - -void kclvm_context_set_kcl_workdir(kclvm_context_t* p, char* workdir); - -void kclvm_context_set_strict_range_check(kclvm_context_t* p, kclvm_bool_t v); - -kclvm_value_ref_t* kclvm_convert_collection_value(kclvm_context_t* ctx, kclvm_value_ref_t* value, kclvm_char_t* tpe, kclvm_value_ref_t* is_in_schema); - -kclvm_value_ref_t* kclvm_crypto_blake3(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_crypto_fileblake3(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_crypto_filesha256(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_crypto_filesha512(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_crypto_md5(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_crypto_sha1(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_crypto_sha224(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_crypto_sha256(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_crypto_sha384(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_crypto_sha512(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_crypto_uuid(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_datetime_date(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_datetime_now(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_datetime_ticks(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_datetime_today(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_datetime_validate(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -void kclvm_default_collection_insert_int_pointer(kclvm_value_ref_t* p, kclvm_char_t* key, uint64_t* ptr); - -void kclvm_default_collection_insert_value(kclvm_value_ref_t* p, kclvm_char_t* key, kclvm_value_ref_t* value); - -void kclvm_dict_clear(kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_dict_get(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_value_ref_t* key); - -kclvm_value_ref_t* kclvm_dict_get_entry(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key); - -kclvm_value_ref_t* kclvm_dict_get_value(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key); - -kclvm_value_ref_t* kclvm_dict_get_value_by_path(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* path); - -kclvm_bool_t kclvm_dict_has_value(kclvm_value_ref_t* p, kclvm_char_t* key); - -void kclvm_dict_insert(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key, kclvm_value_ref_t* v, kclvm_size_t op, kclvm_size_t insert_index, kclvm_bool_t has_insert_index); - -void kclvm_dict_insert_unpack(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_value_ref_t* v); - -void kclvm_dict_insert_value(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_value_ref_t* key, kclvm_value_ref_t* v, kclvm_size_t op, kclvm_size_t insert_index, kclvm_bool_t has_insert_index); - -kclvm_bool_t kclvm_dict_is_override_attr(kclvm_value_ref_t* p, kclvm_char_t* key); - -kclvm_value_ref_t* kclvm_dict_keys(kclvm_context_t* ctx, kclvm_value_ref_t* p); - -kclvm_size_t kclvm_dict_len(kclvm_value_ref_t* p); - -void kclvm_dict_merge(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key, kclvm_value_ref_t* v, kclvm_size_t op, kclvm_size_t insert_index, kclvm_bool_t has_insert_index); - -void kclvm_dict_remove(kclvm_value_ref_t* p, kclvm_char_t* key); - -void kclvm_dict_safe_insert(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key, kclvm_value_ref_t* v, kclvm_size_t op, kclvm_size_t insert_index, kclvm_bool_t has_insert_index); - -void kclvm_dict_set_value(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key, kclvm_value_ref_t* val); - -void kclvm_dict_update(kclvm_value_ref_t* p, kclvm_value_ref_t* v); - -void kclvm_dict_update_key_value(kclvm_value_ref_t* p, kclvm_value_ref_t* key, kclvm_value_ref_t* v); - -kclvm_value_ref_t* kclvm_dict_values(kclvm_context_t* ctx, kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_file_abs(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_file_append(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_file_cp(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_file_current(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_file_delete(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_file_exists(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_file_glob(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_file_mkdir(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_file_modpath(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_file_mv(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_file_read(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_file_read_env(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_file_size(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_file_workdir(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_file_write(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_iterator_cur_key(kclvm_iterator_t* p); - -kclvm_value_ref_t* kclvm_iterator_cur_value(kclvm_iterator_t* p); - -void kclvm_iterator_delete(kclvm_iterator_t* p); - -kclvm_bool_t kclvm_iterator_is_end(kclvm_iterator_t* p); - -kclvm_value_ref_t* kclvm_iterator_next_value(kclvm_iterator_t* p, kclvm_value_ref_t* host); - -kclvm_value_ref_t* kclvm_json_decode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_json_dump_to_file(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_json_encode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_json_validate(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -void kclvm_list_append(kclvm_value_ref_t* p, kclvm_value_ref_t* v); - -void kclvm_list_append_bool(kclvm_value_ref_t* p, kclvm_bool_t v); - -void kclvm_list_append_float(kclvm_value_ref_t* p, kclvm_float_t v); - -void kclvm_list_append_int(kclvm_value_ref_t* p, kclvm_int_t v); - -void kclvm_list_append_str(kclvm_value_ref_t* p, kclvm_char_t* v); - -void kclvm_list_append_unpack(kclvm_value_ref_t* p, kclvm_value_ref_t* v); - -void kclvm_list_clear(kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_list_count(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_value_ref_t* item); - -kclvm_value_ref_t* kclvm_list_find(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_value_ref_t* item); - -kclvm_value_ref_t* kclvm_list_get(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_size_t i); - -kclvm_value_ref_t* kclvm_list_get_option(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_size_t i); - -void kclvm_list_insert(kclvm_value_ref_t* p, kclvm_value_ref_t* index, kclvm_value_ref_t* value); - -kclvm_size_t kclvm_list_len(kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_list_pop(kclvm_context_t* ctx, kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_list_pop_first(kclvm_context_t* ctx, kclvm_value_ref_t* p); - -void kclvm_list_remove_at(kclvm_value_ref_t* p, kclvm_size_t i); - -void kclvm_list_resize(kclvm_value_ref_t* p, kclvm_size_t newsize); - -void kclvm_list_set(kclvm_value_ref_t* p, kclvm_size_t i, kclvm_value_ref_t* v); - -kclvm_value_ref_t* kclvm_manifests_yaml_stream(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_ceil(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_exp(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_expm1(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_factorial(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_floor(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_gcd(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_isfinite(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_isinf(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_isnan(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_log(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_log10(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_log1p(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_log2(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_modf(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_pow(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_math_sqrt(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_CIDR_host(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_CIDR_netmask(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_CIDR_subnet(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_CIDR_subnets(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_IP_string(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_fqdn(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_is_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_is_IP_in_CIDR(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_is_IPv4(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_is_global_unicast_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_is_interface_local_multicast_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_is_link_local_multicast_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_is_link_local_unicast_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_is_loopback_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_is_multicast_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_is_unspecified_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_join_host_port(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_parse_CIDR(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_parse_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_split_host_port(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_to_IP6(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_net_to_IP4(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -void kclvm_plugin_init(void* fn_ptr); - -kclvm_value_ref_t* kclvm_plugin_invoke(kclvm_context_t* ctx, char* method, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -char* kclvm_plugin_invoke_json(char* method, char* args, char* kwargs); - -kclvm_value_ref_t* kclvm_regex_compile(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_regex_findall(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_regex_match(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_regex_replace(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_regex_search(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_regex_split(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_runtime_catch(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -void kclvm_schema_assert(kclvm_context_t* ctx, kclvm_value_ref_t* value, kclvm_value_ref_t* msg, kclvm_value_ref_t* config_meta); - -void kclvm_schema_backtrack_cache(kclvm_context_t* ctx, kclvm_value_ref_t* schema, kclvm_value_ref_t* cache, kclvm_value_ref_t* cal_map, kclvm_char_t* name, kclvm_value_ref_t* runtime_type); - -void kclvm_schema_default_settings(kclvm_value_ref_t* schema_value, kclvm_value_ref_t* _config_value, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs, kclvm_char_t* runtime_type); - -void kclvm_schema_do_check_with_index_sign_attr(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs, uint64_t* check_fn_ptr, kclvm_char_t* attr_name); - -kclvm_value_ref_t* kclvm_schema_get_value(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key, kclvm_value_ref_t* config, kclvm_value_ref_t* config_meta, kclvm_value_ref_t* cal_map, kclvm_char_t* target_attr, kclvm_value_ref_t* backtrack_level_map, kclvm_value_ref_t* backtrack_cache, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_schema_instances(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -void kclvm_schema_optional_check(kclvm_context_t* ctx, kclvm_value_ref_t* p); - -void kclvm_schema_value_check(kclvm_context_t* ctx, kclvm_value_ref_t* schema_value, kclvm_value_ref_t* schema_config, kclvm_value_ref_t* _config_meta, kclvm_char_t* schema_name, kclvm_value_ref_t* index_sign_value, kclvm_char_t* key_name, kclvm_char_t* key_type, kclvm_char_t* value_type, kclvm_bool_t _any_other); - -kclvm_value_ref_t* kclvm_schema_value_new(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs, kclvm_value_ref_t* schema_value_or_func, kclvm_value_ref_t* config, kclvm_value_ref_t* config_meta, kclvm_char_t* pkgpath); - -void kclvm_scope_add_setter(kclvm_context_t* _ctx, kclvm_eval_scope_t* scope, char* pkg, char* name, uint64_t* setter); - -void kclvm_scope_delete(kclvm_eval_scope_t* scope); - -kclvm_value_ref_t* kclvm_scope_get(kclvm_context_t* ctx, kclvm_eval_scope_t* scope, char* pkg, char* name, char* target, kclvm_value_ref_t* default); - -kclvm_eval_scope_t* kclvm_scope_new(); - -void kclvm_scope_set(kclvm_context_t* _ctx, kclvm_eval_scope_t* scope, char* pkg, char* name, kclvm_value_ref_t* value); - -kclvm_value_ref_t* kclvm_template_execute(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_template_html_escape(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_units_to_G(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_units_to_Gi(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_units_to_K(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_units_to_Ki(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_units_to_M(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_units_to_Mi(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_units_to_P(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_units_to_Pi(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_units_to_T(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_units_to_Ti(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_units_to_m(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_units_to_n(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_units_to_u(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_value_Bool(kclvm_context_t* ctx, kclvm_bool_t v); - -kclvm_decorator_value_t* kclvm_value_Decorator(kclvm_context_t* ctx, kclvm_char_t* name, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs, kclvm_value_ref_t* config_meta, kclvm_char_t* attr_name, kclvm_value_ref_t* config_value, kclvm_value_ref_t* is_schema_target); - -kclvm_value_ref_t* kclvm_value_Dict(kclvm_context_t* ctx); - -kclvm_value_ref_t* kclvm_value_False(kclvm_context_t* ctx); - -kclvm_value_ref_t* kclvm_value_Float(kclvm_context_t* ctx, kclvm_float_t v); - -kclvm_value_ref_t* kclvm_value_Function(kclvm_context_t* ctx, uint64_t* fn_ptr, kclvm_value_ref_t* closure, kclvm_char_t* name, kclvm_bool_t is_external); - -kclvm_value_ref_t* kclvm_value_Function_using_ptr(kclvm_context_t* ctx, uint64_t* fn_ptr, kclvm_char_t* name); - -kclvm_value_ref_t* kclvm_value_Int(kclvm_context_t* ctx, kclvm_int_t v); - -kclvm_value_ref_t* kclvm_value_List(kclvm_context_t* ctx); - -kclvm_value_ref_t* kclvm_value_List10(kclvm_context_t* ctx, kclvm_value_ref_t* v1, kclvm_value_ref_t* v2, kclvm_value_ref_t* v3, kclvm_value_ref_t* v4, kclvm_value_ref_t* v5, kclvm_value_ref_t* v6, kclvm_value_ref_t* v7, kclvm_value_ref_t* v8, kclvm_value_ref_t* v9, kclvm_value_ref_t* v10); - -kclvm_value_ref_t* kclvm_value_List6(kclvm_context_t* ctx, kclvm_value_ref_t* v1, kclvm_value_ref_t* v2, kclvm_value_ref_t* v3, kclvm_value_ref_t* v4, kclvm_value_ref_t* v5, kclvm_value_ref_t* v6); - -kclvm_value_ref_t* kclvm_value_None(kclvm_context_t* ctx); - -kclvm_value_ref_t* kclvm_value_Schema(kclvm_context_t* ctx); - -kclvm_value_ref_t* kclvm_value_Str(kclvm_context_t* ctx, kclvm_char_t* v); - -kclvm_char_t* kclvm_value_Str_ptr(kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_value_True(kclvm_context_t* ctx); - -kclvm_value_ref_t* kclvm_value_Undefined(kclvm_context_t* ctx); - -kclvm_value_ref_t* kclvm_value_Unit(kclvm_context_t* ctx, kclvm_float_t v, kclvm_int_t raw, kclvm_char_t* unit); - -kclvm_value_ref_t* kclvm_value_as(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -uint64_t* kclvm_value_check_function_ptr(kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_value_cmp_equal_to(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_cmp_greater_than(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_cmp_greater_than_or_equal(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_cmp_less_than(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_cmp_less_than_or_equal(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_cmp_not_equal_to(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_deep_copy(kclvm_context_t* ctx, kclvm_value_ref_t* p); - -void kclvm_value_delete(kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_value_from_json(kclvm_context_t* ctx, kclvm_char_t* s); - -kclvm_value_ref_t* kclvm_value_function_invoke(kclvm_value_ref_t* p, kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs, kclvm_char_t* pkgpath, kclvm_value_ref_t* is_in_schema); - -uint64_t* kclvm_value_function_ptr(kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_value_in(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_is(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_is_not(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_bool_t kclvm_value_is_truthy(kclvm_value_ref_t* p); - -kclvm_iterator_t* kclvm_value_iter(kclvm_value_ref_t* p); - -kclvm_size_t kclvm_value_len(kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_value_load_attr(kclvm_context_t* ctx, kclvm_value_ref_t* obj, kclvm_char_t* key); - -kclvm_value_ref_t* kclvm_value_load_attr_option(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key); - -kclvm_value_ref_t* kclvm_value_logic_and(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_logic_or(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_not_in(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_add(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_aug_add(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_aug_bit_and(kclvm_context_t* _ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_aug_bit_lshift(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_aug_bit_or(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_aug_bit_rshift(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_aug_bit_xor(kclvm_context_t* _ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_aug_div(kclvm_context_t* _ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_aug_floor_div(kclvm_context_t* _ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_aug_mod(kclvm_context_t* _ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_aug_mul(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_aug_pow(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_aug_sub(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_bit_and(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_bit_lshift(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_bit_or(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_bit_rshift(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_bit_xor(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_div(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_floor_div(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_mod(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_mul(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_pow(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_op_sub(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_plan_to_json(kclvm_context_t* ctx, kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_value_plan_to_yaml(kclvm_context_t* ctx, kclvm_value_ref_t* p); - -void kclvm_value_remove_item(kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_schema_function(kclvm_context_t* ctx, uint64_t* fn_ptr, uint64_t* check_fn_ptr, kclvm_value_ref_t* attr_map, kclvm_char_t* tpe); - -kclvm_value_ref_t* kclvm_value_schema_with_config(kclvm_context_t* ctx, kclvm_value_ref_t* schema_dict, kclvm_value_ref_t* config, kclvm_value_ref_t* config_meta, kclvm_char_t* name, kclvm_char_t* pkgpath, kclvm_value_ref_t* is_sub_schema, kclvm_value_ref_t* record_instance, kclvm_value_ref_t* instance_pkgpath, kclvm_value_ref_t* optional_mapping, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_value_slice(kclvm_context_t* ctx, kclvm_value_ref_t* x, kclvm_value_ref_t* a, kclvm_value_ref_t* b, kclvm_value_ref_t* step); - -kclvm_value_ref_t* kclvm_value_slice_option(kclvm_context_t* ctx, kclvm_value_ref_t* x, kclvm_value_ref_t* a, kclvm_value_ref_t* b, kclvm_value_ref_t* step); - -kclvm_value_ref_t* kclvm_value_subscr(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_subscr_option(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); - -void kclvm_value_subscr_set(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_value_ref_t* index, kclvm_value_ref_t* val); - -kclvm_value_ref_t* kclvm_value_to_json_value(kclvm_context_t* ctx, kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_value_to_json_value_with_null(kclvm_context_t* ctx, kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_value_to_str_value(kclvm_context_t* ctx, kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_value_to_yaml_value(kclvm_context_t* ctx, kclvm_value_ref_t* p); - -kclvm_value_ref_t* kclvm_value_unary_l_not(kclvm_context_t* ctx, kclvm_value_ref_t* a); - -kclvm_value_ref_t* kclvm_value_unary_minus(kclvm_context_t* ctx, kclvm_value_ref_t* a); - -kclvm_value_ref_t* kclvm_value_unary_not(kclvm_context_t* ctx, kclvm_value_ref_t* a); - -kclvm_value_ref_t* kclvm_value_unary_plus(kclvm_context_t* ctx, kclvm_value_ref_t* a); - -kclvm_value_ref_t* kclvm_value_union(kclvm_context_t* ctx, kclvm_value_ref_t* schema, kclvm_value_ref_t* b); - -kclvm_value_ref_t* kclvm_value_union_all(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); - -kclvm_value_ref_t* kclvm_yaml_decode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_yaml_decode_all(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_yaml_dump_all_to_file(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_yaml_dump_to_file(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_yaml_encode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_yaml_encode_all(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -kclvm_value_ref_t* kclvm_yaml_validate(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // _kclvm_h_ diff --git a/kclvm/runtime/src/_kclvm.ll b/kclvm/runtime/src/_kclvm.ll deleted file mode 100644 index a76c5d142..000000000 --- a/kclvm/runtime/src/_kclvm.ll +++ /dev/null @@ -1,700 +0,0 @@ -; Copyright The KCL Authors. All rights reserved. - -; Auto generated, DONOT EDIT!!! - -%"kclvm_bool_t" = type i8 - -%"kclvm_buffer_t" = type { i8* } - -%"kclvm_char_t" = type i8 - -%"kclvm_context_t" = type { i8* } - -%"kclvm_decorator_value_t" = type opaque - -%"kclvm_eval_scope_t" = type { i8* } - -%"kclvm_float_t" = type double - -%"kclvm_int_t" = type i64 - -%"kclvm_iterator_t" = type { i8* } - -%"kclvm_kind_t" = type i32 - -%"kclvm_size_t" = type i32 - -%"kclvm_type_t" = type { i8* } - -%"kclvm_value_ref_t" = type { i8* } - -%"kclvm_value_t" = type { i8* } - -declare void @kclvm_assert(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %value, %kclvm_value_ref_t* %msg); - -declare %kclvm_value_ref_t* @kclvm_base32_decode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_base32_encode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_base64_decode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_base64_encode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_abs(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_all_true(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_any_true(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_bin(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_bool(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_dict(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_float(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_hex(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_int(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_isnullish(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_isunique(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_len(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_list(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_max(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_min(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_multiplyof(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_oct(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_option(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare void @kclvm_builtin_option_init(%kclvm_context_t* %ctx, i8* %key, i8* %value); - -declare %kclvm_value_ref_t* @kclvm_builtin_option_reset(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_ord(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_pow(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_print(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_range(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_round(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_sorted(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_capitalize(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_chars(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_count(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_endswith(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_find(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_format(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_index(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_isalnum(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_isalpha(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_isdigit(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_islower(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_isspace(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_istitle(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_isupper(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_join(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_lower(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_lstrip(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_removeprefix(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_removesuffix(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_replace(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_rfind(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_rindex(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_rsplit(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_rstrip(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_split(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_splitlines(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_startswith(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_strip(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_title(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_str_upper(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_sum(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_typeof(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_builtin_zip(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare void @kclvm_config_attr_map(%kclvm_value_ref_t* %value, %kclvm_char_t* %name, %kclvm_char_t* %type_str); - -declare void @kclvm_context_delete(%kclvm_context_t* %p); - -declare i8* @kclvm_context_invoke(%kclvm_context_t* %p, i8* %method, i8* %args, i8* %kwargs); - -declare %kclvm_context_t* @kclvm_context_new(); - -declare %kclvm_bool_t @kclvm_context_pkgpath_is_imported(%kclvm_context_t* %ctx, %kclvm_char_t* %pkgpath); - -declare void @kclvm_context_set_debug_mode(%kclvm_context_t* %p, %kclvm_bool_t %v); - -declare void @kclvm_context_set_disable_none(%kclvm_context_t* %p, %kclvm_bool_t %v); - -declare void @kclvm_context_set_disable_schema_check(%kclvm_context_t* %p, %kclvm_bool_t %v); - -declare void @kclvm_context_set_import_names(%kclvm_context_t* %p, %kclvm_value_ref_t* %import_names); - -declare void @kclvm_context_set_kcl_filename(%kclvm_context_t* %ctx, i8* %filename); - -declare void @kclvm_context_set_kcl_line_col(%kclvm_context_t* %ctx, i32 %line, i32 %col); - -declare void @kclvm_context_set_kcl_location(%kclvm_context_t* %p, i8* %filename, i32 %line, i32 %col); - -declare void @kclvm_context_set_kcl_modpath(%kclvm_context_t* %p, i8* %module_path); - -declare void @kclvm_context_set_kcl_pkgpath(%kclvm_context_t* %p, i8* %pkgpath); - -declare void @kclvm_context_set_kcl_workdir(%kclvm_context_t* %p, i8* %workdir); - -declare void @kclvm_context_set_strict_range_check(%kclvm_context_t* %p, %kclvm_bool_t %v); - -declare %kclvm_value_ref_t* @kclvm_convert_collection_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %value, %kclvm_char_t* %tpe, %kclvm_value_ref_t* %is_in_schema); - -declare %kclvm_value_ref_t* @kclvm_crypto_blake3(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_crypto_fileblake3(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_crypto_filesha256(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_crypto_filesha512(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_crypto_md5(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_crypto_sha1(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_crypto_sha224(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_crypto_sha256(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_crypto_sha384(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_crypto_sha512(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_crypto_uuid(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_datetime_date(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_datetime_now(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_datetime_ticks(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_datetime_today(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_datetime_validate(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare void @kclvm_default_collection_insert_int_pointer(%kclvm_value_ref_t* %p, %kclvm_char_t* %key, i64* %ptr); - -declare void @kclvm_default_collection_insert_value(%kclvm_value_ref_t* %p, %kclvm_char_t* %key, %kclvm_value_ref_t* %value); - -declare void @kclvm_dict_clear(%kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_dict_get(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_value_ref_t* %key); - -declare %kclvm_value_ref_t* @kclvm_dict_get_entry(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key); - -declare %kclvm_value_ref_t* @kclvm_dict_get_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key); - -declare %kclvm_value_ref_t* @kclvm_dict_get_value_by_path(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %path); - -declare %kclvm_bool_t @kclvm_dict_has_value(%kclvm_value_ref_t* %p, %kclvm_char_t* %key); - -declare void @kclvm_dict_insert(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key, %kclvm_value_ref_t* %v, %kclvm_size_t %op, %kclvm_size_t %insert_index, %kclvm_bool_t %has_insert_index); - -declare void @kclvm_dict_insert_unpack(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_value_ref_t* %v); - -declare void @kclvm_dict_insert_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_value_ref_t* %key, %kclvm_value_ref_t* %v, %kclvm_size_t %op, %kclvm_size_t %insert_index, %kclvm_bool_t %has_insert_index); - -declare %kclvm_bool_t @kclvm_dict_is_override_attr(%kclvm_value_ref_t* %p, %kclvm_char_t* %key); - -declare %kclvm_value_ref_t* @kclvm_dict_keys(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -declare %kclvm_size_t @kclvm_dict_len(%kclvm_value_ref_t* %p); - -declare void @kclvm_dict_merge(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key, %kclvm_value_ref_t* %v, %kclvm_size_t %op, %kclvm_size_t %insert_index, %kclvm_bool_t %has_insert_index); - -declare void @kclvm_dict_remove(%kclvm_value_ref_t* %p, %kclvm_char_t* %key); - -declare void @kclvm_dict_safe_insert(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key, %kclvm_value_ref_t* %v, %kclvm_size_t %op, %kclvm_size_t %insert_index, %kclvm_bool_t %has_insert_index); - -declare void @kclvm_dict_set_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key, %kclvm_value_ref_t* %val); - -declare void @kclvm_dict_update(%kclvm_value_ref_t* %p, %kclvm_value_ref_t* %v); - -declare void @kclvm_dict_update_key_value(%kclvm_value_ref_t* %p, %kclvm_value_ref_t* %key, %kclvm_value_ref_t* %v); - -declare %kclvm_value_ref_t* @kclvm_dict_values(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_file_abs(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_file_append(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_file_cp(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_file_current(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_file_delete(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_file_exists(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_file_glob(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_file_mkdir(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_file_modpath(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_file_mv(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_file_read(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_file_read_env(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_file_size(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_file_workdir(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_file_write(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_iterator_cur_key(%kclvm_iterator_t* %p); - -declare %kclvm_value_ref_t* @kclvm_iterator_cur_value(%kclvm_iterator_t* %p); - -declare void @kclvm_iterator_delete(%kclvm_iterator_t* %p); - -declare %kclvm_bool_t @kclvm_iterator_is_end(%kclvm_iterator_t* %p); - -declare %kclvm_value_ref_t* @kclvm_iterator_next_value(%kclvm_iterator_t* %p, %kclvm_value_ref_t* %host); - -declare %kclvm_value_ref_t* @kclvm_json_decode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_json_dump_to_file(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_json_encode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_json_validate(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare void @kclvm_list_append(%kclvm_value_ref_t* %p, %kclvm_value_ref_t* %v); - -declare void @kclvm_list_append_bool(%kclvm_value_ref_t* %p, %kclvm_bool_t %v); - -declare void @kclvm_list_append_float(%kclvm_value_ref_t* %p, %kclvm_float_t %v); - -declare void @kclvm_list_append_int(%kclvm_value_ref_t* %p, %kclvm_int_t %v); - -declare void @kclvm_list_append_str(%kclvm_value_ref_t* %p, %kclvm_char_t* %v); - -declare void @kclvm_list_append_unpack(%kclvm_value_ref_t* %p, %kclvm_value_ref_t* %v); - -declare void @kclvm_list_clear(%kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_list_count(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_value_ref_t* %item); - -declare %kclvm_value_ref_t* @kclvm_list_find(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_value_ref_t* %item); - -declare %kclvm_value_ref_t* @kclvm_list_get(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_size_t %i); - -declare %kclvm_value_ref_t* @kclvm_list_get_option(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_size_t %i); - -declare void @kclvm_list_insert(%kclvm_value_ref_t* %p, %kclvm_value_ref_t* %index, %kclvm_value_ref_t* %value); - -declare %kclvm_size_t @kclvm_list_len(%kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_list_pop(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_list_pop_first(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -declare void @kclvm_list_remove_at(%kclvm_value_ref_t* %p, %kclvm_size_t %i); - -declare void @kclvm_list_resize(%kclvm_value_ref_t* %p, %kclvm_size_t %newsize); - -declare void @kclvm_list_set(%kclvm_value_ref_t* %p, %kclvm_size_t %i, %kclvm_value_ref_t* %v); - -declare %kclvm_value_ref_t* @kclvm_manifests_yaml_stream(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_ceil(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_exp(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_expm1(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_factorial(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_floor(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_gcd(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_isfinite(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_isinf(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_isnan(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_log(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_log10(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_log1p(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_log2(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_modf(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_pow(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_math_sqrt(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_CIDR_host(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_CIDR_netmask(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_CIDR_subnet(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_CIDR_subnets(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_IP_string(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_fqdn(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_is_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_is_IP_in_CIDR(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_is_IPv4(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_is_global_unicast_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_is_interface_local_multicast_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_is_link_local_multicast_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_is_link_local_unicast_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_is_loopback_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_is_multicast_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_is_unspecified_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_join_host_port(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_parse_CIDR(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_parse_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_split_host_port(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_to_IP6(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_net_to_IP4(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare void @kclvm_plugin_init(i8* %fn_ptr); - -declare %kclvm_value_ref_t* @kclvm_plugin_invoke(%kclvm_context_t* %ctx, i8* %method, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare i8* @kclvm_plugin_invoke_json(i8* %method, i8* %args, i8* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_regex_compile(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_regex_findall(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_regex_match(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_regex_replace(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_regex_search(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_regex_split(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_runtime_catch(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare void @kclvm_schema_assert(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %value, %kclvm_value_ref_t* %msg, %kclvm_value_ref_t* %config_meta); - -declare void @kclvm_schema_backtrack_cache(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %schema, %kclvm_value_ref_t* %cache, %kclvm_value_ref_t* %cal_map, %kclvm_char_t* %name, %kclvm_value_ref_t* %runtime_type); - -declare void @kclvm_schema_default_settings(%kclvm_value_ref_t* %schema_value, %kclvm_value_ref_t* %_config_value, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs, %kclvm_char_t* %runtime_type); - -declare void @kclvm_schema_do_check_with_index_sign_attr(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs, i64* %check_fn_ptr, %kclvm_char_t* %attr_name); - -declare %kclvm_value_ref_t* @kclvm_schema_get_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key, %kclvm_value_ref_t* %config, %kclvm_value_ref_t* %config_meta, %kclvm_value_ref_t* %cal_map, %kclvm_char_t* %target_attr, %kclvm_value_ref_t* %backtrack_level_map, %kclvm_value_ref_t* %backtrack_cache, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_schema_instances(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare void @kclvm_schema_optional_check(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -declare void @kclvm_schema_value_check(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %schema_value, %kclvm_value_ref_t* %schema_config, %kclvm_value_ref_t* %_config_meta, %kclvm_char_t* %schema_name, %kclvm_value_ref_t* %index_sign_value, %kclvm_char_t* %key_name, %kclvm_char_t* %key_type, %kclvm_char_t* %value_type, %kclvm_bool_t %_any_other); - -declare %kclvm_value_ref_t* @kclvm_schema_value_new(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs, %kclvm_value_ref_t* %schema_value_or_func, %kclvm_value_ref_t* %config, %kclvm_value_ref_t* %config_meta, %kclvm_char_t* %pkgpath); - -declare void @kclvm_scope_add_setter(%kclvm_context_t* %_ctx, %kclvm_eval_scope_t* %scope, i8* %pkg, i8* %name, i64* %setter); - -declare void @kclvm_scope_delete(%kclvm_eval_scope_t* %scope); - -declare %kclvm_value_ref_t* @kclvm_scope_get(%kclvm_context_t* %ctx, %kclvm_eval_scope_t* %scope, i8* %pkg, i8* %name, i8* %target, %kclvm_value_ref_t* %default); - -declare %kclvm_eval_scope_t* @kclvm_scope_new(); - -declare void @kclvm_scope_set(%kclvm_context_t* %_ctx, %kclvm_eval_scope_t* %scope, i8* %pkg, i8* %name, %kclvm_value_ref_t* %value); - -declare %kclvm_value_ref_t* @kclvm_template_execute(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_template_html_escape(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_units_to_G(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_units_to_Gi(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_units_to_K(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_units_to_Ki(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_units_to_M(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_units_to_Mi(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_units_to_P(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_units_to_Pi(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_units_to_T(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_units_to_Ti(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_units_to_m(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_units_to_n(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_units_to_u(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_value_Bool(%kclvm_context_t* %ctx, %kclvm_bool_t %v); - -declare %kclvm_decorator_value_t* @kclvm_value_Decorator(%kclvm_context_t* %ctx, %kclvm_char_t* %name, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs, %kclvm_value_ref_t* %config_meta, %kclvm_char_t* %attr_name, %kclvm_value_ref_t* %config_value, %kclvm_value_ref_t* %is_schema_target); - -declare %kclvm_value_ref_t* @kclvm_value_Dict(%kclvm_context_t* %ctx); - -declare %kclvm_value_ref_t* @kclvm_value_False(%kclvm_context_t* %ctx); - -declare %kclvm_value_ref_t* @kclvm_value_Float(%kclvm_context_t* %ctx, %kclvm_float_t %v); - -declare %kclvm_value_ref_t* @kclvm_value_Function(%kclvm_context_t* %ctx, i64* %fn_ptr, %kclvm_value_ref_t* %closure, %kclvm_char_t* %name, %kclvm_bool_t %is_external); - -declare %kclvm_value_ref_t* @kclvm_value_Function_using_ptr(%kclvm_context_t* %ctx, i64* %fn_ptr, %kclvm_char_t* %name); - -declare %kclvm_value_ref_t* @kclvm_value_Int(%kclvm_context_t* %ctx, %kclvm_int_t %v); - -declare %kclvm_value_ref_t* @kclvm_value_List(%kclvm_context_t* %ctx); - -declare %kclvm_value_ref_t* @kclvm_value_List10(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %v1, %kclvm_value_ref_t* %v2, %kclvm_value_ref_t* %v3, %kclvm_value_ref_t* %v4, %kclvm_value_ref_t* %v5, %kclvm_value_ref_t* %v6, %kclvm_value_ref_t* %v7, %kclvm_value_ref_t* %v8, %kclvm_value_ref_t* %v9, %kclvm_value_ref_t* %v10); - -declare %kclvm_value_ref_t* @kclvm_value_List6(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %v1, %kclvm_value_ref_t* %v2, %kclvm_value_ref_t* %v3, %kclvm_value_ref_t* %v4, %kclvm_value_ref_t* %v5, %kclvm_value_ref_t* %v6); - -declare %kclvm_value_ref_t* @kclvm_value_None(%kclvm_context_t* %ctx); - -declare %kclvm_value_ref_t* @kclvm_value_Schema(%kclvm_context_t* %ctx); - -declare %kclvm_value_ref_t* @kclvm_value_Str(%kclvm_context_t* %ctx, %kclvm_char_t* %v); - -declare %kclvm_char_t* @kclvm_value_Str_ptr(%kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_value_True(%kclvm_context_t* %ctx); - -declare %kclvm_value_ref_t* @kclvm_value_Undefined(%kclvm_context_t* %ctx); - -declare %kclvm_value_ref_t* @kclvm_value_Unit(%kclvm_context_t* %ctx, %kclvm_float_t %v, %kclvm_int_t %raw, %kclvm_char_t* %unit); - -declare %kclvm_value_ref_t* @kclvm_value_as(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare i64* @kclvm_value_check_function_ptr(%kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_value_cmp_equal_to(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_cmp_greater_than(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_cmp_greater_than_or_equal(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_cmp_less_than(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_cmp_less_than_or_equal(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_cmp_not_equal_to(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_deep_copy(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -declare void @kclvm_value_delete(%kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_value_from_json(%kclvm_context_t* %ctx, %kclvm_char_t* %s); - -declare %kclvm_value_ref_t* @kclvm_value_function_invoke(%kclvm_value_ref_t* %p, %kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs, %kclvm_char_t* %pkgpath, %kclvm_value_ref_t* %is_in_schema); - -declare i64* @kclvm_value_function_ptr(%kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_value_in(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_is(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_is_not(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_bool_t @kclvm_value_is_truthy(%kclvm_value_ref_t* %p); - -declare %kclvm_iterator_t* @kclvm_value_iter(%kclvm_value_ref_t* %p); - -declare %kclvm_size_t @kclvm_value_len(%kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_value_load_attr(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %obj, %kclvm_char_t* %key); - -declare %kclvm_value_ref_t* @kclvm_value_load_attr_option(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key); - -declare %kclvm_value_ref_t* @kclvm_value_logic_and(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_logic_or(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_not_in(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_add(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_aug_add(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_aug_bit_and(%kclvm_context_t* %_ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_aug_bit_lshift(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_aug_bit_or(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_aug_bit_rshift(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_aug_bit_xor(%kclvm_context_t* %_ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_aug_div(%kclvm_context_t* %_ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_aug_floor_div(%kclvm_context_t* %_ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_aug_mod(%kclvm_context_t* %_ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_aug_mul(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_aug_pow(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_aug_sub(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_bit_and(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_bit_lshift(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_bit_or(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_bit_rshift(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_bit_xor(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_div(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_floor_div(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_mod(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_mul(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_pow(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_op_sub(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_plan_to_json(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_value_plan_to_yaml(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -declare void @kclvm_value_remove_item(%kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_schema_function(%kclvm_context_t* %ctx, i64* %fn_ptr, i64* %check_fn_ptr, %kclvm_value_ref_t* %attr_map, %kclvm_char_t* %tpe); - -declare %kclvm_value_ref_t* @kclvm_value_schema_with_config(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %schema_dict, %kclvm_value_ref_t* %config, %kclvm_value_ref_t* %config_meta, %kclvm_char_t* %name, %kclvm_char_t* %pkgpath, %kclvm_value_ref_t* %is_sub_schema, %kclvm_value_ref_t* %record_instance, %kclvm_value_ref_t* %instance_pkgpath, %kclvm_value_ref_t* %optional_mapping, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_value_slice(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %x, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b, %kclvm_value_ref_t* %step); - -declare %kclvm_value_ref_t* @kclvm_value_slice_option(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %x, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b, %kclvm_value_ref_t* %step); - -declare %kclvm_value_ref_t* @kclvm_value_subscr(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_subscr_option(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -declare void @kclvm_value_subscr_set(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_value_ref_t* %index, %kclvm_value_ref_t* %val); - -declare %kclvm_value_ref_t* @kclvm_value_to_json_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_value_to_json_value_with_null(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_value_to_str_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_value_to_yaml_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -declare %kclvm_value_ref_t* @kclvm_value_unary_l_not(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a); - -declare %kclvm_value_ref_t* @kclvm_value_unary_minus(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a); - -declare %kclvm_value_ref_t* @kclvm_value_unary_not(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a); - -declare %kclvm_value_ref_t* @kclvm_value_unary_plus(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a); - -declare %kclvm_value_ref_t* @kclvm_value_union(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %schema, %kclvm_value_ref_t* %b); - -declare %kclvm_value_ref_t* @kclvm_value_union_all(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -declare %kclvm_value_ref_t* @kclvm_yaml_decode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_yaml_decode_all(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_yaml_dump_all_to_file(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_yaml_dump_to_file(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_yaml_encode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_yaml_encode_all(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -declare %kclvm_value_ref_t* @kclvm_yaml_validate(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -define void @__kcl_keep_link_runtime(%kclvm_value_ref_t* %_a, %kclvm_context_t* %_b) { - call %kclvm_value_ref_t* @kclvm_value_None(%kclvm_context_t* %_b) - ret void -} diff --git a/kclvm/runtime/src/_kclvm.rs b/kclvm/runtime/src/_kclvm.rs deleted file mode 100644 index 0dedc77b7..000000000 --- a/kclvm/runtime/src/_kclvm.rs +++ /dev/null @@ -1,374 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. - -// Auto generated, DONOT EDIT!!! - -#[allow(dead_code, non_camel_case_types)] -#[derive(Clone, PartialEq, Eq, Debug, Hash)] -pub enum ApiType { - Value, -} - -impl std::fmt::Display for ApiType { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - match self { - ApiType::Value => write!(f, "{:?}", "api::kclvm::Value"), - } - } -} - -impl ApiType { - #[allow(dead_code)] - pub fn name(&self) -> String { - format!("{self:?}") - } -} - -#[allow(dead_code, non_camel_case_types)] -#[derive(Clone, PartialEq, Eq, Debug, Hash)] -pub enum ApiFunc { - kclvm_assert, - kclvm_base32_decode, - kclvm_base32_encode, - kclvm_base64_decode, - kclvm_base64_encode, - kclvm_builtin_abs, - kclvm_builtin_all_true, - kclvm_builtin_any_true, - kclvm_builtin_bin, - kclvm_builtin_bool, - kclvm_builtin_dict, - kclvm_builtin_float, - kclvm_builtin_hex, - kclvm_builtin_int, - kclvm_builtin_isnullish, - kclvm_builtin_isunique, - kclvm_builtin_len, - kclvm_builtin_list, - kclvm_builtin_max, - kclvm_builtin_min, - kclvm_builtin_multiplyof, - kclvm_builtin_oct, - kclvm_builtin_option, - kclvm_builtin_option_init, - kclvm_builtin_option_reset, - kclvm_builtin_ord, - kclvm_builtin_pow, - kclvm_builtin_print, - kclvm_builtin_range, - kclvm_builtin_round, - kclvm_builtin_sorted, - kclvm_builtin_str, - kclvm_builtin_str_capitalize, - kclvm_builtin_str_chars, - kclvm_builtin_str_count, - kclvm_builtin_str_endswith, - kclvm_builtin_str_find, - kclvm_builtin_str_format, - kclvm_builtin_str_index, - kclvm_builtin_str_isalnum, - kclvm_builtin_str_isalpha, - kclvm_builtin_str_isdigit, - kclvm_builtin_str_islower, - kclvm_builtin_str_isspace, - kclvm_builtin_str_istitle, - kclvm_builtin_str_isupper, - kclvm_builtin_str_join, - kclvm_builtin_str_lower, - kclvm_builtin_str_lstrip, - kclvm_builtin_str_removeprefix, - kclvm_builtin_str_removesuffix, - kclvm_builtin_str_replace, - kclvm_builtin_str_rfind, - kclvm_builtin_str_rindex, - kclvm_builtin_str_rsplit, - kclvm_builtin_str_rstrip, - kclvm_builtin_str_split, - kclvm_builtin_str_splitlines, - kclvm_builtin_str_startswith, - kclvm_builtin_str_strip, - kclvm_builtin_str_title, - kclvm_builtin_str_upper, - kclvm_builtin_sum, - kclvm_builtin_typeof, - kclvm_builtin_zip, - kclvm_config_attr_map, - kclvm_context_delete, - kclvm_context_invoke, - kclvm_context_new, - kclvm_context_pkgpath_is_imported, - kclvm_context_set_debug_mode, - kclvm_context_set_disable_none, - kclvm_context_set_disable_schema_check, - kclvm_context_set_import_names, - kclvm_context_set_kcl_filename, - kclvm_context_set_kcl_line_col, - kclvm_context_set_kcl_location, - kclvm_context_set_kcl_modpath, - kclvm_context_set_kcl_pkgpath, - kclvm_context_set_kcl_workdir, - kclvm_context_set_strict_range_check, - kclvm_convert_collection_value, - kclvm_crypto_blake3, - kclvm_crypto_fileblake3, - kclvm_crypto_filesha256, - kclvm_crypto_filesha512, - kclvm_crypto_md5, - kclvm_crypto_sha1, - kclvm_crypto_sha224, - kclvm_crypto_sha256, - kclvm_crypto_sha384, - kclvm_crypto_sha512, - kclvm_crypto_uuid, - kclvm_datetime_date, - kclvm_datetime_now, - kclvm_datetime_ticks, - kclvm_datetime_today, - kclvm_datetime_validate, - kclvm_default_collection_insert_int_pointer, - kclvm_default_collection_insert_value, - kclvm_dict_clear, - kclvm_dict_get, - kclvm_dict_get_entry, - kclvm_dict_get_value, - kclvm_dict_get_value_by_path, - kclvm_dict_has_value, - kclvm_dict_insert, - kclvm_dict_insert_unpack, - kclvm_dict_insert_value, - kclvm_dict_is_override_attr, - kclvm_dict_keys, - kclvm_dict_len, - kclvm_dict_merge, - kclvm_dict_remove, - kclvm_dict_safe_insert, - kclvm_dict_set_value, - kclvm_dict_update, - kclvm_dict_update_key_value, - kclvm_dict_values, - kclvm_file_abs, - kclvm_file_append, - kclvm_file_cp, - kclvm_file_current, - kclvm_file_delete, - kclvm_file_exists, - kclvm_file_glob, - kclvm_file_mkdir, - kclvm_file_modpath, - kclvm_file_mv, - kclvm_file_read, - kclvm_file_read_env, - kclvm_file_size, - kclvm_file_workdir, - kclvm_file_write, - kclvm_iterator_cur_key, - kclvm_iterator_cur_value, - kclvm_iterator_delete, - kclvm_iterator_is_end, - kclvm_iterator_next_value, - kclvm_json_decode, - kclvm_json_dump_to_file, - kclvm_json_encode, - kclvm_json_validate, - kclvm_list_append, - kclvm_list_append_bool, - kclvm_list_append_float, - kclvm_list_append_int, - kclvm_list_append_str, - kclvm_list_append_unpack, - kclvm_list_clear, - kclvm_list_count, - kclvm_list_find, - kclvm_list_get, - kclvm_list_get_option, - kclvm_list_insert, - kclvm_list_len, - kclvm_list_pop, - kclvm_list_pop_first, - kclvm_list_remove_at, - kclvm_list_resize, - kclvm_list_set, - kclvm_manifests_yaml_stream, - kclvm_math_ceil, - kclvm_math_exp, - kclvm_math_expm1, - kclvm_math_factorial, - kclvm_math_floor, - kclvm_math_gcd, - kclvm_math_isfinite, - kclvm_math_isinf, - kclvm_math_isnan, - kclvm_math_log, - kclvm_math_log10, - kclvm_math_log1p, - kclvm_math_log2, - kclvm_math_modf, - kclvm_math_pow, - kclvm_math_sqrt, - kclvm_net_CIDR_host, - kclvm_net_CIDR_netmask, - kclvm_net_CIDR_subnet, - kclvm_net_CIDR_subnets, - kclvm_net_IP_string, - kclvm_net_fqdn, - kclvm_net_is_IP, - kclvm_net_is_IP_in_CIDR, - kclvm_net_is_IPv4, - kclvm_net_is_global_unicast_IP, - kclvm_net_is_interface_local_multicast_IP, - kclvm_net_is_link_local_multicast_IP, - kclvm_net_is_link_local_unicast_IP, - kclvm_net_is_loopback_IP, - kclvm_net_is_multicast_IP, - kclvm_net_is_unspecified_IP, - kclvm_net_join_host_port, - kclvm_net_parse_CIDR, - kclvm_net_parse_IP, - kclvm_net_split_host_port, - kclvm_net_to_IP6, - kclvm_net_to_IP4, - kclvm_plugin_init, - kclvm_plugin_invoke, - kclvm_plugin_invoke_json, - kclvm_regex_compile, - kclvm_regex_findall, - kclvm_regex_match, - kclvm_regex_replace, - kclvm_regex_search, - kclvm_regex_split, - kclvm_runtime_catch, - kclvm_schema_assert, - kclvm_schema_backtrack_cache, - kclvm_schema_default_settings, - kclvm_schema_do_check_with_index_sign_attr, - kclvm_schema_get_value, - kclvm_schema_instances, - kclvm_schema_optional_check, - kclvm_schema_value_check, - kclvm_schema_value_new, - kclvm_scope_add_setter, - kclvm_scope_delete, - kclvm_scope_get, - kclvm_scope_new, - kclvm_scope_set, - kclvm_template_execute, - kclvm_template_html_escape, - kclvm_units_to_G, - kclvm_units_to_Gi, - kclvm_units_to_K, - kclvm_units_to_Ki, - kclvm_units_to_M, - kclvm_units_to_Mi, - kclvm_units_to_P, - kclvm_units_to_Pi, - kclvm_units_to_T, - kclvm_units_to_Ti, - kclvm_units_to_m, - kclvm_units_to_n, - kclvm_units_to_u, - kclvm_value_Bool, - kclvm_value_Decorator, - kclvm_value_Dict, - kclvm_value_False, - kclvm_value_Float, - kclvm_value_Function, - kclvm_value_Function_using_ptr, - kclvm_value_Int, - kclvm_value_List, - kclvm_value_List10, - kclvm_value_List6, - kclvm_value_None, - kclvm_value_Schema, - kclvm_value_Str, - kclvm_value_Str_ptr, - kclvm_value_True, - kclvm_value_Undefined, - kclvm_value_Unit, - kclvm_value_as, - kclvm_value_check_function_ptr, - kclvm_value_cmp_equal_to, - kclvm_value_cmp_greater_than, - kclvm_value_cmp_greater_than_or_equal, - kclvm_value_cmp_less_than, - kclvm_value_cmp_less_than_or_equal, - kclvm_value_cmp_not_equal_to, - kclvm_value_deep_copy, - kclvm_value_delete, - kclvm_value_from_json, - kclvm_value_function_invoke, - kclvm_value_function_ptr, - kclvm_value_in, - kclvm_value_is, - kclvm_value_is_not, - kclvm_value_is_truthy, - kclvm_value_iter, - kclvm_value_len, - kclvm_value_load_attr, - kclvm_value_load_attr_option, - kclvm_value_logic_and, - kclvm_value_logic_or, - kclvm_value_not_in, - kclvm_value_op_add, - kclvm_value_op_aug_add, - kclvm_value_op_aug_bit_and, - kclvm_value_op_aug_bit_lshift, - kclvm_value_op_aug_bit_or, - kclvm_value_op_aug_bit_rshift, - kclvm_value_op_aug_bit_xor, - kclvm_value_op_aug_div, - kclvm_value_op_aug_floor_div, - kclvm_value_op_aug_mod, - kclvm_value_op_aug_mul, - kclvm_value_op_aug_pow, - kclvm_value_op_aug_sub, - kclvm_value_op_bit_and, - kclvm_value_op_bit_lshift, - kclvm_value_op_bit_or, - kclvm_value_op_bit_rshift, - kclvm_value_op_bit_xor, - kclvm_value_op_div, - kclvm_value_op_floor_div, - kclvm_value_op_mod, - kclvm_value_op_mul, - kclvm_value_op_pow, - kclvm_value_op_sub, - kclvm_value_plan_to_json, - kclvm_value_plan_to_yaml, - kclvm_value_remove_item, - kclvm_value_schema_function, - kclvm_value_schema_with_config, - kclvm_value_slice, - kclvm_value_slice_option, - kclvm_value_subscr, - kclvm_value_subscr_option, - kclvm_value_subscr_set, - kclvm_value_to_json_value, - kclvm_value_to_json_value_with_null, - kclvm_value_to_str_value, - kclvm_value_to_yaml_value, - kclvm_value_unary_l_not, - kclvm_value_unary_minus, - kclvm_value_unary_not, - kclvm_value_unary_plus, - kclvm_value_union, - kclvm_value_union_all, - kclvm_yaml_decode, - kclvm_yaml_decode_all, - kclvm_yaml_dump_all_to_file, - kclvm_yaml_dump_to_file, - kclvm_yaml_encode, - kclvm_yaml_encode_all, - kclvm_yaml_validate, -} - -impl std::fmt::Display for ApiFunc { - fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { - write!(f, "{self:?}") - } -} - -impl ApiFunc { - #[allow(dead_code)] - pub fn name(&self) -> String { - format!("{self:?}") - } -} diff --git a/kclvm/runtime/src/_kclvm_addr.rs b/kclvm/runtime/src/_kclvm_addr.rs deleted file mode 100644 index b3e4be5db..000000000 --- a/kclvm/runtime/src/_kclvm_addr.rs +++ /dev/null @@ -1,390 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. - -// Auto generated, DONOT EDIT!!! - -#[allow(dead_code)] -pub fn _kclvm_get_fn_ptr_by_name(name: &str) -> u64 { - match name { - "kclvm_assert" => crate::kclvm_assert as *const () as u64, - "kclvm_base32_decode" => crate::kclvm_base32_decode as *const () as u64, - "kclvm_base32_encode" => crate::kclvm_base32_encode as *const () as u64, - "kclvm_base64_decode" => crate::kclvm_base64_decode as *const () as u64, - "kclvm_base64_encode" => crate::kclvm_base64_encode as *const () as u64, - "kclvm_builtin_abs" => crate::kclvm_builtin_abs as *const () as u64, - "kclvm_builtin_all_true" => crate::kclvm_builtin_all_true as *const () as u64, - "kclvm_builtin_any_true" => crate::kclvm_builtin_any_true as *const () as u64, - "kclvm_builtin_bin" => crate::kclvm_builtin_bin as *const () as u64, - "kclvm_builtin_bool" => crate::kclvm_builtin_bool as *const () as u64, - "kclvm_builtin_dict" => crate::kclvm_builtin_dict as *const () as u64, - "kclvm_builtin_float" => crate::kclvm_builtin_float as *const () as u64, - "kclvm_builtin_hex" => crate::kclvm_builtin_hex as *const () as u64, - "kclvm_builtin_int" => crate::kclvm_builtin_int as *const () as u64, - "kclvm_builtin_isnullish" => crate::kclvm_builtin_isnullish as *const () as u64, - "kclvm_builtin_isunique" => crate::kclvm_builtin_isunique as *const () as u64, - "kclvm_builtin_len" => crate::kclvm_builtin_len as *const () as u64, - "kclvm_builtin_list" => crate::kclvm_builtin_list as *const () as u64, - "kclvm_builtin_max" => crate::kclvm_builtin_max as *const () as u64, - "kclvm_builtin_min" => crate::kclvm_builtin_min as *const () as u64, - "kclvm_builtin_multiplyof" => crate::kclvm_builtin_multiplyof as *const () as u64, - "kclvm_builtin_oct" => crate::kclvm_builtin_oct as *const () as u64, - "kclvm_builtin_option" => crate::kclvm_builtin_option as *const () as u64, - "kclvm_builtin_option_init" => crate::kclvm_builtin_option_init as *const () as u64, - "kclvm_builtin_option_reset" => crate::kclvm_builtin_option_reset as *const () as u64, - "kclvm_builtin_ord" => crate::kclvm_builtin_ord as *const () as u64, - "kclvm_builtin_pow" => crate::kclvm_builtin_pow as *const () as u64, - "kclvm_builtin_print" => crate::kclvm_builtin_print as *const () as u64, - "kclvm_builtin_range" => crate::kclvm_builtin_range as *const () as u64, - "kclvm_builtin_round" => crate::kclvm_builtin_round as *const () as u64, - "kclvm_builtin_sorted" => crate::kclvm_builtin_sorted as *const () as u64, - "kclvm_builtin_str" => crate::kclvm_builtin_str as *const () as u64, - "kclvm_builtin_str_capitalize" => crate::kclvm_builtin_str_capitalize as *const () as u64, - "kclvm_builtin_str_chars" => crate::kclvm_builtin_str_chars as *const () as u64, - "kclvm_builtin_str_count" => crate::kclvm_builtin_str_count as *const () as u64, - "kclvm_builtin_str_endswith" => crate::kclvm_builtin_str_endswith as *const () as u64, - "kclvm_builtin_str_find" => crate::kclvm_builtin_str_find as *const () as u64, - "kclvm_builtin_str_format" => crate::kclvm_builtin_str_format as *const () as u64, - "kclvm_builtin_str_index" => crate::kclvm_builtin_str_index as *const () as u64, - "kclvm_builtin_str_isalnum" => crate::kclvm_builtin_str_isalnum as *const () as u64, - "kclvm_builtin_str_isalpha" => crate::kclvm_builtin_str_isalpha as *const () as u64, - "kclvm_builtin_str_isdigit" => crate::kclvm_builtin_str_isdigit as *const () as u64, - "kclvm_builtin_str_islower" => crate::kclvm_builtin_str_islower as *const () as u64, - "kclvm_builtin_str_isspace" => crate::kclvm_builtin_str_isspace as *const () as u64, - "kclvm_builtin_str_istitle" => crate::kclvm_builtin_str_istitle as *const () as u64, - "kclvm_builtin_str_isupper" => crate::kclvm_builtin_str_isupper as *const () as u64, - "kclvm_builtin_str_join" => crate::kclvm_builtin_str_join as *const () as u64, - "kclvm_builtin_str_lower" => crate::kclvm_builtin_str_lower as *const () as u64, - "kclvm_builtin_str_lstrip" => crate::kclvm_builtin_str_lstrip as *const () as u64, - "kclvm_builtin_str_removeprefix" => { - crate::kclvm_builtin_str_removeprefix as *const () as u64 - } - "kclvm_builtin_str_removesuffix" => { - crate::kclvm_builtin_str_removesuffix as *const () as u64 - } - "kclvm_builtin_str_replace" => crate::kclvm_builtin_str_replace as *const () as u64, - "kclvm_builtin_str_rfind" => crate::kclvm_builtin_str_rfind as *const () as u64, - "kclvm_builtin_str_rindex" => crate::kclvm_builtin_str_rindex as *const () as u64, - "kclvm_builtin_str_rsplit" => crate::kclvm_builtin_str_rsplit as *const () as u64, - "kclvm_builtin_str_rstrip" => crate::kclvm_builtin_str_rstrip as *const () as u64, - "kclvm_builtin_str_split" => crate::kclvm_builtin_str_split as *const () as u64, - "kclvm_builtin_str_splitlines" => crate::kclvm_builtin_str_splitlines as *const () as u64, - "kclvm_builtin_str_startswith" => crate::kclvm_builtin_str_startswith as *const () as u64, - "kclvm_builtin_str_strip" => crate::kclvm_builtin_str_strip as *const () as u64, - "kclvm_builtin_str_title" => crate::kclvm_builtin_str_title as *const () as u64, - "kclvm_builtin_str_upper" => crate::kclvm_builtin_str_upper as *const () as u64, - "kclvm_builtin_sum" => crate::kclvm_builtin_sum as *const () as u64, - "kclvm_builtin_typeof" => crate::kclvm_builtin_typeof as *const () as u64, - "kclvm_builtin_zip" => crate::kclvm_builtin_zip as *const () as u64, - "kclvm_config_attr_map" => crate::kclvm_config_attr_map as *const () as u64, - "kclvm_context_delete" => crate::kclvm_context_delete as *const () as u64, - "kclvm_context_invoke" => crate::kclvm_context_invoke as *const () as u64, - "kclvm_context_new" => crate::kclvm_context_new as *const () as u64, - "kclvm_context_pkgpath_is_imported" => { - crate::kclvm_context_pkgpath_is_imported as *const () as u64 - } - "kclvm_context_set_debug_mode" => crate::kclvm_context_set_debug_mode as *const () as u64, - "kclvm_context_set_disable_none" => { - crate::kclvm_context_set_disable_none as *const () as u64 - } - "kclvm_context_set_disable_schema_check" => { - crate::kclvm_context_set_disable_schema_check as *const () as u64 - } - "kclvm_context_set_import_names" => { - crate::kclvm_context_set_import_names as *const () as u64 - } - "kclvm_context_set_kcl_filename" => { - crate::kclvm_context_set_kcl_filename as *const () as u64 - } - "kclvm_context_set_kcl_line_col" => { - crate::kclvm_context_set_kcl_line_col as *const () as u64 - } - "kclvm_context_set_kcl_location" => { - crate::kclvm_context_set_kcl_location as *const () as u64 - } - "kclvm_context_set_kcl_modpath" => crate::kclvm_context_set_kcl_modpath as *const () as u64, - "kclvm_context_set_kcl_pkgpath" => crate::kclvm_context_set_kcl_pkgpath as *const () as u64, - "kclvm_context_set_kcl_workdir" => crate::kclvm_context_set_kcl_workdir as *const () as u64, - "kclvm_context_set_strict_range_check" => { - crate::kclvm_context_set_strict_range_check as *const () as u64 - } - "kclvm_convert_collection_value" => { - crate::kclvm_convert_collection_value as *const () as u64 - } - "kclvm_crypto_blake3" => crate::kclvm_crypto_blake3 as *const () as u64, - "kclvm_crypto_fileblake3" => crate::kclvm_crypto_fileblake3 as *const () as u64, - "kclvm_crypto_filesha256" => crate::kclvm_crypto_filesha256 as *const () as u64, - "kclvm_crypto_filesha512" => crate::kclvm_crypto_filesha512 as *const () as u64, - "kclvm_crypto_md5" => crate::kclvm_crypto_md5 as *const () as u64, - "kclvm_crypto_sha1" => crate::kclvm_crypto_sha1 as *const () as u64, - "kclvm_crypto_sha224" => crate::kclvm_crypto_sha224 as *const () as u64, - "kclvm_crypto_sha256" => crate::kclvm_crypto_sha256 as *const () as u64, - "kclvm_crypto_sha384" => crate::kclvm_crypto_sha384 as *const () as u64, - "kclvm_crypto_sha512" => crate::kclvm_crypto_sha512 as *const () as u64, - "kclvm_crypto_uuid" => crate::kclvm_crypto_uuid as *const () as u64, - "kclvm_datetime_date" => crate::kclvm_datetime_date as *const () as u64, - "kclvm_datetime_now" => crate::kclvm_datetime_now as *const () as u64, - "kclvm_datetime_ticks" => crate::kclvm_datetime_ticks as *const () as u64, - "kclvm_datetime_today" => crate::kclvm_datetime_today as *const () as u64, - "kclvm_datetime_validate" => crate::kclvm_datetime_validate as *const () as u64, - "kclvm_default_collection_insert_int_pointer" => { - crate::kclvm_default_collection_insert_int_pointer as *const () as u64 - } - "kclvm_default_collection_insert_value" => { - crate::kclvm_default_collection_insert_value as *const () as u64 - } - "kclvm_dict_clear" => crate::kclvm_dict_clear as *const () as u64, - "kclvm_dict_get" => crate::kclvm_dict_get as *const () as u64, - "kclvm_dict_get_entry" => crate::kclvm_dict_get_entry as *const () as u64, - "kclvm_dict_get_value" => crate::kclvm_dict_get_value as *const () as u64, - "kclvm_dict_get_value_by_path" => crate::kclvm_dict_get_value_by_path as *const () as u64, - "kclvm_dict_has_value" => crate::kclvm_dict_has_value as *const () as u64, - "kclvm_dict_insert" => crate::kclvm_dict_insert as *const () as u64, - "kclvm_dict_insert_unpack" => crate::kclvm_dict_insert_unpack as *const () as u64, - "kclvm_dict_insert_value" => crate::kclvm_dict_insert_value as *const () as u64, - "kclvm_dict_is_override_attr" => crate::kclvm_dict_is_override_attr as *const () as u64, - "kclvm_dict_keys" => crate::kclvm_dict_keys as *const () as u64, - "kclvm_dict_len" => crate::kclvm_dict_len as *const () as u64, - "kclvm_dict_merge" => crate::kclvm_dict_merge as *const () as u64, - "kclvm_dict_remove" => crate::kclvm_dict_remove as *const () as u64, - "kclvm_dict_safe_insert" => crate::kclvm_dict_safe_insert as *const () as u64, - "kclvm_dict_set_value" => crate::kclvm_dict_set_value as *const () as u64, - "kclvm_dict_update" => crate::kclvm_dict_update as *const () as u64, - "kclvm_dict_update_key_value" => crate::kclvm_dict_update_key_value as *const () as u64, - "kclvm_dict_values" => crate::kclvm_dict_values as *const () as u64, - "kclvm_file_abs" => crate::kclvm_file_abs as *const () as u64, - "kclvm_file_append" => crate::kclvm_file_append as *const () as u64, - "kclvm_file_cp" => crate::kclvm_file_cp as *const () as u64, - "kclvm_file_current" => crate::kclvm_file_current as *const () as u64, - "kclvm_file_delete" => crate::kclvm_file_delete as *const () as u64, - "kclvm_file_exists" => crate::kclvm_file_exists as *const () as u64, - "kclvm_file_glob" => crate::kclvm_file_glob as *const () as u64, - "kclvm_file_mkdir" => crate::kclvm_file_mkdir as *const () as u64, - "kclvm_file_modpath" => crate::kclvm_file_modpath as *const () as u64, - "kclvm_file_mv" => crate::kclvm_file_mv as *const () as u64, - "kclvm_file_read" => crate::kclvm_file_read as *const () as u64, - "kclvm_file_read_env" => crate::kclvm_file_read_env as *const () as u64, - "kclvm_file_size" => crate::kclvm_file_size as *const () as u64, - "kclvm_file_workdir" => crate::kclvm_file_workdir as *const () as u64, - "kclvm_file_write" => crate::kclvm_file_write as *const () as u64, - "kclvm_iterator_cur_key" => crate::kclvm_iterator_cur_key as *const () as u64, - "kclvm_iterator_cur_value" => crate::kclvm_iterator_cur_value as *const () as u64, - "kclvm_iterator_delete" => crate::kclvm_iterator_delete as *const () as u64, - "kclvm_iterator_is_end" => crate::kclvm_iterator_is_end as *const () as u64, - "kclvm_iterator_next_value" => crate::kclvm_iterator_next_value as *const () as u64, - "kclvm_json_decode" => crate::kclvm_json_decode as *const () as u64, - "kclvm_json_dump_to_file" => crate::kclvm_json_dump_to_file as *const () as u64, - "kclvm_json_encode" => crate::kclvm_json_encode as *const () as u64, - "kclvm_json_validate" => crate::kclvm_json_validate as *const () as u64, - "kclvm_list_append" => crate::kclvm_list_append as *const () as u64, - "kclvm_list_append_bool" => crate::kclvm_list_append_bool as *const () as u64, - "kclvm_list_append_float" => crate::kclvm_list_append_float as *const () as u64, - "kclvm_list_append_int" => crate::kclvm_list_append_int as *const () as u64, - "kclvm_list_append_str" => crate::kclvm_list_append_str as *const () as u64, - "kclvm_list_append_unpack" => crate::kclvm_list_append_unpack as *const () as u64, - "kclvm_list_clear" => crate::kclvm_list_clear as *const () as u64, - "kclvm_list_count" => crate::kclvm_list_count as *const () as u64, - "kclvm_list_find" => crate::kclvm_list_find as *const () as u64, - "kclvm_list_get" => crate::kclvm_list_get as *const () as u64, - "kclvm_list_get_option" => crate::kclvm_list_get_option as *const () as u64, - "kclvm_list_insert" => crate::kclvm_list_insert as *const () as u64, - "kclvm_list_len" => crate::kclvm_list_len as *const () as u64, - "kclvm_list_pop" => crate::kclvm_list_pop as *const () as u64, - "kclvm_list_pop_first" => crate::kclvm_list_pop_first as *const () as u64, - "kclvm_list_remove_at" => crate::kclvm_list_remove_at as *const () as u64, - "kclvm_list_resize" => crate::kclvm_list_resize as *const () as u64, - "kclvm_list_set" => crate::kclvm_list_set as *const () as u64, - "kclvm_manifests_yaml_stream" => crate::kclvm_manifests_yaml_stream as *const () as u64, - "kclvm_math_ceil" => crate::kclvm_math_ceil as *const () as u64, - "kclvm_math_exp" => crate::kclvm_math_exp as *const () as u64, - "kclvm_math_expm1" => crate::kclvm_math_expm1 as *const () as u64, - "kclvm_math_factorial" => crate::kclvm_math_factorial as *const () as u64, - "kclvm_math_floor" => crate::kclvm_math_floor as *const () as u64, - "kclvm_math_gcd" => crate::kclvm_math_gcd as *const () as u64, - "kclvm_math_isfinite" => crate::kclvm_math_isfinite as *const () as u64, - "kclvm_math_isinf" => crate::kclvm_math_isinf as *const () as u64, - "kclvm_math_isnan" => crate::kclvm_math_isnan as *const () as u64, - "kclvm_math_log" => crate::kclvm_math_log as *const () as u64, - "kclvm_math_log10" => crate::kclvm_math_log10 as *const () as u64, - "kclvm_math_log1p" => crate::kclvm_math_log1p as *const () as u64, - "kclvm_math_log2" => crate::kclvm_math_log2 as *const () as u64, - "kclvm_math_modf" => crate::kclvm_math_modf as *const () as u64, - "kclvm_math_pow" => crate::kclvm_math_pow as *const () as u64, - "kclvm_math_sqrt" => crate::kclvm_math_sqrt as *const () as u64, - "kclvm_net_CIDR_host" => crate::kclvm_net_CIDR_host as *const () as u64, - "kclvm_net_CIDR_netmask" => crate::kclvm_net_CIDR_netmask as *const () as u64, - "kclvm_net_CIDR_subnet" => crate::kclvm_net_CIDR_subnet as *const () as u64, - "kclvm_net_CIDR_subnets" => crate::kclvm_net_CIDR_subnets as *const () as u64, - "kclvm_net_IP_string" => crate::kclvm_net_IP_string as *const () as u64, - "kclvm_net_fqdn" => crate::kclvm_net_fqdn as *const () as u64, - "kclvm_net_is_IP" => crate::kclvm_net_is_IP as *const () as u64, - "kclvm_net_is_IPv4" => crate::kclvm_net_is_IPv4 as *const () as u64, - "kclvm_net_is_global_unicast_IP" => { - crate::kclvm_net_is_global_unicast_IP as *const () as u64 - } - "kclvm_net_is_interface_local_multicast_IP" => { - crate::kclvm_net_is_interface_local_multicast_IP as *const () as u64 - } - "kclvm_net_is_link_local_multicast_IP" => { - crate::kclvm_net_is_link_local_multicast_IP as *const () as u64 - } - "kclvm_net_is_link_local_unicast_IP" => { - crate::kclvm_net_is_link_local_unicast_IP as *const () as u64 - } - "kclvm_net_is_loopback_IP" => crate::kclvm_net_is_loopback_IP as *const () as u64, - "kclvm_net_is_multicast_IP" => crate::kclvm_net_is_multicast_IP as *const () as u64, - "kclvm_net_is_unspecified_IP" => crate::kclvm_net_is_unspecified_IP as *const () as u64, - "kclvm_net_parse_CIDR" => crate::kclvm_net_parse_CIDR as *const () as u64, - "kclvm_net_is_IP_in_CIDR" => crate::kclvm_net_is_IP_in_CIDR as *const () as u64, - "kclvm_net_join_host_port" => crate::kclvm_net_join_host_port as *const () as u64, - "kclvm_net_parse_IP" => crate::kclvm_net_parse_IP as *const () as u64, - "kclvm_net_split_host_port" => crate::kclvm_net_split_host_port as *const () as u64, - "kclvm_net_to_IP6" => crate::kclvm_net_to_IP6 as *const () as u64, - "kclvm_net_to_IP4" => crate::kclvm_net_to_IP4 as *const () as u64, - "kclvm_plugin_init" => crate::kclvm_plugin_init as *const () as u64, - "kclvm_plugin_invoke" => crate::kclvm_plugin_invoke as *const () as u64, - "kclvm_plugin_invoke_json" => crate::kclvm_plugin_invoke_json as *const () as u64, - "kclvm_regex_compile" => crate::kclvm_regex_compile as *const () as u64, - "kclvm_regex_findall" => crate::kclvm_regex_findall as *const () as u64, - "kclvm_regex_match" => crate::kclvm_regex_match as *const () as u64, - "kclvm_regex_replace" => crate::kclvm_regex_replace as *const () as u64, - "kclvm_regex_search" => crate::kclvm_regex_search as *const () as u64, - "kclvm_regex_split" => crate::kclvm_regex_split as *const () as u64, - "kclvm_runtime_catch" => crate::kclvm_runtime_catch as *const () as u64, - "kclvm_schema_assert" => crate::kclvm_schema_assert as *const () as u64, - "kclvm_schema_backtrack_cache" => crate::kclvm_schema_backtrack_cache as *const () as u64, - "kclvm_schema_default_settings" => crate::kclvm_schema_default_settings as *const () as u64, - "kclvm_schema_do_check_with_index_sign_attr" => { - crate::kclvm_schema_do_check_with_index_sign_attr as *const () as u64 - } - "kclvm_schema_get_value" => crate::kclvm_schema_get_value as *const () as u64, - "kclvm_schema_instances" => crate::kclvm_schema_instances as *const () as u64, - "kclvm_schema_optional_check" => crate::kclvm_schema_optional_check as *const () as u64, - "kclvm_schema_value_check" => crate::kclvm_schema_value_check as *const () as u64, - "kclvm_schema_value_new" => crate::kclvm_schema_value_new as *const () as u64, - "kclvm_scope_add_setter" => crate::kclvm_scope_add_setter as *const () as u64, - "kclvm_scope_delete" => crate::kclvm_scope_delete as *const () as u64, - "kclvm_scope_get" => crate::kclvm_scope_get as *const () as u64, - "kclvm_scope_new" => crate::kclvm_scope_new as *const () as u64, - "kclvm_scope_set" => crate::kclvm_scope_set as *const () as u64, - "kclvm_template_execute" => crate::kclvm_template_execute as *const () as u64, - "kclvm_template_html_escape" => crate::kclvm_template_html_escape as *const () as u64, - "kclvm_units_to_G" => crate::kclvm_units_to_G as *const () as u64, - "kclvm_units_to_Gi" => crate::kclvm_units_to_Gi as *const () as u64, - "kclvm_units_to_K" => crate::kclvm_units_to_K as *const () as u64, - "kclvm_units_to_Ki" => crate::kclvm_units_to_Ki as *const () as u64, - "kclvm_units_to_M" => crate::kclvm_units_to_M as *const () as u64, - "kclvm_units_to_Mi" => crate::kclvm_units_to_Mi as *const () as u64, - "kclvm_units_to_P" => crate::kclvm_units_to_P as *const () as u64, - "kclvm_units_to_Pi" => crate::kclvm_units_to_Pi as *const () as u64, - "kclvm_units_to_T" => crate::kclvm_units_to_T as *const () as u64, - "kclvm_units_to_Ti" => crate::kclvm_units_to_Ti as *const () as u64, - "kclvm_units_to_m" => crate::kclvm_units_to_m as *const () as u64, - "kclvm_units_to_n" => crate::kclvm_units_to_n as *const () as u64, - "kclvm_units_to_u" => crate::kclvm_units_to_u as *const () as u64, - "kclvm_value_Bool" => crate::kclvm_value_Bool as *const () as u64, - "kclvm_value_Decorator" => crate::kclvm_value_Decorator as *const () as u64, - "kclvm_value_Dict" => crate::kclvm_value_Dict as *const () as u64, - "kclvm_value_False" => crate::kclvm_value_False as *const () as u64, - "kclvm_value_Float" => crate::kclvm_value_Float as *const () as u64, - "kclvm_value_Function" => crate::kclvm_value_Function as *const () as u64, - "kclvm_value_Function_using_ptr" => { - crate::kclvm_value_Function_using_ptr as *const () as u64 - } - "kclvm_value_Int" => crate::kclvm_value_Int as *const () as u64, - "kclvm_value_List" => crate::kclvm_value_List as *const () as u64, - "kclvm_value_List10" => crate::kclvm_value_List10 as *const () as u64, - "kclvm_value_List6" => crate::kclvm_value_List6 as *const () as u64, - "kclvm_value_None" => crate::kclvm_value_None as *const () as u64, - "kclvm_value_Schema" => crate::kclvm_value_Schema as *const () as u64, - "kclvm_value_Str" => crate::kclvm_value_Str as *const () as u64, - "kclvm_value_Str_ptr" => crate::kclvm_value_Str_ptr as *const () as u64, - "kclvm_value_True" => crate::kclvm_value_True as *const () as u64, - "kclvm_value_Undefined" => crate::kclvm_value_Undefined as *const () as u64, - "kclvm_value_Unit" => crate::kclvm_value_Unit as *const () as u64, - "kclvm_value_as" => crate::kclvm_value_as as *const () as u64, - "kclvm_value_check_function_ptr" => { - crate::kclvm_value_check_function_ptr as *const () as u64 - } - "kclvm_value_cmp_equal_to" => crate::kclvm_value_cmp_equal_to as *const () as u64, - "kclvm_value_cmp_greater_than" => crate::kclvm_value_cmp_greater_than as *const () as u64, - "kclvm_value_cmp_greater_than_or_equal" => { - crate::kclvm_value_cmp_greater_than_or_equal as *const () as u64 - } - "kclvm_value_cmp_less_than" => crate::kclvm_value_cmp_less_than as *const () as u64, - "kclvm_value_cmp_less_than_or_equal" => { - crate::kclvm_value_cmp_less_than_or_equal as *const () as u64 - } - "kclvm_value_cmp_not_equal_to" => crate::kclvm_value_cmp_not_equal_to as *const () as u64, - "kclvm_value_deep_copy" => crate::kclvm_value_deep_copy as *const () as u64, - "kclvm_value_delete" => crate::kclvm_value_delete as *const () as u64, - "kclvm_value_from_json" => crate::kclvm_value_from_json as *const () as u64, - "kclvm_value_function_invoke" => crate::kclvm_value_function_invoke as *const () as u64, - "kclvm_value_function_ptr" => crate::kclvm_value_function_ptr as *const () as u64, - "kclvm_value_in" => crate::kclvm_value_in as *const () as u64, - "kclvm_value_is" => crate::kclvm_value_is as *const () as u64, - "kclvm_value_is_not" => crate::kclvm_value_is_not as *const () as u64, - "kclvm_value_is_truthy" => crate::kclvm_value_is_truthy as *const () as u64, - "kclvm_value_iter" => crate::kclvm_value_iter as *const () as u64, - "kclvm_value_len" => crate::kclvm_value_len as *const () as u64, - "kclvm_value_load_attr" => crate::kclvm_value_load_attr as *const () as u64, - "kclvm_value_load_attr_option" => crate::kclvm_value_load_attr_option as *const () as u64, - "kclvm_value_logic_and" => crate::kclvm_value_logic_and as *const () as u64, - "kclvm_value_logic_or" => crate::kclvm_value_logic_or as *const () as u64, - "kclvm_value_not_in" => crate::kclvm_value_not_in as *const () as u64, - "kclvm_value_op_add" => crate::kclvm_value_op_add as *const () as u64, - "kclvm_value_op_aug_add" => crate::kclvm_value_op_aug_add as *const () as u64, - "kclvm_value_op_aug_bit_and" => crate::kclvm_value_op_aug_bit_and as *const () as u64, - "kclvm_value_op_aug_bit_lshift" => crate::kclvm_value_op_aug_bit_lshift as *const () as u64, - "kclvm_value_op_aug_bit_or" => crate::kclvm_value_op_aug_bit_or as *const () as u64, - "kclvm_value_op_aug_bit_rshift" => crate::kclvm_value_op_aug_bit_rshift as *const () as u64, - "kclvm_value_op_aug_bit_xor" => crate::kclvm_value_op_aug_bit_xor as *const () as u64, - "kclvm_value_op_aug_div" => crate::kclvm_value_op_aug_div as *const () as u64, - "kclvm_value_op_aug_floor_div" => crate::kclvm_value_op_aug_floor_div as *const () as u64, - "kclvm_value_op_aug_mod" => crate::kclvm_value_op_aug_mod as *const () as u64, - "kclvm_value_op_aug_mul" => crate::kclvm_value_op_aug_mul as *const () as u64, - "kclvm_value_op_aug_pow" => crate::kclvm_value_op_aug_pow as *const () as u64, - "kclvm_value_op_aug_sub" => crate::kclvm_value_op_aug_sub as *const () as u64, - "kclvm_value_op_bit_and" => crate::kclvm_value_op_bit_and as *const () as u64, - "kclvm_value_op_bit_lshift" => crate::kclvm_value_op_bit_lshift as *const () as u64, - "kclvm_value_op_bit_or" => crate::kclvm_value_op_bit_or as *const () as u64, - "kclvm_value_op_bit_rshift" => crate::kclvm_value_op_bit_rshift as *const () as u64, - "kclvm_value_op_bit_xor" => crate::kclvm_value_op_bit_xor as *const () as u64, - "kclvm_value_op_div" => crate::kclvm_value_op_div as *const () as u64, - "kclvm_value_op_floor_div" => crate::kclvm_value_op_floor_div as *const () as u64, - "kclvm_value_op_mod" => crate::kclvm_value_op_mod as *const () as u64, - "kclvm_value_op_mul" => crate::kclvm_value_op_mul as *const () as u64, - "kclvm_value_op_pow" => crate::kclvm_value_op_pow as *const () as u64, - "kclvm_value_op_sub" => crate::kclvm_value_op_sub as *const () as u64, - "kclvm_value_plan_to_json" => crate::kclvm_value_plan_to_json as *const () as u64, - "kclvm_value_plan_to_yaml" => crate::kclvm_value_plan_to_yaml as *const () as u64, - "kclvm_value_remove_item" => crate::kclvm_value_remove_item as *const () as u64, - "kclvm_value_schema_function" => crate::kclvm_value_schema_function as *const () as u64, - "kclvm_value_schema_with_config" => { - crate::kclvm_value_schema_with_config as *const () as u64 - } - "kclvm_value_slice" => crate::kclvm_value_slice as *const () as u64, - "kclvm_value_slice_option" => crate::kclvm_value_slice_option as *const () as u64, - "kclvm_value_subscr" => crate::kclvm_value_subscr as *const () as u64, - "kclvm_value_subscr_option" => crate::kclvm_value_subscr_option as *const () as u64, - "kclvm_value_subscr_set" => crate::kclvm_value_subscr_set as *const () as u64, - "kclvm_value_to_json_value" => crate::kclvm_value_to_json_value as *const () as u64, - "kclvm_value_to_json_value_with_null" => { - crate::kclvm_value_to_json_value_with_null as *const () as u64 - } - "kclvm_value_to_str_value" => crate::kclvm_value_to_str_value as *const () as u64, - "kclvm_value_to_yaml_value" => crate::kclvm_value_to_yaml_value as *const () as u64, - "kclvm_value_unary_l_not" => crate::kclvm_value_unary_l_not as *const () as u64, - "kclvm_value_unary_minus" => crate::kclvm_value_unary_minus as *const () as u64, - "kclvm_value_unary_not" => crate::kclvm_value_unary_not as *const () as u64, - "kclvm_value_unary_plus" => crate::kclvm_value_unary_plus as *const () as u64, - "kclvm_value_union" => crate::kclvm_value_union as *const () as u64, - "kclvm_value_union_all" => crate::kclvm_value_union_all as *const () as u64, - "kclvm_yaml_decode" => crate::kclvm_yaml_decode as *const () as u64, - "kclvm_yaml_decode_all" => crate::kclvm_yaml_decode_all as *const () as u64, - "kclvm_yaml_dump_all_to_file" => crate::kclvm_yaml_dump_all_to_file as *const () as u64, - "kclvm_yaml_dump_to_file" => crate::kclvm_yaml_dump_to_file as *const () as u64, - "kclvm_yaml_encode" => crate::kclvm_yaml_encode as *const () as u64, - "kclvm_yaml_encode_all" => crate::kclvm_yaml_encode_all as *const () as u64, - "kclvm_yaml_validate" => crate::kclvm_yaml_validate as *const () as u64, - _ => panic!("unknown {name}"), - } -} diff --git a/kclvm/runtime/src/_kclvm_api_spec.rs b/kclvm/runtime/src/_kclvm_api_spec.rs deleted file mode 100644 index a9d0ae9bc..000000000 --- a/kclvm/runtime/src/_kclvm_api_spec.rs +++ /dev/null @@ -1,1332 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. - -// Auto generated by command, DONOT EDIT!!! - -// api-spec: kclvm_context_new -// api-spec(c): kclvm_context_t* kclvm_context_new(); -// api-spec(llvm): declare %kclvm_context_t* @kclvm_context_new(); - -// api-spec: kclvm_context_delete -// api-spec(c): void kclvm_context_delete(kclvm_context_t* p); -// api-spec(llvm): declare void @kclvm_context_delete(%kclvm_context_t* %p); - -// api-spec: kclvm_context_set_kcl_location -// api-spec(c): void kclvm_context_set_kcl_location(kclvm_context_t* p, char* filename, int32_t line, int32_t col); -// api-spec(llvm): declare void @kclvm_context_set_kcl_location(%kclvm_context_t* %p, i8* %filename, i32 %line, i32 %col); - -// api-spec: kclvm_context_set_kcl_pkgpath -// api-spec(c): void kclvm_context_set_kcl_pkgpath(kclvm_context_t* p, char* pkgpath); -// api-spec(llvm): declare void @kclvm_context_set_kcl_pkgpath(%kclvm_context_t* %p, i8* %pkgpath); - -// api-spec: kclvm_context_set_kcl_modpath -// api-spec(c): void kclvm_context_set_kcl_modpath(kclvm_context_t* p, char* module_path); -// api-spec(llvm): declare void @kclvm_context_set_kcl_modpath(%kclvm_context_t* %p, i8* %module_path); - -// api-spec: kclvm_context_set_kcl_workdir -// api-spec(c): void kclvm_context_set_kcl_workdir(kclvm_context_t* p, char* workdir); -// api-spec(llvm): declare void @kclvm_context_set_kcl_workdir(%kclvm_context_t* %p, i8* %workdir); - -// api-spec: kclvm_context_set_kcl_filename -// api-spec(c): void kclvm_context_set_kcl_filename(kclvm_context_t* ctx, char* filename); -// api-spec(llvm): declare void @kclvm_context_set_kcl_filename(%kclvm_context_t* %ctx, i8* %filename); - -// api-spec: kclvm_context_set_kcl_line_col -// api-spec(c): void kclvm_context_set_kcl_line_col(kclvm_context_t* ctx, int32_t line, int32_t col); -// api-spec(llvm): declare void @kclvm_context_set_kcl_line_col(%kclvm_context_t* %ctx, i32 %line, i32 %col); - -// api-spec: kclvm_scope_new -// api-spec(c): kclvm_eval_scope_t* kclvm_scope_new(); -// api-spec(llvm): declare %kclvm_eval_scope_t* @kclvm_scope_new(); - -// api-spec: kclvm_scope_delete -// api-spec(c): void kclvm_scope_delete(kclvm_eval_scope_t* scope); -// api-spec(llvm): declare void @kclvm_scope_delete(%kclvm_eval_scope_t* %scope); - -// api-spec: kclvm_scope_add_setter -// api-spec(c): void kclvm_scope_add_setter(kclvm_context_t* _ctx, kclvm_eval_scope_t* scope, char* pkg, char* name, uint64_t* setter); -// api-spec(llvm): declare void @kclvm_scope_add_setter(%kclvm_context_t* %_ctx, %kclvm_eval_scope_t* %scope, i8* %pkg, i8* %name, i64* %setter); - -// api-spec: kclvm_scope_set -// api-spec(c): void kclvm_scope_set(kclvm_context_t* _ctx, kclvm_eval_scope_t* scope, char* pkg, char* name, kclvm_value_ref_t* value); -// api-spec(llvm): declare void @kclvm_scope_set(%kclvm_context_t* %_ctx, %kclvm_eval_scope_t* %scope, i8* %pkg, i8* %name, %kclvm_value_ref_t* %value); - -// api-spec: kclvm_scope_get -// api-spec(c): kclvm_value_ref_t* kclvm_scope_get(kclvm_context_t* ctx, kclvm_eval_scope_t* scope, char* pkg, char* name, char* target, kclvm_value_ref_t* default); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_scope_get(%kclvm_context_t* %ctx, %kclvm_eval_scope_t* %scope, i8* %pkg, i8* %name, i8* %target, %kclvm_value_ref_t* %default); - -// api-spec: kclvm_context_set_debug_mode -// api-spec(c): void kclvm_context_set_debug_mode(kclvm_context_t* p, kclvm_bool_t v); -// api-spec(llvm): declare void @kclvm_context_set_debug_mode(%kclvm_context_t* %p, %kclvm_bool_t %v); - -// api-spec: kclvm_context_set_strict_range_check -// api-spec(c): void kclvm_context_set_strict_range_check(kclvm_context_t* p, kclvm_bool_t v); -// api-spec(llvm): declare void @kclvm_context_set_strict_range_check(%kclvm_context_t* %p, %kclvm_bool_t %v); - -// api-spec: kclvm_context_set_disable_none -// api-spec(c): void kclvm_context_set_disable_none(kclvm_context_t* p, kclvm_bool_t v); -// api-spec(llvm): declare void @kclvm_context_set_disable_none(%kclvm_context_t* %p, %kclvm_bool_t %v); - -// api-spec: kclvm_context_set_disable_schema_check -// api-spec(c): void kclvm_context_set_disable_schema_check(kclvm_context_t* p, kclvm_bool_t v); -// api-spec(llvm): declare void @kclvm_context_set_disable_schema_check(%kclvm_context_t* %p, %kclvm_bool_t %v); - -// api-spec: kclvm_context_invoke -// api-spec(c): char* kclvm_context_invoke(kclvm_context_t* p, char* method, char* args, char* kwargs); -// api-spec(llvm): declare i8* @kclvm_context_invoke(%kclvm_context_t* %p, i8* %method, i8* %args, i8* %kwargs); - -// api-spec: kclvm_context_pkgpath_is_imported -// api-spec(c): kclvm_bool_t kclvm_context_pkgpath_is_imported(kclvm_context_t* ctx, kclvm_char_t* pkgpath); -// api-spec(llvm): declare %kclvm_bool_t @kclvm_context_pkgpath_is_imported(%kclvm_context_t* %ctx, %kclvm_char_t* %pkgpath); - -// api-spec: kclvm_context_set_import_names -// api-spec(c): void kclvm_context_set_import_names(kclvm_context_t* p, kclvm_value_ref_t* import_names); -// api-spec(llvm): declare void @kclvm_context_set_import_names(%kclvm_context_t* %p, %kclvm_value_ref_t* %import_names); - -// api-spec: kclvm_value_Undefined -// api-spec(c): kclvm_value_ref_t* kclvm_value_Undefined(kclvm_context_t* ctx); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_Undefined(%kclvm_context_t* %ctx); - -// api-spec: kclvm_value_None -// api-spec(c): kclvm_value_ref_t* kclvm_value_None(kclvm_context_t* ctx); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_None(%kclvm_context_t* %ctx); - -// api-spec: kclvm_value_True -// api-spec(c): kclvm_value_ref_t* kclvm_value_True(kclvm_context_t* ctx); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_True(%kclvm_context_t* %ctx); - -// api-spec: kclvm_value_False -// api-spec(c): kclvm_value_ref_t* kclvm_value_False(kclvm_context_t* ctx); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_False(%kclvm_context_t* %ctx); - -// api-spec: kclvm_value_Bool -// api-spec(c): kclvm_value_ref_t* kclvm_value_Bool(kclvm_context_t* ctx, kclvm_bool_t v); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_Bool(%kclvm_context_t* %ctx, %kclvm_bool_t %v); - -// api-spec: kclvm_value_Int -// api-spec(c): kclvm_value_ref_t* kclvm_value_Int(kclvm_context_t* ctx, kclvm_int_t v); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_Int(%kclvm_context_t* %ctx, %kclvm_int_t %v); - -// api-spec: kclvm_value_Float -// api-spec(c): kclvm_value_ref_t* kclvm_value_Float(kclvm_context_t* ctx, kclvm_float_t v); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_Float(%kclvm_context_t* %ctx, %kclvm_float_t %v); - -// api-spec: kclvm_value_Unit -// api-spec(c): kclvm_value_ref_t* kclvm_value_Unit(kclvm_context_t* ctx, kclvm_float_t v, kclvm_int_t raw, kclvm_char_t* unit); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_Unit(%kclvm_context_t* %ctx, %kclvm_float_t %v, %kclvm_int_t %raw, %kclvm_char_t* %unit); - -// api-spec: kclvm_value_Str -// api-spec(c): kclvm_value_ref_t* kclvm_value_Str(kclvm_context_t* ctx, kclvm_char_t* v); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_Str(%kclvm_context_t* %ctx, %kclvm_char_t* %v); - -// api-spec: kclvm_value_List -// api-spec(c): kclvm_value_ref_t* kclvm_value_List(kclvm_context_t* ctx); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_List(%kclvm_context_t* %ctx); - -// api-spec: kclvm_value_List6 -// api-spec(c): kclvm_value_ref_t* kclvm_value_List6(kclvm_context_t* ctx, kclvm_value_ref_t* v1, kclvm_value_ref_t* v2, kclvm_value_ref_t* v3, kclvm_value_ref_t* v4, kclvm_value_ref_t* v5, kclvm_value_ref_t* v6); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_List6(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %v1, %kclvm_value_ref_t* %v2, %kclvm_value_ref_t* %v3, %kclvm_value_ref_t* %v4, %kclvm_value_ref_t* %v5, %kclvm_value_ref_t* %v6); - -// api-spec: kclvm_value_List10 -// api-spec(c): kclvm_value_ref_t* kclvm_value_List10(kclvm_context_t* ctx, kclvm_value_ref_t* v1, kclvm_value_ref_t* v2, kclvm_value_ref_t* v3, kclvm_value_ref_t* v4, kclvm_value_ref_t* v5, kclvm_value_ref_t* v6, kclvm_value_ref_t* v7, kclvm_value_ref_t* v8, kclvm_value_ref_t* v9, kclvm_value_ref_t* v10); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_List10(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %v1, %kclvm_value_ref_t* %v2, %kclvm_value_ref_t* %v3, %kclvm_value_ref_t* %v4, %kclvm_value_ref_t* %v5, %kclvm_value_ref_t* %v6, %kclvm_value_ref_t* %v7, %kclvm_value_ref_t* %v8, %kclvm_value_ref_t* %v9, %kclvm_value_ref_t* %v10); - -// api-spec: kclvm_value_Dict -// api-spec(c): kclvm_value_ref_t* kclvm_value_Dict(kclvm_context_t* ctx); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_Dict(%kclvm_context_t* %ctx); - -// api-spec: kclvm_value_Schema -// api-spec(c): kclvm_value_ref_t* kclvm_value_Schema(kclvm_context_t* ctx); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_Schema(%kclvm_context_t* %ctx); - -// api-spec: kclvm_value_schema_with_config -// api-spec(c): kclvm_value_ref_t* kclvm_value_schema_with_config(kclvm_context_t* ctx, kclvm_value_ref_t* schema_dict, kclvm_value_ref_t* config, kclvm_value_ref_t* config_meta, kclvm_char_t* name, kclvm_char_t* pkgpath, kclvm_value_ref_t* is_sub_schema, kclvm_value_ref_t* record_instance, kclvm_value_ref_t* instance_pkgpath, kclvm_value_ref_t* optional_mapping, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_schema_with_config(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %schema_dict, %kclvm_value_ref_t* %config, %kclvm_value_ref_t* %config_meta, %kclvm_char_t* %name, %kclvm_char_t* %pkgpath, %kclvm_value_ref_t* %is_sub_schema, %kclvm_value_ref_t* %record_instance, %kclvm_value_ref_t* %instance_pkgpath, %kclvm_value_ref_t* %optional_mapping, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_value_Function -// api-spec(c): kclvm_value_ref_t* kclvm_value_Function(kclvm_context_t* ctx, uint64_t* fn_ptr, kclvm_value_ref_t* closure, kclvm_char_t* name, kclvm_bool_t is_external); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_Function(%kclvm_context_t* %ctx, i64* %fn_ptr, %kclvm_value_ref_t* %closure, %kclvm_char_t* %name, %kclvm_bool_t %is_external); - -// api-spec: kclvm_value_Function_using_ptr -// api-spec(c): kclvm_value_ref_t* kclvm_value_Function_using_ptr(kclvm_context_t* ctx, uint64_t* fn_ptr, kclvm_char_t* name); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_Function_using_ptr(%kclvm_context_t* %ctx, i64* %fn_ptr, %kclvm_char_t* %name); - -// api-spec: kclvm_value_schema_function -// api-spec(c): kclvm_value_ref_t* kclvm_value_schema_function(kclvm_context_t* ctx, uint64_t* fn_ptr, uint64_t* check_fn_ptr, kclvm_value_ref_t* attr_map, kclvm_char_t* tpe); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_schema_function(%kclvm_context_t* %ctx, i64* %fn_ptr, i64* %check_fn_ptr, %kclvm_value_ref_t* %attr_map, %kclvm_char_t* %tpe); - -// api-spec: kclvm_value_from_json -// api-spec(c): kclvm_value_ref_t* kclvm_value_from_json(kclvm_context_t* ctx, kclvm_char_t* s); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_from_json(%kclvm_context_t* %ctx, %kclvm_char_t* %s); - -// api-spec: kclvm_value_to_json_value -// api-spec(c): kclvm_value_ref_t* kclvm_value_to_json_value(kclvm_context_t* ctx, kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_to_json_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -// api-spec: kclvm_value_to_json_value_with_null -// api-spec(c): kclvm_value_ref_t* kclvm_value_to_json_value_with_null(kclvm_context_t* ctx, kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_to_json_value_with_null(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -// api-spec: kclvm_value_plan_to_json -// api-spec(c): kclvm_value_ref_t* kclvm_value_plan_to_json(kclvm_context_t* ctx, kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_plan_to_json(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -// api-spec: kclvm_value_plan_to_yaml -// api-spec(c): kclvm_value_ref_t* kclvm_value_plan_to_yaml(kclvm_context_t* ctx, kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_plan_to_yaml(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -// api-spec: kclvm_value_to_yaml_value -// api-spec(c): kclvm_value_ref_t* kclvm_value_to_yaml_value(kclvm_context_t* ctx, kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_to_yaml_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -// api-spec: kclvm_value_to_str_value -// api-spec(c): kclvm_value_ref_t* kclvm_value_to_str_value(kclvm_context_t* ctx, kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_to_str_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -// api-spec: kclvm_value_Str_ptr -// api-spec(c): kclvm_char_t* kclvm_value_Str_ptr(kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_char_t* @kclvm_value_Str_ptr(%kclvm_value_ref_t* %p); - -// api-spec: kclvm_value_function_ptr -// api-spec(c): uint64_t* kclvm_value_function_ptr(kclvm_value_ref_t* p); -// api-spec(llvm): declare i64* @kclvm_value_function_ptr(%kclvm_value_ref_t* %p); - -// api-spec: kclvm_value_check_function_ptr -// api-spec(c): uint64_t* kclvm_value_check_function_ptr(kclvm_value_ref_t* p); -// api-spec(llvm): declare i64* @kclvm_value_check_function_ptr(%kclvm_value_ref_t* %p); - -// api-spec: kclvm_value_function_invoke -// api-spec(c): kclvm_value_ref_t* kclvm_value_function_invoke(kclvm_value_ref_t* p, kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs, kclvm_char_t* pkgpath, kclvm_value_ref_t* is_in_schema); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_function_invoke(%kclvm_value_ref_t* %p, %kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs, %kclvm_char_t* %pkgpath, %kclvm_value_ref_t* %is_in_schema); - -// api-spec: kclvm_value_deep_copy -// api-spec(c): kclvm_value_ref_t* kclvm_value_deep_copy(kclvm_context_t* ctx, kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_deep_copy(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -// api-spec: kclvm_value_delete -// api-spec(c): void kclvm_value_delete(kclvm_value_ref_t* p); -// api-spec(llvm): declare void @kclvm_value_delete(%kclvm_value_ref_t* %p); - -// api-spec: kclvm_value_iter -// api-spec(c): kclvm_iterator_t* kclvm_value_iter(kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_iterator_t* @kclvm_value_iter(%kclvm_value_ref_t* %p); - -// api-spec: kclvm_iterator_delete -// api-spec(c): void kclvm_iterator_delete(kclvm_iterator_t* p); -// api-spec(llvm): declare void @kclvm_iterator_delete(%kclvm_iterator_t* %p); - -// api-spec: kclvm_iterator_is_end -// api-spec(c): kclvm_bool_t kclvm_iterator_is_end(kclvm_iterator_t* p); -// api-spec(llvm): declare %kclvm_bool_t @kclvm_iterator_is_end(%kclvm_iterator_t* %p); - -// api-spec: kclvm_iterator_cur_key -// api-spec(c): kclvm_value_ref_t* kclvm_iterator_cur_key(kclvm_iterator_t* p); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_iterator_cur_key(%kclvm_iterator_t* %p); - -// api-spec: kclvm_iterator_cur_value -// api-spec(c): kclvm_value_ref_t* kclvm_iterator_cur_value(kclvm_iterator_t* p); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_iterator_cur_value(%kclvm_iterator_t* %p); - -// api-spec: kclvm_iterator_next_value -// api-spec(c): kclvm_value_ref_t* kclvm_iterator_next_value(kclvm_iterator_t* p, kclvm_value_ref_t* host); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_iterator_next_value(%kclvm_iterator_t* %p, %kclvm_value_ref_t* %host); - -// api-spec: kclvm_list_len -// api-spec(c): kclvm_size_t kclvm_list_len(kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_size_t @kclvm_list_len(%kclvm_value_ref_t* %p); - -// api-spec: kclvm_list_resize -// api-spec(c): void kclvm_list_resize(kclvm_value_ref_t* p, kclvm_size_t newsize); -// api-spec(llvm): declare void @kclvm_list_resize(%kclvm_value_ref_t* %p, %kclvm_size_t %newsize); - -// api-spec: kclvm_list_clear -// api-spec(c): void kclvm_list_clear(kclvm_value_ref_t* p); -// api-spec(llvm): declare void @kclvm_list_clear(%kclvm_value_ref_t* %p); - -// api-spec: kclvm_list_count -// api-spec(c): kclvm_value_ref_t* kclvm_list_count(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_value_ref_t* item); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_list_count(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_value_ref_t* %item); - -// api-spec: kclvm_list_find -// api-spec(c): kclvm_value_ref_t* kclvm_list_find(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_value_ref_t* item); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_list_find(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_value_ref_t* %item); - -// api-spec: kclvm_list_insert -// api-spec(c): void kclvm_list_insert(kclvm_value_ref_t* p, kclvm_value_ref_t* index, kclvm_value_ref_t* value); -// api-spec(llvm): declare void @kclvm_list_insert(%kclvm_value_ref_t* %p, %kclvm_value_ref_t* %index, %kclvm_value_ref_t* %value); - -// api-spec: kclvm_list_get -// api-spec(c): kclvm_value_ref_t* kclvm_list_get(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_size_t i); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_list_get(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_size_t %i); - -// api-spec: kclvm_list_get_option -// api-spec(c): kclvm_value_ref_t* kclvm_list_get_option(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_size_t i); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_list_get_option(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_size_t %i); - -// api-spec: kclvm_list_set -// api-spec(c): void kclvm_list_set(kclvm_value_ref_t* p, kclvm_size_t i, kclvm_value_ref_t* v); -// api-spec(llvm): declare void @kclvm_list_set(%kclvm_value_ref_t* %p, %kclvm_size_t %i, %kclvm_value_ref_t* %v); - -// api-spec: kclvm_list_pop -// api-spec(c): kclvm_value_ref_t* kclvm_list_pop(kclvm_context_t* ctx, kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_list_pop(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -// api-spec: kclvm_list_pop_first -// api-spec(c): kclvm_value_ref_t* kclvm_list_pop_first(kclvm_context_t* ctx, kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_list_pop_first(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -// api-spec: kclvm_list_append -// api-spec(c): void kclvm_list_append(kclvm_value_ref_t* p, kclvm_value_ref_t* v); -// api-spec(llvm): declare void @kclvm_list_append(%kclvm_value_ref_t* %p, %kclvm_value_ref_t* %v); - -// api-spec: kclvm_list_append_bool -// api-spec(c): void kclvm_list_append_bool(kclvm_value_ref_t* p, kclvm_bool_t v); -// api-spec(llvm): declare void @kclvm_list_append_bool(%kclvm_value_ref_t* %p, %kclvm_bool_t %v); - -// api-spec: kclvm_list_append_int -// api-spec(c): void kclvm_list_append_int(kclvm_value_ref_t* p, kclvm_int_t v); -// api-spec(llvm): declare void @kclvm_list_append_int(%kclvm_value_ref_t* %p, %kclvm_int_t %v); - -// api-spec: kclvm_list_append_float -// api-spec(c): void kclvm_list_append_float(kclvm_value_ref_t* p, kclvm_float_t v); -// api-spec(llvm): declare void @kclvm_list_append_float(%kclvm_value_ref_t* %p, %kclvm_float_t %v); - -// api-spec: kclvm_list_append_str -// api-spec(c): void kclvm_list_append_str(kclvm_value_ref_t* p, kclvm_char_t* v); -// api-spec(llvm): declare void @kclvm_list_append_str(%kclvm_value_ref_t* %p, %kclvm_char_t* %v); - -// api-spec: kclvm_list_append_unpack -// api-spec(c): void kclvm_list_append_unpack(kclvm_value_ref_t* p, kclvm_value_ref_t* v); -// api-spec(llvm): declare void @kclvm_list_append_unpack(%kclvm_value_ref_t* %p, %kclvm_value_ref_t* %v); - -// api-spec: kclvm_list_remove_at -// api-spec(c): void kclvm_list_remove_at(kclvm_value_ref_t* p, kclvm_size_t i); -// api-spec(llvm): declare void @kclvm_list_remove_at(%kclvm_value_ref_t* %p, %kclvm_size_t %i); - -// api-spec: kclvm_dict_len -// api-spec(c): kclvm_size_t kclvm_dict_len(kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_size_t @kclvm_dict_len(%kclvm_value_ref_t* %p); - -// api-spec: kclvm_dict_clear -// api-spec(c): void kclvm_dict_clear(kclvm_value_ref_t* p); -// api-spec(llvm): declare void @kclvm_dict_clear(%kclvm_value_ref_t* %p); - -// api-spec: kclvm_dict_is_override_attr -// api-spec(c): kclvm_bool_t kclvm_dict_is_override_attr(kclvm_value_ref_t* p, kclvm_char_t* key); -// api-spec(llvm): declare %kclvm_bool_t @kclvm_dict_is_override_attr(%kclvm_value_ref_t* %p, %kclvm_char_t* %key); - -// api-spec: kclvm_dict_get -// api-spec(c): kclvm_value_ref_t* kclvm_dict_get(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_value_ref_t* key); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_dict_get(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_value_ref_t* %key); - -// api-spec: kclvm_dict_has_value -// api-spec(c): kclvm_bool_t kclvm_dict_has_value(kclvm_value_ref_t* p, kclvm_char_t* key); -// api-spec(llvm): declare %kclvm_bool_t @kclvm_dict_has_value(%kclvm_value_ref_t* %p, %kclvm_char_t* %key); - -// api-spec: kclvm_dict_get_value -// api-spec(c): kclvm_value_ref_t* kclvm_dict_get_value(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_dict_get_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key); - -// api-spec: kclvm_dict_get_entry -// api-spec(c): kclvm_value_ref_t* kclvm_dict_get_entry(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_dict_get_entry(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key); - -// api-spec: kclvm_dict_get_value_by_path -// api-spec(c): kclvm_value_ref_t* kclvm_dict_get_value_by_path(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* path); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_dict_get_value_by_path(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %path); - -// api-spec: kclvm_dict_set_value -// api-spec(c): void kclvm_dict_set_value(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key, kclvm_value_ref_t* val); -// api-spec(llvm): declare void @kclvm_dict_set_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key, %kclvm_value_ref_t* %val); - -// api-spec: kclvm_dict_keys -// api-spec(c): kclvm_value_ref_t* kclvm_dict_keys(kclvm_context_t* ctx, kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_dict_keys(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -// api-spec: kclvm_dict_values -// api-spec(c): kclvm_value_ref_t* kclvm_dict_values(kclvm_context_t* ctx, kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_dict_values(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -// api-spec: kclvm_dict_insert -// api-spec(c): void kclvm_dict_insert(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key, kclvm_value_ref_t* v, kclvm_size_t op, kclvm_size_t insert_index, kclvm_bool_t has_insert_index); -// api-spec(llvm): declare void @kclvm_dict_insert(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key, %kclvm_value_ref_t* %v, %kclvm_size_t %op, %kclvm_size_t %insert_index, %kclvm_bool_t %has_insert_index); - -// api-spec: kclvm_dict_merge -// api-spec(c): void kclvm_dict_merge(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key, kclvm_value_ref_t* v, kclvm_size_t op, kclvm_size_t insert_index, kclvm_bool_t has_insert_index); -// api-spec(llvm): declare void @kclvm_dict_merge(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key, %kclvm_value_ref_t* %v, %kclvm_size_t %op, %kclvm_size_t %insert_index, %kclvm_bool_t %has_insert_index); - -// api-spec: kclvm_dict_insert_value -// api-spec(c): void kclvm_dict_insert_value(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_value_ref_t* key, kclvm_value_ref_t* v, kclvm_size_t op, kclvm_size_t insert_index, kclvm_bool_t has_insert_index); -// api-spec(llvm): declare void @kclvm_dict_insert_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_value_ref_t* %key, %kclvm_value_ref_t* %v, %kclvm_size_t %op, %kclvm_size_t %insert_index, %kclvm_bool_t %has_insert_index); - -// api-spec: kclvm_dict_update_key_value -// api-spec(c): void kclvm_dict_update_key_value(kclvm_value_ref_t* p, kclvm_value_ref_t* key, kclvm_value_ref_t* v); -// api-spec(llvm): declare void @kclvm_dict_update_key_value(%kclvm_value_ref_t* %p, %kclvm_value_ref_t* %key, %kclvm_value_ref_t* %v); - -// api-spec: kclvm_dict_safe_insert -// api-spec(c): void kclvm_dict_safe_insert(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key, kclvm_value_ref_t* v, kclvm_size_t op, kclvm_size_t insert_index, kclvm_bool_t has_insert_index); -// api-spec(llvm): declare void @kclvm_dict_safe_insert(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key, %kclvm_value_ref_t* %v, %kclvm_size_t %op, %kclvm_size_t %insert_index, %kclvm_bool_t %has_insert_index); - -// api-spec: kclvm_dict_insert_unpack -// api-spec(c): void kclvm_dict_insert_unpack(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_value_ref_t* v); -// api-spec(llvm): declare void @kclvm_dict_insert_unpack(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_value_ref_t* %v); - -// api-spec: kclvm_default_collection_insert_int_pointer -// api-spec(c): void kclvm_default_collection_insert_int_pointer(kclvm_value_ref_t* p, kclvm_char_t* key, uint64_t* ptr); -// api-spec(llvm): declare void @kclvm_default_collection_insert_int_pointer(%kclvm_value_ref_t* %p, %kclvm_char_t* %key, i64* %ptr); - -// api-spec: kclvm_default_collection_insert_value -// api-spec(c): void kclvm_default_collection_insert_value(kclvm_value_ref_t* p, kclvm_char_t* key, kclvm_value_ref_t* value); -// api-spec(llvm): declare void @kclvm_default_collection_insert_value(%kclvm_value_ref_t* %p, %kclvm_char_t* %key, %kclvm_value_ref_t* %value); - -// api-spec: kclvm_dict_remove -// api-spec(c): void kclvm_dict_remove(kclvm_value_ref_t* p, kclvm_char_t* key); -// api-spec(llvm): declare void @kclvm_dict_remove(%kclvm_value_ref_t* %p, %kclvm_char_t* %key); - -// api-spec: kclvm_dict_update -// api-spec(c): void kclvm_dict_update(kclvm_value_ref_t* p, kclvm_value_ref_t* v); -// api-spec(llvm): declare void @kclvm_dict_update(%kclvm_value_ref_t* %p, %kclvm_value_ref_t* %v); - -// api-spec: kclvm_value_is_truthy -// api-spec(c): kclvm_bool_t kclvm_value_is_truthy(kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_bool_t @kclvm_value_is_truthy(%kclvm_value_ref_t* %p); - -// api-spec: kclvm_value_len -// api-spec(c): kclvm_size_t kclvm_value_len(kclvm_value_ref_t* p); -// api-spec(llvm): declare %kclvm_size_t @kclvm_value_len(%kclvm_value_ref_t* %p); - -// api-spec: kclvm_value_cmp_equal_to -// api-spec(c): kclvm_value_ref_t* kclvm_value_cmp_equal_to(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_cmp_equal_to(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_cmp_not_equal_to -// api-spec(c): kclvm_value_ref_t* kclvm_value_cmp_not_equal_to(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_cmp_not_equal_to(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_cmp_less_than -// api-spec(c): kclvm_value_ref_t* kclvm_value_cmp_less_than(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_cmp_less_than(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_cmp_less_than_or_equal -// api-spec(c): kclvm_value_ref_t* kclvm_value_cmp_less_than_or_equal(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_cmp_less_than_or_equal(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_cmp_greater_than -// api-spec(c): kclvm_value_ref_t* kclvm_value_cmp_greater_than(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_cmp_greater_than(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_cmp_greater_than_or_equal -// api-spec(c): kclvm_value_ref_t* kclvm_value_cmp_greater_than_or_equal(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_cmp_greater_than_or_equal(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_is -// api-spec(c): kclvm_value_ref_t* kclvm_value_is(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_is(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_is_not -// api-spec(c): kclvm_value_ref_t* kclvm_value_is_not(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_is_not(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_in -// api-spec(c): kclvm_value_ref_t* kclvm_value_in(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_in(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_not_in -// api-spec(c): kclvm_value_ref_t* kclvm_value_not_in(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_not_in(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_as -// api-spec(c): kclvm_value_ref_t* kclvm_value_as(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_as(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_unary_plus -// api-spec(c): kclvm_value_ref_t* kclvm_value_unary_plus(kclvm_context_t* ctx, kclvm_value_ref_t* a); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_unary_plus(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a); - -// api-spec: kclvm_value_unary_minus -// api-spec(c): kclvm_value_ref_t* kclvm_value_unary_minus(kclvm_context_t* ctx, kclvm_value_ref_t* a); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_unary_minus(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a); - -// api-spec: kclvm_value_unary_not -// api-spec(c): kclvm_value_ref_t* kclvm_value_unary_not(kclvm_context_t* ctx, kclvm_value_ref_t* a); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_unary_not(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a); - -// api-spec: kclvm_value_unary_l_not -// api-spec(c): kclvm_value_ref_t* kclvm_value_unary_l_not(kclvm_context_t* ctx, kclvm_value_ref_t* a); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_unary_l_not(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a); - -// api-spec: kclvm_value_op_add -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_add(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_add(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_sub -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_sub(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_sub(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_mul -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_mul(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_mul(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_div -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_div(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_div(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_mod -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_mod(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_mod(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_pow -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_pow(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_pow(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_floor_div -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_floor_div(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_floor_div(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_bit_lshift -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_bit_lshift(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_bit_lshift(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_bit_rshift -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_bit_rshift(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_bit_rshift(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_bit_and -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_bit_and(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_bit_and(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_bit_xor -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_bit_xor(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_bit_xor(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_bit_or -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_bit_or(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_bit_or(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_aug_add -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_aug_add(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_aug_add(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_aug_sub -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_aug_sub(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_aug_sub(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_aug_mul -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_aug_mul(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_aug_mul(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_aug_div -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_aug_div(kclvm_context_t* _ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_aug_div(%kclvm_context_t* %_ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_aug_mod -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_aug_mod(kclvm_context_t* _ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_aug_mod(%kclvm_context_t* %_ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_aug_pow -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_aug_pow(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_aug_pow(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_aug_floor_div -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_aug_floor_div(kclvm_context_t* _ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_aug_floor_div(%kclvm_context_t* %_ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_aug_bit_lshift -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_aug_bit_lshift(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_aug_bit_lshift(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_aug_bit_rshift -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_aug_bit_rshift(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_aug_bit_rshift(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_aug_bit_and -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_aug_bit_and(kclvm_context_t* _ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_aug_bit_and(%kclvm_context_t* %_ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_aug_bit_xor -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_aug_bit_xor(kclvm_context_t* _ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_aug_bit_xor(%kclvm_context_t* %_ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_op_aug_bit_or -// api-spec(c): kclvm_value_ref_t* kclvm_value_op_aug_bit_or(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_op_aug_bit_or(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_union -// api-spec(c): kclvm_value_ref_t* kclvm_value_union(kclvm_context_t* ctx, kclvm_value_ref_t* schema, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_union(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %schema, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_logic_and -// api-spec(c): kclvm_value_ref_t* kclvm_value_logic_and(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_logic_and(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_logic_or -// api-spec(c): kclvm_value_ref_t* kclvm_value_logic_or(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_logic_or(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_subscr -// api-spec(c): kclvm_value_ref_t* kclvm_value_subscr(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_subscr(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_subscr_set -// api-spec(c): void kclvm_value_subscr_set(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_value_ref_t* index, kclvm_value_ref_t* val); -// api-spec(llvm): declare void @kclvm_value_subscr_set(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_value_ref_t* %index, %kclvm_value_ref_t* %val); - -// api-spec: kclvm_value_subscr_option -// api-spec(c): kclvm_value_ref_t* kclvm_value_subscr_option(kclvm_context_t* ctx, kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_subscr_option(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_load_attr -// api-spec(c): kclvm_value_ref_t* kclvm_value_load_attr(kclvm_context_t* ctx, kclvm_value_ref_t* obj, kclvm_char_t* key); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_load_attr(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %obj, %kclvm_char_t* %key); - -// api-spec: kclvm_value_load_attr_option -// api-spec(c): kclvm_value_ref_t* kclvm_value_load_attr_option(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_load_attr_option(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key); - -// api-spec: kclvm_value_remove_item -// api-spec(c): void kclvm_value_remove_item(kclvm_value_ref_t* a, kclvm_value_ref_t* b); -// api-spec(llvm): declare void @kclvm_value_remove_item(%kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b); - -// api-spec: kclvm_value_slice -// api-spec(c): kclvm_value_ref_t* kclvm_value_slice(kclvm_context_t* ctx, kclvm_value_ref_t* x, kclvm_value_ref_t* a, kclvm_value_ref_t* b, kclvm_value_ref_t* step); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_slice(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %x, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b, %kclvm_value_ref_t* %step); - -// api-spec: kclvm_value_slice_option -// api-spec(c): kclvm_value_ref_t* kclvm_value_slice_option(kclvm_context_t* ctx, kclvm_value_ref_t* x, kclvm_value_ref_t* a, kclvm_value_ref_t* b, kclvm_value_ref_t* step); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_slice_option(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %x, %kclvm_value_ref_t* %a, %kclvm_value_ref_t* %b, %kclvm_value_ref_t* %step); - -// api-spec: kclvm_schema_backtrack_cache -// api-spec(c): void kclvm_schema_backtrack_cache(kclvm_context_t* ctx, kclvm_value_ref_t* schema, kclvm_value_ref_t* cache, kclvm_value_ref_t* cal_map, kclvm_char_t* name, kclvm_value_ref_t* runtime_type); -// api-spec(llvm): declare void @kclvm_schema_backtrack_cache(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %schema, %kclvm_value_ref_t* %cache, %kclvm_value_ref_t* %cal_map, %kclvm_char_t* %name, %kclvm_value_ref_t* %runtime_type); - -// api-spec: kclvm_schema_instances -// api-spec(c): kclvm_value_ref_t* kclvm_schema_instances(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_schema_instances(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_schema_value_check -// api-spec(c): void kclvm_schema_value_check(kclvm_context_t* ctx, kclvm_value_ref_t* schema_value, kclvm_value_ref_t* schema_config, kclvm_value_ref_t* _config_meta, kclvm_char_t* schema_name, kclvm_value_ref_t* index_sign_value, kclvm_char_t* key_name, kclvm_char_t* key_type, kclvm_char_t* value_type, kclvm_bool_t _any_other); -// api-spec(llvm): declare void @kclvm_schema_value_check(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %schema_value, %kclvm_value_ref_t* %schema_config, %kclvm_value_ref_t* %_config_meta, %kclvm_char_t* %schema_name, %kclvm_value_ref_t* %index_sign_value, %kclvm_char_t* %key_name, %kclvm_char_t* %key_type, %kclvm_char_t* %value_type, %kclvm_bool_t %_any_other); - -// api-spec: kclvm_schema_do_check_with_index_sign_attr -// api-spec(c): void kclvm_schema_do_check_with_index_sign_attr(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs, uint64_t* check_fn_ptr, kclvm_char_t* attr_name); -// api-spec(llvm): declare void @kclvm_schema_do_check_with_index_sign_attr(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs, i64* %check_fn_ptr, %kclvm_char_t* %attr_name); - -// api-spec: kclvm_schema_optional_check -// api-spec(c): void kclvm_schema_optional_check(kclvm_context_t* ctx, kclvm_value_ref_t* p); -// api-spec(llvm): declare void @kclvm_schema_optional_check(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p); - -// api-spec: kclvm_schema_default_settings -// api-spec(c): void kclvm_schema_default_settings(kclvm_value_ref_t* schema_value, kclvm_value_ref_t* _config_value, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs, kclvm_char_t* runtime_type); -// api-spec(llvm): declare void @kclvm_schema_default_settings(%kclvm_value_ref_t* %schema_value, %kclvm_value_ref_t* %_config_value, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs, %kclvm_char_t* %runtime_type); - -// api-spec: kclvm_schema_assert -// api-spec(c): void kclvm_schema_assert(kclvm_context_t* ctx, kclvm_value_ref_t* value, kclvm_value_ref_t* msg, kclvm_value_ref_t* config_meta); -// api-spec(llvm): declare void @kclvm_schema_assert(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %value, %kclvm_value_ref_t* %msg, %kclvm_value_ref_t* %config_meta); - -// api-spec: kclvm_schema_value_new -// api-spec(c): kclvm_value_ref_t* kclvm_schema_value_new(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs, kclvm_value_ref_t* schema_value_or_func, kclvm_value_ref_t* config, kclvm_value_ref_t* config_meta, kclvm_char_t* pkgpath); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_schema_value_new(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs, %kclvm_value_ref_t* %schema_value_or_func, %kclvm_value_ref_t* %config, %kclvm_value_ref_t* %config_meta, %kclvm_char_t* %pkgpath); - -// api-spec: kclvm_convert_collection_value -// api-spec(c): kclvm_value_ref_t* kclvm_convert_collection_value(kclvm_context_t* ctx, kclvm_value_ref_t* value, kclvm_char_t* tpe, kclvm_value_ref_t* is_in_schema); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_convert_collection_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %value, %kclvm_char_t* %tpe, %kclvm_value_ref_t* %is_in_schema); - -// api-spec: kclvm_schema_get_value -// api-spec(c): kclvm_value_ref_t* kclvm_schema_get_value(kclvm_context_t* ctx, kclvm_value_ref_t* p, kclvm_char_t* key, kclvm_value_ref_t* config, kclvm_value_ref_t* config_meta, kclvm_value_ref_t* cal_map, kclvm_char_t* target_attr, kclvm_value_ref_t* backtrack_level_map, kclvm_value_ref_t* backtrack_cache, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_schema_get_value(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %p, %kclvm_char_t* %key, %kclvm_value_ref_t* %config, %kclvm_value_ref_t* %config_meta, %kclvm_value_ref_t* %cal_map, %kclvm_char_t* %target_attr, %kclvm_value_ref_t* %backtrack_level_map, %kclvm_value_ref_t* %backtrack_cache, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_config_attr_map -// api-spec(c): void kclvm_config_attr_map(kclvm_value_ref_t* value, kclvm_char_t* name, kclvm_char_t* type_str); -// api-spec(llvm): declare void @kclvm_config_attr_map(%kclvm_value_ref_t* %value, %kclvm_char_t* %name, %kclvm_char_t* %type_str); - -// api-spec: kclvm_value_Decorator -// api-spec(c): kclvm_decorator_value_t* kclvm_value_Decorator(kclvm_context_t* ctx, kclvm_char_t* name, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs, kclvm_value_ref_t* config_meta, kclvm_char_t* attr_name, kclvm_value_ref_t* config_value, kclvm_value_ref_t* is_schema_target); -// api-spec(llvm): declare %kclvm_decorator_value_t* @kclvm_value_Decorator(%kclvm_context_t* %ctx, %kclvm_char_t* %name, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs, %kclvm_value_ref_t* %config_meta, %kclvm_char_t* %attr_name, %kclvm_value_ref_t* %config_value, %kclvm_value_ref_t* %is_schema_target); - -// api-spec: kclvm_builtin_str_lower -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_lower(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_lower(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_upper -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_upper(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_upper(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_capitalize -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_capitalize(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_capitalize(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_chars -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_chars(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_chars(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_count -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_count(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_count(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_endswith -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_endswith(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_endswith(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_find -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_find(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_find(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_format -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_format(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_format(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_str_index -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_index(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_index(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_isalnum -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_isalnum(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_isalnum(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_isalpha -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_isalpha(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_isalpha(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_isdigit -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_isdigit(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_isdigit(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_islower -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_islower(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_islower(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_isspace -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_isspace(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_isspace(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_istitle -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_istitle(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_istitle(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_isupper -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_isupper(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_isupper(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_join -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_join(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_join(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_lstrip -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_lstrip(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_lstrip(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_rstrip -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_rstrip(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_rstrip(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_replace -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_replace(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_replace(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_removeprefix -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_removeprefix(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_removeprefix(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_removesuffix -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_removesuffix(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_removesuffix(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_rfind -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_rfind(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_rfind(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_rindex -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_rindex(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_rindex(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_rsplit -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_rsplit(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_rsplit(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_str_split -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_split(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_split(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_str_splitlines -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_splitlines(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_splitlines(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_str_startswith -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_startswith(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_startswith(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_strip -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_strip(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_strip(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_str_title -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str_title(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str_title(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_base32_encode -// api-spec(c): kclvm_value_ref_t* kclvm_base32_encode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_base32_encode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_base32_decode -// api-spec(c): kclvm_value_ref_t* kclvm_base32_decode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_base32_decode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_base64_encode -// api-spec(c): kclvm_value_ref_t* kclvm_base64_encode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_base64_encode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_base64_decode -// api-spec(c): kclvm_value_ref_t* kclvm_base64_decode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_base64_decode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_value_union_all -// api-spec(c): kclvm_value_ref_t* kclvm_value_union_all(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_value_union_all(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_crypto_md5 -// api-spec(c): kclvm_value_ref_t* kclvm_crypto_md5(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_crypto_md5(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_crypto_sha1 -// api-spec(c): kclvm_value_ref_t* kclvm_crypto_sha1(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_crypto_sha1(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_crypto_sha224 -// api-spec(c): kclvm_value_ref_t* kclvm_crypto_sha224(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_crypto_sha224(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_crypto_sha256 -// api-spec(c): kclvm_value_ref_t* kclvm_crypto_sha256(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_crypto_sha256(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_crypto_sha384 -// api-spec(c): kclvm_value_ref_t* kclvm_crypto_sha384(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_crypto_sha384(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_crypto_sha512 -// api-spec(c): kclvm_value_ref_t* kclvm_crypto_sha512(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_crypto_sha512(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_crypto_blake3 -// api-spec(c): kclvm_value_ref_t* kclvm_crypto_blake3(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_crypto_blake3(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_crypto_uuid -// api-spec(c): kclvm_value_ref_t* kclvm_crypto_uuid(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_crypto_uuid(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_crypto_filesha256 -// api-spec(c): kclvm_value_ref_t* kclvm_crypto_filesha256(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_crypto_filesha256(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_crypto_filesha512 -// api-spec(c): kclvm_value_ref_t* kclvm_crypto_filesha512(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_crypto_filesha512(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_crypto_fileblake3 -// api-spec(c): kclvm_value_ref_t* kclvm_crypto_fileblake3(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_crypto_fileblake3(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_datetime_today -// api-spec(c): kclvm_value_ref_t* kclvm_datetime_today(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_datetime_today(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_datetime_now -// api-spec(c): kclvm_value_ref_t* kclvm_datetime_now(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_datetime_now(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_datetime_ticks -// api-spec(c): kclvm_value_ref_t* kclvm_datetime_ticks(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_datetime_ticks(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_datetime_date -// api-spec(c): kclvm_value_ref_t* kclvm_datetime_date(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_datetime_date(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_datetime_validate -// api-spec(c): kclvm_value_ref_t* kclvm_datetime_validate(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_datetime_validate(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_json_encode -// api-spec(c): kclvm_value_ref_t* kclvm_json_encode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_json_encode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_json_decode -// api-spec(c): kclvm_value_ref_t* kclvm_json_decode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_json_decode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_json_validate -// api-spec(c): kclvm_value_ref_t* kclvm_json_validate(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_json_validate(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_json_dump_to_file -// api-spec(c): kclvm_value_ref_t* kclvm_json_dump_to_file(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_json_dump_to_file(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_manifests_yaml_stream -// api-spec(c): kclvm_value_ref_t* kclvm_manifests_yaml_stream(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_manifests_yaml_stream(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_ceil -// api-spec(c): kclvm_value_ref_t* kclvm_math_ceil(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_ceil(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_factorial -// api-spec(c): kclvm_value_ref_t* kclvm_math_factorial(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_factorial(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_floor -// api-spec(c): kclvm_value_ref_t* kclvm_math_floor(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_floor(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_gcd -// api-spec(c): kclvm_value_ref_t* kclvm_math_gcd(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_gcd(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_isfinite -// api-spec(c): kclvm_value_ref_t* kclvm_math_isfinite(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_isfinite(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_isinf -// api-spec(c): kclvm_value_ref_t* kclvm_math_isinf(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_isinf(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_isnan -// api-spec(c): kclvm_value_ref_t* kclvm_math_isnan(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_isnan(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_modf -// api-spec(c): kclvm_value_ref_t* kclvm_math_modf(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_modf(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_exp -// api-spec(c): kclvm_value_ref_t* kclvm_math_exp(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_exp(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_expm1 -// api-spec(c): kclvm_value_ref_t* kclvm_math_expm1(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_expm1(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_log -// api-spec(c): kclvm_value_ref_t* kclvm_math_log(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_log(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_log1p -// api-spec(c): kclvm_value_ref_t* kclvm_math_log1p(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_log1p(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_log2 -// api-spec(c): kclvm_value_ref_t* kclvm_math_log2(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_log2(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_log10 -// api-spec(c): kclvm_value_ref_t* kclvm_math_log10(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_log10(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_pow -// api-spec(c): kclvm_value_ref_t* kclvm_math_pow(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_pow(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_math_sqrt -// api-spec(c): kclvm_value_ref_t* kclvm_math_sqrt(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_math_sqrt(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_split_host_port -// api-spec(c): kclvm_value_ref_t* kclvm_net_split_host_port(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_split_host_port(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_join_host_port -// api-spec(c): kclvm_value_ref_t* kclvm_net_join_host_port(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_join_host_port(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_fqdn -// api-spec(c): kclvm_value_ref_t* kclvm_net_fqdn(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_fqdn(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_parse_IP -// api-spec(c): kclvm_value_ref_t* kclvm_net_parse_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_parse_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_to_IP4 -// api-spec(c): kclvm_value_ref_t* kclvm_net_to_IP4(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_to_IP4(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_to_IP6 -// api-spec(c): kclvm_value_ref_t* kclvm_net_to_IP6(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_to_IP6(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_IP_string -// api-spec(c): kclvm_value_ref_t* kclvm_net_IP_string(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_IP_string(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_is_IPv4 -// api-spec(c): kclvm_value_ref_t* kclvm_net_is_IPv4(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_is_IPv4(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_is_IP -// api-spec(c): kclvm_value_ref_t* kclvm_net_is_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_is_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_is_loopback_IP -// api-spec(c): kclvm_value_ref_t* kclvm_net_is_loopback_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_is_loopback_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_is_multicast_IP -// api-spec(c): kclvm_value_ref_t* kclvm_net_is_multicast_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_is_multicast_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_is_interface_local_multicast_IP -// api-spec(c): kclvm_value_ref_t* kclvm_net_is_interface_local_multicast_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_is_interface_local_multicast_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_is_link_local_multicast_IP -// api-spec(c): kclvm_value_ref_t* kclvm_net_is_link_local_multicast_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_is_link_local_multicast_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_is_link_local_unicast_IP -// api-spec(c): kclvm_value_ref_t* kclvm_net_is_link_local_unicast_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_is_link_local_unicast_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_is_global_unicast_IP -// api-spec(c): kclvm_value_ref_t* kclvm_net_is_global_unicast_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_is_global_unicast_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_parse_CIDR -// api-spec(c): kclvm_value_ref_t* kclvm_net_parse_CIDR(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_parse_CIDR(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_is_IP_in_CIDR -// api-spec(c): kclvm_value_ref_t* kclvm_net_is_IP_in_CIDR(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_is_IP_in_CIDR(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_is_unspecified_IP -// api-spec(c): kclvm_value_ref_t* kclvm_net_is_unspecified_IP(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_is_unspecified_IP(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_CIDR_subnet -// api-spec(c): kclvm_value_ref_t* kclvm_net_CIDR_subnet(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_CIDR_subnet(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_CIDR_subnets -// api-spec(c): kclvm_value_ref_t* kclvm_net_CIDR_subnets(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_CIDR_subnets(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_CIDR_host -// api-spec(c): kclvm_value_ref_t* kclvm_net_CIDR_host(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_CIDR_host(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_net_CIDR_netmask -// api-spec(c): kclvm_value_ref_t* kclvm_net_CIDR_netmask(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_net_CIDR_netmask(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_regex_match -// api-spec(c): kclvm_value_ref_t* kclvm_regex_match(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_regex_match(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_regex_replace -// api-spec(c): kclvm_value_ref_t* kclvm_regex_replace(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_regex_replace(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_regex_compile -// api-spec(c): kclvm_value_ref_t* kclvm_regex_compile(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_regex_compile(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_regex_findall -// api-spec(c): kclvm_value_ref_t* kclvm_regex_findall(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_regex_findall(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_regex_search -// api-spec(c): kclvm_value_ref_t* kclvm_regex_search(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_regex_search(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_regex_split -// api-spec(c): kclvm_value_ref_t* kclvm_regex_split(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_regex_split(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_assert -// api-spec(c): void kclvm_assert(kclvm_context_t* ctx, kclvm_value_ref_t* value, kclvm_value_ref_t* msg); -// api-spec(llvm): declare void @kclvm_assert(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %value, %kclvm_value_ref_t* %msg); - -// api-spec: kclvm_builtin_option_init -// api-spec(c): void kclvm_builtin_option_init(kclvm_context_t* ctx, char* key, char* value); -// api-spec(llvm): declare void @kclvm_builtin_option_init(%kclvm_context_t* %ctx, i8* %key, i8* %value); - -// api-spec: kclvm_builtin_option_reset -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_option_reset(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_option_reset(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_option -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_option(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_option(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_print -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_print(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_print(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_len -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_len(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_len(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_any_true -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_any_true(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_any_true(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_isunique -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_isunique(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_isunique(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_sorted -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_sorted(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_sorted(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_int -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_int(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_int(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_float -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_float(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_float(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_bool -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_bool(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_bool(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_str -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_str(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_str(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_max -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_max(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_max(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_min -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_min(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_min(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_multiplyof -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_multiplyof(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_multiplyof(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_abs -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_abs(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_abs(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_all_true -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_all_true(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_all_true(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_hex -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_hex(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_hex(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_sum -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_sum(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_sum(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_pow -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_pow(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_pow(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_round -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_round(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_round(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_zip -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_zip(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_zip(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_builtin_list -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_list(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_list(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_dict -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_dict(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_dict(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_typeof -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_typeof(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_typeof(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_bin -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_bin(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_bin(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_oct -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_oct(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_oct(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_ord -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_ord(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_ord(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_range -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_range(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_range(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_builtin_isnullish -// api-spec(c): kclvm_value_ref_t* kclvm_builtin_isnullish(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_builtin_isnullish(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_plugin_init -// api-spec(c): void kclvm_plugin_init(void* fn_ptr); -// api-spec(llvm): declare void @kclvm_plugin_init(i8* %fn_ptr); - -// api-spec: kclvm_plugin_invoke -// api-spec(c): kclvm_value_ref_t* kclvm_plugin_invoke(kclvm_context_t* ctx, char* method, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_plugin_invoke(%kclvm_context_t* %ctx, i8* %method, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_plugin_invoke_json -// api-spec(c): char* kclvm_plugin_invoke_json(char* method, char* args, char* kwargs); -// api-spec(llvm): declare i8* @kclvm_plugin_invoke_json(i8* %method, i8* %args, i8* %kwargs); - -// api-spec: kclvm_units_to_n -// api-spec(c): kclvm_value_ref_t* kclvm_units_to_n(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_units_to_n(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_units_to_u -// api-spec(c): kclvm_value_ref_t* kclvm_units_to_u(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_units_to_u(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_units_to_m -// api-spec(c): kclvm_value_ref_t* kclvm_units_to_m(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_units_to_m(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_units_to_K -// api-spec(c): kclvm_value_ref_t* kclvm_units_to_K(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_units_to_K(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_units_to_M -// api-spec(c): kclvm_value_ref_t* kclvm_units_to_M(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_units_to_M(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_units_to_G -// api-spec(c): kclvm_value_ref_t* kclvm_units_to_G(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_units_to_G(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_units_to_T -// api-spec(c): kclvm_value_ref_t* kclvm_units_to_T(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_units_to_T(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_units_to_P -// api-spec(c): kclvm_value_ref_t* kclvm_units_to_P(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_units_to_P(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_units_to_Ki -// api-spec(c): kclvm_value_ref_t* kclvm_units_to_Ki(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_units_to_Ki(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_units_to_Mi -// api-spec(c): kclvm_value_ref_t* kclvm_units_to_Mi(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_units_to_Mi(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_units_to_Gi -// api-spec(c): kclvm_value_ref_t* kclvm_units_to_Gi(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_units_to_Gi(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_units_to_Ti -// api-spec(c): kclvm_value_ref_t* kclvm_units_to_Ti(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_units_to_Ti(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_units_to_Pi -// api-spec(c): kclvm_value_ref_t* kclvm_units_to_Pi(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_units_to_Pi(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_yaml_encode -// api-spec(c): kclvm_value_ref_t* kclvm_yaml_encode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_yaml_encode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_yaml_encode_all -// api-spec(c): kclvm_value_ref_t* kclvm_yaml_encode_all(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_yaml_encode_all(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_yaml_decode -// api-spec(c): kclvm_value_ref_t* kclvm_yaml_decode(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_yaml_decode(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_yaml_decode_all -// api-spec(c): kclvm_value_ref_t* kclvm_yaml_decode_all(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_yaml_decode_all(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_yaml_dump_to_file -// api-spec(c): kclvm_value_ref_t* kclvm_yaml_dump_to_file(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_yaml_dump_to_file(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_yaml_dump_all_to_file -// api-spec(c): kclvm_value_ref_t* kclvm_yaml_dump_all_to_file(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_yaml_dump_all_to_file(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_yaml_validate -// api-spec(c): kclvm_value_ref_t* kclvm_yaml_validate(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_yaml_validate(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_file_read -// api-spec(c): kclvm_value_ref_t* kclvm_file_read(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_read(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_file_glob -// api-spec(c): kclvm_value_ref_t* kclvm_file_glob(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_glob(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_file_modpath -// api-spec(c): kclvm_value_ref_t* kclvm_file_modpath(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_modpath(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_file_workdir -// api-spec(c): kclvm_value_ref_t* kclvm_file_workdir(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_workdir(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_file_current -// api-spec(c): kclvm_value_ref_t* kclvm_file_current(kclvm_context_t* ctx, kclvm_value_ref_t* _args, kclvm_value_ref_t* _kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_current(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %_args, %kclvm_value_ref_t* %_kwargs); - -// api-spec: kclvm_file_exists -// api-spec(c): kclvm_value_ref_t* kclvm_file_exists(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_exists(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_file_abs -// api-spec(c): kclvm_value_ref_t* kclvm_file_abs(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_abs(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_file_mkdir -// api-spec(c): kclvm_value_ref_t* kclvm_file_mkdir(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_mkdir(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_file_delete -// api-spec(c): kclvm_value_ref_t* kclvm_file_delete(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_delete(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_file_cp -// api-spec(c): kclvm_value_ref_t* kclvm_file_cp(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_cp(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_file_mv -// api-spec(c): kclvm_value_ref_t* kclvm_file_mv(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_mv(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_file_size -// api-spec(c): kclvm_value_ref_t* kclvm_file_size(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_size(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_file_write -// api-spec(c): kclvm_value_ref_t* kclvm_file_write(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_write(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_file_append -// api-spec(c): kclvm_value_ref_t* kclvm_file_append(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_append(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_file_read_env -// api-spec(c): kclvm_value_ref_t* kclvm_file_read_env(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_file_read_env(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_template_execute -// api-spec(c): kclvm_value_ref_t* kclvm_template_execute(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_template_execute(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_template_html_escape -// api-spec(c): kclvm_value_ref_t* kclvm_template_html_escape(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_template_html_escape(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - -// api-spec: kclvm_runtime_catch -// api-spec(c): kclvm_value_ref_t* kclvm_runtime_catch(kclvm_context_t* ctx, kclvm_value_ref_t* args, kclvm_value_ref_t* kwargs); -// api-spec(llvm): declare %kclvm_value_ref_t* @kclvm_runtime_catch(%kclvm_context_t* %ctx, %kclvm_value_ref_t* %args, %kclvm_value_ref_t* %kwargs); - diff --git a/kclvm/runtime/src/_kclvm_undefined_wasm.txt b/kclvm/runtime/src/_kclvm_undefined_wasm.txt deleted file mode 100644 index 7524e7d15..000000000 --- a/kclvm/runtime/src/_kclvm_undefined_wasm.txt +++ /dev/null @@ -1 +0,0 @@ -kclvm_plugin_invoke_json_wasm \ No newline at end of file diff --git a/kclvm/runtime/src/api/kclvm.rs b/kclvm/runtime/src/api/kclvm.rs deleted file mode 100644 index 0dea5a7bf..000000000 --- a/kclvm/runtime/src/api/kclvm.rs +++ /dev/null @@ -1,464 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -use crate::{new_mut_ptr, val_plan::PlanOptions}; -use generational_arena::Index; -use kclvm_primitives::{IndexMap, IndexSet}; -use serde::{Deserialize, Serialize}; -use std::collections::{HashMap, HashSet}; -use std::panic::{RefUnwindSafe, UnwindSafe}; -use std::rc::Rc; -use std::sync::Arc; -use std::{ - cell::RefCell, - cmp::Ordering, - hash::{Hash, Hasher}, -}; - -/* - * Single instance name constants Undefined, None, True, False - */ -#[allow(non_upper_case_globals)] -pub const UNDEFINED: Value = Value::undefined; -#[allow(non_upper_case_globals)] -pub const NONE: Value = Value::none; -#[allow(non_upper_case_globals)] -pub const TRUE: Value = Value::bool_value(true); -#[allow(non_upper_case_globals)] -pub const FALSE: Value = Value::bool_value(false); - -/* - * Runtime types - */ - -#[derive(Clone, PartialEq, Debug, Default)] -pub enum Type { - #[default] - Any, - Bool, - BoolLit(bool), - Int, - IntLit(i64), - Float, - FloatLit(f64), - Str, - StrLit(String), - List(ListType), - Dict(DictType), - Union(UnionType), - Schema(SchemaType), - Func(FuncType), -} - -#[derive(PartialEq, Clone, Default, Debug)] -pub struct ListType { - pub elem_type: Box, -} - -#[derive(PartialEq, Clone, Default, Debug)] -pub struct DictType { - pub key_type: Box, - pub elem_type: Box, -} - -#[derive(PartialEq, Clone, Default, Debug)] -pub struct UnionType { - pub elem_types: Vec, -} - -/// The runtime schema type. -#[derive(PartialEq, Clone, Default, Debug)] -pub struct SchemaType { - /// The schema runtime type name. - pub name: String, - /// Schema attributes. - pub attrs: IndexMap, - /// Schema index signature. - pub has_index_signature: bool, - /// Schema runtime function value. - pub func: ValueRef, -} - -#[derive(PartialEq, Clone, Default, Debug)] -pub struct FuncType { - pub args_types: Vec, - pub return_type: Box, -} - -#[repr(C)] -#[allow(non_camel_case_types)] -#[derive(Clone, Debug)] -pub struct ValueRef { - pub rc: Rc>, -} - -impl Eq for ValueRef {} - -impl PartialEq for ValueRef { - fn eq(&self, other: &Self) -> bool { - self.cmp_equal(other) - } -} - -impl Ord for ValueRef { - fn cmp(&self, other: &ValueRef) -> Ordering { - let ord = match *self.rc.borrow() { - Value::int_value(a) => match *other.rc.borrow() { - Value::int_value(b) => a.partial_cmp(&b), - Value::float_value(b) => (a as f64).partial_cmp(&b), - _ => None, - }, - Value::float_value(a) => match *other.rc.borrow() { - Value::int_value(b) => a.partial_cmp(&(b as f64)), - Value::float_value(b) => a.partial_cmp(&b), - _ => None, - }, - Value::str_value(ref a) => match &*other.rc.borrow() { - Value::str_value(ref b) => a.partial_cmp(b), - _ => None, - }, - _ => None, - }; - match ord { - Some(ord) => ord, - _ => panic!( - "cannot compare {} and {}", - self.type_str(), - other.type_str() - ), - } - } -} - -impl PartialOrd for ValueRef { - fn partial_cmp(&self, other: &ValueRef) -> Option { - Some(self.cmp(other)) - } -} - -impl Hash for ValueRef { - fn hash(&self, state: &mut H) { - match &*self.rc.borrow() { - Value::undefined => 0.hash(state), - Value::none => 0.hash(state), - Value::int_value(v) => (*v as f64).to_bits().hash(state), - Value::unit_value(_real, raw, unit) => { - raw.hash(state); - unit.hash(state); - } - Value::float_value(v) => v.to_bits().hash(state), - Value::bool_value(v) => v.hash(state), - Value::str_value(ref v) => (*v).hash(state), - Value::list_value(ref v) => { - for i in 0..v.values.len() { - v.values[i].hash(state); - } - } - Value::dict_value(ref v) => { - for (k, v) in v.values.iter() { - (*k).hash(state); - v.hash(state); - } - } - Value::schema_value(ref v) => { - for (k, v) in v.config.values.iter() { - (*k).hash(state); - v.hash(state); - } - } - Value::func_value(ref v) => { - v.fn_ptr.hash(state); - } - } - } -} - -impl Default for ValueRef { - fn default() -> Self { - Self { - rc: Rc::new(RefCell::new(Value::undefined)), - } - } -} - -impl ValueRef { - // Returns whether self and x refer to the same Value - pub fn is_same_ref(&self, x: &Self) -> bool { - std::ptr::eq(&*self.rc.borrow(), &*x.rc.borrow()) - } - - pub fn into_raw(self, ctx: &mut Context) -> *mut Self { - new_mut_ptr(ctx, self) - } - - pub fn from_raw(&self) { - // If value is a func, clear the captured ValueRef to break circular reference. - if let Value::func_value(val) = &mut *self.rc.borrow_mut() { - val.closure = ValueRef::none(); - } - } -} - -#[allow(non_camel_case_types)] -#[derive(Clone, PartialEq, Debug)] -pub enum Value { - undefined, - none, - bool_value(bool), - int_value(i64), - float_value(f64), - str_value(String), - list_value(Box), - dict_value(Box), - schema_value(Box), - func_value(Box), - unit_value(f64, i64, String), // (Real value, raw value, unit string) -} - -impl Default for Value { - fn default() -> Self { - Self::undefined - } -} - -#[derive(PartialEq, Eq, Clone, Default, Debug)] -pub struct ListValue { - pub values: Vec, -} - -#[derive(PartialEq, Eq, Clone, Default, Debug)] -pub struct DictValue { - pub values: IndexMap, - pub ops: IndexMap, - pub insert_indexs: IndexMap, - /// Attribute type annotation string mapping. - pub attr_map: IndexMap, - /// The runtime dict to schema reflect type string. - pub potential_schema: Option, -} - -#[derive(PartialEq, Clone, Default, Debug)] -pub struct SchemaValue { - /// Schema name without the package path prefix. - pub name: String, - /// Schema instance package path, note is it not the schema definition package path. - pub pkgpath: String, - /// Schema values. - pub config: Box, - /// Schema instance config keys e.g., "a" in `MySchema {a = "foo"}` - pub config_keys: Vec, - /// schema config meta information including filename, line and column. - pub config_meta: ValueRef, - /// This map stores which attributes of the schema are optional and which are required. - pub optional_mapping: ValueRef, - /// Schema instance argument values - pub args: ValueRef, - /// Schema instance keyword argument values - pub kwargs: ValueRef, -} - -#[derive(PartialEq, Eq, Clone, Default, Debug)] -pub struct DecoratorValue { - pub name: String, - pub args: ValueRef, - pub kwargs: ValueRef, -} - -#[derive(PartialEq, Eq, Clone, Default, Debug)] -pub struct FuncValue { - pub fn_ptr: u64, - pub check_fn_ptr: u64, - pub closure: ValueRef, - pub name: String, - pub runtime_type: String, - pub is_external: bool, - /// Proxy functions represent the saved functions of the runtime itself, - /// rather than executing KCL defined functions or plugin functions. - pub proxy: Option, -} - -#[allow(non_snake_case)] -#[derive(PartialEq, Eq, Clone, Default, Debug, Serialize, Deserialize)] -pub struct PanicInfo { - // Used to distinguish whether it is an error - // message JSON or a program run result. - #[serde(rename = "__kcl_PanicInfo__")] - pub __kcl_PanicInfo__: bool, - pub backtrace: Vec, - - pub rust_file: String, - pub rust_line: i32, - pub rust_col: i32, - - pub kcl_pkgpath: String, - pub kcl_file: String, - pub kcl_func: String, - pub kcl_line: i32, - pub kcl_col: i32, - pub kcl_arg_msg: String, - - // Only for schema check failed error message - pub kcl_config_meta_file: String, - pub kcl_config_meta_line: i32, - pub kcl_config_meta_col: i32, - pub kcl_config_meta_arg_msg: String, - - pub message: String, - pub err_type_code: i32, - pub is_warning: bool, -} - -#[derive(PartialEq, Eq, Clone, Default, Debug)] -pub struct ContextConfig { - pub debug_mode: bool, - pub strict_range_check: bool, - pub disable_schema_check: bool, -} - -#[derive(PartialEq, Eq, Clone, Debug)] -pub struct ContextBuffer { - pub kclvm_context_invoke_result: String, - /// Custom manifest output string. - pub custom_manifests_output: Option, -} - -impl Default for ContextBuffer { - fn default() -> Self { - Self { - kclvm_context_invoke_result: "\0".to_string(), - custom_manifests_output: None, - } - } -} - -/// Plugin functions -pub type PluginFunction = - Arc anyhow::Result + Send + Sync>; - -#[derive(Clone, Default)] -pub struct Context { - /// Runtime evaluation config. - pub cfg: ContextConfig, - /// kcl.mod path or the pwd path - pub module_path: String, - /// Program work directory - pub workdir: String, - /// Runtime backtrace frame for the debugger. - pub backtrace: Vec, - /// Imported package path to check the cyclic import process. - pub imported_pkgpath: HashSet, - /// Runtime arguments for the option function. - pub option_values: HashMap, - /// All schema instances, the first key is the schema runtime type and - /// the second key is the schema instance package path - pub instances: IndexMap>>, - /// All schema types - pub all_schemas: HashMap, - /// Import graph - pub import_names: IndexMap>, - /// A buffer to store plugin or hooks function calling results. - pub buffer: ContextBuffer, - /// Objects is to store all KCL object pointers at runtime for GC. - pub objects: IndexSet, - /// Log message used to store print results. - pub log_message: String, - /// Planned JSON result - pub json_result: String, - /// Planned YAML result - pub yaml_result: String, - /// Panic information at runtime - pub panic_info: PanicInfo, - /// Planning options - pub plan_opts: PlanOptions, - /// Builtin plugin functions, the key of the map is the form . e.g., `hello.say_hello` - pub plugin_functions: IndexMap, -} - -impl UnwindSafe for Context {} -impl RefUnwindSafe for Context {} - -#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)] -pub struct BacktraceFrame { - pub file: String, - pub func: String, - pub col: i32, - pub line: i32, -} -impl Default for BacktraceFrame { - fn default() -> Self { - Self { - file: Default::default(), - func: "_kclvm_main".to_string(), - col: Default::default(), - line: Default::default(), - } - } -} - -impl BacktraceFrame { - pub fn from_panic_info(info: &PanicInfo) -> Self { - Self { - file: info.kcl_file.clone(), - func: info.kcl_func.clone(), - col: info.kcl_col, - line: info.kcl_line, - } - } -} - -impl Context { - pub fn new() -> Self { - Context { - instances: IndexMap::default(), - panic_info: PanicInfo { - kcl_func: "kclvm_main".to_string(), - ..Default::default() - }, - ..Default::default() - } - } -} - -#[repr(C)] -#[derive(Clone, PartialEq, Eq, Debug, Hash)] -pub enum Kind { - Invalid = 0, - Undefined = 1, - None = 2, - Bool = 3, - Int = 4, - Float = 5, - Str = 6, - List = 7, - Dict = 8, - Schema = 9, - Error = 10, - Any = 11, - Union = 12, - BoolLit = 13, - IntLit = 14, - FloatLit = 15, - StrLit = 16, - Unit = 17, - Func = 18, -} - -#[derive(Clone, PartialEq, Eq, Debug, Hash, Default)] -pub enum ConfigEntryOperationKind { - #[default] - Union = 0, - Override = 1, - Insert = 2, -} - -impl ConfigEntryOperationKind { - pub fn from_i32(v: i32) -> Self { - match v { - x if x == ConfigEntryOperationKind::Union as i32 => ConfigEntryOperationKind::Union, - x if x == ConfigEntryOperationKind::Override as i32 => { - ConfigEntryOperationKind::Override - } - x if x == ConfigEntryOperationKind::Insert as i32 => ConfigEntryOperationKind::Insert, - _ => panic!("Invalid AttrOpKind integer {v}, expected 0, 1 or 2"), - } - } -} diff --git a/kclvm/runtime/src/api/mod.rs b/kclvm/runtime/src/api/mod.rs deleted file mode 100644 index d9ceae469..000000000 --- a/kclvm/runtime/src/api/mod.rs +++ /dev/null @@ -1,10 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -pub mod kclvm; -pub use self::kclvm::*; - -pub mod utils; -pub use self::utils::*; - -pub mod error; -pub use self::error::*; diff --git a/kclvm/runtime/src/api/utils.rs b/kclvm/runtime/src/api/utils.rs deleted file mode 100644 index cfdf2bf34..000000000 --- a/kclvm/runtime/src/api/utils.rs +++ /dev/null @@ -1,108 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -use std::os::raw::c_char; - -use crate::{kclvm_size_t, Context, ValueRef}; - -/// New a mutable raw pointer. -/// Safety: The caller must ensure that `ctx` lives longer than the returned pointer -/// and that the pointer is properly deallocated by calling `free_mut_ptr`. -pub fn new_mut_ptr(ctx: &mut Context, x: ValueRef) -> *mut ValueRef { - let ptr = Box::into_raw(Box::new(x)); - // Store the object pointer address to - // drop it it after execution is complete - ctx.objects.insert(ptr as usize); - ptr -} - -/// Free a mutable raw pointer. -/// Safety: The caller must ensure `p` is a valid pointer obtained from `new_mut_ptr`. -pub fn free_mut_ptr(p: *mut T) { - if !p.is_null() { - unsafe { - drop(Box::from_raw(p)); - } - } -} - -/// Convert a const raw pointer to a immutable borrow. -/// Safety: The caller must ensure that `p` is valid for the lifetime `'a`. -pub fn ptr_as_ref<'a, T>(p: *const T) -> &'a T { - assert!(!p.is_null()); - unsafe { &*p } -} - -/// Convert a mutable raw pointer to a mutable borrow. -/// Safety: The caller must ensure that `p` is valid for the lifetime `'a`. -pub fn mut_ptr_as_ref<'a, T>(p: *mut T) -> &'a mut T { - assert!(!p.is_null()); - - unsafe { &mut *p } -} - -/// Copy str to mutable pointer with length -pub(crate) fn copy_str_to(v: &str, p: *mut c_char, size: *mut kclvm_size_t) { - assert!(!p.is_null() || !size.is_null()); - - unsafe { - let c_str_ptr = v.as_ptr() as *const c_char; - let c_str_len = v.len() as i32; - if c_str_len <= *size { - std::ptr::copy(c_str_ptr, p, c_str_len as usize); - *size = c_str_len - } - } -} - -/// Convert a C str pointer to a Rust &str. -/// Safety: The caller must ensure that `s` is a valid null-terminated C string. -pub fn c2str<'a>(p: *const c_char) -> &'a str { - assert!(!p.is_null()); - - let s = unsafe { std::ffi::CStr::from_ptr(p) }.to_str().unwrap(); - s -} - -/// Convert a C str pointer pointer to a Rust Vec. -pub fn c2str_vec(ptr_array: *const *const c_char) -> Vec { - assert!(!ptr_array.is_null()); - - let mut result = Vec::new(); - let mut index = 0; - - unsafe { - loop { - let current_ptr = *ptr_array.offset(index); - if current_ptr.is_null() { - break; - } - let c_str = std::ffi::CStr::from_ptr(current_ptr); - let rust_string = c_str.to_string_lossy().to_string(); - result.push(rust_string); - index += 1; - } - } - - result -} - -pub fn assert_panic(msg: &str, func: F) { - match std::panic::catch_unwind(func) { - Ok(_v) => { - panic!("not panic, expect={msg}"); - } - Err(e) => match e.downcast::() { - Ok(v) => { - let got = v.to_string(); - assert!(got.contains(msg), "expect={msg}, got={got}"); - } - Err(e) => match e.downcast::<&str>() { - Ok(v) => { - let got = v.to_string(); - assert!(got.contains(msg), "expect={msg}, got={got}"); - } - _ => unreachable!(), - }, - }, - }; -} diff --git a/kclvm/runtime/src/base32/mod.rs b/kclvm/runtime/src/base32/mod.rs deleted file mode 100644 index 9cb7b3d7b..000000000 --- a/kclvm/runtime/src/base32/mod.rs +++ /dev/null @@ -1,44 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -extern crate base32; -use crate::*; -use base32::{decode, encode, Alphabet}; - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_base32_encode( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { - let s = encode(Alphabet::RFC4648 { padding: true }, s.as_bytes()); - return ValueRef::str(s.as_str()).into_raw(ctx); - } - panic!("encode() missing 1 required positional argument: 'value'"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_base32_decode( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { - if let Some(de_str) = decode(Alphabet::RFC4648 { padding: true }, &s) { - if let Ok(s) = std::str::from_utf8(&de_str) { - return ValueRef::str(s).into_raw(ctx); - } - } - // Handle decoding errors - return ValueRef::none().into_raw(ctx); - } - panic!("decode() missing 1 required positional argument: 'value'"); -} diff --git a/kclvm/runtime/src/base64/mod.rs b/kclvm/runtime/src/base64/mod.rs deleted file mode 100644 index 68107e3b4..000000000 --- a/kclvm/runtime/src/base64/mod.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -extern crate base64; -use base64::{decode, encode}; - -use crate::*; - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_base64_encode( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { - let s = encode(s); - return ValueRef::str(s.as_str()).into_raw(ctx); - } - panic!("encode() missing 1 required positional argument: 'value'"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_base64_decode( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { - let de_str = decode(s).unwrap(); - return ValueRef::str(std::str::from_utf8(&de_str).unwrap()).into_raw(ctx); - } - panic!("decode() missing 1 required positional argument: 'value'"); -} diff --git a/kclvm/runtime/src/collection/mod.rs b/kclvm/runtime/src/collection/mod.rs deleted file mode 100644 index e7ab78517..000000000 --- a/kclvm/runtime/src/collection/mod.rs +++ /dev/null @@ -1,31 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -use crate::*; - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_value_union_all( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let ctx = mut_ptr_as_ref(ctx); - if let Some(arg) = args.arg_0() { - if !arg.is_truthy() || !arg.is_list() { - return ValueRef::dict(None).into_raw(ctx); - } - let value = arg.as_list_ref(); - if value.values.is_empty() { - return ValueRef::dict(None).into_raw(ctx); - } - let mut result = value.values[0].deep_copy(); - for (i, v) in value.values.iter().enumerate() { - if i > 0 { - result.bin_aug_union_with(ctx, v); - } - } - return result.into_raw(ctx); - } - panic!("union_all() takes at least 1 argument (0 given)") -} diff --git a/kclvm/runtime/src/context/api.rs b/kclvm/runtime/src/context/api.rs deleted file mode 100644 index 8c43a60a8..000000000 --- a/kclvm/runtime/src/context/api.rs +++ /dev/null @@ -1,328 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. -#![allow(clippy::missing_safety_doc)] - -use crate::*; -use std::os::raw::c_char; - -use self::eval::LazyEvalScope; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_context_t = Context; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_eval_scope_t = LazyEvalScope; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_kind_t = Kind; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_type_t = Type; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_value_t = Value; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_char_t = c_char; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_size_t = i32; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_bool_t = i8; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_int_t = i64; - -#[allow(dead_code, non_camel_case_types)] -type kclvm_float_t = f64; - -// ---------------------------------------------------------------------------- -// new/delete -// ---------------------------------------------------------------------------- - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_new() -> *mut kclvm_context_t { - Box::into_raw(Box::new(Context::new())) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_delete(p: *mut kclvm_context_t) { - let ctx = mut_ptr_as_ref(p); - for o in &ctx.objects { - let ptr = (*o) as *mut kclvm_value_ref_t; - kclvm_value_delete(ptr); - } - free_mut_ptr(p); -} - -// ---------------------------------------------------------------------------- -// panic_info -// ---------------------------------------------------------------------------- - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_set_kcl_location( - p: *mut kclvm_context_t, - filename: *const c_char, - line: i32, - col: i32, -) { - let p = mut_ptr_as_ref(p); - if !filename.is_null() { - p.set_kcl_location_info(None, Some(c2str(filename)), Some(line), Some(col)); - } else { - p.set_kcl_location_info(None, None, Some(line), Some(col)); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_set_kcl_pkgpath( - p: *mut kclvm_context_t, - pkgpath: *const c_char, -) { - let p = mut_ptr_as_ref(p); - if !pkgpath.is_null() { - p.set_kcl_pkgpath(c2str(pkgpath)); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_set_kcl_modpath( - p: *mut kclvm_context_t, - module_path: *const c_char, -) { - let p = mut_ptr_as_ref(p); - if !module_path.is_null() { - p.set_kcl_module_path(c2str(module_path)); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_set_kcl_workdir( - p: *mut kclvm_context_t, - workdir: *const c_char, -) { - let p = mut_ptr_as_ref(p); - if !workdir.is_null() { - p.set_kcl_workdir(c2str(workdir)); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_set_kcl_filename( - ctx: *mut kclvm_context_t, - filename: *const c_char, -) { - let ctx = mut_ptr_as_ref(ctx); - if !filename.is_null() { - ctx.set_kcl_filename(c2str(filename)); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_set_kcl_line_col( - ctx: *mut kclvm_context_t, - line: i32, - col: i32, -) { - let ctx = mut_ptr_as_ref(ctx); - ctx.set_kcl_line_col(line, col); -} - -// ---------------------------------------------------------------------------- -// Global values and evaluation scope. -// ---------------------------------------------------------------------------- - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_scope_new() -> *mut kclvm_eval_scope_t { - Box::into_raw(Box::default()) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_scope_delete(scope: *mut kclvm_eval_scope_t) { - drop(Box::from_raw(scope)); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_scope_add_setter( - _ctx: *mut kclvm_context_t, - scope: *mut kclvm_eval_scope_t, - pkg: *const c_char, - name: *const c_char, - setter: *const u64, -) { - let scope = mut_ptr_as_ref(scope); - let pkg = c2str(pkg); - let name = c2str(name); - let key = format!("{}.{}", pkg, name); - if !scope.setters.contains_key(&key) { - scope.setters.insert(key.clone(), vec![]); - } - if let Some(setters) = scope.setters.get_mut(&key) { - setters.push(setter as u64); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_scope_set( - _ctx: *mut kclvm_context_t, - scope: *mut kclvm_eval_scope_t, - pkg: *const c_char, - name: *const c_char, - value: *const kclvm_value_ref_t, -) { - let scope = mut_ptr_as_ref(scope); - let value = ptr_as_ref(value); - let pkg = c2str(pkg); - let name = c2str(name); - let key = format!("{}.{}", pkg, name); - scope.set_value(&key, value); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_scope_get( - ctx: *mut kclvm_context_t, - scope: *mut kclvm_eval_scope_t, - pkg: *const c_char, - name: *const c_char, - target: *const c_char, - default: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let scope = mut_ptr_as_ref(scope); - let pkg = c2str(pkg); - let name = c2str(name); - let target = format!("{}.{}", pkg, c2str(target)); - let key = format!("{}.{}", pkg, name); - // Existing values or existing but not yet calculated values. - if scope.contains_key(&key) || scope.setters.contains_key(&key) { - scope.get_value(ctx, &key, &target).into_raw(ctx) - } else { - default - } -} - -// ---------------------------------------------------------------------------- -// CLI config -// ---------------------------------------------------------------------------- - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_set_debug_mode( - p: *mut kclvm_context_t, - v: kclvm_bool_t, -) { - let p = mut_ptr_as_ref(p); - p.cfg.debug_mode = v != 0; -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_set_strict_range_check( - p: *mut kclvm_context_t, - v: kclvm_bool_t, -) { - let p = mut_ptr_as_ref(p); - p.cfg.strict_range_check = v != 0; -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_set_disable_none( - p: *mut kclvm_context_t, - v: kclvm_bool_t, -) { - let p = mut_ptr_as_ref(p); - p.plan_opts.disable_none = v != 0; -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_set_disable_schema_check( - p: *mut kclvm_context_t, - v: kclvm_bool_t, -) { - let p = mut_ptr_as_ref(p); - p.cfg.disable_schema_check = v != 0; -} - -// ---------------------------------------------------------------------------- -// invoke -// ---------------------------------------------------------------------------- - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_invoke( - p: *mut kclvm_context_t, - method: *const c_char, - args: *const c_char, - kwargs: *const c_char, -) -> *const c_char { - let p = mut_ptr_as_ref(p); - let method = c2str(method); - - let args = kclvm_value_from_json(p, args); - let kwargs = kclvm_value_from_json(p, kwargs); - let result = _kclvm_context_invoke(p, method, args, kwargs); - - p.buffer.kclvm_context_invoke_result = ptr_as_ref(result).to_json_string_with_null(); - let result_json = p.buffer.kclvm_context_invoke_result.as_ptr() as *const c_char; - - kclvm_value_delete(args); - kclvm_value_delete(kwargs); - kclvm_value_delete(result); - - result_json -} - -unsafe fn _kclvm_context_invoke( - ctx: *mut kclvm_context_t, - method: &str, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - - let fn_addr = _kclvm_get_fn_ptr_by_name(method); - if fn_addr == 0 { - panic!("null fn ptr"); - } - - let ptr = (&fn_addr as *const u64) as *const () - as *const extern "C-unwind" fn( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, - ) -> *mut kclvm_value_ref_t; - - unsafe { (*ptr)(ctx, args, kwargs) } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_pkgpath_is_imported( - ctx: *mut kclvm_context_t, - pkgpath: *const kclvm_char_t, -) -> kclvm_bool_t { - let pkgpath = c2str(pkgpath); - let ctx = mut_ptr_as_ref(ctx); - let result = ctx.imported_pkgpath.contains(pkgpath); - ctx.imported_pkgpath.insert(pkgpath.to_string()); - result as kclvm_bool_t -} - -// ---------------------------------------------------------------------------- -// END -// ---------------------------------------------------------------------------- diff --git a/kclvm/runtime/src/context/mod.rs b/kclvm/runtime/src/context/mod.rs deleted file mode 100644 index ec24cc733..000000000 --- a/kclvm/runtime/src/context/mod.rs +++ /dev/null @@ -1,191 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -pub mod api; -pub use api::*; -use std::fmt; - -use crate::{kclvm_value_delete, kclvm_value_ref_t, BacktraceFrame, PanicInfo, RuntimePanicRecord}; - -impl fmt::Display for PanicInfo { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{self:?}") - } -} - -impl PanicInfo { - pub fn to_json_string(&self) -> String { - let result = serde_json::to_string(&self); - match result { - Ok(res) => res, - _ => { - panic!("PanicInfo Deserialize Failed") - } - } - } - - /// Parse a json string to a PanicInfo. - pub fn from_json_string(s: &str) -> Self { - let result = serde_json::from_str(s); - match result { - Ok(res) => res, - _ => { - panic!("PanicInfo Deserialize Failed") - } - } - } - - /// Parse a string or json string to a PanicInfo. - pub fn from_string(s: &str) -> Self { - let result = serde_json::from_str(s); - match result { - Ok(res) => res, - Err(_) => PanicInfo { - __kcl_PanicInfo__: true, - message: s.to_string(), - err_type_code: crate::RuntimeErrorType::EvaluationError as i32, - ..Default::default() - }, - } - } -} - -impl From for PanicInfo { - fn from(value: String) -> Self { - Self::from_string(&value) - } -} - -impl PanicInfo { - /// New a [`PanicInfo`] from error message [`value`] and the position that error occur. - pub fn from_ast_pos(value: String, pos: (String, u64, u64, u64, u64)) -> Self { - let mut panic_info = Self::from_string(&value); - panic_info.kcl_file = pos.0; - panic_info.kcl_line = pos.1 as i32; - panic_info.kcl_col = pos.2 as i32; - panic_info - } -} - -impl From<&str> for PanicInfo { - fn from(value: &str) -> Self { - Self::from_string(value) - } -} - -impl crate::Context { - pub fn into_raw(self) -> *mut Self { - Box::into_raw(Box::new(self)) - } - - pub fn get_panic_info_json_string(&self) -> Option { - if self.panic_info.__kcl_PanicInfo__ { - Some(self.panic_info.to_json_string()) - } else { - None - } - } - - pub fn set_kcl_pkgpath(&mut self, pkgpath: &str) { - self.panic_info.kcl_pkgpath = pkgpath.to_string(); - } - - pub fn set_kcl_module_path(&mut self, module_path: &str) { - self.module_path = module_path.to_string(); - } - - pub fn set_kcl_workdir(&mut self, workdir: &str) { - self.workdir = workdir.to_string(); - } - - pub fn set_kcl_filename(&mut self, file: &str) { - if !file.is_empty() { - self.panic_info.kcl_file = file.to_string(); - } - } - - pub fn set_kcl_line_col(&mut self, line: i32, col: i32) { - self.panic_info.kcl_line = line; - self.panic_info.kcl_col = col; - } - - pub fn set_kcl_location_info( - &mut self, - arg_msg: Option<&str>, - file: Option<&str>, - line: Option, - col: Option, - ) { - if let Some(s) = arg_msg { - self.panic_info.kcl_arg_msg = s.to_string(); - } - if let Some(s) = file { - self.panic_info.kcl_file = s.to_string(); - } - if let Some(line) = line { - self.panic_info.kcl_line = line; - } - if let Some(col) = col { - self.panic_info.kcl_col = col; - } - } - - pub fn set_kcl_config_meta_location_info( - &mut self, - arg_msg: Option<&str>, - file: Option<&str>, - line: Option, - col: Option, - ) { - if let Some(s) = arg_msg { - self.panic_info.kcl_config_meta_arg_msg = s.to_string(); - } - if let Some(s) = file { - self.panic_info.kcl_config_meta_file = s.to_string(); - } - if let Some(line) = line { - self.panic_info.kcl_config_meta_line = line; - } - if let Some(col) = col { - self.panic_info.kcl_config_meta_col = col; - } - } - - pub fn set_err_type(&mut self, err_type: &crate::RuntimeErrorType) { - self.panic_info.__kcl_PanicInfo__ = true; - self.panic_info.err_type_code = *err_type as i32; - } - - pub fn set_warning_message(&mut self, msg: &str) { - self.panic_info.__kcl_PanicInfo__ = true; - self.panic_info.message = msg.to_string(); - self.panic_info.is_warning = true; - } - - pub fn set_panic_info(&mut self, record: &RuntimePanicRecord) { - self.panic_info.__kcl_PanicInfo__ = true; - - self.panic_info.message = record.message.clone(); - if self.cfg.debug_mode { - self.panic_info.backtrace = self.backtrace.clone(); - self.panic_info.backtrace.push(BacktraceFrame { - file: self.panic_info.kcl_file.clone(), - func: self.panic_info.kcl_func.clone(), - col: self.panic_info.kcl_col, - line: self.panic_info.kcl_line, - }); - } - - self.panic_info.rust_file = record.rust_file.clone(); - self.panic_info.rust_line = record.rust_line; - self.panic_info.rust_col = record.rust_col; - } - - pub fn gc(&self) { - unsafe { - for o in &self.objects { - let ptr = (*o) as *mut kclvm_value_ref_t; - kclvm_value_delete(ptr); - } - } - } -} diff --git a/kclvm/runtime/src/crypto/mod.rs b/kclvm/runtime/src/crypto/mod.rs deleted file mode 100644 index dc4d3f310..000000000 --- a/kclvm/runtime/src/crypto/mod.rs +++ /dev/null @@ -1,342 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -extern crate blake3; -extern crate md5; -extern crate sha1; -extern crate sha2; - -use core::panic; -use std::{fs::File, io::Read}; - -use crate::encoding::encode_text; -use sha2::{Digest, Sha224, Sha256, Sha384, Sha512}; - -use crate::*; -use uuid::Uuid; - -#[allow(non_camel_case_types)] -type kclvm_value_ref_t = ValueRef; - -// md5(value: str, encoding: str = "utf-8") -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_crypto_md5( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { - let encoding = get_call_arg_str(args, kwargs, 1, Some("encoding")); - let bytes = encode_text(&s, encoding).unwrap(); - let hex = format!("{:x}", md5::compute(bytes)); - return ValueRef::str(hex.as_ref()).into_raw(ctx); - } - panic!("md5() missing 1 required positional argument: 'value'"); -} - -// sha1(value: str, encoding: str = "utf-8") -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_crypto_sha1( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { - let encoding = get_call_arg_str(args, kwargs, 1, Some("encoding")); - let bytes = encode_text(&s, encoding).unwrap(); - let hex = sha1::Sha1::from(bytes).digest().to_string(); - return ValueRef::str(hex.as_ref()).into_raw(ctx); - } - panic!("sha1() missing 1 required positional argument: 'value'"); -} - -// sha224(value: str, encoding: str = "utf-8") -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_crypto_sha224( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { - let encoding = get_call_arg_str(args, kwargs, 1, Some("encoding")); - let bytes = encode_text(&s, encoding).unwrap(); - let mut hasher = Sha224::new(); - hasher.update(bytes); - let result = hasher.finalize(); - - let mut hex = String::with_capacity(2 * Sha256::output_size()); - use std::fmt::Write; - - for byte in result { - let _ = write!(&mut hex, "{byte:02x}"); - } - - return ValueRef::str(hex.as_ref()).into_raw(ctx); - } - panic!("sha224() missing 1 required positional argument: 'value'"); -} - -// sha256(value: str, encoding: str = "utf-8") -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_crypto_sha256( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { - let encoding = get_call_arg_str(args, kwargs, 1, Some("encoding")); - let bytes = encode_text(&s, encoding).unwrap(); - let mut hasher = Sha256::new(); - hasher.update(bytes); - let result = hasher.finalize(); - - let mut hex = String::with_capacity(2 * Sha256::output_size()); - use std::fmt::Write; - - for byte in result { - let _ = write!(&mut hex, "{byte:02x}"); - } - - return ValueRef::str(hex.as_ref()).into_raw(ctx); - } - panic!("sha256() missing 1 required positional argument: 'value'"); -} - -// sha384(value: str, encoding: str = "utf-8") -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_crypto_sha384( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { - let encoding = get_call_arg_str(args, kwargs, 1, Some("encoding")); - let bytes = encode_text(&s, encoding).unwrap(); - let mut hasher = Sha384::new(); - hasher.update(bytes); - let result = hasher.finalize(); - - let mut hex = String::with_capacity(2 * Sha256::output_size()); - use std::fmt::Write; - - for byte in result { - let _ = write!(&mut hex, "{byte:02x}"); - } - - return ValueRef::str(hex.as_ref()).into_raw(ctx); - } - panic!("sha384() missing 1 required positional argument: 'value'"); -} - -// sha512(value: str, encoding: str = "utf-8") -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_crypto_sha512( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { - let encoding = get_call_arg_str(args, kwargs, 1, Some("encoding")); - let bytes = encode_text(&s, encoding).unwrap(); - let mut hasher = Sha512::new(); - hasher.update(bytes); - let result = hasher.finalize(); - - let mut hex = String::with_capacity(2 * Sha256::output_size()); - use std::fmt::Write; - - for byte in result { - let _ = write!(&mut hex, "{byte:02x}"); - } - - return ValueRef::str(hex.as_ref()).into_raw(ctx); - } - panic!("sha512() missing 1 required positional argument: 'value'"); -} - -// blake3(value: str, encoding: str = "utf-8") -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_crypto_blake3( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(s) = get_call_arg_str(args, kwargs, 0, Some("value")) { - let encoding = get_call_arg_str(args, kwargs, 1, Some("encoding")); - let bytes = encode_text(&s, encoding).unwrap(); - let hasher = blake3::hash(&bytes); - - let mut hex = String::with_capacity(2 * blake3::OUT_LEN); - use std::fmt::Write; - - for byte in hasher.as_bytes() { - let _ = write!(&mut hex, "{byte:02x}"); - } - - return ValueRef::str(hex.as_ref()).into_raw(ctx); - } - panic!("blake3() missing 1 required positional argument: 'value'"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_crypto_uuid( - ctx: *mut kclvm_context_t, - _args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - return ValueRef::str(Uuid::new_v4().to_string().as_ref()).into_raw(ctx); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_crypto_filesha256( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(filepath) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { - // Open the file - let mut file = File::open(&filepath) - .unwrap_or_else(|e| panic!("failed to access file '{}': {}", filepath, e)); - - // Create a SHA256 hasher instance - let mut hasher = Sha256::new(); - - // Read the file content and update the hasher - let mut buffer = Vec::new(); - file.read_to_end(&mut buffer) - .unwrap_or_else(|e| panic!("failed to read file '{}': {}", filepath, e)); - hasher.update(&buffer); - - // Compute the SHA256 hash - let hash_result = hasher.finalize(); - - let mut hex = String::with_capacity(2 * Sha256::output_size()); - use std::fmt::Write; - - for byte in hash_result { - let _ = write!(&mut hex, "{byte:02x}"); - } - - return ValueRef::str(hex.as_str()).into_raw(ctx); - } - panic!("filesha256() missing 1 required positional argument: 'filepath'"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_crypto_filesha512( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(filepath) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { - let mut file = File::open(&filepath) - .unwrap_or_else(|e| panic!("failed to access file '{}': {}", filepath, e)); - - let mut hasher = Sha512::new(); - - let mut buffer = [0; 4096]; - while let Ok(bytes_read) = file.read(&mut buffer) { - if bytes_read == 0 { - break; // End of file - } - hasher.update(&buffer[..bytes_read]); - } - - let hash_result = hasher.finalize(); - - let hex = hash_result - .iter() - .map(|byte| format!("{byte:02x}")) - .collect::(); - - return ValueRef::str(&hex).into_raw(ctx); - } - panic!("filesha512() missing 1 required positional argument: 'filepath'"); -} - -// fileblake3 -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_crypto_fileblake3( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(filepath) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { - let mut file = File::open(&filepath) - .unwrap_or_else(|e| panic!("failed to access file '{}': {}", filepath, e)); - - let mut buffer = Vec::new(); - file.read_to_end(&mut buffer) - .unwrap_or_else(|e| panic!("failed to read file '{}': {}", filepath, e)); - - let hasher = blake3::hash(&buffer); - - let mut hex = String::with_capacity(2 * blake3::OUT_LEN); - use std::fmt::Write; - - for byte in hasher.as_bytes() { - let _ = write!(&mut hex, "{byte:02x}"); - } - - return ValueRef::str(hex.as_str()).into_raw(ctx); - } - panic!("fileblake3() missing 1 required positional argument: 'filepath'"); -} diff --git a/kclvm/runtime/src/datetime/mod.rs b/kclvm/runtime/src/datetime/mod.rs deleted file mode 100644 index fd28b9ee0..000000000 --- a/kclvm/runtime/src/datetime/mod.rs +++ /dev/null @@ -1,109 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -extern crate chrono; - -use chrono::{prelude::Local, NaiveDate, NaiveDateTime, NaiveTime}; - -use crate::*; - -/// Return the "%Y-%m-%d %H:%M:%S.%{ticks}" format date. -/// `today() -> str` -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_datetime_today( - ctx: *mut kclvm_context_t, - _args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let s = Local::now(); - let ctx = mut_ptr_as_ref(ctx); - ValueRef::str(&(s.format("%Y-%m-%d %H:%M:%S").to_string() + "." + &s.timestamp().to_string())) - .into_raw(ctx) -} - -/// Return the local time format. e.g. 'Sat Jun 06 16:26:11 1998' or format the combined date and time per the specified format string, -/// and the default date format is "%a %b %d %H:%M:%S %Y". -/// `now() -> str` -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_datetime_now( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let s = Local::now(); - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let format = get_call_arg_str(args, kwargs, 0, Some("format")) - .unwrap_or_else(|| "%a %b %d %H:%M:%S %Y".to_string()); - ValueRef::str(&s.format(&format).to_string()).into_raw(ctx) -} - -/// Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. -/// `ticks() -> float` -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_datetime_ticks( - ctx: *mut kclvm_context_t, - _args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let x = Local::now().timestamp(); - ValueRef::float(x as f64).into_raw(ctx) -} - -/// Return the %Y-%m-%d %H:%M:%S format date. -/// `date() -> str` -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_datetime_date( - ctx: *mut kclvm_context_t, - _args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let s = Local::now(); - let ctx = mut_ptr_as_ref(ctx); - ValueRef::str(&s.format("%Y-%m-%d %H:%M:%S").to_string()).into_raw(ctx) -} - -/// Validates whether the provided date string matches the specified format. -/// `validate(str, str) -> bool` -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_datetime_validate( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - if let Some(date) = get_call_arg_str(args, kwargs, 0, Some("date")) { - if let Some(format) = get_call_arg_str(args, kwargs, 1, Some("format")) { - let result = validate_date(&date, &format); - return ValueRef::bool(result).into_raw(ctx); - } - panic!("validate() takes 2 positional arguments (1 given)"); - } - panic!("validate() takes 2 positional arguments (0 given)"); -} - -/// Validates whether the provided date string matches the specified format. -/// -/// # Parameters -/// - `date`: A string slice representing the date to be validated. -/// - `format`: A string slice representing the expected format for the date. -/// -/// # Returns -/// - Returns `true` if the date string successfully parses according to the specified format, -/// otherwise, returns `false`. -#[inline] -fn validate_date(date: &str, format: &str) -> bool { - NaiveDateTime::parse_from_str(date, format) - .map(|_| true) - .or_else(|_| NaiveDate::parse_from_str(date, format).map(|_| true)) - .or_else(|_| NaiveTime::parse_from_str(date, format).map(|_| true)) - .is_ok() -} diff --git a/kclvm/runtime/src/encoding/mod.rs b/kclvm/runtime/src/encoding/mod.rs deleted file mode 100644 index 026706b7f..000000000 --- a/kclvm/runtime/src/encoding/mod.rs +++ /dev/null @@ -1,44 +0,0 @@ -use anyhow::{bail, Result}; -use encoding_rs::Encoding; - -/// Encoding string value to bytes with specific encoding format. -pub fn encode_text(value: &str, encoding: Option) -> Result> { - if let Some(encoding_name) = encoding { - let encoding_name = normalize_encoding_name(&encoding_name)?; - - // Look up the encoding by label - if let Some(encoding) = Encoding::for_label(encoding_name.as_bytes()) { - // Encode the string - let (cow, _, had_errors) = encoding.encode(value); - - if had_errors { - bail!( - "encoding errors occurred while encoding to {}", - encoding_name - ); - } - - Ok(cow.into_owned()) - } else { - bail!("unknown encoding {}", encoding_name) - } - } else { - Ok(value.as_bytes().to_vec()) - } -} - -fn normalize_encoding_name(encoding: &str) -> Result { - if let Some(i) = encoding.find(|c: char| c == ' ' || c.is_ascii_uppercase()) { - let mut out = encoding.as_bytes().to_owned(); - for byte in &mut out[i..] { - if *byte == b' ' { - *byte = b'-'; - } else { - byte.make_ascii_lowercase(); - } - } - String::from_utf8(out).map_err(|e| anyhow::anyhow!(e)) - } else { - Ok(encoding.into()) - } -} diff --git a/kclvm/runtime/src/eval/mod.rs b/kclvm/runtime/src/eval/mod.rs deleted file mode 100644 index 71a2c97aa..000000000 --- a/kclvm/runtime/src/eval/mod.rs +++ /dev/null @@ -1,124 +0,0 @@ -use std::{ - mem::transmute_copy, - panic::{RefUnwindSafe, UnwindSafe}, -}; - -use crate::{ - kclvm_context_t, kclvm_eval_scope_t, kclvm_value_ref_t, mut_ptr_as_ref, Context, ValueRef, -}; -use kclvm_primitives::IndexMap; - -/// Variable setter function type. fn(ctx: &mut Context, scope: &mut ScopeEval, args: ValueRef, kwargs: ValueRef) -> ValueRef. -pub type SetterFuncType = unsafe extern "C-unwind" fn( - *mut kclvm_context_t, - *mut kclvm_eval_scope_t, -) -> *const kclvm_value_ref_t; - -/// LazyEvalScope represents a scope of sequentially independent calculations, where -/// the calculation of values is lazy and only recursively performed through -/// backtracking when needed. -#[derive(PartialEq, Clone, Default, Debug)] -pub struct LazyEvalScope { - /// Temp variable values. - pub vars: IndexMap, - /// Variable value cache. - pub cache: IndexMap, - /// Backtrack levels. - pub levels: IndexMap, - /// Variable setter function pointers. - pub setters: IndexMap>, - /// Calculate times without backtracking. - pub cal_times: IndexMap, -} - -impl LazyEvalScope { - #[inline] - pub fn is_backtracking(&self, key: &str) -> bool { - let level = self.levels.get(key).unwrap_or(&0); - *level > 0 - } - - #[inline] - pub fn setter_len(&self, key: &str) -> usize { - self.setters.get(key).unwrap_or(&vec![]).len() - } - - #[inline] - pub fn cal_increment(&mut self, key: &str) -> bool { - if self.is_backtracking(key) { - false - } else { - let cal_time = *self.cal_times.get(key).unwrap_or(&0); - let next_cal_time = cal_time + 1; - self.cal_times.insert(key.to_string(), next_cal_time); - next_cal_time >= self.setter_len(key) - } - } - - #[inline] - pub fn contains_key(&self, key: &str) -> bool { - self.vars.contains_key(key) - } - - /// Get the value from the context. - pub fn get_value(&mut self, ctx: &mut Context, key: &str, target: &str) -> ValueRef { - let value = match self.vars.get(key) { - Some(value) => value.clone(), - None => ValueRef::undefined(), - }; - // Deal in-place modify and return it self immediately. - if key == target && (!self.is_backtracking(key) || self.setter_len(key) <= 1) { - value - } else { - match self.cache.get(key) { - Some(value) => value.clone(), - None => { - match &self.setters.get(key) { - Some(setters) if !setters.is_empty() => { - // Call all setters function to calculate the value recursively. - let level = *self.levels.get(key).unwrap_or(&0); - let next_level = level + 1; - self.levels.insert(key.to_string(), next_level); - let n = setters.len(); - let index = n - next_level; - if index >= n { - value - } else { - let fn_ptr = setters[index]; - unsafe { - let ctx_ref = mut_ptr_as_ref(ctx); - let panic_info = ctx_ref.panic_info.clone(); - let setter_fn: SetterFuncType = transmute_copy(&fn_ptr); - // Restore the panic info of current schema attribute. - ctx_ref.panic_info = panic_info; - // Call setter functions - setter_fn(ctx, self) - }; - self.levels.insert(key.to_string(), level); - let value = match self.vars.get(key) { - Some(value) => value.clone(), - None => ValueRef::undefined(), - }; - self.cache.insert(key.to_string(), value.clone()); - value - } - } - _ => value, - } - } - } - } - } - - /// Set value to the context. - #[inline] - pub fn set_value(&mut self, key: &str, value: &ValueRef) { - self.vars.insert(key.to_string(), value.clone()); - if self.cal_increment(key) && self.cache.get(key).is_none() { - self.cache.insert(key.to_string(), value.clone()); - } - } -} - -impl UnwindSafe for LazyEvalScope {} -impl RefUnwindSafe for LazyEvalScope {} diff --git a/kclvm/runtime/src/file/mod.rs b/kclvm/runtime/src/file/mod.rs deleted file mode 100644 index d5841a925..000000000 --- a/kclvm/runtime/src/file/mod.rs +++ /dev/null @@ -1,369 +0,0 @@ -mod utils; - -use std::{fs, io::ErrorKind}; - -use crate::*; -use glob::glob; -use std::io::Write; -use std::path::Path; - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_read( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(x) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { - let contents = fs::read_to_string(&x) - .unwrap_or_else(|e| panic!("failed to access the file '{}': {}", x, e)); - - let s = ValueRef::str(contents.as_ref()); - return s.into_raw(ctx); - } - - panic!("read() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_glob( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - let pattern = get_call_arg_str(args, kwargs, 0, Some("pattern")) - .expect("glob() takes exactly one argument (0 given)"); - - let mut matched_paths = vec![]; - for entry in glob(&pattern).unwrap_or_else(|e| panic!("Failed to read glob pattern: {}", e)) { - match entry { - Ok(path) => matched_paths.push(path.display().to_string()), - Err(e) => panic!("failed to access the file matching '{}': {}", pattern, e), - } - } - - ValueRef::list_str(matched_paths.as_slice()).into_raw(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_modpath( - ctx: *mut kclvm_context_t, - _args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let s = ValueRef::str(ctx.module_path.as_ref()); - s.into_raw(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_workdir( - ctx: *mut kclvm_context_t, - _args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let s = ValueRef::str(ctx.workdir.as_ref()); - s.into_raw(ctx) -} - -/// Read the path of the current script or module that is being executed -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_current( - ctx: *mut kclvm_context_t, - _args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let s = ValueRef::str(ctx.panic_info.kcl_file.as_ref()); - s.into_raw(ctx) -} - -/// Whether this file path exists. Returns true if the path points at -/// an existing entity. This function will traverse symbolic links to -/// query information about the destination file. -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_exists( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(path) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { - let exist = Path::new(&path).exists(); - return ValueRef::bool(exist).into_raw(ctx); - } - - panic!("read() takes exactly one argument (0 given)"); -} - -/// Returns the canonical, absolute form of the path with all intermediate -/// components normalized and symbolic links resolved. -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_abs( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(path) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { - if let Ok(abs_path) = Path::new(&path).canonicalize() { - return ValueRef::str(abs_path.to_str().unwrap()).into_raw(ctx); - } else { - panic!("Could not get the absolute path of {path}"); - } - } - - panic!("read() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_mkdir( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(path) = get_call_arg_str(args, kwargs, 0, Some("directory")) { - let exists = get_call_arg_bool(args, kwargs, 1, Some("exists")).unwrap_or_default(); - if let Err(e) = fs::create_dir_all(&path) { - // Ignore the file exists error. - if exists && matches!(e.kind(), ErrorKind::AlreadyExists) { - return ValueRef::none().into_raw(ctx); - } - panic!("Failed to create directory '{}': {}", path, e); - } - return ValueRef::none().into_raw(ctx); - } - - panic!("mkdir() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_delete( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(path) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { - if let Err(e) = fs::remove_file(&path) { - match e.kind() { - std::io::ErrorKind::NotFound => { - // if file not found, try to remove it as a directory - if let Err(e) = fs::remove_dir(&path) { - panic!("failed to delete '{}': {}", path, e); - } - } - _ => { - panic!("failed to delete '{}': {}", path, e); - } - } - } - return ValueRef::none().into_raw(ctx); - } - - panic!("delete() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_cp( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(src_path) = get_call_arg_str(args, kwargs, 0, Some("src")) { - if let Some(dest_path) = get_call_arg_str(args, kwargs, 1, Some("dest")) { - let src_path = Path::new(&src_path); - let dest_path = Path::new(&dest_path); - let result = if src_path.is_dir() { - utils::copy_directory(&src_path, &dest_path) - } else { - fs::copy(&src_path, &dest_path).map(|_| ()) - }; - if let Err(e) = result { - panic!( - "Failed to copy from '{}' to '{}': {}", - src_path.display(), - dest_path.display(), - e - ); - } - return ValueRef::none().into_raw(ctx); - } else { - panic!("cp() missing 'dest_path' argument"); - } - } else { - panic!("cp() missing 'src_path' argument"); - } -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_mv( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(src_path) = get_call_arg_str(args, kwargs, 0, Some("src")) { - if let Some(dest_path) = get_call_arg_str(args, kwargs, 1, Some("dest")) { - if let Err(e) = fs::rename(&src_path, &dest_path) { - panic!("Failed to move '{}' to '{}': {}", src_path, dest_path, e); - } - return ValueRef::none().into_raw(ctx); - } else { - panic!("mv() missing 'dest_path' argument"); - } - } else { - panic!("mv() missing 'src_path' argument"); - } -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_size( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(path) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { - let metadata = fs::metadata(&path); - match metadata { - Ok(metadata) => { - let size = metadata.len(); - let value = kclvm::ValueRef::int(size as i64); - return value.into_raw(ctx); - } - Err(e) => { - panic!("failed to get size of '{}': {}", path, e); - } - } - } - - panic!("size() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_write( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(path) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { - if let Some(content) = get_call_arg_str(args, kwargs, 1, Some("content")) { - match fs::File::create(&path) { - Ok(mut file) => { - if let Err(e) = file.write_all(content.as_bytes()) { - panic!("Failed to write to '{}': {}", path, e); - } - return ValueRef::none().into_raw(ctx); - } - Err(e) => panic!("Failed to create file '{}': {}", path, e), - } - } else { - panic!("write() missing 'content' argument"); - } - } else { - panic!("write() missing 'filepath' argument"); - } -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_append( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(path) = get_call_arg_str(args, kwargs, 0, Some("filepath")) { - if let Some(content) = get_call_arg_str(args, kwargs, 1, Some("content")) { - // Open the file in append mode, creating it if it doesn't exist - match fs::OpenOptions::new().append(true).create(true).open(&path) { - Ok(mut file) => { - if let Err(e) = file.write_all(content.as_bytes()) { - panic!("Failed to append to file '{}': {}", path, e); - } - return ValueRef::none().into_raw(ctx); - } - Err(e) => { - panic!("Failed to open or create file '{}': {}", path, e); - } - } - } else { - panic!("append() requires 'content' argument"); - } - } else { - panic!("append() requires 'filepath' argument"); - } -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_file_read_env( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(key) = get_call_arg_str(args, kwargs, 0, Some("key")) { - match std::env::var(key) { - Ok(v) => ValueRef::str(&v).into_raw(ctx), - Err(_) => ValueRef::undefined().into_raw(ctx), - } - } else { - panic!("read_env() requires 'key' argument"); - } -} diff --git a/kclvm/runtime/src/json/mod.rs b/kclvm/runtime/src/json/mod.rs deleted file mode 100644 index 03bc2cd31..000000000 --- a/kclvm/runtime/src/json/mod.rs +++ /dev/null @@ -1,109 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -use crate::*; - -// data, sort_keys=False, indent=None, ignore_private=False, ignore_none=False - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_json_encode( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let ctx = mut_ptr_as_ref(ctx); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("data")) { - let s = ValueRef::str( - arg0.to_json_string_with_options(&args_to_opts(args, kwargs, 1)) - .as_ref(), - ); - return s.into_raw(ctx); - } - panic!("encode() missing 1 required positional argument: 'value'") -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_json_decode( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("value")) { - match ValueRef::from_json(ctx, arg0.as_str().as_ref()) { - Ok(x) => return x.into_raw(ctx), - Err(err) => panic!("{}", err), - } - } - panic!("decode() missing 1 required positional argument: 'value'") -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_json_validate( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("value")) { - match ValueRef::from_json(ctx, arg0.as_str().as_ref()) { - Ok(_) => return kclvm_value_True(ctx), - Err(_) => return kclvm_value_False(ctx), - } - } - panic!("validate() missing 1 required positional argument: 'value'") -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_json_dump_to_file( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let data = args.arg_i(0).or(kwargs.get_by_key("data")); - let filename = args.arg_i(1).or(kwargs.get_by_key("filename")); - match (data, filename) { - (Some(data), Some(filename)) => { - let filename = filename.as_str(); - let json = data.to_json_string_with_options(&args_to_opts(args, kwargs, 2)); - std::fs::write(&filename, json) - .unwrap_or_else(|e| panic!("Unable to write file '{}': {}", filename, e)); - kclvm_value_Undefined(ctx) - } - _ => { - panic!("dump_to_file() missing 2 required positional arguments: 'data' and 'filename'") - } - } -} - -fn args_to_opts(args: &ValueRef, kwargs: &ValueRef, index: usize) -> JsonEncodeOptions { - let mut opts = JsonEncodeOptions::default(); - if let Some(sort_keys) = get_call_arg_bool(args, kwargs, index, Some("sort_keys")) { - opts.sort_keys = sort_keys; - } - if let Some(indent) = get_call_arg_int(args, kwargs, index + 1, Some("indent")) { - opts.indent = indent; - } - if let Some(ignore_private) = get_call_arg_bool(args, kwargs, index + 2, Some("ignore_private")) - { - opts.ignore_private = ignore_private; - } - if let Some(ignore_none) = get_call_arg_bool(args, kwargs, index + 3, Some("ignore_none")) { - opts.ignore_none = ignore_none; - } - opts -} diff --git a/kclvm/runtime/src/lib.rs b/kclvm/runtime/src/lib.rs deleted file mode 100644 index 456144cbf..000000000 --- a/kclvm/runtime/src/lib.rs +++ /dev/null @@ -1,134 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -use kclvm_runtime_internal_macros::runtime_fn; - -// api-spec: kclvm_context_t -// api-spec(c): typedef struct kclvm_context_t kclvm_context_t; -// api-spec(llvm): %"kclvm_context_t" = type { i8* } - -// api-spec: kclvm_eval_scope_t -// api-spec(c): typedef struct kclvm_eval_scope_t kclvm_eval_scope_t; -// api-spec(llvm): %"kclvm_eval_scope_t" = type { i8* } - -// api-spec: kclvm_type_t -// api-spec(c): typedef struct kclvm_type_t kclvm_type_t; -// api-spec(llvm): %"kclvm_type_t" = type { i8* } - -// api-spec: kclvm_value_t -// api-spec(c): typedef struct kclvm_value_t kclvm_value_t; -// api-spec(llvm): %"kclvm_value_t" = type { i8* } - -// api-spec: kclvm_value_ref_t -// api-spec(c): typedef struct kclvm_value_ref_t kclvm_value_ref_t; -// api-spec(llvm): %"kclvm_value_ref_t" = type { i8* } - -// api-spec: kclvm_iterator_t -// api-spec(c): typedef struct kclvm_iterator_t kclvm_iterator_t; -// api-spec(llvm): %"kclvm_iterator_t" = type { i8* } - -// api-spec: kclvm_buffer_t -// api-spec(c): typedef struct kclvm_buffer_t kclvm_buffer_t; -// api-spec(llvm): %"kclvm_buffer_t" = type { i8* } - -// api-spec: kclvm_kind_t -// api-spec(c): typedef enum kclvm_kind_t kclvm_kind_t; -// api-spec(llvm): %"kclvm_kind_t" = type i32 - -// api-spec: kclvm_size_t -// api-spec(c): typedef int32_t kclvm_size_t; -// api-spec(llvm): %"kclvm_size_t" = type i32 - -// api-spec: kclvm_char_t -// api-spec(c): typedef char kclvm_char_t; -// api-spec(llvm): %"kclvm_char_t" = type i8 - -// api-spec: kclvm_bool_t -// api-spec(c): typedef int8_t kclvm_bool_t; -// api-spec(llvm): %"kclvm_bool_t" = type i8 - -// api-spec: kclvm_int_t -// api-spec(c): typedef int64_t kclvm_int_t; -// api-spec(llvm): %"kclvm_int_t" = type i64 - -// api-spec: kclvm_float_t -// api-spec(c): typedef double kclvm_float_t; -// api-spec(llvm): %"kclvm_float_t" = type double - -// api-spec: kclvm_decorator_value_t -// api-spec(c): typedef struct kclvm_decorator_value_t kclvm_decorator_value_t; -// api-spec(llvm): %"kclvm_decorator_value_t" = type opaque - -pub mod api; -pub use self::api::*; - -pub mod context; -pub use self::context::*; - -pub mod types; -pub use self::types::*; - -pub mod unification; - -pub mod value; -pub use self::value::*; - -pub mod base32; -pub use self::base32::*; - -pub mod base64; -pub use self::base64::*; - -pub mod collection; -pub use self::collection::*; - -pub mod crypto; -pub use self::crypto::*; - -mod eval; - -pub mod datetime; -pub use self::datetime::*; - -pub mod encoding; - -pub mod json; -pub use self::json::*; - -pub mod manifests; -pub use self::manifests::*; - -pub mod math; -pub use self::math::*; - -pub mod net; -pub use self::net::*; - -pub mod regex; -pub use self::regex::*; - -pub mod stdlib; -pub use self::stdlib::*; - -pub mod units; -pub use self::units::*; - -pub mod yaml; -pub use self::yaml::*; - -pub mod file; -pub use self::file::*; - -pub mod template; -pub use self::template::*; - -pub mod panic; -pub use self::panic::*; - -pub mod _kcl_run; -pub use self::_kcl_run::*; - -pub mod _kclvm; -pub use self::_kclvm::*; - -pub mod _kclvm_addr; -pub use self::_kclvm_addr::*; diff --git a/kclvm/runtime/src/manifests/mod.rs b/kclvm/runtime/src/manifests/mod.rs deleted file mode 100644 index bb2f0dad4..000000000 --- a/kclvm/runtime/src/manifests/mod.rs +++ /dev/null @@ -1,102 +0,0 @@ -//! KCL manifests system module -//! -//! Copyright The KCL Authors. All rights reserved. - -use crate::*; - -#[cfg(test)] -mod tests; -mod yaml; - -#[allow(non_camel_case_types)] -type kclvm_value_ref_t = ValueRef; - -/// The function is to serialize a list of KCL objects to YAML and output using the style with -/// the `---\n` separator, and put it to the custom manifest output in the context. -/// -/// ManifestsYamlStreamOptions contain these options -/// - sort_keys: Sort the encode result by keys (defaults to false). -/// - ignore_private: Whether to ignore the attribute whose name starts with -/// a character `_` (defaults to false). -/// - ignore_none: Whether to ignore the attribute whose value is `None` (defaults to false). -/// - sep: Which separator to use between YAML documents (defaults to "---"). -/// More information: https://github.com/kcl-lang/kcl/issues/94 -/// -/// - Function signature. -/// -/// ```kcl, no run -/// schema ManifestsYamlStreamOptions: -/// sort_keys: bool = False -/// ignore_private: bool = True -/// ignore_none: bool = False -/// separator: str = "---\n" -/// -/// manifests.yaml_stream(values: [any], * , opts: ManifestsYamlStreamOptions = ManifestsYamlStreamOptions {}) -/// ``` -/// -/// - Usage -/// -/// ```kcl, no run -/// import manifests -/// -/// config1 = {k1 = "v1"} -/// config2 = {k2 = "v2"} -/// -/// manifests.yaml_stream([config1, config2]) -/// manifests.yaml_stream([config1, config2], opts = { -/// sort_keys = True -/// ignore_none = True -/// }) -/// ``` -/// TODO: more options on the function `yaml_stream`. -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_manifests_yaml_stream( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - // Get the YAML encode options from the second keyword argument `opts`. - let opts = match kwargs.kwarg("opts").or_else(|| args.arg_i(1)) { - Some(opts) => { - if opts.is_config() { - // Get options or default. - YamlEncodeOptions { - sort_keys: opts - .get_by_key("sort_keys") - .unwrap_or_else(|| ValueRef::bool(false)) - .as_bool(), - ignore_private: opts - .get_by_key("ignore_private") - .unwrap_or_else(|| ValueRef::bool(true)) - .as_bool(), - ignore_none: opts - .get_by_key("ignore_none") - .unwrap_or_else(|| ValueRef::bool(false)) - .as_bool(), - sep: opts - .get_by_key("sep") - .unwrap_or_else(|| ValueRef::str("---")) - .as_str(), - } - } else { - panic!( - "Invalid options arguments in yaml_stream(): expect config, got {}", - opts.type_str() - ) - } - } - None => YamlEncodeOptions::default(), - }; - - if let Some(value) = get_call_arg(args, kwargs, 0, Some("values")) { - self::yaml::encode_yaml_stream_to_manifests(ctx, &value, opts); - } else { - panic!("yaml_stream() missing 1 required positional argument: 'values'"); - } - ValueRef::undefined().into_raw(ctx) -} diff --git a/kclvm/runtime/src/manifests/tests.rs b/kclvm/runtime/src/manifests/tests.rs deleted file mode 100644 index 5c38c539d..000000000 --- a/kclvm/runtime/src/manifests/tests.rs +++ /dev/null @@ -1,121 +0,0 @@ -use crate::*; - -#[test] -fn test_kclvm_manifests_yaml_stream() { - let cases = [ - ( - "a: 1\n", - ValueRef::list(Some(&[&ValueRef::dict(Some(&[("a", &ValueRef::int(1))]))])), - YamlEncodeOptions::default(), - ), - ( - "a: 1\nb: 2\n", - ValueRef::list(Some(&[&ValueRef::dict(Some(&[ - ("a", &ValueRef::int(1)), - ("b", &ValueRef::int(2)), - ]))])), - YamlEncodeOptions::default(), - ), - ( - "a:\n- 1\n- 2\n- 3\nb: s\n", - ValueRef::list(Some(&[&ValueRef::dict(Some(&[ - ("a", &ValueRef::list_int(&[1, 2, 3])), - ("b", &ValueRef::str("s")), - ]))])), - YamlEncodeOptions::default(), - ), - ( - "a: 1\n", - ValueRef::list(Some(&[&ValueRef::dict(Some(&[ - ("a", &ValueRef::int(1)), - ("_b", &ValueRef::none()), - ]))])), - YamlEncodeOptions { - ignore_private: true, - ..Default::default() - }, - ), - ( - "a: 1\nb: null\n", - ValueRef::list(Some(&[&ValueRef::dict(Some(&[ - ("a", &ValueRef::int(1)), - ("b", &ValueRef::none()), - ]))])), - YamlEncodeOptions::default(), - ), - ( - "a: 1\n", - ValueRef::list(Some(&[&ValueRef::dict(Some(&[ - ("a", &ValueRef::int(1)), - ("_b", &ValueRef::int(2)), - ("c", &ValueRef::none()), - ("d", &ValueRef::undefined()), - ]))])), - YamlEncodeOptions { - ignore_private: true, - ignore_none: true, - ..Default::default() - }, - ), - ]; - for (yaml_str, value, opts) in cases { - let mut ctx = Context::default(); - let opts = ValueRef::dict(Some(&[ - ("sort_keys", &ValueRef::bool(opts.sort_keys)), - ("ignore_private", &ValueRef::bool(opts.ignore_private)), - ("ignore_none", &ValueRef::bool(opts.ignore_none)), - ("sep", &ValueRef::str(&opts.sep)), - ])); - let mut args = ValueRef::list(None); - args.list_append(&value); - let mut kwargs = ValueRef::dict(None); - kwargs.dict_insert( - &mut ctx, - "opts", - &opts, - ConfigEntryOperationKind::Override, - None, - ); - kclvm_manifests_yaml_stream(&mut ctx, &args, &kwargs); - assert_eq!( - Some(yaml_str.to_string()), - ctx.buffer.custom_manifests_output - ); - } -} - -#[test] -fn test_kclvm_manifests_yaml_stream_invalid() { - let prev_hook = std::panic::take_hook(); - // Disable print panic info in stderr. - std::panic::set_hook(Box::new(|_| {})); - assert_panic( - "yaml_stream() missing 1 required positional argument: 'values'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_manifests_yaml_stream(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "Invalid options arguments in yaml_stream(): expect config, got str", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(Some(&[("opts", &ValueRef::str("invalid_kwarg"))])) - .into_raw(&mut ctx); - kclvm_manifests_yaml_stream(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "Invalid options arguments in yaml_stream(): expect config, got NoneType", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(Some(&[("opts", &ValueRef::none())])).into_raw(&mut ctx); - kclvm_manifests_yaml_stream(ctx.into_raw(), args, kwargs); - }, - ); - std::panic::set_hook(prev_hook); -} diff --git a/kclvm/runtime/src/math/mod.rs b/kclvm/runtime/src/math/mod.rs deleted file mode 100644 index 9ca5f8317..000000000 --- a/kclvm/runtime/src/math/mod.rs +++ /dev/null @@ -1,394 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -extern crate num_integer; - -use crate::*; - -// https://docs.python.org/3/library/math.html -// https://doc.rust-lang.org/std/primitive.f64.html -// https://github.com/RustPython/RustPython/blob/main/stdlib/src/math.rs - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_ceil( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { - return kclvm_value_Int(ctx, x); - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - return kclvm_value_Int(ctx, x.ceil() as i64); - } - - panic!("ceil() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_factorial( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - fn factorial(num: i64) -> i64 { - if num >= 21 { - // overflow: 21! = 51090942171709440000 - // MaxInt64: 9223372036854775807 - panic!("factorial() result overflow"); - } - match num { - 0 => 1, - 1 => 1, - _ => factorial(num - 1) * num, - } - } - - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { - if x >= 0 { - return kclvm_value_Int(ctx, factorial(x)); - } - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - if x >= 0.0 && (x as i64 as f64) == x { - return kclvm_value_Float(ctx, factorial(x as i64) as f64); - } - } - - if args.args_len() > 0 { - panic!("factorial() only accepts integral values") - } - panic!("factorial() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_floor( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { - return kclvm_value_Int(ctx, x); - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - return kclvm_value_Int(ctx, x.floor() as i64); - } - - panic!("floor() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_gcd( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(a) = args.arg_i_int(0, None).or(kwargs.kwarg_int("a", None)) { - if let Some(b) = args.arg_i_int(1, None).or(kwargs.kwarg_int("b", None)) { - return kclvm_value_Int(ctx, num_integer::gcd(a, b)); - } - } - - panic!( - "gcd() takes exactly two arguments ({} given)", - args.args_len() - ); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_isfinite( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if args - .arg_i_int(0, None) - .or(kwargs.kwarg_int("x", None)) - .is_some() - { - return kclvm_value_Bool(ctx, true as i8); - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - return kclvm_value_Bool(ctx, x.is_finite() as i8); - } - - panic!("isfinite() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_isinf( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if args - .arg_i_int(0, None) - .or(kwargs.kwarg_int("x", None)) - .is_some() - { - return kclvm_value_Bool(ctx, false as i8); - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - return kclvm_value_Bool(ctx, x.is_infinite() as i8); - } - if args.arg_i_bool(0, None).is_some() { - return kclvm_value_Bool(ctx, false as i8); - } - - panic!("isinf() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_isnan( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if args - .arg_i_int(0, None) - .or(kwargs.kwarg_int("x", None)) - .is_some() - { - return kclvm_value_Bool(ctx, false as i8); - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - return kclvm_value_Bool(ctx, x.is_nan() as i8); - } - - panic!("isnan() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_modf( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let ctx = mut_ptr_as_ref(ctx); - let kwargs = ptr_as_ref(kwargs); - - if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { - let list = ValueRef::list_float(&[0.0, x as f64]); - return list.into_raw(ctx); - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - if !x.is_finite() { - if x.is_infinite() { - let list = ValueRef::list_float(&[0.0_f64.copysign(x), x]); - return list.into_raw(ctx); - } else if x.is_nan() { - let list = ValueRef::list_float(&[x, x]); - return list.into_raw(ctx); - } - } - let list = ValueRef::list_float(&[x.fract(), x.trunc()]); - return list.into_raw(ctx); - } - - panic!("modf() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_exp( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { - return kclvm_value_Float(ctx, (x as f64).exp()); - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - return kclvm_value_Float(ctx, x.exp()); - } - panic!("exp() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_expm1( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { - return kclvm_value_Float(ctx, (x as f64).exp_m1()); - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - return kclvm_value_Float(ctx, x.exp_m1()); - } - panic!("expm1() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_log( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { - if let Some(base) = args - .arg_i_float(1, Some(std::f64::consts::E)) - .or_else(|| kwargs.kwarg_float("e", Some(std::f64::consts::E))) - { - return kclvm_value_Int(ctx, (x as f64).log(base) as i64); - } - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - if let Some(base) = args - .arg_i_float(1, Some(std::f64::consts::E)) - .or_else(|| kwargs.kwarg_float("e", Some(std::f64::consts::E))) - { - return kclvm_value_Float(ctx, x.log(base)); - } - } - panic!("log() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_log1p( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { - return kclvm_value_Float(ctx, ((x + 1) as f64).ln_1p()); - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - return kclvm_value_Float(ctx, (x + 1.0).ln_1p()); - } - panic!("log1p() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_log2( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { - return kclvm_value_Int(ctx, (x as f64).log2() as i64); - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - return kclvm_value_Float(ctx, x.log2()); - } - panic!("log2() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_log10( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { - return kclvm_value_Float(ctx, (x as f64).log10()); - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - return kclvm_value_Float(ctx, x.log10()); - } - panic!("log10() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_pow( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { - if let Some(n) = args.arg_i_int(1, None).or(kwargs.kwarg_int("n", None)) { - if n < 0 { - return kclvm_value_Float(ctx, (x as f64).powf(n as f64)); - } else { - return kclvm_value_Int(ctx, x.pow(n as u32)); - } - } - if let Some(n) = args.arg_i_float(1, None).or(kwargs.kwarg_float("n", None)) { - return kclvm_value_Float(ctx, (x as f64).powf(n)); - } - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - if let Some(n) = args.arg_i_int(1, None).or(kwargs.kwarg_int("n", None)) { - return kclvm_value_Float(ctx, x.powi(n as i32)); - } - if let Some(n) = args.arg_i_float(1, None).or(kwargs.kwarg_float("n", None)) { - return kclvm_value_Float(ctx, x.powf(n)); - } - } - panic!("pow() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_math_sqrt( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(x) = args.arg_i_int(0, None).or(kwargs.kwarg_int("x", None)) { - return kclvm_value_Float(ctx, (x as f64).sqrt()); - } - if let Some(x) = args.arg_i_float(0, None).or(kwargs.kwarg_float("x", None)) { - return kclvm_value_Float(ctx, x.sqrt()); - } - panic!("sqrt() takes exactly one argument (0 given)"); -} diff --git a/kclvm/runtime/src/net/mod.rs b/kclvm/runtime/src/net/mod.rs deleted file mode 100644 index f53b7dd84..000000000 --- a/kclvm/runtime/src/net/mod.rs +++ /dev/null @@ -1,2300 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -use crate::*; -use cidr::{IpCidr, Ipv4Cidr, Ipv6Cidr}; -use itertools::Itertools; -use std::net::IpAddr; -use std::net::IpAddr::V4; -use std::net::IpAddr::V6; -use std::net::Ipv4Addr; -use std::net::Ipv6Addr; -use std::str::FromStr; - -// split_host_port(ip_end_point: str) -> List[str] - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_split_host_port( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(ip_end_point) = get_call_arg(args, kwargs, 0, Some("ip_end_point")) { - let ip_end_point_str = ip_end_point.as_str(); - match ip_end_point_str.rsplit_once(':') { - None => panic!( - "ip_end_point \"{}\" missing port", - ip_end_point_str.escape_default() - ), - Some((host, port)) => { - if host.starts_with('[') { - match ip_end_point_str.find(']') { - None => panic!( - "ip_end_point \"{}\" missing ']'", - ip_end_point_str.escape_default() - ), - Some(end) => { - if end > host.len() || !ip_end_point_str[end + 1..].starts_with(':') { - panic!( - "ip_end_point \"{}\" missing port", - ip_end_point_str.escape_default() - ); - } - if end < host.len() - 1 { - panic!( - "ip_end_point \"{}\" too many colons", - ip_end_point_str.escape_default() - ); - } - if ip_end_point_str[1..].contains('[') { - panic!( - "ip_end_point \"{}\" unexpected '['", - ip_end_point_str.escape_default() - ); - } - if port.contains(']') { - panic!( - "ip_end_point \"{}\" unexpected ']'", - ip_end_point_str.escape_default() - ); - } - return ValueRef::list(Some(&[ - &ValueRef::str(&host[1..end]), - &ValueRef::str(port), - ])) - .into_raw(ctx); - } - } - } - if host.contains(':') { - panic!( - "ip_end_point \"{}\" too many colons", - ip_end_point_str.escape_default() - ); - } - if ip_end_point_str[1..].contains('[') { - panic!( - "ip_end_point \"{}\" unexpected '['", - ip_end_point_str.escape_default() - ); - } - if ip_end_point_str.contains(']') { - panic!( - "ip_end_point \"{}\" unexpected ']'", - ip_end_point_str.escape_default() - ); - } - return ValueRef::list(Some(&[&ValueRef::str(host), &ValueRef::str(port)])) - .into_raw(ctx); - } - } - } - - panic!("split_host_port() missing 1 required positional argument: 'ip_end_point'"); -} - -// join_host_port(host, port) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_join_host_port( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(host) = get_call_arg(args, kwargs, 0, Some("host")) { - if let Some(port) = get_call_arg(args, kwargs, 1, Some("port")) { - if host.as_str().contains(':') { - return ValueRef::str(format!("[{host}]:{port}").as_ref()).into_raw(ctx); - } - return ValueRef::str(format!("{host}:{port}").as_ref()).into_raw(ctx); - } - } - panic!("join_host_port() missing 2 required positional arguments: 'host' and 'port'"); -} - -// fqdn(name: str = '') -> str - -#[cfg(not(target_arch = "wasm32"))] -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_fqdn( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - use std::net::ToSocketAddrs; - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let name = get_call_arg_str(args, kwargs, 0, Some("name")).unwrap_or_default(); - let hostname = if name.is_empty() { - match hostname::get() { - Ok(name) => name.to_string_lossy().into_owned(), - Err(_) => return ValueRef::str("").into_raw(ctx), - } - } else { - name - }; - match (hostname.as_str(), 0).to_socket_addrs() { - Ok(mut addrs) => { - if let Some(addr) = addrs.next() { - match dns_lookup::lookup_addr(&addr.ip()) { - Ok(fqdn) => ValueRef::str(&fqdn), - Err(_) => ValueRef::str(&hostname), - } - } else { - ValueRef::str(&hostname) - } - } - Err(_) => ValueRef::str(&hostname), - } - .into_raw(ctx) -} - -#[cfg(target_arch = "wasm32")] -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_fqdn( - _ctx: *mut kclvm_context_t, - _args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - panic!("fqdn() do not support the WASM target"); -} - -// parse_IP(ip) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_parse_IP( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - kclvm_net_IP_string(ctx, args, kwargs) -} - -// to_IP4(ip) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_to_IP4( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { - match Ipv4Addr::from_str(ip.as_ref()) { - Ok(addr) => { - let s = format!("{addr}"); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - Err(_e) => match Ipv6Addr::from_str(ip.as_ref()) { - Ok(addr) => { - if let Some(v4) = addr.to_ipv4() { - let s = format!("{v4}"); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - let s = format!("can not parse {} ipv6 to ipv4!", ip); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - Err(e) => { - let s = format!("can not both parse {} to ipv6 and ipv4,err:{}", ip, e); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - }, - } - } - panic!("IP_string() missing 1 required positional argument: 'ip'"); -} - -// to_IP6(ip) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_to_IP6( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { - match Ipv6Addr::from_str(ip.as_ref()) { - Ok(addr) => { - let s = format!("{addr}"); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - Err(_) => { - match Ipv4Addr::from_str(ip.as_ref()) { - Ok(addr) => { - // Convert IPv4 to IPv6-mapped address (::ffff:0:0/96) - let v6 = addr.to_ipv6_mapped(); - let s = format!("{v6}"); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - Err(e) => { - let s = format!("can not both parse {} to ipv6 and ipv4,err:{}", ip, e); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - } - } - } - } - panic!("IP_string() missing 1 required positional argument: 'ip'"); -} - -// IP_string(ip: str) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_IP_string( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { - if let Ok(addr) = Ipv4Addr::from_str(ip.as_ref()) { - let s = format!("{addr}"); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { - let s = format!("{addr}"); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - - return ValueRef::str("").into_raw(ctx); - } - - panic!("IP_string() missing 1 required positional argument: 'ip'"); -} - -// is_IPv4(ip: str) -> bool - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_is_IPv4( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { - if let Ok(_addr) = Ipv4Addr::from_str(ip.as_ref()) { - return kclvm_value_True(ctx); - } - if let Ok(_addr) = Ipv6Addr::from_str(ip.as_ref()) { - return kclvm_value_False(ctx); - } - - return kclvm_value_False(ctx); - } - - panic!("is_IPv4() missing 1 required positional argument: 'ip'"); -} - -// is_IP(ip: str) -> bool - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_is_IP( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { - if Ipv4Addr::from_str(ip.as_ref()).is_ok() || Ipv6Addr::from_str(ip.as_ref()).is_ok() { - kclvm_value_True(ctx) - } else { - kclvm_value_False(ctx) - } - } else { - panic!("is_IP() missing 1 required positional argument: 'ip'"); - } -} - -// is_loopback_IP(ip: str) -> bool - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_is_loopback_IP( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { - if let Ok(addr) = Ipv4Addr::from_str(ip.as_ref()) { - let x = addr.is_loopback(); - return kclvm_value_Bool(ctx, x as i8); - } - if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { - let x = addr.is_loopback(); - return kclvm_value_Bool(ctx, x as i8); - } - - return kclvm_value_False(ctx); - } - - panic!("is_loopback_IP() missing 1 required positional argument: 'ip'"); -} - -// is_multicast_IP(ip: str) -> bool - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_is_multicast_IP( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { - if let Ok(addr) = Ipv4Addr::from_str(ip.as_ref()) { - let x = addr.is_multicast(); - return kclvm_value_Bool(ctx, x as i8); - } - if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { - let x = addr.is_multicast(); - return kclvm_value_Bool(ctx, x as i8); - } - - return kclvm_value_False(ctx); - } - - panic!("kclvm_net_is_multicast_IP() missing 1 required positional argument: 'ip'"); -} - -// is_interface_local_multicast_IP(ip: str) -> bool - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_is_interface_local_multicast_IP( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { - if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { - // For IPv6, interface-local multicast addresses start with ffx1::/16 - let is_interface_local = (addr.segments()[0] & 0xff0f) == 0xff01; - let x = is_interface_local && addr.is_multicast(); - return kclvm_value_Bool(ctx, x as i8); - } - return kclvm_value_Bool(ctx, 0); // False for IPv4 and invalid IP addresses - } - panic!("is_interface_local_multicast_IP() missing 1 required positional argument: 'ip'"); -} - -// is_link_local_multicast_IP(ip: str) -> bool - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_is_link_local_multicast_IP( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { - if let Ok(addr) = Ipv4Addr::from_str(ip.as_ref()) { - // For IPv4, link-local multicast addresses are in the range 224.0.0.0/24 - let is_link_local_multicast = - addr.octets()[0] == 224 && addr.octets()[1] == 0 && addr.octets()[2] == 0; - let x = is_link_local_multicast && addr.is_multicast(); - return kclvm_value_Bool(ctx, x as i8); - } - if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { - // For IPv6, link-local multicast addresses start with ffx2::/16 - let is_link_local_multicast = (addr.segments()[0] & 0xff0f) == 0xff02; - let x = is_link_local_multicast && addr.is_multicast(); - return kclvm_value_Bool(ctx, x as i8); - } - return kclvm_value_Bool(ctx, 0); // False for invalid IP addresses - } - - panic!("is_link_local_multicast_IP() missing 1 required positional argument: 'ip'"); -} - -// is_link_local_unicast_IP(ip: str) -> bool - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_is_link_local_unicast_IP( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { - if let Ok(addr) = Ipv4Addr::from_str(ip.as_ref()) { - let x = addr.is_link_local() && (!addr.is_multicast()); - return kclvm_value_Bool(ctx, x as i8); - } - if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { - let x = Ipv6Addr_is_unicast_link_local(&addr) && (!addr.is_multicast()); - return kclvm_value_Bool(ctx, x as i8); - } - return kclvm_value_False(ctx); - } - - panic!("is_link_local_unicast_IP() missing 1 required positional argument: 'ip'"); -} - -#[allow(non_camel_case_types, non_snake_case)] -fn Ipv6Addr_is_global(_self: &std::net::Ipv6Addr) -> bool { - let segments = _self.segments(); - // 2000::/3 global unicast - if (segments[0] & 0xe000) == 0x2000 { - // 2001:db8::/32 documentation - if segments[0] == 0x2001 && segments[1] == 0xdb8 { - return false; - } - // 2001:2::/48 benchmarking - if segments[0] == 0x2001 && segments[1] == 2 && segments[2] == 0 { - return false; - } - return true; - } - // 64:ff9b::/96 NAT64 - if segments[0] == 0x64 - && segments[1] == 0xff9b - && segments[2] == 0 - && segments[3] == 0 - && segments[4] == 0 - && segments[5] == 0 - { - let ipv4 = Ipv4Addr::from(((segments[6] as u32) << 16) + segments[7] as u32); - return Ipv4Addr_is_global(&ipv4) && (!ipv4.is_multicast()); - } - return false; -} - -#[allow(non_camel_case_types, non_snake_case)] -pub const fn Ipv6Addr_is_unicast_link_local(_self: &Ipv6Addr) -> bool { - (_self.segments()[0] & 0xffc0) == 0xfe80 -} - -// is_global_unicast_IP(ip: str) -> bool - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_is_global_unicast_IP( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { - if let Ok(addr) = Ipv4Addr::from_str(ip.as_ref()) { - let x = Ipv4Addr_is_global(&addr) && (!addr.is_multicast()); - return kclvm_value_Bool(ctx, x as i8); - } - if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { - return kclvm_value_Bool(ctx, Ipv6Addr_is_global(&addr) as i8); - } - - return kclvm_value_False(ctx); - } - - panic!("is_global_unicast_IP() missing 1 required positional argument: 'ip'"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_parse_CIDR( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(cidr) = get_call_arg(args, kwargs, 0, Some("cidr")) { - if let Ok(cidr) = IpCidr::from_str(&cidr.as_str()) { - let ip = ValueRef::str(&cidr.first_address().to_string()); - let mask = ValueRef::int(cidr.network_length().into()); - return ValueRef::dict(Some(&[("ip", &ip), ("mask", &mask)])).into_raw(ctx); - } - return ValueRef::dict(None).into_raw(ctx); - } - - panic!("parse_CIDR() missing 1 required positional argument: 'cidr'"); -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_is_IP_in_CIDR( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - let ip = match get_call_arg_str(args, kwargs, 0, Some("ip")) { - None => { - panic!("is_IP_in_CIDR() missing 2 required positional arguments: 'ip' and 'cidr'"); - } - Some(ip) => match IpAddr::from_str(ip.as_str()) { - Err(err) => panic!("is_IP_in_CIDR() invalid ip: {}", err), - Ok(ip) => ip, - }, - }; - let cidr = match get_call_arg_str(args, kwargs, 1, Some("cidr")) { - None => { - panic!("is_IP_in_CIDR() missing 2 required positional arguments: 'ip' and 'cidr'"); - } - Some(cidr) => match IpCidr::from_str(&cidr.as_str()) { - Err(err) => panic!("is_IP_in_CIDR() invalid cidr: {}", err), - Ok(cidr) => cidr, - }, - }; - - if cidr.is_ipv6() { - match ip { - IpAddr::V4(ip) => { - return kclvm_value_Bool( - ctx, - cidr.contains(&IpAddr::V6(ip.to_ipv6_mapped())) as i8, - ); - } - IpAddr::V6(_ip) => {} - } - } - return kclvm_value_Bool(ctx, cidr.contains(&ip) as i8); -} - -#[allow(non_camel_case_types, non_snake_case)] -fn Ipv4Addr_is_global(_self: &std::net::Ipv4Addr) -> bool { - // check if this address is 192.0.0.9 or 192.0.0.10. These addresses are the only two - // globally routable addresses in the 192.0.0.0/24 range. - if u32::from_be_bytes(_self.octets()) == 0xc0000009 - || u32::from_be_bytes(_self.octets()) == 0xc000000a - { - return true; - } - !_self.is_private() - && !_self.is_loopback() - && !_self.is_link_local() - && !_self.is_broadcast() - && !_self.is_documentation() - && !Ipv4Addr_is_shared(_self) // _self.is_shared() - && !Ipv4Addr_is_ietf_protocol_assignment(_self) // _self.is_ietf_protocol_assignment() - && !Ipv4Addr_is_reserved(_self) // _self.is_reserved() - && !Ipv4Addr_is_benchmarking(_self) // _self.is_benchmarking() - // Make sure the address is not in 0.0.0.0/8 - && _self.octets()[0] != 0 -} - -#[allow(non_camel_case_types, non_snake_case)] -const fn Ipv4Addr_is_shared(_self: &std::net::Ipv4Addr) -> bool { - _self.octets()[0] == 100 && (_self.octets()[1] & 0b1100_0000 == 0b0100_0000) -} -#[allow(non_camel_case_types, non_snake_case)] -const fn Ipv4Addr_is_ietf_protocol_assignment(_self: &std::net::Ipv4Addr) -> bool { - _self.octets()[0] == 192 && _self.octets()[1] == 0 && _self.octets()[2] == 0 -} -#[allow(non_camel_case_types, non_snake_case)] -const fn Ipv4Addr_is_reserved(_self: &std::net::Ipv4Addr) -> bool { - _self.octets()[0] & 240 == 240 && !_self.is_broadcast() -} -#[allow(non_camel_case_types, non_snake_case)] -const fn Ipv4Addr_is_benchmarking(_self: &std::net::Ipv4Addr) -> bool { - _self.octets()[0] == 198 && (_self.octets()[1] & 0xfe) == 18 -} - -// is_unspecified_IP(ip: str) -> bool - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_is_unspecified_IP( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(ip) = get_call_arg_str(args, kwargs, 0, Some("ip")) { - if let Ok(addr) = Ipv4Addr::from_str(ip.as_ref()) { - return kclvm_value_Bool(ctx, addr.is_unspecified() as i8); - } - if let Ok(addr) = Ipv6Addr::from_str(ip.as_ref()) { - return kclvm_value_Bool(ctx, addr.is_unspecified() as i8); - } - return kclvm_value_False(ctx); - } - panic!("is_unspecified_IP() missing 1 required positional argument: 'ip'"); -} - -// CIDR_subnet(cidr: str, additional_bits: int, net_num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_CIDR_subnet( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - let cidr = match get_call_arg(args, kwargs, 0, Some("cidr")) { - None => { - panic!("CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'"); - } - Some(cidr) => match IpCidr::from_str(&cidr.as_str()) { - Err(err) => { - panic!("CIDR_subnet() invalid cidr: {}", err) - } - Ok(cidr) => cidr, - }, - }; - - let additional_bits = match get_call_arg(args, kwargs, 1, Some("additional_bits")) { - None => { - panic!("CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'"); - } - Some(additional_bits) => additional_bits.must_as_strict_int(), - }; - if additional_bits < 0 { - panic!("CIDR_subnet() invalid additional_bits: cannot be negative"); - } - - let net_num = match get_call_arg(args, kwargs, 2, Some("net_num")) { - None => { - panic!("CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'"); - } - Some(net_num) => net_num.must_as_strict_int(), - }; - if net_num < 0 { - panic!("CIDR_subnet() invalid net_num: cannot be negative"); - } - - match CIDR_allocate(cidr, additional_bits, net_num) { - Ok(value) => return value.into_raw(ctx), - Err(message) => panic!("CIDR_subnet() {}", message), - }; -} - -#[allow(non_camel_case_types, non_snake_case)] -fn CIDR_allocate(cidr: IpCidr, additional_bits: i64, net_num: i64) -> Result { - let len = cidr.network_length() as i64 + additional_bits; - let new_cidr = match cidr.first_address() { - V4(ipv4) => { - if len > 32 { - return Err(format!("invalid additional_bits: would extend network length to {} bits, which is too long for IPv4", len)); - } - if net_num >= (1 << additional_bits) { - return Err(format!( - "additional_bits of {} does not accommodate a net_num of {}", - additional_bits, net_num - )); - } - match Ipv4Cidr::new( - Ipv4Addr::from_bits(ipv4.to_bits() + (net_num << (32 - len)) as u32), - len as u8, - ) { - Err(_e) => unreachable!(), - Ok(cidr) => format!("{}/{}", cidr.first_address(), cidr.network_length()), - } - } - V6(ipv6) => { - if len > 128 { - return Err(format!("invalid additional_bits: would extend network length to {} bits, which is too long for IPv6", len)); - } - if additional_bits < 64 && net_num as u64 >= (1u64 << additional_bits) { - return Err(format!( - "additional_bits of {} does not accommodate a net_num of {}", - additional_bits, net_num - )); - } - if len == 0 { - return Ok(ValueRef::str("::/0")); - } - match Ipv6Cidr::new( - Ipv6Addr::from_bits(ipv6.to_bits() + ((net_num as u128) << (128 - len))), - len as u8, - ) { - Err(_e) => unreachable!(), - Ok(cidr) => format!("{}/{}", cidr.first_address(), cidr.network_length()), - } - } - }; - Ok(ValueRef::str(new_cidr.as_str())) -} - -// CIDR_subnets(cidr: str, additional_bits: [int]) -> [str] - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_CIDR_subnets( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - let cidr = match get_call_arg(args, kwargs, 0, Some("cidr")) { - None => { - panic!("CIDR_subnets() missing 2 required positional arguments: 'cidr' and 'additional_bits'"); - } - Some(cidr) => match IpCidr::from_str(&cidr.as_str()) { - Err(err) => { - panic!("CIDR_subnets() invalid cidr: {}", err) - } - Ok(cidr) => cidr, - }, - }; - - let additional_bits_valueref = match get_call_arg(args, kwargs, 1, Some("additional_bits")) { - None => { - panic!("CIDR_subnets() missing 2 required positional arguments: 'cidr' and 'additional_bits'"); - } - Some(additional_bits) => additional_bits, - }; - let additional_bits = additional_bits_valueref.as_list_ref(); - - let mut net_num: Vec = Vec::with_capacity(additional_bits.values.len()); - for new_additional in additional_bits.values.iter() { - let mut num = 0i64; - let bits = new_additional.must_as_strict_int(); - - if bits < 0 { - panic!("CIDR_subnets() invalid additional_bits: cannot be negative"); - } - let new_bits = cidr.network_length() as i64 + bits; - if cidr.is_ipv4() && new_bits > 32 { - panic!("CIDR_subnets() invalid additional_bits: would extend network length to {} bits, which is too long for IPv4", new_bits); - } - if cidr.is_ipv6() { - if bits > 63 { - panic!("CIDR_subnets() invalid additional_bits: cannot extend more than 63 bits") - } - if new_bits > 128 { - panic!("CIDR_subnets() invalid additional_bits: would extend network length to {} bits, which is too long for IPv6", new_bits); - } - } - - let mut try_again = true; - while try_again { - try_again = false; - for i in 0..net_num.len() { - let mut allocated_num = net_num[i]; - let mut allocated_bits = additional_bits.values[i].must_as_strict_int(); - if allocated_bits > bits { - allocated_num >>= allocated_bits - bits; - allocated_bits = bits - } - if allocated_bits < bits { - allocated_num <<= bits - allocated_bits; - } - if allocated_num == num { - num += 1 << (bits - allocated_bits); - try_again = true; - } - } - } - net_num.push(num); - } - - let mut subnets = Vec::with_capacity(net_num.len()); - for (additional, num) in additional_bits.values.iter().zip_eq(net_num.iter()) { - if *num as u64 >= (1u64 << additional.must_as_strict_int()) { - match subnets.pop() { - None => unreachable!(), - Some(last) => panic!("CIDR_subnets() not enough remaining address space for a subnet with a prefix of {} bits after {}", cidr.network_length() as i64 + additional.must_as_strict_int(), last) - } - } - let subnet = match CIDR_allocate(cidr, additional.must_as_strict_int(), *num) { - Ok(value) => value, - Err(message) => panic!("CIDR_subnets {}", message), - }; - subnets.push(subnet); - } - ValueRef::list(Some(subnets.iter().collect_vec().as_slice())).into_raw(ctx) -} - -// CIDR_host(cidr: str, host_num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_CIDR_host( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - let cidr = match get_call_arg(args, kwargs, 0, Some("cidr")) { - None => { - panic!("CIDR_host() missing 2 required positional arguments: 'cidr' and 'host_num'"); - } - Some(cidr) => match IpCidr::from_str(&cidr.as_str()) { - Err(err) => { - panic!("CIDR_host() invalid cidr: {}", err) - } - Ok(cidr) => cidr, - }, - }; - - let host_num = match get_call_arg(args, kwargs, 1, Some("host_num")) { - None => { - panic!("CIDR_host() missing 2 required positional arguments: 'cidr' and 'host_num'"); - } - Some(net_num) => net_num.must_as_strict_int(), - }; - - let host_len = cidr.family().len() - cidr.network_length(); - let abs_host_num = match host_num < 0 { - true => -(host_num + 1), - false => host_num, - } as u64; - if host_len < 64 && (1u64 << host_len) <= abs_host_num { - panic!( - "CIDR_host() prefix of {} does not accommodate a host numbered {}", - cidr.network_length(), - host_num - ); - } - - let addr = match cidr.first_address() { - V4(ipv4) => { - let mut bits = ipv4.to_bits() as i64; - if host_num < 0 { - bits += 1i64 << host_len - } - bits += host_num; - Ipv4Addr::from_bits(bits as u32).to_string() - } - V6(ipv6) => { - let mut bits = ipv6.to_bits(); - if host_len == 128 { - bits = host_num as u128; - } else { - let host_bits = match host_num < 0 { - true => (1u128 << host_len) - (-(host_num as i128)) as u128, - false => host_num as u128, - }; - bits += host_bits; - } - Ipv6Addr::from_bits(bits).to_string() - } - }; - return ValueRef::str(addr.as_str()).into_raw(ctx); -} - -// CIDR_netmask(cidr: str) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_net_CIDR_netmask( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - let cidr = match get_call_arg(args, kwargs, 0, Some("cidr")) { - None => { - panic!("CIDR_netmask() missing 1 required positional argument: 'cidr'"); - } - Some(cidr) => match IpCidr::from_str(&cidr.as_str()) { - Err(err) => { - panic!("CIDR_netmask() invalid cidr: {}", err) - } - Ok(cidr) => cidr, - }, - }; - - if cidr.is_ipv6() { - panic!("CIDR_netmask() IPv6 addresses cannot have a netmask") - } - - let bits = -1i64 << (32 - cidr.network_length()); - return ValueRef::str(Ipv4Addr::from_bits(bits as u32).to_string().as_str()).into_raw(ctx); -} - -#[cfg(test)] -mod test_net { - use super::*; - - #[test] - #[allow(non_snake_case)] - fn test_to_ip4() { - let cases = [ - ("::FFFF:192.168.1.10", "192.168.1.10"), - ( - "::FFFF:192.168.x.10", - "can not both parse ::FFFF:192.168.x.10 to ipv6 and ipv4,err:invalid IPv6 address syntax", - ), - ("::FFFF:10.0.0.1", "10.0.0.1"), - ("::FFFF:172.16.0.1", "172.16.0.1"), - ("::FFFF:127.0.0.1", "127.0.0.1"), - ("0000:0000:0000:0000:0000:FFFF:0A00:0001", "10.0.0.1"), - ("::FFFF:224.0.0.1", "224.0.0.1"), - ( - "::FFFF:invalid.ip", - "can not both parse ::FFFF:invalid.ip to ipv6 and ipv4,err:invalid IPv6 address syntax" - ), - // IPv4-mapped IPv6 addresses - ("::FFFF:0A00:0001", "10.0.0.1"), - ("0:0:0:0:0:FFFF:AC10:0001", "172.16.0.1"), - ]; - let mut ctx = Context::default(); - for (ip6, expected) in cases.iter() { - unsafe { - let actual = &*kclvm_net_to_IP4( - &mut ctx, - &ValueRef::list(Some(&[&ValueRef::str(ip6)])), - &ValueRef::dict(None), - ); - assert_eq!(&ValueRef::str(expected), actual, "{} positional", ip6,); - } - } - } - - #[test] - #[allow(non_snake_case)] - fn test_to_ip6() { - let cases = [ - ("192.168.1.10", "::ffff:192.168.1.10"), - ( - "192.168.x.10", - "can not both parse 192.168.x.10 to ipv6 and ipv4,err:invalid IPv4 address syntax", - ), - ("10.0.0.1", "::ffff:10.0.0.1"), - ("172.16.0.1", "::ffff:172.16.0.1"), - ("127.0.0.1", "::ffff:127.0.0.1"), - ("224.0.0.1", "::ffff:224.0.0.1"), - ( - "invalid.ip", - "can not both parse invalid.ip to ipv6 and ipv4,err:invalid IPv4 address syntax", - ), - // IPv6 addresses - ("2001:db8::1", "2001:db8::1"), - ("::1", "::1"), - ( - "2001:db8:::1", - "can not both parse 2001:db8:::1 to ipv6 and ipv4,err:invalid IPv4 address syntax", - ), - ]; - let mut ctx = Context::default(); - for (ip4, expected) in cases.iter() { - unsafe { - let actual = &*kclvm_net_to_IP6( - &mut ctx, - &ValueRef::list(Some(&[&ValueRef::str(ip4)])), - &ValueRef::dict(None), - ); - assert_eq!(&ValueRef::str(expected), actual, "{} positional", ip4,); - } - } - } - - #[test] - fn test_split_host_port() { - let cases = [ - ( - ValueRef::str("invalid.invalid:21"), - ValueRef::list(Some(&[ - &ValueRef::str("invalid.invalid"), - &ValueRef::str("21"), - ])), - ), - ( - ValueRef::str("192.0.2.1:14"), - ValueRef::list(Some(&[&ValueRef::str("192.0.2.1"), &ValueRef::str("14")])), - ), - ( - ValueRef::str("[2001:db8::]:80"), - ValueRef::list(Some(&[&ValueRef::str("2001:db8::"), &ValueRef::str("80")])), - ), - ]; - let mut ctx = Context::default(); - for (ip_end_point, expected) in cases.iter() { - unsafe { - let actual = &*kclvm_net_split_host_port( - &mut ctx, - &ValueRef::list(Some(&[&ip_end_point])), - &ValueRef::dict(None), - ); - assert_eq!(expected, actual); - } - unsafe { - let actual = &*kclvm_net_split_host_port( - &mut ctx, - &ValueRef::list(None), - &ValueRef::dict(Some(&[("ip_end_point", ip_end_point)])), - ); - assert_eq!(expected, actual); - } - } - } - #[test] - fn test_split_host_port_invalid() { - let prev_hook = std::panic::take_hook(); - // Disable print panic info in stderr. - std::panic::set_hook(Box::new(|_| {})); - assert_panic( - "split_host_port() missing 1 required positional argument: 'ip_end_point'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_split_host_port(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic("ip_end_point \"test-host\" missing port", || { - let ctx = Context::new(); - let args = &ValueRef::list(Some(&[&ValueRef::str("test-host")])); - kclvm_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); - }); - assert_panic("ip_end_point \"test-host:7:80\" too many colons", || { - let ctx = Context::new(); - let args = &ValueRef::list(Some(&[&ValueRef::str("test-host:7:80")])); - kclvm_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); - }); - assert_panic("ip_end_point \"[2001:db8::]\" missing port", || { - let ctx = Context::new(); - let args = &ValueRef::list(Some(&[&ValueRef::str("[2001:db8::]")])); - kclvm_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); - }); - assert_panic("ip_end_point \"[2001:db8::]80\" missing port", || { - let ctx = Context::new(); - let args = &ValueRef::list(Some(&[&ValueRef::str("[2001:db8::]80")])); - kclvm_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); - }); - assert_panic("ip_end_point \"[2001:db8::]9:80\" missing port", || { - let ctx = Context::new(); - let args = &ValueRef::list(Some(&[&ValueRef::str("[2001:db8::]9:80")])); - kclvm_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); - }); - assert_panic("ip_end_point \"[2001:db8::]:9:80\" too many colons", || { - let ctx = Context::new(); - let args = &ValueRef::list(Some(&[&ValueRef::str("[2001:db8::]:9:80")])); - kclvm_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); - }); - assert_panic("ip_end_point \"[2001:db8:::80\" missing ']'", || { - let ctx = Context::new(); - let args = &ValueRef::list(Some(&[&ValueRef::str("[2001:db8:::80")])); - kclvm_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); - }); - assert_panic("ip_end_point \"t[est-host:80\" unexpected '['", || { - let ctx = Context::new(); - let args = &ValueRef::list(Some(&[&ValueRef::str("t[est-host:80")])); - kclvm_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); - }); - assert_panic("ip_end_point \"]test-host:80\" unexpected ']'", || { - let ctx = Context::new(); - let args = &ValueRef::list(Some(&[&ValueRef::str("]test-host:80")])); - kclvm_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); - }); - assert_panic("ip_end_point \"[[2001:db8::]:80\" unexpected '['", || { - let ctx = Context::new(); - let args = &ValueRef::list(Some(&[&ValueRef::str("[[2001:db8::]:80")])); - kclvm_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); - }); - assert_panic("ip_end_point \"[2001:db8::]:]80\" unexpected ']'", || { - let ctx = Context::new(); - let args = &ValueRef::list(Some(&[&ValueRef::str("[2001:db8::]:]80")])); - kclvm_net_split_host_port(ctx.into_raw(), args, &ValueRef::dict(None)); - }); - std::panic::set_hook(prev_hook); - } - - #[test] - fn test_join_host_port() { - let cases = [ - ( - ValueRef::str("invalid.invalid"), - ValueRef::int(21), - ValueRef::str("invalid.invalid:21"), - ), - ( - ValueRef::str("invalid.invalid"), - ValueRef::str("21"), - ValueRef::str("invalid.invalid:21"), - ), - ( - ValueRef::str("192.0.2.1"), - ValueRef::int(14), - ValueRef::str("192.0.2.1:14"), - ), - ( - ValueRef::str("192.0.2.1"), - ValueRef::str("14"), - ValueRef::str("192.0.2.1:14"), - ), - ( - ValueRef::str("2001:db8::"), - ValueRef::int(14), - ValueRef::str("[2001:db8::]:14"), - ), - ( - ValueRef::str("2001:db8::"), - ValueRef::str("14"), - ValueRef::str("[2001:db8::]:14"), - ), - ]; - let mut ctx = Context::default(); - for (host, port, expected) in cases.iter() { - unsafe { - let actual = &*kclvm_net_join_host_port( - &mut ctx, - &ValueRef::list(Some(&[&host, &port])), - &ValueRef::dict(None), - ); - assert_eq!(expected, actual); - } - unsafe { - let actual = &*kclvm_net_join_host_port( - &mut ctx, - &ValueRef::list(None), - &ValueRef::dict(Some(&[("host", host), ("port", port)])), - ); - assert_eq!(expected, actual); - } - } - } - - #[test] - fn test_join_host_port_invalid() { - let prev_hook = std::panic::take_hook(); - // Disable print panic info in stderr. - std::panic::set_hook(Box::new(|_| {})); - assert_panic( - "join_host_port() missing 2 required positional arguments: 'host' and 'port'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_join_host_port(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "join_host_port() missing 2 required positional arguments: 'host' and 'port'", - || { - let mut ctx = Context::new(); - let args = - ValueRef::list(Some(&[&ValueRef::str("invalid.invalid")])).into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_join_host_port(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "join_host_port() missing 2 required positional arguments: 'host' and 'port'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(Some(&[("host", &ValueRef::str("invalid.invalid"))])) - .into_raw(&mut ctx); - kclvm_net_join_host_port(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "join_host_port() missing 2 required positional arguments: 'host' and 'port'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = - ValueRef::dict(Some(&[("port", &ValueRef::str("80"))])).into_raw(&mut ctx); - kclvm_net_join_host_port(ctx.into_raw(), args, kwargs); - }, - ); - std::panic::set_hook(prev_hook); - } - - #[test] - #[allow(non_snake_case)] - fn test_parse_CIDR() { - let cases = [ - ( - ValueRef::str("0.0.0.0/0"), - ValueRef::dict(Some(&[ - ("ip", &ValueRef::str("0.0.0.0")), - ("mask", &ValueRef::int(0)), - ])), - ), - ( - ValueRef::str("::/0"), - ValueRef::dict(Some(&[ - ("ip", &ValueRef::str("::")), - ("mask", &ValueRef::int(0)), - ])), - ), - ( - ValueRef::str("10.0.0.0/8"), - ValueRef::dict(Some(&[ - ("ip", &ValueRef::str("10.0.0.0")), - ("mask", &ValueRef::int(8)), - ])), - ), - ( - ValueRef::str("2001:db8::/56"), - ValueRef::dict(Some(&[ - ("ip", &ValueRef::str("2001:db8::")), - ("mask", &ValueRef::int(56)), - ])), - ), - ( - ValueRef::str("10.1.2.3/32"), - ValueRef::dict(Some(&[ - ("ip", &ValueRef::str("10.1.2.3")), - ("mask", &ValueRef::int(32)), - ])), - ), - ( - ValueRef::str("2001:db8:1:2:3:4:5:7/128"), - ValueRef::dict(Some(&[ - ("ip", &ValueRef::str("2001:db8:1:2:3:4:5:7")), - ("mask", &ValueRef::int(128)), - ])), - ), - ( - ValueRef::str("10.1.2.3"), - ValueRef::dict(Some(&[ - ("ip", &ValueRef::str("10.1.2.3")), - ("mask", &ValueRef::int(32)), - ])), - ), - ( - ValueRef::str("2001:db8:1:2:3:4:5:7"), - ValueRef::dict(Some(&[ - ("ip", &ValueRef::str("2001:db8:1:2:3:4:5:7")), - ("mask", &ValueRef::int(128)), - ])), - ), - (ValueRef::str("10.0.0/8"), ValueRef::dict(None)), - (ValueRef::str("10.0.0.0/33"), ValueRef::dict(None)), - ( - ValueRef::str("2001:db8:1:2:3:4:5:7/129"), - ValueRef::dict(None), - ), - (ValueRef::str("0.0.0.0/256"), ValueRef::dict(None)), - (ValueRef::str("::/256"), ValueRef::dict(None)), - (ValueRef::str("10.0.0.0/8/8"), ValueRef::dict(None)), - (ValueRef::str("2001:db8::/56/56"), ValueRef::dict(None)), - (ValueRef::str("0.0.0.0/-1"), ValueRef::dict(None)), - (ValueRef::str("::/-1"), ValueRef::dict(None)), - (ValueRef::str("10.128.0.0/8"), ValueRef::dict(None)), - (ValueRef::str("2001:db8::/16"), ValueRef::dict(None)), - (ValueRef::str("10.1.2.3/31"), ValueRef::dict(None)), - ( - ValueRef::str("2001:db8:1:2:3:4:5:7/127"), - ValueRef::dict(None), - ), - ]; - let mut ctx = Context::default(); - for (cidr, expected) in cases.iter() { - unsafe { - let actual = &*kclvm_net_parse_CIDR( - &mut ctx, - &ValueRef::list(Some(&[&cidr])), - &ValueRef::dict(None), - ); - assert_eq!(expected, actual, "{} positional", cidr); - } - unsafe { - let actual = &*kclvm_net_parse_CIDR( - &mut ctx, - &ValueRef::list(None), - &ValueRef::dict(Some(&[("cidr", cidr)])), - ); - assert_eq!(expected, actual, "{} named", cidr); - } - } - } - - #[test] - #[allow(non_snake_case)] - fn test_parse_CIDR_invalid() { - let prev_hook = std::panic::take_hook(); - // Disable print panic info in stderr. - std::panic::set_hook(Box::new(|_| {})); - assert_panic( - "parse_CIDR() missing 1 required positional argument: 'cidr'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_parse_CIDR(ctx.into_raw(), args, kwargs); - }, - ); - std::panic::set_hook(prev_hook); - } - - #[test] - #[allow(non_snake_case)] - fn test_is_IP_in_CIDR() { - let cases = [ - ( - "0.0.0.0/0", - vec!["0.0.0.0", "255.255.255.255"], - vec!["::", "2001:db8::"], - ), - ( - "::/0", - vec![ - "::", - "2001:db8::", - "10.1.2.3", - "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", - ], - vec![], - ), - ( - "10.0.0.0/8", - vec!["10.0.0.0", "10.1.2.3", "10.255.255.255"], - vec!["9.255.255.255", "11.0.0.0", "a000::"], - ), - ( - "2001:db8::/56", - vec!["2001:db8::", "2001:db8:0000:ff:ffff:ffff:ffff:ffff"], - vec![ - "2001:db7:ffff:ffff:ffff:ffff:ffff:ffff", - "2001:db8:0:100::", - "10.1.2.3", - ], - ), - ( - "10.1.2.3/32", - vec!["10.1.2.3"], - vec!["10.1.2.2", "10.1.2.4", "0a01:0203::"], - ), - ( - "2001:db8:1:2:3:4:5:7/128", - vec!["2001:db8:1:2:3:4:5:7"], - vec!["2001:db8:1:2:3:4:5:6", "2001:db8:1:2:3:4:5:8", "10.1.2.3"], - ), - ( - "10.1.2.3", - vec!["10.1.2.3"], - vec!["10.1.2.2", "10.1.2.4", "0a01:0203::"], - ), - ( - "2001:db8:1:2:3:4:5:7", - vec!["2001:db8:1:2:3:4:5:7"], - vec!["2001:db8:1:2:3:4:5:6", "2001:db8:1:2:3:4:5:8", "10.1.2.3"], - ), - ]; - let mut ctx = Context::default(); - for (cidr, expect_in, expect_not_in) in cases.iter() { - for ip in expect_in.iter() { - unsafe { - let actual = &*kclvm_net_is_IP_in_CIDR( - &mut ctx, - &ValueRef::list(Some(&[&ValueRef::str(ip), &ValueRef::str(cidr)])), - &ValueRef::dict(None), - ); - assert_eq!( - &ValueRef::bool(true), - actual, - "{} in {} positional", - ip, - cidr - ); - } - unsafe { - let actual = &*kclvm_net_is_IP_in_CIDR( - &mut ctx, - &ValueRef::list(None), - &ValueRef::dict(Some(&[ - ("cidr", &ValueRef::str(cidr)), - ("ip", &ValueRef::str(ip)), - ])), - ); - assert_eq!(&ValueRef::bool(true), actual, "{} in {} named", ip, cidr); - } - } - for ip in expect_not_in.iter() { - unsafe { - let actual = &*kclvm_net_is_IP_in_CIDR( - &mut ctx, - &ValueRef::list(Some(&[&ValueRef::str(ip), &ValueRef::str(cidr)])), - &ValueRef::dict(None), - ); - assert_eq!( - &ValueRef::bool(false), - actual, - "{} not in {} positional", - ip, - cidr - ); - } - unsafe { - let actual = &*kclvm_net_is_IP_in_CIDR( - &mut ctx, - &ValueRef::list(None), - &ValueRef::dict(Some(&[ - ("cidr", &ValueRef::str(cidr)), - ("ip", &ValueRef::str(ip)), - ])), - ); - assert_eq!( - &ValueRef::bool(false), - actual, - "{} not in {} named", - ip, - cidr - ); - } - } - } - } - - #[test] - #[allow(non_snake_case)] - fn test_is_IP_in_CIDR_invalid() { - let prev_hook = std::panic::take_hook(); - // Disable print panic info in stderr. - std::panic::set_hook(Box::new(|_| {})); - assert_panic( - "is_IP_in_CIDR() missing 2 required positional arguments: 'ip' and 'cidr'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_is_IP_in_CIDR(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "is_IP_in_CIDR() missing 2 required positional arguments: 'ip' and 'cidr'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(Some(&[&ValueRef::str("10.1.2.3")])).into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_is_IP_in_CIDR(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "is_IP_in_CIDR() missing 2 required positional arguments: 'ip' and 'cidr'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = - ValueRef::dict(Some(&[("ip", &ValueRef::str("10.1.2.3"))])).into_raw(&mut ctx); - kclvm_net_is_IP_in_CIDR(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "is_IP_in_CIDR() missing 2 required positional arguments: 'ip' and 'cidr'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(Some(&[("cidr", &ValueRef::str("10.0.0.0/8"))])) - .into_raw(&mut ctx); - kclvm_net_is_IP_in_CIDR(ctx.into_raw(), args, kwargs); - }, - ); - let cases = [ - ("10.0.0/8", "10.0.0.1", "is_IP_in_CIDR() invalid cidr: couldn't parse address in network: invalid IP address syntax"), - ("10.0.0.0/33", "10.0.0.1", "is_IP_in_CIDR() invalid cidr: invalid length for network: Network length 33 is too long for Ipv4 (maximum: 32)"), - ("2001:db8:1:2:3:4:5:7/129", "2001:db8::", "is_IP_in_CIDR() invalid cidr: invalid length for network: Network length 129 is too long for Ipv6 (maximum: 128)"), - ("0.0.0.0/256", "10.0.0.1", "is_IP_in_CIDR() invalid cidr: couldn't parse length in network: number too large to fit in target type"), - ("::/256", "2001:db8::", "is_IP_in_CIDR() invalid cidr: couldn't parse length in network: number too large to fit in target type"), - ("10.0.0.0/8/8", "10.0.0.1", "is_IP_in_CIDR() invalid cidr: couldn't parse address in network: invalid IP address syntax"), - ("2001:db8::/56/56", "2001:db8::", "is_IP_in_CIDR() invalid cidr: couldn't parse address in network: invalid IP address syntax"), - ("0.0.0.0/-1", "10.0.0.1", "is_IP_in_CIDR() invalid cidr: couldn't parse length in network: invalid digit found in string"), - ("::/-1", "2001:db8::", "is_IP_in_CIDR() invalid cidr: couldn't parse length in network: invalid digit found in string"), - ("10.128.0.0/8", "10.0.0.1", "is_IP_in_CIDR() invalid cidr: host part of address was not zero"), - ("2001:db8::/16", "2001:db8::", "is_IP_in_CIDR() invalid cidr: host part of address was not zero"), - ("10.1.2.3/31", "10.0.0.1", "is_IP_in_CIDR() invalid cidr: host part of address was not zero"), - ("2001:db8:1:2:3:4:5:7/127", "2001:db8::", "is_IP_in_CIDR() invalid cidr: host part of address was not zero"), - ("10.0.0.0/8", "10.0.0", "is_IP_in_CIDR() invalid ip: invalid IP address syntax"), - ("2001:db8::/56", "2001:db8:::", "is_IP_in_CIDR() invalid ip: invalid IP address syntax"), - ]; - for (cidr, ip, expect_error) in cases.iter() { - assert_panic(expect_error, || { - let mut ctx = Context::new(); - let args = ValueRef::list(Some(&[&ValueRef::str(ip), &ValueRef::str(cidr)])) - .into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_is_IP_in_CIDR(ctx.into_raw(), args, kwargs); - }); - } - std::panic::set_hook(prev_hook); - } - - #[test] - #[allow(non_snake_case)] - fn test_CIDR_subnet() { - let cases = [ - ("0.0.0.0/0", 0i64, 0i64, "0.0.0.0/0"), - ("0.0.0.0/0", 1, 1, "128.0.0.0/1"), - ("0.0.0.0/0", 8, 10, "10.0.0.0/8"), - ("0.0.0.0/0", 9, 11, "5.128.0.0/9"), - ("0.0.0.0/0", 32, 4294967295, "255.255.255.255/32"), - ("10.0.0.0/8", 9, 11, "10.5.128.0/17"), - ("10.0.0.0/8", 24, 16777215, "10.255.255.255/32"), - ("255.1.2.254/31", 1, 1, "255.1.2.255/32"), - ("255.255.255.254/31", 1, 1, "255.255.255.255/32"), - ("255.255.255.255/32", 0, 0, "255.255.255.255/32"), - ("::/0", 0, 0, "::/0"), - ("::/0", 1, 1, "8000::/1"), - ("::/0", 16, 10, "a::/16"), - ("::/0", 17, 11, "5:8000::/17"), - ("::/0", 63, 9223372036854775807, "ffff:ffff:ffff:fffe::/63"), - ("::/0", 64, 9223372036854775807, "7fff:ffff:ffff:ffff::/64"), - ( - "ffff:ffff:ffff:ffff:8000::/65", - 63, - 9223372036854775807, - "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128", - ), - ("2001:db8::/56", 8, 5, "2001:db8:0:5::/64"), - ( - "2001:db8:1:2:3:4:5:fffe/127", - 1, - 1, - "2001:db8:1:2:3:4:5:ffff/128", - ), - ("2001:db8:1:2:3:4:5:7/128", 0, 0, "2001:db8:1:2:3:4:5:7/128"), - ]; - let mut ctx = Context::default(); - for (cidr, additional_bits, net_num, expected) in cases.iter() { - unsafe { - let actual = &*kclvm_net_CIDR_subnet( - &mut ctx, - &ValueRef::list(Some(&[ - &ValueRef::str(cidr), - &ValueRef::int(*additional_bits), - &ValueRef::int(*net_num), - ])), - &ValueRef::dict(None), - ); - assert_eq!( - &ValueRef::str(expected), - actual, - "{} {} {} positional", - cidr, - additional_bits, - net_num - ); - } - unsafe { - let actual = &*kclvm_net_CIDR_subnet( - &mut ctx, - &ValueRef::list(None), - &ValueRef::dict(Some(&[ - ("cidr", &ValueRef::str(cidr)), - ("additional_bits", &ValueRef::int(*additional_bits)), - ("net_num", &ValueRef::int(*net_num)), - ])), - ); - assert_eq!( - &ValueRef::str(expected), - actual, - "{} {} {} named", - cidr, - additional_bits, - net_num - ); - } - } - } - - #[test] - #[allow(non_snake_case)] - fn test_CIDR_subnet_invalid() { - let prev_hook = std::panic::take_hook(); - // Disable print panic info in stderr. - std::panic::set_hook(Box::new(|_| {})); - assert_panic( - "CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_CIDR_subnet(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(Some(&[&ValueRef::str("10.1.2.3"), &ValueRef::int(1)])).into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_CIDR_subnet(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = - ValueRef::dict(Some(&[("cidr", &ValueRef::str("10.1.2.3")),("additional_bits", &ValueRef::int(1))])).into_raw(&mut ctx); - kclvm_net_CIDR_subnet(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = - ValueRef::dict(Some(&[("cidr", &ValueRef::str("10.1.2.3")),("net_num", &ValueRef::int(1))])).into_raw(&mut ctx); - kclvm_net_CIDR_subnet(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "CIDR_subnet() missing 3 required positional arguments: 'cidr', 'additional_bits', and 'net_num'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = - ValueRef::dict(Some(&[("additional_bits", &ValueRef::int(1)),("net_num", &ValueRef::int(1))])).into_raw(&mut ctx); - kclvm_net_CIDR_subnet(ctx.into_raw(), args, kwargs); - }, - ); - let cases = [ - ("10.0.0/8", 1i64, 0i64, "CIDR_subnet() invalid cidr: couldn't parse address in network: invalid IP address syntax"), - ("10.0.0.0/33", 1, 0, "CIDR_subnet() invalid cidr: invalid length for network: Network length 33 is too long for Ipv4 (maximum: 32)"), - ("2001:db8:1:2:3:4:5:7/129", 1, 0, "CIDR_subnet() invalid cidr: invalid length for network: Network length 129 is too long for Ipv6 (maximum: 128)"), - ("0.0.0.0/256", 1, 0, "CIDR_subnet() invalid cidr: couldn't parse length in network: number too large to fit in target type"), - ("::/256", 1, 0, "CIDR_subnet() invalid cidr: couldn't parse length in network: number too large to fit in target type"), - ("10.0.0.0/8/8", 1, 0, "CIDR_subnet() invalid cidr: couldn't parse address in network: invalid IP address syntax"), - ("2001:db8::/56/56", 1, 0, "CIDR_subnet() invalid cidr: couldn't parse address in network: invalid IP address syntax"), - ("0.0.0.0/-1", 1, 0, "CIDR_subnet() invalid cidr: couldn't parse length in network: invalid digit found in string"), - ("::/-1", 1, 0, "CIDR_subnet() invalid cidr: couldn't parse length in network: invalid digit found in string"), - ("10.128.0.0/8", 1, 0, "CIDR_subnet() invalid cidr: host part of address was not zero"), - ("2001:db8::/16", 1, 0, "CIDR_subnet() invalid cidr: host part of address was not zero"), - ("10.1.2.3/31", 1, 0, "CIDR_subnet() invalid cidr: host part of address was not zero"), - ("2001:db8:1:2:3:4:5:7/127", 1, 0, "CIDR_subnet() invalid cidr: host part of address was not zero"), - ("10.0.0.0/8", -1, 0, "CIDR_subnet() invalid additional_bits: cannot be negative"), - ("2001:db8::/64", 1, -1, "CIDR_subnet() invalid net_num: cannot be negative"), - ("10.0.0.0/8", 25, 0, "CIDR_subnet() invalid additional_bits: would extend network length to 33 bits, which is too long for IPv4"), - ("2001:db8::/65", 64, 0, "CIDR_subnet() invalid additional_bits: would extend network length to 129 bits, which is too long for IPv6"), - ("10.0.0.0/8", 8, 256, "CIDR_subnet() additional_bits of 8 does not accommodate a net_num of 256"), - ("2001:db8::/64", 8, 256, "CIDR_subnet() additional_bits of 8 does not accommodate a net_num of 256"), - ]; - for (cidr, additional_bits, net_num, expect_error) in cases.iter() { - assert_panic(expect_error, || { - let mut ctx = Context::new(); - let args = ValueRef::list(Some(&[ - &ValueRef::str(cidr), - &ValueRef::int(*additional_bits), - &ValueRef::int(*net_num), - ])) - .into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_CIDR_subnet(ctx.into_raw(), args, kwargs); - }); - } - std::panic::set_hook(prev_hook); - } - - #[test] - #[allow(non_snake_case)] - fn test_CIDR_subnets() { - let cases = [ - ("0.0.0.0/0", vec![0i64], vec!["0.0.0.0/0"]), - ("0.0.0.0/0", vec![], vec![]), - ("0.0.0.0/0", vec![1, 1], vec!["0.0.0.0/1", "128.0.0.0/1"]), - ( - "0.0.0.0/0", - vec![8, 9, 9, 32, 32], - vec![ - "0.0.0.0/8", - "1.0.0.0/9", - "1.128.0.0/9", - "2.0.0.0/32", - "2.0.0.1/32", - ], - ), - ( - "0.0.0.0/0", - vec![8, 32, 32, 9], - vec!["0.0.0.0/8", "1.0.0.0/32", "1.0.0.1/32", "1.128.0.0/9"], - ), - ( - "10.0.0.0/8", - vec![8, 9, 9, 9, 8], - vec![ - "10.0.0.0/16", - "10.1.0.0/17", - "10.1.128.0/17", - "10.2.0.0/17", - "10.3.0.0/16", - ], - ), - ( - "10.0.0.0/8", - vec![8, 10, 8, 9, 10, 10], - vec![ - "10.0.0.0/16", - "10.1.0.0/18", - "10.2.0.0/16", - "10.1.128.0/17", - "10.1.64.0/18", - "10.3.0.0/18", - ], - ), - ( - "255.1.2.254/31", - vec![1, 1], - vec!["255.1.2.254/32", "255.1.2.255/32"], - ), - ("255.255.255.255/32", vec![0], vec!["255.255.255.255/32"]), - ("::/0", vec![0], vec!["::/0"]), - ("::/0", vec![], vec![]), - ("::/0", vec![1, 1], vec!["::/1", "8000::/1"]), - ( - "::/0", - vec![8, 9, 9, 63, 63], - vec!["::/8", "100::/9", "180::/9", "200::/63", "200:0:0:2::/63"], - ), - ( - "::/0", - vec![8, 63, 63, 9], - vec!["::/8", "100::/63", "100:0:0:2::/63", "180::/9"], - ), - ( - "2001:db8::/65", - vec![8, 63, 63, 63, 8], - vec![ - "2001:db8::/73", - "2001:db8:0:0:80::/128", - "2001:db8::80:0:0:1/128", - "2001:db8::80:0:0:2/128", - "2001:db8:0:0:100::/73", - ], - ), - ( - "2001:db8::/65", - vec![8, 10, 8, 9, 10, 10], - vec![ - "2001:db8::/73", - "2001:db8:0:0:80::/75", - "2001:db8:0:0:100::/73", - "2001:db8:0:0:c0::/74", - "2001:db8:0:0:a0::/75", - "2001:db8:0:0:180::/75", - ], - ), - ]; - let mut ctx = Context::default(); - for (cidr, additional_bits, expected) in cases.iter() { - let additional_bits_valueref = additional_bits - .iter() - .map(|x| ValueRef::int(*x)) - .collect::>(); - let expected_valueref = expected - .iter() - .map(|x| ValueRef::str(*x)) - .collect::>(); - unsafe { - let actual = &*kclvm_net_CIDR_subnets( - &mut ctx, - &ValueRef::list(Some(&[ - &ValueRef::str(cidr), - &ValueRef::list(Some(&additional_bits_valueref.iter().collect::>())), - ])), - &ValueRef::dict(None), - ); - assert_eq!( - &ValueRef::list(Some(&expected_valueref.iter().collect::>())), - actual, - "{} {:?} positional", - cidr, - additional_bits, - ); - } - unsafe { - let actual = &*kclvm_net_CIDR_subnets( - &mut ctx, - &ValueRef::list(None), - &ValueRef::dict(Some(&[ - ("cidr", &ValueRef::str(cidr)), - ( - "additional_bits", - &ValueRef::list(Some( - &additional_bits_valueref.iter().collect::>(), - )), - ), - ])), - ); - assert_eq!( - &ValueRef::list(Some(&expected_valueref.iter().collect::>())), - actual, - "{} {:?} named", - cidr, - additional_bits, - ); - } - } - } - - #[test] - #[allow(non_snake_case)] - fn test_CIDR_subnets_invalid() { - let prev_hook = std::panic::take_hook(); - // Disable print panic info in stderr. - std::panic::set_hook(Box::new(|_| {})); - assert_panic( - "CIDR_subnets() missing 2 required positional arguments: 'cidr' and 'additional_bits'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_CIDR_subnets(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "CIDR_subnets() missing 2 required positional arguments: 'cidr' and 'additional_bits'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(Some(&[&ValueRef::str("10.1.2.3")])).into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_CIDR_subnets(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "CIDR_subnets() missing 2 required positional arguments: 'cidr' and 'additional_bits'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(Some(&[("cidr", &ValueRef::str("10.1.2.3"))])) - .into_raw(&mut ctx); - kclvm_net_CIDR_subnets(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "CIDR_subnets() missing 2 required positional arguments: 'cidr' and 'additional_bits'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(Some(&[("additional_bits", &ValueRef::int(1))])) - .into_raw(&mut ctx); - kclvm_net_CIDR_subnets(ctx.into_raw(), args, kwargs); - }, - ); - let cases = [ - ("10.0.0/8", vec![1i64], "CIDR_subnets() invalid cidr: couldn't parse address in network: invalid IP address syntax"), - ("10.0.0.0/33", vec![1], "CIDR_subnets() invalid cidr: invalid length for network: Network length 33 is too long for Ipv4 (maximum: 32)"), - ("2001:db8:1:2:3:4:5:7/129", vec![1], "CIDR_subnets() invalid cidr: invalid length for network: Network length 129 is too long for Ipv6 (maximum: 128)"), - ("0.0.0.0/256", vec![1], "CIDR_subnets() invalid cidr: couldn't parse length in network: number too large to fit in target type"), - ("::/256", vec![1], "CIDR_subnets() invalid cidr: couldn't parse length in network: number too large to fit in target type"), - ("10.0.0.0/8/8", vec![1], "CIDR_subnets() invalid cidr: couldn't parse address in network: invalid IP address syntax"), - ("2001:db8::/56/56", vec![1], "CIDR_subnets() invalid cidr: couldn't parse address in network: invalid IP address syntax"), - ("0.0.0.0/-1", vec![1], "CIDR_subnets() invalid cidr: couldn't parse length in network: invalid digit found in string"), - ("::/-1", vec![1], "CIDR_subnets() invalid cidr: couldn't parse length in network: invalid digit found in string"), - ("10.128.0.0/8", vec![1], "CIDR_subnets() invalid cidr: host part of address was not zero"), - ("2001:db8::/16", vec![1], "CIDR_subnets() invalid cidr: host part of address was not zero"), - ("10.1.2.3/31", vec![1], "CIDR_subnets() invalid cidr: host part of address was not zero"), - ("2001:db8:1:2:3:4:5:7/127", vec![1], "CIDR_subnets() invalid cidr: host part of address was not zero"), - ("10.0.0.0/8", vec![3, 2, -1], "CIDR_subnets() invalid additional_bits: cannot be negative"), - ("10.0.0.0/8", vec![3, 2, 25], "CIDR_subnets() invalid additional_bits: would extend network length to 33 bits, which is too long for IPv4"), - ("2001:db8::/32", vec![3, 2, 64], "CIDR_subnets() invalid additional_bits: cannot extend more than 63 bits"), - ("2001:db8::/66", vec![3, 2, 63], "CIDR_subnets() invalid additional_bits: would extend network length to 129 bits, which is too long for IPv6"), - ("10.0.0.0/8", vec![1, 1, 1], "CIDR_subnets() not enough remaining address space for a subnet with a prefix of 9 bits after 10.128.0.0/9"), - ("2001:db8::/126", vec![1, 1, 1], "CIDR_subnets() not enough remaining address space for a subnet with a prefix of 127 bits after 2001:db8::2/127"), - ]; - for (cidr, additional_bits, expect_error) in cases.iter() { - assert_panic(expect_error, || { - let additional_bits_valueref = additional_bits - .iter() - .map(|x| ValueRef::int(*x)) - .collect::>(); - let mut ctx = Context::new(); - let args = ValueRef::list(Some(&[ - &ValueRef::str(cidr), - &ValueRef::list(Some(&additional_bits_valueref.iter().collect::>())), - ])) - .into_raw(&mut ctx); - - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_CIDR_subnets(ctx.into_raw(), args, kwargs); - }); - } - std::panic::set_hook(prev_hook); - } - - #[test] - #[allow(non_snake_case)] - fn test_CIDR_host() { - let cases = [ - ("0.0.0.0/0", 0i64, "0.0.0.0"), - ("0.0.0.0/0", 1, "0.0.0.1"), - ("0.0.0.0/0", -1, "255.255.255.255"), - ("0.0.0.0/0", 256, "0.0.1.0"), - ("0.0.0.0/0", -256, "255.255.255.0"), - ("0.0.0.0/0", 4294967295, "255.255.255.255"), - ("0.0.0.0/0", -4294967296, "0.0.0.0"), - ("10.0.0.0/8", 11, "10.0.0.11"), - ("10.0.0.0/8", 16777215, "10.255.255.255"), - ("10.0.0.0/8", -1, "10.255.255.255"), - ("255.1.2.254/31", 1, "255.1.2.255"), - ("255.255.255.254/31", 1, "255.255.255.255"), - ("255.255.255.255/32", 0, "255.255.255.255"), - ("255.255.255.255/32", -1, "255.255.255.255"), - ("::/0", 0, "::"), - ("::/0", 1, "::1"), - ("::/0", 16, "::10"), - ("::/0", -1, "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"), - ("::/0", 9223372036854775807, "::7fff:ffff:ffff:ffff"), - ("::/0", -9223372036854775808, "ffff:ffff:ffff:ffff:8000::"), - ( - "2001:db8:0:2:8000::/65", - 9223372036854775807, - "2001:db8:0:2:ffff:ffff:ffff:ffff", - ), - ( - "2001:db8:0:2:8000::/65", - -9223372036854775808, - "2001:db8:0:2:8000::", - ), - ( - "ffff:ffff:ffff:ffff:8000::/65", - 9223372036854775807, - "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", - ), - ("2001:db8::/56", 5, "2001:db8::5"), - ("2001:db8:1:2:3:4:5:fffe/127", 1, "2001:db8:1:2:3:4:5:ffff"), - ("2001:db8:1:2:3:4:5:fffe/127", -1, "2001:db8:1:2:3:4:5:ffff"), - ("2001:db8:1:2:3:4:5:7/128", 0, "2001:db8:1:2:3:4:5:7"), - ("2001:db8:1:2:3:4:5:7/128", -1, "2001:db8:1:2:3:4:5:7"), - ]; - let mut ctx = Context::default(); - for (cidr, host_num, expected) in cases.iter() { - unsafe { - let actual = &*kclvm_net_CIDR_host( - &mut ctx, - &ValueRef::list(Some(&[&ValueRef::str(cidr), &ValueRef::int(*host_num)])), - &ValueRef::dict(None), - ); - assert_eq!( - &ValueRef::str(expected), - actual, - "{} {} positional", - cidr, - host_num - ); - } - unsafe { - let actual = &*kclvm_net_CIDR_host( - &mut ctx, - &ValueRef::list(None), - &ValueRef::dict(Some(&[ - ("cidr", &ValueRef::str(cidr)), - ("host_num", &ValueRef::int(*host_num)), - ])), - ); - assert_eq!( - &ValueRef::str(expected), - actual, - "{} {} named", - cidr, - host_num - ); - } - } - } - - #[test] - #[allow(non_snake_case)] - fn test_CIDR_host_invalid() { - let prev_hook = std::panic::take_hook(); - // Disable print panic info in stderr. - std::panic::set_hook(Box::new(|_| {})); - assert_panic( - "CIDR_host() missing 2 required positional arguments: 'cidr' and 'host_num'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_CIDR_host(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "CIDR_host() missing 2 required positional arguments: 'cidr' and 'host_num'", - || { - let mut ctx = Context::new(); - let args = - ValueRef::list(Some(&[&ValueRef::str("10.1.2.3/32")])).into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_CIDR_host(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "CIDR_host() missing 2 required positional arguments: 'cidr' and 'host_num'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = ValueRef::dict(Some(&[("cidr", &ValueRef::str("10.1.2.3/32"))])) - .into_raw(&mut ctx); - kclvm_net_CIDR_host(ctx.into_raw(), args, kwargs); - }, - ); - assert_panic( - "CIDR_host() missing 2 required positional arguments: 'cidr' and 'host_num'", - || { - let mut ctx = Context::new(); - let args = ValueRef::list(None).into_raw(&mut ctx); - let kwargs = - ValueRef::dict(Some(&[("host_num", &ValueRef::int(1))])).into_raw(&mut ctx); - kclvm_net_CIDR_host(ctx.into_raw(), args, kwargs); - }, - ); - let cases = [ - ("10.0.0/8", 0i64, "CIDR_host() invalid cidr: couldn't parse address in network: invalid IP address syntax"), - ("10.0.0.0/33", 0, "CIDR_host() invalid cidr: invalid length for network: Network length 33 is too long for Ipv4 (maximum: 32)"), - ("2001:db8:1:2:3:4:5:7/129", 0, "CIDR_host() invalid cidr: invalid length for network: Network length 129 is too long for Ipv6 (maximum: 128)"), - ("0.0.0.0/256", 0, "CIDR_host() invalid cidr: couldn't parse length in network: number too large to fit in target type"), - ("::/256", 0, "CIDR_host() invalid cidr: couldn't parse length in network: number too large to fit in target type"), - ("10.0.0.0/8/8", 0, "CIDR_host() invalid cidr: couldn't parse address in network: invalid IP address syntax"), - ("2001:db8::/56/56", 0, "CIDR_host() invalid cidr: couldn't parse address in network: invalid IP address syntax"), - ("0.0.0.0/-1", 0, "CIDR_host() invalid cidr: couldn't parse length in network: invalid digit found in string"), - ("::/-1", 0, "CIDR_host() invalid cidr: couldn't parse length in network: invalid digit found in string"), - ("10.128.0.0/8", 0, "CIDR_host() invalid cidr: host part of address was not zero"), - ("2001:db8::/16", 0, "CIDR_host() invalid cidr: host part of address was not zero"), - ("10.1.2.3/31", 0, "CIDR_host() invalid cidr: host part of address was not zero"), - ("2001:db8:1:2:3:4:5:7/127", 0, "CIDR_host() invalid cidr: host part of address was not zero"), - ("10.0.0.0/24", 256, "CIDR_host() prefix of 24 does not accommodate a host numbered 256"), - ("10.0.0.0/24", -257, "CIDR_host() prefix of 24 does not accommodate a host numbered -257"), - ("10.0.0.0/32", 1, "CIDR_host() prefix of 32 does not accommodate a host numbered 1"), - ("10.0.0.0/32", -2, "CIDR_host() prefix of 32 does not accommodate a host numbered -2"), - ("0.0.0.0/0", 4294967296, "CIDR_host() prefix of 0 does not accommodate a host numbered 4294967296"), - ("0.0.0.0/0", -4294967297, "CIDR_host() prefix of 0 does not accommodate a host numbered -4294967297"), - ("2001:db8::/120", 256, "CIDR_host() prefix of 120 does not accommodate a host numbered 256"), - ("2001:db8::/120", -257, "CIDR_host() prefix of 120 does not accommodate a host numbered -257"), - ("2001:db8::/66", 9223372036854775807, "CIDR_host() prefix of 66 does not accommodate a host numbered 9223372036854775807"), - ("2001:db8::/66", -9223372036854775808, "CIDR_host() prefix of 66 does not accommodate a host numbered -9223372036854775808"), - ]; - for (cidr, host_num, expect_error) in cases.iter() { - assert_panic(expect_error, || { - let mut ctx = Context::new(); - let args = ValueRef::list(Some(&[&ValueRef::str(cidr), &ValueRef::int(*host_num)])) - .into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_CIDR_host(ctx.into_raw(), args, kwargs); - }); - } - std::panic::set_hook(prev_hook); - } - - #[test] - #[allow(non_snake_case)] - fn test_CIDR_netmask() { - let cases = [ - ("0.0.0.0/0", "0.0.0.0"), - ("0.0.0.0/1", "128.0.0.0"), - ("0.0.0.0/24", "255.255.255.0"), - ("0.0.0.0/31", "255.255.255.254"), - ("0.0.0.0/32", "255.255.255.255"), - ("10.0.0.0/8", "255.0.0.0"), - ]; - let mut ctx = Context::default(); - for (cidr, expected) in cases.iter() { - unsafe { - let actual = &*kclvm_net_CIDR_netmask( - &mut ctx, - &ValueRef::list(Some(&[&ValueRef::str(cidr)])), - &ValueRef::dict(None), - ); - assert_eq!(&ValueRef::str(expected), actual, "{} positional", cidr,); - } - unsafe { - let actual = &*kclvm_net_CIDR_netmask( - &mut ctx, - &ValueRef::list(None), - &ValueRef::dict(Some(&[("cidr", &ValueRef::str(cidr))])), - ); - assert_eq!(&ValueRef::str(expected), actual, "{} named", cidr,); - } - } - } - - #[test] - #[allow(non_snake_case)] - fn test_CIDR_netmask_invalid() { - let prev_hook = std::panic::take_hook(); - // Disable print panic info in stderr. - std::panic::set_hook(Box::new(|_| {})); - let cases = [ - ("10.0.0/8", "CIDR_netmask() invalid cidr: couldn't parse address in network: invalid IP address syntax"), - ("10.0.0.0/33", "CIDR_netmask() invalid cidr: invalid length for network: Network length 33 is too long for Ipv4 (maximum: 32)"), - ("0.0.0.0/256", "CIDR_netmask() invalid cidr: couldn't parse length in network: number too large to fit in target type"), - ("10.0.0.0/8/8", "CIDR_netmask() invalid cidr: couldn't parse address in network: invalid IP address syntax"), - ("0.0.0.0/-1", "CIDR_netmask() invalid cidr: couldn't parse length in network: invalid digit found in string"), - ("10.128.0.0/8", "CIDR_netmask() invalid cidr: host part of address was not zero"), - ("10.1.2.3/31", "CIDR_netmask() invalid cidr: host part of address was not zero"), - ("2001:db8::/64", "CIDR_netmask() IPv6 addresses cannot have a netmask"), - ]; - for (cidr, expect_error) in cases.iter() { - assert_panic(expect_error, || { - let mut ctx = Context::new(); - let args = ValueRef::list(Some(&[&ValueRef::str(cidr)])).into_raw(&mut ctx); - let kwargs = ValueRef::dict(None).into_raw(&mut ctx); - kclvm_net_CIDR_netmask(ctx.into_raw(), args, kwargs); - }); - } - std::panic::set_hook(prev_hook); - } - - #[test] - #[allow(non_snake_case)] - fn test_is_interface_local_multicast_IP() { - let cases = [("ff11::1", true), ("224.0.0.0", false)]; - let mut ctx = Context::default(); - for (ip, expect) in cases.iter() { - unsafe { - let actual = &*kclvm_net_is_interface_local_multicast_IP( - &mut ctx, - &ValueRef::dict(None), - &ValueRef::dict(Some(&[("ip", &ValueRef::str(ip))])), - ); - assert_eq!(*expect, actual.as_bool(), "ip: {} ", ip); - } - } - } - - #[test] - #[allow(non_snake_case)] - fn test_is_link_local_multicast_IP() { - let cases = [("ff12::1", true)]; - let mut ctx = Context::default(); - for (ip, expect) in cases.iter() { - unsafe { - let actual = &*kclvm_net_is_link_local_multicast_IP( - &mut ctx, - &ValueRef::dict(None), - &ValueRef::dict(Some(&[("ip", &ValueRef::str(ip))])), - ); - assert_eq!(*expect, actual.as_bool(), "ip: {} ", ip); - } - } - } - - #[test] - #[allow(non_snake_case)] - fn test_is_global_unicast_IP() { - let cases = [ - ("2607:f8b0:4005:802::200e", true), - ("64:ff9b::800:1", true), - ("220.181.108.89", true), - ]; - let mut ctx = Context::default(); - for (ip, expect) in cases.iter() { - unsafe { - let actual = &*kclvm_net_is_global_unicast_IP( - &mut ctx, - &ValueRef::dict(None), - &ValueRef::dict(Some(&[("ip", &ValueRef::str(ip))])), - ); - assert_eq!(*expect, actual.as_bool(), "ip: {} ", ip); - } - } - } - - #[test] - #[allow(non_snake_case)] - fn test_is_multicast_IP() { - let cases = [("239.255.255.255", true)]; - let mut ctx = Context::default(); - for (ip, expect) in cases.iter() { - unsafe { - let actual = &*kclvm_net_is_multicast_IP( - &mut ctx, - &ValueRef::dict(None), - &ValueRef::dict(Some(&[("ip", &ValueRef::str(ip))])), - ); - assert_eq!(*expect, actual.as_bool(), "ip: {} ", ip); - } - } - } - - #[test] - #[allow(non_snake_case)] - fn test_is_loopback_IP() { - let cases = [("127.0.0.1", true)]; - let mut ctx = Context::default(); - for (ip, expect) in cases.iter() { - unsafe { - let actual = &*kclvm_net_is_loopback_IP( - &mut ctx, - &ValueRef::dict(None), - &ValueRef::dict(Some(&[("ip", &ValueRef::str(ip))])), - ); - assert_eq!(*expect, actual.as_bool(), "ip: {} ", ip); - } - } - } - - #[test] - #[allow(non_snake_case)] - fn test_is_link_local_unicast_IP() { - let cases = [("fe80::2012:1", true)]; - let mut ctx = Context::default(); - for (ip, expect) in cases.iter() { - unsafe { - let actual = &*kclvm_net_is_link_local_unicast_IP( - &mut ctx, - &ValueRef::dict(None), - &ValueRef::dict(Some(&[("ip", &ValueRef::str(ip))])), - ); - assert_eq!(*expect, actual.as_bool(), "ip: {} ", ip); - } - } - } - - #[test] - #[allow(non_snake_case)] - fn test_is_unspecified_IP() { - let cases = [("0.0.0.0", true)]; - let mut ctx = Context::default(); - for (ip, expect) in cases.iter() { - unsafe { - let actual = &*kclvm_net_is_unspecified_IP( - &mut ctx, - &ValueRef::dict(None), - &ValueRef::dict(Some(&[("ip", &ValueRef::str(ip))])), - ); - assert_eq!(*expect, actual.as_bool(), "ip: {}", ip); - } - } - } -} diff --git a/kclvm/runtime/src/panic/mod.rs b/kclvm/runtime/src/panic/mod.rs deleted file mode 100644 index bd853afbe..000000000 --- a/kclvm/runtime/src/panic/mod.rs +++ /dev/null @@ -1,123 +0,0 @@ -use std::{any::Any, mem::transmute_copy, os::raw::c_char}; - -use std::cell::UnsafeCell; -use std::panic::catch_unwind; -use std::panic::AssertUnwindSafe; -use std::panic::RefUnwindSafe; -use std::panic::UnwindSafe; - -use crate::*; - -/// Executes the provided function and catches any potential runtime errors. -/// Returns undefined if execution is successful, otherwise returns an error -/// message in case of a runtime panic. -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_runtime_catch( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(func) = get_call_arg(args, kwargs, 0, Some("func")) { - let func = func.as_function(); - if ctx.cfg.debug_mode { - ctx.backtrace - .push(BacktraceFrame::from_panic_info(&ctx.panic_info)); - ctx.panic_info.kcl_func = func.name.clone(); - } - let now_meta_info = ctx.panic_info.clone(); - let fn_ptr = func.fn_ptr; - let wrapper = UnsafeWrapper::new(|| { - let args = ValueRef::list(None).into_raw(ctx); - let kwargs = ValueRef::dict(None).into_raw(ctx); - unsafe { - let call_fn: SchemaTypeFunc = transmute_copy(&fn_ptr); - // Call schema constructor twice - if func.is_external { - let name = format!("{}\0", func.name); - kclvm_plugin_invoke(ctx, name.as_ptr() as *const c_char, args, kwargs) - } else { - call_fn(ctx, args, kwargs) - }; - }; - }); - let result = catch_unwind(AssertUnwindSafe(|| unsafe { - (wrapper.get())(); - })); - if ctx.cfg.debug_mode { - ctx.backtrace.pop(); - } - ctx.panic_info = now_meta_info; - return match result { - Ok(_) => ValueRef::undefined(), - Err(err) => ValueRef::str(&err_to_str(err)), - } - .into_raw(ctx); - } - panic!("catch() takes exactly one argument (0 given)"); -} - -#[inline] -pub fn is_runtime_catch_function(ptr: u64) -> bool { - ptr == kclvm_runtime_catch as *const () as u64 -} - -/// Convert an error to string. -pub fn err_to_str(err: Box) -> String { - if let Some(s) = err.downcast_ref::<&str>() { - s.to_string() - } else if let Some(s) = err.downcast_ref::<&String>() { - (*s).clone() - } else if let Some(s) = err.downcast_ref::() { - (*s).clone() - } else { - "".to_string() - } -} - -/// A wrapper struct that holds a value of type T inside an UnsafeCell. -/// UnsafeCell is the core primitive for interior mutability in Rust. -pub struct UnsafeWrapper { - value: UnsafeCell, -} - -impl UnsafeWrapper { - /// Creates a new instance of UnsafeWrapper with the provided value. - /// - /// # Arguments - /// - /// * `value` - The value to be wrapped inside an UnsafeCell. - /// - /// # Returns - /// - /// A new instance of UnsafeWrapper containing the provided value. - pub fn new(value: T) -> Self { - UnsafeWrapper { - value: UnsafeCell::new(value), - } - } - - /// Provides a mutable reference to the inner value. - /// - /// # Safety - /// - /// This is an unsafe function because obtaining multiple mutable references - /// can lead to undefined behavior. The caller must ensure that the returned - /// reference does not violate Rust's borrowing rules. - /// - /// # Returns - /// - /// A mutable reference to the inner value of type T. - pub unsafe fn get(&self) -> &mut T { - &mut *self.value.get() - } -} - -// Implementing the UnwindSafe and RefUnwindSafe traits for UnsafeWrapper -// to ensure it can be safely used across panic boundaries. -impl UnwindSafe for UnsafeWrapper {} -impl RefUnwindSafe for UnsafeWrapper {} diff --git a/kclvm/runtime/src/regex/mod.rs b/kclvm/runtime/src/regex/mod.rs deleted file mode 100644 index b5dda9a9c..000000000 --- a/kclvm/runtime/src/regex/mod.rs +++ /dev/null @@ -1,197 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -extern crate fancy_regex; - -use crate::*; - -// match(string: str, pattern: str) -> bool: - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_regex_match( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(string) = get_call_arg_str(args, kwargs, 0, Some("string")) { - if let Some(pattern) = get_call_arg_str(args, kwargs, 1, Some("pattern")) { - let re = fancy_regex::Regex::new(pattern.as_ref()).unwrap(); - match re.is_match(string.as_ref()) { - Ok(ok) => { - if ok { - return kclvm_value_Bool(ctx, 1); - } else { - return kclvm_value_Bool(ctx, 0); - } - } - _ => return kclvm_value_Bool(ctx, 0), - } - } - } - - panic!("match() missing 2 required positional arguments: 'string' and 'pattern'") -} - -// replace(string: str, pattern: str, replace: str, count: int = 0): - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_regex_replace( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - if let Some(string) = get_call_arg_str(args, kwargs, 0, Some("string")) { - if let Some(pattern) = get_call_arg_str(args, kwargs, 1, Some("pattern")) { - if let Some(replace) = get_call_arg_str(args, kwargs, 2, Some("replace")) { - let count = get_call_arg_int(args, kwargs, 3, Some("count")).unwrap_or_else(|| 0); - let re = fancy_regex::Regex::new(pattern.as_ref()).unwrap(); - let s = re.replacen(string.as_ref(), count as usize, replace.as_ref() as &str); - return ValueRef::str(&s).into_raw(ctx); - } - panic!("replace() missing the required positional argument: 'replace'"); - } - panic!("replace() missing the required positional argument: 'pattern'"); - } - panic!("replace() missing 3 required positional arguments: 'string', 'pattern', and 'replace"); -} - -// compile(pattern: str) -> bool: - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_regex_compile( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(pattern) = get_call_arg_str(args, kwargs, 0, Some("pattern")) { - match fancy_regex::Regex::new(pattern.as_ref()) { - Ok(_) => return kclvm_value_Bool(ctx, 1), - _ => return kclvm_value_Bool(ctx, 0), - } - } - panic!("compile() missing the required positional argument: 'pattern'") -} - -// findall(string: str, pattern: str) -> [str]: - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_regex_findall( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - if let Some(string) = get_call_arg_str(args, kwargs, 0, Some("string")) { - if let Some(pattern) = get_call_arg_str(args, kwargs, 1, Some("pattern")) { - let mut list = ValueRef::list(None); - - for x in fancy_regex::Regex::new(pattern.as_ref()) - .unwrap() - .captures_iter(string.as_ref()) - .flatten() - { - let len = x.len(); - if len < 3 { - list.list_append(&ValueRef::str(x.get(0).unwrap().as_str())); - } else { - let mut sub_list = ValueRef::list(None); - for i in 1..len { - sub_list.list_append(&ValueRef::str(x.get(i).unwrap().as_str())); - } - list.list_append(&sub_list) - } - } - - return list.into_raw(ctx); - } - panic!("findall() missing the required positional argument: 'pattern'") - } - panic!("findall() missing 2 required positional arguments: 'string' and 'pattern'") -} - -// search(string: str, pattern: str): - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_regex_search( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(string) = get_call_arg_str(args, kwargs, 0, Some("string")) { - if let Some(pattern) = get_call_arg_str(args, kwargs, 1, Some("pattern")) { - let re = fancy_regex::Regex::new(pattern.as_ref()).unwrap(); - - if let Ok(Some(..)) = re.find(string.as_ref()) { - return kclvm_value_Bool(ctx, 1); - } - return kclvm_value_Bool(ctx, 0); - } - panic!("search() missing the required positional argument: 'pattern'"); - } - panic!("search() missing 2 required positional arguments: 'string' and 'pattern'"); -} - -// split(string: str, pattern: str, maxsplit: int = 0): - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_regex_split( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - if let Some(string) = get_call_arg_str(args, kwargs, 0, Some("string")) { - if let Some(pattern) = get_call_arg_str(args, kwargs, 1, Some("pattern")) { - let maxsplit = get_call_arg_int(args, kwargs, 2, Some("maxsplit")).unwrap_or_else(|| 0); - let mut list = ValueRef::list(None); - - let re = fancy_regex::Regex::new(pattern.as_ref()).unwrap(); - - let mut fields: Vec = Vec::new(); - let mut current_pos = 0; - loop { - let capture = re - .captures_from_pos(string.as_ref(), current_pos) - .map_or(None, |c| c); - if let Some(Some(cap)) = capture.map(|c| c.get(0)) { - fields.push(string[current_pos..cap.start()].to_string()); - if maxsplit > 0 && fields.len() >= (maxsplit as usize) { - break; - } - current_pos = cap.end(); - } else { - fields.push(string[current_pos..].to_string()); - break; - } - } - - for s in fields { - list.list_append(&ValueRef::str(s.as_ref())); - } - return list.into_raw(ctx); - } - panic!("split() missing the required positional argument: 'pattern'"); - } - panic!("split() missing 2 required positional arguments: 'string' and 'pattern'"); -} diff --git a/kclvm/runtime/src/stdlib/assert_api.rs b/kclvm/runtime/src/stdlib/assert_api.rs deleted file mode 100644 index 2aa14548a..000000000 --- a/kclvm/runtime/src/stdlib/assert_api.rs +++ /dev/null @@ -1,25 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -use crate::*; - -#[allow(non_camel_case_types)] -type kclvm_value_ref_t = ValueRef; - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_assert( - ctx: *mut kclvm_context_t, - value: *const kclvm_value_ref_t, - msg: *const kclvm_value_ref_t, -) { - let value = ptr_as_ref(value); - let msg = ptr_as_ref(msg); - - if !value.is_truthy() { - let ctx = mut_ptr_as_ref(ctx); - ctx.set_err_type(&RuntimeErrorType::AssertionError); - - let msg = msg.as_str(); - panic!("{}", msg); - } -} diff --git a/kclvm/runtime/src/stdlib/builtin_api.rs b/kclvm/runtime/src/stdlib/builtin_api.rs deleted file mode 100644 index eb3107985..000000000 --- a/kclvm/runtime/src/stdlib/builtin_api.rs +++ /dev/null @@ -1,691 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. -#![allow(clippy::missing_safety_doc)] - -use std::os::raw::c_char; - -use crate::*; - -#[allow(non_camel_case_types)] -type kclvm_value_ref_t = ValueRef; - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_option_init( - ctx: *mut kclvm_context_t, - key: *const c_char, - value: *const c_char, -) { - let ctx = mut_ptr_as_ref(ctx); - ctx.builtin_option_init(c2str(key), c2str(value)); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_option_reset( - ctx: *mut kclvm_context_t, - _args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let ctx_ref = mut_ptr_as_ref(ctx); - - ctx_ref.builtin_option_reset(); - kclvm_value_Undefined(ctx) -} - -// def kcl_option(name: str, *, type="", required=False, default=None, help="", file="", line=0) -> typing.Any: - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_option( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - fn _value_to_type(this: &ValueRef, typ: String) -> ValueRef { - if typ.is_empty() { - return this.clone(); - } - if typ == "bool" { - match *this.rc.borrow() { - Value::bool_value(ref v) => { - return ValueRef::bool(*v); - } - Value::int_value(ref v) => { - return ValueRef::bool(*v != 0); - } - Value::float_value(ref v) => { - return ValueRef::bool(*v != 0.0); - } - Value::str_value(ref v) => { - return ValueRef::bool(v == "True" || v == "true"); - } - _ => { - return ValueRef::undefined(); - } - } - } - if typ == "int" { - match *this.rc.borrow() { - Value::bool_value(ref v) => { - if *v { - return ValueRef::int(1); - } else { - return ValueRef::int(0); - } - } - Value::int_value(ref v) => { - return ValueRef::int(*v); - } - Value::float_value(ref v) => { - return ValueRef::int(*v as i64); - } - Value::str_value(ref v) => { - match v.parse::() { - Ok(n) => return ValueRef::int(n), - _ => panic!("cannot use '{v}' as type '{typ}'"), - }; - } - _ => { - let err_msg = format!("cannot use '{this}' as type '{typ}'"); - panic!("{}", err_msg); - } - } - } - if typ == "float" { - match *this.rc.borrow() { - Value::bool_value(ref v) => { - if *v { - return ValueRef::float(1.0); - } else { - return ValueRef::float(0.0); - } - } - Value::int_value(ref v) => { - return ValueRef::float(*v as f64); - } - Value::float_value(ref v) => { - return ValueRef::float(*v); - } - Value::str_value(ref v) => { - match v.parse::() { - Ok(n) => return ValueRef::float(n), - _ => return ValueRef::float(0.0), - }; - } - _ => { - let err_msg = format!("cannot use '{this}' as type '{typ}'"); - panic!("{}", err_msg); - } - } - } - if typ == "str" { - match *this.rc.borrow() { - Value::bool_value(ref v) => { - let s = format!("{}", *v); - return ValueRef::str(s.as_ref()); - } - Value::int_value(ref v) => { - let s = format!("{}", *v); - return ValueRef::str(s.as_ref()); - } - Value::float_value(ref v) => { - let s = format!("{}", *v); - return ValueRef::str(s.as_ref()); - } - Value::str_value(ref v) => { - return ValueRef::str(v.as_ref()); - } - _ => { - let err_msg = format!("cannot use '{this}' as type '{typ}'"); - panic!("{}", err_msg); - } - } - } - if typ == "list" { - match *this.rc.borrow() { - Value::list_value(_) => { - return this.clone(); - } - _ => { - let err_msg = format!("cannot use '{this}' as type '{typ}'"); - panic!("{}", err_msg); - } - } - } - if typ == "dict" { - match *this.rc.borrow() { - Value::dict_value(_) => { - return this.clone(); - } - _ => { - let err_msg = format!("cannot use '{this}' as type '{typ}'"); - panic!("{}", err_msg); - } - } - } - - panic!("unknown type '{typ}'"); - } - - if let Some(arg0) = get_call_arg_str(args, kwargs, 0, Some("key")) { - if let Some(x) = ctx.option_values.get(&arg0) { - if let Some(kwarg_type) = get_call_arg_str(args, kwargs, 1, Some("type")) { - return _value_to_type(x, kwarg_type).into_raw(ctx); - } - return x.clone().into_raw(ctx); - } else if let Some(kwarg_default) = get_call_arg(args, kwargs, 3, Some("default")) { - if let Some(kwarg_type) = get_call_arg_str(args, kwargs, 1, Some("type")) { - return _value_to_type(&kwarg_default, kwarg_type).into_raw(ctx); - } - return kwarg_default.into_raw(ctx); - } - } - let required = get_call_arg_bool(args, kwargs, 2, Some("required")).unwrap_or_default(); - if required { - let name = - get_call_arg_str(args, kwargs, 0, Some("key")).unwrap_or_else(|| "?".to_string()); - panic!("option('{name}') must be initialized, try '-D {name}=?' argument"); - } - ValueRef::none().into_raw(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_print( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx_ref = mut_ptr_as_ref(ctx); - // args - let list = args.as_list_ref(); - let values: Vec = list.values.iter().map(|v| v.to_string()).collect(); - ctx_ref.log_message.push_str(&values.join(" ")); - let dict = kwargs.as_dict_ref(); - // kwargs: end - if let Some(c) = dict.values.get("end") { - ctx_ref.log_message.push_str(&format!("{c}")); - } else { - ctx_ref.log_message.push('\n'); - } - kclvm_value_None(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_len( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg) = get_call_arg(args, kwargs, 0, Some("inval")) { - return kclvm_value_Int(ctx, arg.len() as i64); - } - panic!("len() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_any_true( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("inval")) { - return kclvm_value_Bool(ctx, arg0.any_true() as i8); - } - kclvm_value_Bool(ctx, 0) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_isunique( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("inval")) { - return kclvm_value_Bool(ctx, arg0.isunique() as i8); - } - kclvm_value_Bool(ctx, 0) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_sorted( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("inval")) { - let reverse = get_call_arg(args, kwargs, 1, Some("reverse")); - return arg0.sorted(reverse.as_ref()).into_raw(ctx); - } - panic!("sorted() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_int( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("number")) { - let base = get_call_arg(args, kwargs, 1, Some("base")); - return arg0.convert_to_int(ctx, base.as_ref()).into_raw(ctx); - } - panic!("int() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_float( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("number")) { - return arg0.convert_to_float(ctx).into_raw(ctx); - } - panic!("float() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_bool( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("x")) { - return ValueRef::bool(arg0.is_truthy()).into_raw(ctx); - } - panic!("bool() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("x")) { - return ValueRef::str(&arg0.to_string()).into_raw(ctx); - } - ValueRef::str("").into_raw(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_max( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - if args.args_len() > 1 { - return args.max_value().into_raw(ctx); - } - if let Some(arg0) = args.arg_0() { - return arg0.max_value().into_raw(ctx); - } - panic!("max() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_min( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - if args.args_len() > 1 { - return args.min_value().into_raw(ctx); - } - if let Some(arg0) = args.arg_0() { - return arg0.min_value().into_raw(ctx); - } - panic!("min() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_multiplyof( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let (Some(arg0), Some(arg1)) = ( - get_call_arg(args, kwargs, 0, Some("a")), - get_call_arg(args, kwargs, 1, Some("b")), - ) { - return builtin::multiplyof(&arg0, &arg1).into_raw(ctx); - } - panic!( - "multiplyof() takes exactly two argument ({} given)", - args.args_len() - ); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_abs( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("inval")) { - return arg0.abs().into_raw(ctx); - } - panic!("abs() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_all_true( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("inval")) { - return kclvm_value_Bool(ctx, arg0.all_true() as i8); - } - kclvm_value_Bool(ctx, 0) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_hex( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("number")) { - return arg0.hex().into_raw(ctx); - } - panic!("hex() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_sum( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx_ref = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - match get_call_arg(args, kwargs, 0, Some("iterable")) { - Some(arg0) => match get_call_arg(args, kwargs, 1, Some("start")) { - Some(arg1) => arg0.sum(ctx_ref, &arg1).into_raw(ctx_ref), - _ => arg0.sum(ctx_ref, &ValueRef::int(0)).into_raw(ctx_ref), - }, - _ => kclvm_value_Undefined(ctx), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_pow( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx_ref = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - match ( - get_call_arg(args, kwargs, 0, Some("x")), - get_call_arg(args, kwargs, 1, Some("y")), - ) { - (Some(arg0), Some(arg1)) => match get_call_arg(args, kwargs, 2, Some("z")) { - Some(arg2) => builtin::pow(&arg0, &arg1, &arg2).into_raw(ctx_ref), - _ => builtin::pow(&arg0, &arg1, &ValueRef::none()).into_raw(ctx_ref), - }, - _ => kclvm_value_Undefined(ctx), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_round( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx_ref = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - match get_call_arg(args, kwargs, 0, Some("number")) { - Some(arg0) => match get_call_arg(args, kwargs, 1, Some("ndigits")) { - Some(arg1) => builtin::round(&arg0, &arg1).into_raw(ctx_ref), - _ => builtin::round(&arg0, &ValueRef::none()).into_raw(ctx_ref), - }, - _ => kclvm_value_Undefined(ctx), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_zip( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - args.zip().into_raw(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_list( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if args.args_len() > 0 { - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("x")) { - return builtin::list(Some(&arg0)).into_raw(ctx); - } - panic!("invalid arguments in list() function"); - } else { - builtin::list(None).into_raw(ctx) - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_dict( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let mut dict = ValueRef::dict(None); - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("x")) { - let v = builtin::dict(ctx, Some(&arg0)); - dict.dict_insert_unpack(ctx, &v); - } - let v = builtin::dict(ctx, Some(kwargs)); - dict.dict_insert_unpack(ctx, &v); - dict.into_raw(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_typeof( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("x")) { - if let Some(full_name) = get_call_arg(args, kwargs, 1, Some("full_name")) { - return builtin::type_of(&arg0, &full_name).into_raw(ctx); - } - return builtin::type_of(&arg0, &ValueRef::bool(false)).into_raw(ctx); - } - - panic!("typeof() missing 1 required positional argument: 'x'"); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_bin( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("number")) { - return arg0.bin().into_raw(ctx); - } - panic!("bin() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_oct( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("number")) { - return arg0.oct().into_raw(ctx); - } - panic!("oct() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_ord( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("c")) { - return arg0.ord().into_raw(ctx); - } - panic!("ord() takes exactly one argument (0 given)"); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_range( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let ctx_ref = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - match get_call_arg(args, kwargs, 0, Some("start")) { - Some(arg0) => match get_call_arg(args, kwargs, 1, Some("stop")) { - Some(arg1) => match get_call_arg(args, kwargs, 2, Some("step")) { - Some(arg2) => builtin::range(&arg0, &arg1, &arg2).into_raw(ctx_ref), - _ => builtin::range(&arg0, &arg1, &ValueRef::int(1)).into_raw(ctx_ref), - }, - _ => builtin::range(&ValueRef::int(0), &arg0, &ValueRef::int(1)).into_raw(ctx_ref), - }, - _ => kclvm_value_Undefined(ctx), - } -} - -/// Return `True` if the input value is `None` or `Undefined`, and `False` otherwise. -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_isnullish( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("inval")) { - return ValueRef::bool(arg0.is_none_or_undefined()).into_raw(ctx); - } - panic!("is_nullable() takes exactly one argument (0 given)"); -} diff --git a/kclvm/runtime/src/stdlib/plugin.rs b/kclvm/runtime/src/stdlib/plugin.rs deleted file mode 100644 index 0d6bbc800..000000000 --- a/kclvm/runtime/src/stdlib/plugin.rs +++ /dev/null @@ -1,125 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -#![allow(clippy::missing_safety_doc)] - -use crate::*; - -use lazy_static::lazy_static; -use std::os::raw::c_char; -use std::sync::Mutex; - -lazy_static! { - static ref PLUGIN_HANDLER_FN_PTR: Mutex< - Option< - extern "C-unwind" fn( - method: *const c_char, - args_json: *const c_char, - kwargs_json: *const c_char, - ) -> *const c_char, - >, - > = Mutex::new(None); -} - -/// KCL plugin module prefix -pub const PLUGIN_MODULE_PREFIX: &str = "kcl_plugin."; - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_plugin_init( - fn_ptr: extern "C-unwind" fn( - method: *const c_char, - args_json: *const c_char, - kwargs_json: *const c_char, - ) -> *const c_char, -) { - let mut fn_ptr_guard = PLUGIN_HANDLER_FN_PTR.lock().unwrap(); - *fn_ptr_guard = Some(fn_ptr); -} - -// import kcl_plugin.hello -// hello.say_hello() -// -// => return kclvm_plugin_invoke("kcl_plugin.hello.say_hello", args, kwargs) - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_plugin_invoke( - ctx: *mut kclvm_context_t, - method: *const c_char, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx_ref = mut_ptr_as_ref(ctx); - let method_ref = c2str(method); - let plugin_short_method = match method_ref.strip_prefix(PLUGIN_MODULE_PREFIX) { - Some(s) => s, - None => method_ref, - }; - if let Some(func) = ctx_ref.plugin_functions.get(plugin_short_method) { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let result = func(ctx_ref, args, kwargs); - return result.unwrap().into_raw(ctx_ref); - } - let args_s = kclvm_value_to_json_value_with_null(ctx, args); - let kwargs_s = kclvm_value_to_json_value_with_null(ctx, kwargs); - - let args_json = kclvm_value_Str_ptr(args_s); - let kwargs_json = kclvm_value_Str_ptr(kwargs_s); - - let result_json = kclvm_plugin_invoke_json(method, args_json, kwargs_json); - - // Value delete by context. - // kclvm_value_delete(args_s); - // kclvm_value_delete(kwargs_s); - - let ptr = kclvm_value_from_json(ctx, result_json); - { - if let Some(msg) = ptr_as_ref(ptr).dict_get_value("__kcl_PanicInfo__") { - let ctx = mut_ptr_as_ref(ctx); - ctx.set_err_type(&RuntimeErrorType::EvaluationError); - - panic!("{}", msg.as_str()); - } - } - - ptr -} - -#[cfg(not(target_arch = "wasm32"))] -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_plugin_invoke_json( - method: *const c_char, - args: *const c_char, - kwargs: *const c_char, -) -> *const c_char { - let fn_ptr_guard = PLUGIN_HANDLER_FN_PTR.lock().unwrap(); - if let Some(fn_ptr) = *fn_ptr_guard { - fn_ptr(method, args, kwargs) - } else { - panic!("plugin handler is nil, should call kclvm_plugin_init at first"); - } -} - -#[cfg(target_arch = "wasm32")] -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_plugin_invoke_json( - method: *const c_char, - args: *const c_char, - kwargs: *const c_char, -) -> *const c_char { - unsafe { - return kclvm_plugin_invoke_json_wasm(method, args, kwargs); - } -} - -#[cfg(target_arch = "wasm32")] -extern "C-unwind" { - pub fn kclvm_plugin_invoke_json_wasm( - method: *const c_char, - args: *const c_char, - kwargs: *const c_char, - ) -> *const c_char; -} diff --git a/kclvm/runtime/src/template/mod.rs b/kclvm/runtime/src/template/mod.rs deleted file mode 100644 index dd0d34706..000000000 --- a/kclvm/runtime/src/template/mod.rs +++ /dev/null @@ -1,55 +0,0 @@ -use std::collections::HashMap; - -use crate::*; -use handlebars::{html_escape, Handlebars}; - -/// Applies a parsed template to the specified data object and -/// returns the string output. -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_template_execute( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(template) = get_call_arg_str(args, kwargs, 0, Some("template")) { - let mut handlebars = Handlebars::new(); - handlebars - .register_template_string("template", template) - .expect("register template failed"); - let data = get_call_arg(args, kwargs, 1, Some("data")).unwrap_or(ValueRef::dict(None)); - let data: HashMap = HashMap::from_iter( - data.as_dict_ref() - .values - .iter() - .map(|(k, v)| (k.to_string(), v.build_json(&Default::default()))), - ); - let result = handlebars - .render("template", &data) - .expect("render template failed"); - return ValueRef::str(&result).into_raw(ctx); - } - panic!("execute() takes exactly one argument (0 given)"); -} - -/// Replaces the characters `&"<>` with the equivalent html / xml entities. -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_template_html_escape( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(data) = get_call_arg_str(args, kwargs, 0, Some("data")) { - return ValueRef::str(&html_escape(&data)).into_raw(ctx); - } - panic!("html_escape() takes exactly one argument (0 given)"); -} diff --git a/kclvm/runtime/src/types/str.rs b/kclvm/runtime/src/types/str.rs deleted file mode 100644 index cbfd7f0b6..000000000 --- a/kclvm/runtime/src/types/str.rs +++ /dev/null @@ -1,34 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -use crate::*; - -impl Type { - pub fn type_str(&self) -> String { - match self { - Type::Any => KCL_TYPE_ANY.to_string(), - Type::Bool => BUILTIN_TYPE_BOOL.to_string(), - Type::BoolLit(ref v) => format!("{BUILTIN_TYPE_BOOL}({v})"), - Type::Int => BUILTIN_TYPE_INT.to_string(), - Type::IntLit(ref v) => format!("{BUILTIN_TYPE_INT}({v})"), - Type::Float => BUILTIN_TYPE_FLOAT.to_string(), - Type::FloatLit(ref v) => format!("{BUILTIN_TYPE_FLOAT}({v})"), - Type::Str => BUILTIN_TYPE_STR.to_string(), - Type::StrLit(ref v) => format!("{BUILTIN_TYPE_STR}({v})"), - Type::List(ref v) => format!("[{}]", v.elem_type.type_str()), - Type::Dict(ref v) => { - format!("{{{}:{}}}", v.key_type.type_str(), v.elem_type.type_str()) - } - Type::Union(ref v) => match v.elem_types.len() { - 0 => String::new(), - 1 => v.elem_types[0].type_str(), - _ => { - let mut types = Vec::new(); - let _ = v.elem_types.iter().map(|e| types.push(e.type_str())); - types.join(" | ") - } - }, - Type::Schema(ref v) => v.name.to_string(), - Type::Func(ref _v) => "func".to_string(), - } - } -} diff --git a/kclvm/runtime/src/units/mod.rs b/kclvm/runtime/src/units/mod.rs deleted file mode 100644 index 742d4ace2..000000000 --- a/kclvm/runtime/src/units/mod.rs +++ /dev/null @@ -1,443 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -use crate::*; - -#[derive(Debug)] -#[allow(non_camel_case_types, dead_code)] -enum to_unit_suffix { - n, - u, - m, - k, - K, - M, - G, - T, - P, - Ki, - Mi, - Gi, - Ti, - Pi, -} - -use phf::{phf_map, Map}; - -pub const IEC_SUFFIX: &str = "i"; -pub const EXPONENTS: Map<&str, i8> = phf_map! { - "n" => -3, - "u" => -2, - "m" => -1, - "k" => 1, - "K" => 1, - "M" => 2, - "G" => 3, - "T" => 4, - "P" => 5, -}; -pub const INVALID_UNITS: [&str; 4] = ["ni", "ui", "mi", "ki"]; - -// to_n(num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_units_to_n( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(num) = get_call_arg(args, kwargs, 0, Some("num")) { - let num = num.convert_to_float(ctx).as_float(); - let s = to_unit(num, to_unit_suffix::n); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - panic!("to_n() missing 1 required positional argument: 'num'"); -} - -// to_u(num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_units_to_u( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(num) = get_call_arg(args, kwargs, 0, Some("num")) { - let num = num.convert_to_float(ctx).as_float(); - let s = to_unit(num, to_unit_suffix::u); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - panic!("to_u() missing 1 required positional argument: 'num'"); -} - -// to_m(num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_units_to_m( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(num) = get_call_arg(args, kwargs, 0, Some("num")) { - let num = num.convert_to_float(ctx).as_float(); - let s = to_unit(num, to_unit_suffix::m); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - panic!("to_m() missing 1 required positional argument: 'num'"); -} - -// to_K(num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_units_to_K( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { - let s = to_unit(num, to_unit_suffix::K); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - panic!("to_K() missing 1 required positional argument: 'num'"); -} - -// to_M(num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_units_to_M( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { - let s = to_unit(num, to_unit_suffix::M); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - panic!("to_M() missing 1 required positional argument: 'num'"); -} - -// to_G(num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_units_to_G( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { - let s = to_unit(num, to_unit_suffix::G); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - panic!("to_G() missing 1 required positional argument: 'num'"); -} - -// to_T(num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_units_to_T( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { - let s = to_unit(num, to_unit_suffix::T); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - panic!("to_T() missing 1 required positional argument: 'num'"); -} - -// to_P(num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_units_to_P( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { - let s = to_unit(num, to_unit_suffix::P); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - panic!("to_P() missing 1 required positional argument: 'num'"); -} - -// to_Ki(num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_units_to_Ki( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { - let s = to_unit(num, to_unit_suffix::Ki); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - panic!("to_Ki() missing 1 required positional argument: 'num'"); -} - -// to_Mi(num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_units_to_Mi( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { - let s = to_unit(num, to_unit_suffix::Mi); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - panic!("to_Mi() missing 1 required positional argument: 'num'"); -} - -// to_Gi(num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_units_to_Gi( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { - let s = to_unit(num, to_unit_suffix::Gi); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - panic!("to_Gi() missing 1 required positional argument: 'num'"); -} - -// to_Ti(num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_units_to_Ti( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { - let s = to_unit(num, to_unit_suffix::Ti); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - panic!("to_Ti() missing 1 required positional argument: 'num'"); -} - -// to_Pi(num: int) -> str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_units_to_Pi( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(num) = get_call_arg_num(args, kwargs, 0, Some("num")) { - let s = to_unit(num, to_unit_suffix::Pi); - return ValueRef::str(s.as_ref()).into_raw(ctx); - } - panic!("to_Pi() missing 1 required positional argument: 'num'"); -} - -fn to_unit(num: f64, suffix: to_unit_suffix) -> String { - match suffix { - to_unit_suffix::n => format!("{}{:?}", (num / 1e-09) as i64, suffix), - to_unit_suffix::u => format!("{}{:?}", (num / 1e-06) as i64, suffix), - to_unit_suffix::m => format!("{}{:?}", (num / 0.001) as i64, suffix), - to_unit_suffix::k => format!("{}{:?}", (num / 1_000.0) as i64, suffix), - to_unit_suffix::K => format!("{}{:?}", (num / 1_000.0) as i64, suffix), - to_unit_suffix::M => format!("{}{:?}", (num / 1_000_000.0) as i64, suffix), - to_unit_suffix::G => format!("{}{:?}", (num / 1_000_000_000.0) as i64, suffix), - to_unit_suffix::T => format!("{}{:?}", (num / 1_000_000_000_000.0) as i64, suffix), - to_unit_suffix::P => format!("{}{:?}", (num / 1_000_000_000_000_000.0) as i64, suffix), - to_unit_suffix::Ki => format!("{}{:?}", (num / 1024.0) as i64, suffix), - to_unit_suffix::Mi => format!("{}{:?}", (num / (1024.0 * 1024.0)) as i64, suffix), - to_unit_suffix::Gi => format!("{}{:?}", (num / (1024.0 * 1024.0 * 1024.0)) as i64, suffix), - to_unit_suffix::Ti => format!( - "{}{:?}", - (num / (1024.0 * 1024.0 * 1024.0 * 1024.0)) as i64, - suffix - ), - to_unit_suffix::Pi => format!( - "{}{:?}", - (num / (1024.0 * 1024.0 * 1024.0 * 1024.0 * 1024.0)) as i64, - suffix - ), - } -} - -/// Parse and return number based on input quantity. -/// -/// Supported suffixes: -/// SI: n | u | m | k | K | M | G | T | P -/// IEC: Ki | Mi | Gi | Ti | Pi -/// -/// Input: -/// quantity: &str. -/// -/// Returns: -/// result: i64 -pub fn to_quantity(quantity: &str) -> i64 { - let quantity_len = quantity.len(); - let mut number = quantity; - let mut suffix: Option<&str> = None; - if quantity_len >= 2 && &quantity[quantity_len - 1..] == IEC_SUFFIX { - if EXPONENTS.contains_key(&quantity[quantity_len - 2..quantity_len - 1]) { - number = &quantity[..quantity_len - 2]; - suffix = Some(&quantity[quantity_len - 2..]); - } - } else if quantity_len >= 1 && EXPONENTS.contains_key(&quantity[quantity_len - 1..]) { - number = &quantity[..quantity_len - 1]; - suffix = Some(&quantity[quantity_len - 1..]); - } - if number.is_empty() { - panic!("number can't be empty") - } - let number: i64 = number.parse().unwrap(); - if suffix.is_none() { - return number; - } - let suffix = suffix.unwrap(); - validate_unit(&suffix[0..1]); - let base: i64 = if suffix.ends_with(IEC_SUFFIX) { - 1024 - } else { - 1000 - }; - let exponent = EXPONENTS.get(&suffix[0..1]).unwrap(); - number * (base.pow(*exponent as u32)) -} - -/// Calculate number based on value and binary suffix. -/// -/// Supported suffixes: -/// SI: n | u | m | k | K | M | G | T | P -/// IEC: Ki | Mi | Gi | Ti | Pi -/// -/// Input: -/// value: int. -/// suffix: str. -/// -/// Returns: -/// int -/// -/// Raises: -/// ValueError on invalid or unknown suffix -pub fn cal_num(value: i64, unit: &str) -> f64 { - validate_unit(unit); - let mut base: f64 = 1000.0; - let mut unit = unit; - if unit.len() > 1 && &unit[1..2] == IEC_SUFFIX { - base = 1024.0; - unit = &unit[0..1]; - } - let exponent = EXPONENTS - .get(unit) - .unwrap_or_else(|| panic!("invalid unit {unit}")); - value as f64 * base.powf(*exponent as f64) -} - -#[inline] -pub fn real_uint_value(raw: i64, unit: &str) -> i128 { - (raw as i128) * (u64_unit_value(unit) as i128) -} - -/// Validate the unit is valid -pub fn validate_unit(unit: &str) { - if unit.is_empty() || unit.len() > 2 { - panic!("Invalid suffix {unit}"); - } - if INVALID_UNITS.contains(&unit) { - panic!("Invalid suffix {unit}"); - } - if !EXPONENTS.contains_key(&unit[..1]) { - panic!("Invalid suffix {unit}"); - } -} - -pub fn f64_unit_value(unit: &str) -> f64 { - match unit { - "n" => 1e-09, - "u" => 1e-06, - "m" => 0.001, - _ => 1_f64, - } -} - -pub fn u64_unit_value(unit: &str) -> u64 { - match unit { - "k" => 1_000, - "K" => 1_000, - "M" => 1_000_000, - "G" => 1_000_000_000, - "T" => 1_000_000_000_000, - "P" => 1_000_000_000_000_000, - "Ki" => 1024, - "Mi" => 1048576, - "Gi" => 1073741824, - "Ti" => 1099511627776, - "Pi" => 1125899906842624, - _ => 1_u64, - } -} diff --git a/kclvm/runtime/src/value/api.rs b/kclvm/runtime/src/value/api.rs deleted file mode 100644 index b857a52d6..000000000 --- a/kclvm/runtime/src/value/api.rs +++ /dev/null @@ -1,3144 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. -#![allow(clippy::missing_safety_doc)] - -use std::{mem::transmute_copy, os::raw::c_char}; - -use kclvm_primitives::IndexMap; - -use crate::*; - -use self::{eval::LazyEvalScope, walker::walk_value_mut}; - -#[allow(non_camel_case_types)] -pub type kclvm_context_t = Context; - -#[allow(non_camel_case_types)] -pub type kclvm_eval_scope_t = LazyEvalScope; - -#[allow(non_camel_case_types)] -pub type kclvm_decorator_value_t = DecoratorValue; - -#[allow(non_camel_case_types)] -pub type kclvm_kind_t = Kind; - -#[allow(non_camel_case_types)] -pub type kclvm_type_t = Type; - -#[allow(non_camel_case_types)] -pub type kclvm_value_ref_t = ValueRef; - -#[allow(non_camel_case_types)] -pub type kclvm_iterator_t = ValueIterator; - -#[allow(non_camel_case_types)] -pub type kclvm_char_t = c_char; - -#[allow(non_camel_case_types)] -pub type kclvm_size_t = i32; - -#[allow(non_camel_case_types)] -type kclvm_bool_t = i8; - -#[allow(non_camel_case_types)] -pub type kclvm_int_t = i64; - -#[allow(non_camel_case_types)] -pub type kclvm_float_t = f64; - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_context_set_import_names( - p: *mut kclvm_context_t, - import_names: *const kclvm_value_ref_t, -) { - let p = mut_ptr_as_ref(p); - let import_names = ptr_as_ref(import_names); - - let import_names_dict = import_names.as_dict_ref(); - for (k, v) in &import_names_dict.values { - let mut map = IndexMap::default(); - let v_dict = v.as_dict_ref(); - for (pkgname, pkgpath) in &v_dict.values { - map.insert(pkgname.to_string(), pkgpath.as_str()); - } - p.import_names.insert(k.to_string(), map); - } -} - -// ---------------------------------------------------------------------------- -// values: new -// ---------------------------------------------------------------------------- - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_value_Undefined( - ctx: *mut kclvm_context_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - new_mut_ptr(ctx, ValueRef::undefined()) -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_value_None(ctx: *mut kclvm_context_t) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - new_mut_ptr(ctx, ValueRef::none()) -} - -// bool/int/float/str - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_value_True(ctx: *mut kclvm_context_t) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - kclvm_value_Bool(ctx, 1) -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_value_False(ctx: *mut kclvm_context_t) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - kclvm_value_Bool(ctx, 0) -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_value_Bool( - ctx: *mut kclvm_context_t, - v: kclvm_bool_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - if v != 0 { - ValueRef::bool(true).into_raw(ctx) - } else { - ValueRef::bool(false).into_raw(ctx) - } -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_value_Int( - ctx: *mut kclvm_context_t, - v: kclvm_int_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - new_mut_ptr(ctx, ValueRef::int(v)) -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_value_Float( - ctx: *mut kclvm_context_t, - v: kclvm_float_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - new_mut_ptr(ctx, ValueRef::float(v)) -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_value_Unit( - ctx: *mut kclvm_context_t, - v: kclvm_float_t, - raw: kclvm_int_t, - unit: *const kclvm_char_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let unit = c2str(unit); - new_mut_ptr(ctx, ValueRef::unit(v, raw, unit)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_Str( - ctx: *mut kclvm_context_t, - v: *const kclvm_char_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - unsafe { - if v.is_null() || *v == '\0' as c_char { - return new_mut_ptr(ctx, ValueRef::str("")); - } - } - return new_mut_ptr(ctx, ValueRef::str(c2str(v))); -} - -// list/dict/schema - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_value_List(ctx: *mut kclvm_context_t) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - new_mut_ptr(ctx, ValueRef::list(None)) -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_value_List6( - ctx: *mut kclvm_context_t, - v1: *const kclvm_value_ref_t, - v2: *const kclvm_value_ref_t, - v3: *const kclvm_value_ref_t, - v4: *const kclvm_value_ref_t, - v5: *const kclvm_value_ref_t, - v6: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let values: Vec<&ValueRef> = vec![v1, v2, v3, v4, v5, v6] - .into_iter() - .map(ptr_as_ref) - .collect(); - new_mut_ptr(ctx, ValueRef::list(Some(values.as_slice()))) -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_value_List10( - ctx: *mut kclvm_context_t, - v1: *const kclvm_value_ref_t, - v2: *const kclvm_value_ref_t, - v3: *const kclvm_value_ref_t, - v4: *const kclvm_value_ref_t, - v5: *const kclvm_value_ref_t, - v6: *const kclvm_value_ref_t, - v7: *const kclvm_value_ref_t, - v8: *const kclvm_value_ref_t, - v9: *const kclvm_value_ref_t, - v10: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let values: Vec<&ValueRef> = vec![v1, v2, v3, v4, v5, v6, v7, v8, v9, v10] - .into_iter() - .map(ptr_as_ref) - .collect(); - new_mut_ptr(ctx, ValueRef::list(Some(values.as_slice()))) -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_value_Dict(ctx: *mut kclvm_context_t) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - new_mut_ptr(ctx, ValueRef::dict(None)) -} - -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_value_Schema(ctx: *mut kclvm_context_t) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - new_mut_ptr(ctx, ValueRef::schema()) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_schema_with_config( - ctx: *mut kclvm_context_t, - schema_dict: *const kclvm_value_ref_t, - config: *const kclvm_value_ref_t, - config_meta: *const kclvm_value_ref_t, - name: *const kclvm_char_t, - pkgpath: *const kclvm_char_t, - is_sub_schema: *const kclvm_value_ref_t, - record_instance: *const kclvm_value_ref_t, - instance_pkgpath: *const kclvm_value_ref_t, - optional_mapping: *const kclvm_value_ref_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let schema_dict = ptr_as_ref(schema_dict); - // Config dict - let config = ptr_as_ref(config); - let config_meta = ptr_as_ref(config_meta); - let config_keys: Vec = config.as_dict_ref().values.keys().cloned().collect(); - // Schema meta - let name = c2str(name); - let pkgpath = c2str(pkgpath); - let runtime_type = schema_runtime_type(name, pkgpath); - let is_sub_schema = ptr_as_ref(is_sub_schema); - let record_instance = ptr_as_ref(record_instance); - let instance_pkgpath = ptr_as_ref(instance_pkgpath); - let instance_pkgpath = instance_pkgpath.as_str(); - let optional_mapping = ptr_as_ref(optional_mapping); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - if record_instance.is_truthy() { - // Record schema instance in the context - if !ctx.instances.contains_key(&runtime_type) { - ctx.instances - .insert(runtime_type.clone(), IndexMap::default()); - } - let pkg_instance_map = ctx.instances.get_mut(&runtime_type).unwrap(); - if !pkg_instance_map.contains_key(&instance_pkgpath) { - pkg_instance_map.insert(instance_pkgpath.clone(), vec![]); - } - pkg_instance_map - .get_mut(&instance_pkgpath) - .unwrap() - .push(schema_dict.clone()); - } - // Dict to schema - if is_sub_schema.is_truthy() { - let schema = schema_dict.dict_to_schema( - name, - pkgpath, - &config_keys, - config_meta, - optional_mapping, - Some(args.clone()), - Some(kwargs.clone()), - ); - schema.into_raw(ctx) - } else { - schema_dict.clone().into_raw(ctx) - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_Function( - ctx: *mut kclvm_context_t, - fn_ptr: *const u64, - closure: *const kclvm_value_ref_t, - name: *const kclvm_char_t, - is_external: kclvm_bool_t, -) -> *mut kclvm_value_ref_t { - let ctx = mut_ptr_as_ref(ctx); - let closure = ptr_as_ref(closure); - let name = c2str(name); - new_mut_ptr( - ctx, - ValueRef::func( - fn_ptr as u64, - 0, - closure.clone(), - name, - "", - is_external != 0, - ), - ) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_Function_using_ptr( - ctx: *mut kclvm_context_t, - fn_ptr: *const u64, - name: *const kclvm_char_t, -) -> *mut kclvm_value_ref_t { - let name = c2str(name); - let ctx = mut_ptr_as_ref(ctx); - new_mut_ptr( - ctx, - ValueRef::func(fn_ptr as u64, 0, ValueRef::none(), name, "", false), - ) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_schema_function( - ctx: *mut kclvm_context_t, - fn_ptr: *const u64, - check_fn_ptr: *const u64, - attr_map: *const kclvm_value_ref_t, - tpe: *const kclvm_char_t, -) -> *mut kclvm_value_ref_t { - // Schema function closures - let ctx = mut_ptr_as_ref(ctx); - let is_sub_schema = ValueRef::bool(false); - let config_meta = ValueRef::dict(None); - let config = ValueRef::dict(None); - let schema = ValueRef::dict(None); - let optional_mapping = ValueRef::dict(None); - let cal_map = ValueRef::dict(None); - let backtrack_level_map = ValueRef::dict(None); - let backtrack_cache = ValueRef::dict(None); - let record_instance = ValueRef::bool(false); - let instance_pkgpath = ValueRef::str(MAIN_PKG_PATH); - - let mut schema_args = ValueRef::list(None); - { - let mut schema_args_ref = schema_args.as_list_mut_ref(); - schema_args_ref.values.push(is_sub_schema); - schema_args_ref.values.push(config_meta); - schema_args_ref.values.push(config); - schema_args_ref.values.push(schema); - schema_args_ref.values.push(optional_mapping); - schema_args_ref.values.push(cal_map); - schema_args_ref.values.push(backtrack_level_map); - schema_args_ref.values.push(backtrack_cache); - schema_args_ref.values.push(record_instance); - schema_args_ref.values.push(instance_pkgpath); - } - let runtime_type = c2str(tpe); - let schema_func = ValueRef::func( - fn_ptr as u64, - check_fn_ptr as u64, - schema_args, - "", - runtime_type, - false, - ); - let attr_map = ptr_as_ref(attr_map); - let attr_dict = attr_map.as_dict_ref(); - let schema_ty = SchemaType { - name: runtime_type.to_string(), - attrs: attr_dict - .values - .iter() - .map(|(k, _)| (k.to_string(), Type::any())) // TODO: store schema attr type in the runtime. - .collect(), - has_index_signature: attr_dict.attr_map.contains_key(CAL_MAP_INDEX_SIGNATURE), - func: schema_func.clone(), - }; - ctx.all_schemas.insert(runtime_type.to_string(), schema_ty); - new_mut_ptr(ctx, schema_func) -} - -// ---------------------------------------------------------------------------- -// values: json -// ---------------------------------------------------------------------------- - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_from_json( - ctx: *mut kclvm_context_t, - s: *const kclvm_char_t, -) -> *mut kclvm_value_ref_t { - let ctx_ref = mut_ptr_as_ref(ctx); - if s.is_null() { - return kclvm_value_Undefined(ctx); - } - match ValueRef::from_json(ctx_ref, c2str(s)) { - Ok(x) => x.into_raw(ctx_ref), - _ => kclvm_value_Undefined(ctx), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_to_json_value( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - if p.is_null() { - return kclvm_value_Str(ctx, std::ptr::null()); - } - - let p = ptr_as_ref(p); - let s = p.to_json_string(); - let ctx = mut_ptr_as_ref(ctx); - new_mut_ptr(ctx, ValueRef::str(s.as_ref())) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_to_json_value_with_null( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - if p.is_null() { - return kclvm_value_Str(ctx, std::ptr::null()); - } - - let p = ptr_as_ref(p); - let s = p.to_json_string_with_null(); - let ctx = mut_ptr_as_ref(ctx); - new_mut_ptr(ctx, ValueRef::str(s.as_ref())) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_plan_to_json( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let p = ptr_as_ref(p); - let ctx: &mut Context = mut_ptr_as_ref(ctx); - let value = match ctx.buffer.custom_manifests_output.clone() { - Some(output) => ValueRef::from_yaml_stream(ctx, &output).unwrap(), - None => p.clone(), - }; - let (json_string, yaml_string) = value.plan(ctx); - ctx.json_result = json_string.clone(); - ctx.yaml_result = yaml_string.clone(); - new_mut_ptr(ctx, ValueRef::str(&json_string)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_plan_to_yaml( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let p = ptr_as_ref(p); - let ctx = mut_ptr_as_ref(ctx); - let value = match ctx.buffer.custom_manifests_output.clone() { - Some(output) => ValueRef::from_yaml_stream(ctx, &output).unwrap(), - None => p.clone(), - }; - let (json_string, yaml_string) = value.plan(ctx); - ctx.json_result = json_string.clone(); - ctx.yaml_result = yaml_string.clone(); - new_mut_ptr(ctx, ValueRef::str(&yaml_string)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_to_yaml_value( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - if p.is_null() { - return kclvm_value_Str(ctx, std::ptr::null()); - } - let ctx = mut_ptr_as_ref(ctx); - let p = ptr_as_ref(p); - let s = p.to_yaml_string(); - - new_mut_ptr(ctx, ValueRef::str(s.as_ref())) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_to_str_value( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - if p.is_null() { - return kclvm_value_Str(ctx, std::ptr::null()); - } - - let ctx = mut_ptr_as_ref(ctx); - let p = ptr_as_ref(p); - let s = p.to_string(); - - new_mut_ptr(ctx, ValueRef::str(s.as_ref())) -} - -// ---------------------------------------------------------------------------- -// values: value pointer -// ---------------------------------------------------------------------------- - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_Str_ptr( - p: *const kclvm_value_ref_t, -) -> *const kclvm_char_t { - let p = ptr_as_ref(p); - match &*p.rc.borrow() { - Value::str_value(ref v) => v.as_ptr() as *const c_char, - _ => std::ptr::null(), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_function_ptr( - p: *const kclvm_value_ref_t, -) -> *const u64 { - let p = ptr_as_ref(p); - match &*p.rc.borrow() { - Value::func_value(ref v) => v.fn_ptr as *const u64, - _ => std::ptr::null::(), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_check_function_ptr( - p: *const kclvm_value_ref_t, -) -> *const u64 { - let p = ptr_as_ref(p); - match &*p.rc.borrow() { - Value::func_value(ref v) => v.check_fn_ptr as *const u64, - _ => std::ptr::null::(), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_function_invoke( - p: *const kclvm_value_ref_t, - ctx: *mut kclvm_context_t, - args: *mut kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, - pkgpath: *const kclvm_char_t, - is_in_schema: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let func = ptr_as_ref(p); - let args_ref = mut_ptr_as_ref(args); - if func.is_func() { - let func = func.as_function(); - let fn_ptr = func.fn_ptr; - let closure = &func.closure; - let is_schema = !func.runtime_type.is_empty(); - let ctx_ref = mut_ptr_as_ref(ctx); - if ctx_ref.cfg.debug_mode { - ctx_ref - .backtrace - .push(BacktraceFrame::from_panic_info(&ctx_ref.panic_info)); - ctx_ref.panic_info.kcl_func = func.name.clone(); - } - let now_meta_info = ctx_ref.panic_info.clone(); - unsafe { - let call_fn: SchemaTypeFunc = transmute_copy(&fn_ptr); - // Call schema constructor twice - let value = if is_schema { - let pkgpath = c2str(pkgpath); - // Schema function closure - let mut args_new = args_ref.deep_copy(); - let mut closure_new = closure.deep_copy(); - let config_meta_index: isize = 1; - let cal_map_index: isize = 5; - let record_instance_index = closure.len() - 2; - let instance_pkgpath_index = closure.len() - 1; - args_ref.list_append_unpack(closure); - let args = args_ref.clone().into_raw(ctx_ref); - call_fn(ctx, args, kwargs); - let cal_map = closure.list_get(cal_map_index).unwrap(); - // is sub schema - closure_new.list_set(0, &ValueRef::bool(true)); - // record instance - closure_new.list_set(record_instance_index, &ValueRef::bool(true)); - // instance pkgpath - closure_new.list_set(instance_pkgpath_index, &ValueRef::str(pkgpath)); - // cal map - closure_new.list_set(cal_map_index as usize, &cal_map); - // config meta - let config_meta = schema_config_meta( - &ctx_ref.panic_info.kcl_file, - ctx_ref.panic_info.kcl_line as u64, - ctx_ref.panic_info.kcl_col as u64, - ); - closure_new.list_set(config_meta_index as usize, &config_meta); - args_new.list_append_unpack(&closure_new); - call_fn(ctx, args_new.into_raw(ctx_ref), kwargs) - // Normal kcl function, call directly - } else if func.is_external { - let name = format!("{}\0", func.name); - kclvm_plugin_invoke(ctx, name.as_ptr() as *const c_char, args, kwargs) - } else { - args_ref.list_append_unpack_first(closure); - let args = args_ref.clone().into_raw(ctx_ref); - call_fn(ctx, args, kwargs) - }; - let is_in_schema = ptr_as_ref(is_in_schema); - if is_schema && !is_in_schema.is_truthy() { - let schema_value = ptr_as_ref(value); - schema_value.schema_check_attr_optional(ctx_ref, true); - } - if ctx_ref.cfg.debug_mode { - ctx_ref.backtrace.pop(); - } - ctx_ref.panic_info = now_meta_info; - return value; - }; - } - kclvm_value_Undefined(ctx) -} - -// ---------------------------------------------------------------------------- -// values: method -// ---------------------------------------------------------------------------- - -// clone - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_deep_copy( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let p = ptr_as_ref(p); - let ctx = mut_ptr_as_ref(ctx); - p.deep_copy().into_raw(ctx) -} - -// delete - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_delete(p: *mut kclvm_value_ref_t) { - if p.is_null() { - return; - } - let val = ptr_as_ref(p); - val.from_raw(); - free_mut_ptr(p); -} - -// ---------------------------------------------------------------------------- -// values: iterator -// ---------------------------------------------------------------------------- - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_iter( - p: *const kclvm_value_ref_t, -) -> *mut kclvm_iterator_t { - let p = ptr_as_ref(p); - let iter = ValueIterator::from_value(p); - Box::into_raw(Box::new(iter)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_iterator_delete(p: *mut kclvm_iterator_t) { - free_mut_ptr(p); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_iterator_is_end(p: *mut kclvm_iterator_t) -> kclvm_bool_t { - let p = ptr_as_ref(p); - p.is_end() as kclvm_bool_t -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_iterator_cur_key( - p: *mut kclvm_iterator_t, -) -> *const kclvm_value_ref_t { - let p = ptr_as_ref(p); - match p.key() { - Some(x) => x, - None => std::ptr::null(), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_iterator_cur_value( - p: *mut kclvm_iterator_t, -) -> *const kclvm_value_ref_t { - let p = mut_ptr_as_ref(p); - match p.value() { - Some(x) => x, - None => std::ptr::null(), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_iterator_next_value( - p: *mut kclvm_iterator_t, - host: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let p = mut_ptr_as_ref(p); - let host = ptr_as_ref(host); - - match p.next(host) { - Some(x) => x, - None => std::ptr::null(), - } -} - -// ---------------------------------------------------------------------------- -// values: list -// ---------------------------------------------------------------------------- - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_len(p: *const kclvm_value_ref_t) -> kclvm_size_t { - let p = ptr_as_ref(p); - p.len() as kclvm_size_t -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_resize( - p: *mut kclvm_value_ref_t, - newsize: kclvm_size_t, -) { - let p = mut_ptr_as_ref(p); - p.list_resize(newsize as usize); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_clear(p: *mut kclvm_value_ref_t) { - let p = mut_ptr_as_ref(p); - p.list_clear(); -} - -/// Return number of occurrences of the list value. -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_count( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, - item: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let p = ptr_as_ref(p); - let item = ptr_as_ref(item); - let count = p.list_count(item); - let ctx = mut_ptr_as_ref(ctx); - let count_value = ValueRef::int(count as i64); - count_value.into_raw(ctx) -} - -/// Return first index of the list value. Panic if the value is not present. -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_find( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, - item: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let p = ptr_as_ref(p); - let item = ptr_as_ref(item); - let index = p.list_find(item); - let index_value = ValueRef::int(index as i64); - let ctx = mut_ptr_as_ref(ctx); - index_value.into_raw(ctx) -} - -/// Insert object before index of the list value. -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_insert( - p: *mut kclvm_value_ref_t, - index: *const kclvm_value_ref_t, - value: *const kclvm_value_ref_t, -) { - let p = mut_ptr_as_ref(p); - let index = ptr_as_ref(index); - let value = ptr_as_ref(value); - p.list_insert_at(index.as_int() as usize, value); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_get( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, - i: kclvm_size_t, -) -> *const kclvm_value_ref_t { - let p = ptr_as_ref(p); - let ctx = mut_ptr_as_ref(ctx); - match p.list_get(i as isize) { - Some(x) => x.into_raw(ctx), - _ => panic!("list index out of range"), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_get_option( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, - i: kclvm_size_t, -) -> *const kclvm_value_ref_t { - let p = ptr_as_ref(p); - - match p.list_get_option(i as isize) { - Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), - _ => kclvm_value_Undefined(ctx), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_set( - p: *mut kclvm_value_ref_t, - i: kclvm_size_t, - v: *const kclvm_value_ref_t, -) { - let p = mut_ptr_as_ref(p); - let v = ptr_as_ref(v); - p.list_set(i as usize, v); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_pop( - ctx: *mut kclvm_context_t, - p: *mut kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let p = mut_ptr_as_ref(p); - - match p.list_pop() { - Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), - _ => kclvm_value_Undefined(ctx), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_pop_first( - ctx: *mut kclvm_context_t, - p: *mut kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let p = mut_ptr_as_ref(p); - match p.list_pop_first() { - Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), - _ => kclvm_value_Undefined(ctx), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_append( - p: *mut kclvm_value_ref_t, - v: *const kclvm_value_ref_t, -) { - let p = mut_ptr_as_ref(p); - let v = ptr_as_ref(v); - p.list_append(v); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_append_bool(p: *mut kclvm_value_ref_t, v: kclvm_bool_t) { - let p = mut_ptr_as_ref(p); - p.list_append(&ValueRef::bool(v != 0)); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_append_int(p: *mut kclvm_value_ref_t, v: kclvm_int_t) { - let p = mut_ptr_as_ref(p); - p.list_append(&ValueRef::int(v)); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_append_float( - p: *mut kclvm_value_ref_t, - v: kclvm_float_t, -) { - let p = mut_ptr_as_ref(p); - p.list_append(&ValueRef::float(v)); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_append_str( - p: *mut kclvm_value_ref_t, - v: *const kclvm_char_t, -) { - let p = mut_ptr_as_ref(p); - p.list_append(&ValueRef::str(c2str(v))); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_append_unpack( - p: *mut kclvm_value_ref_t, - v: *const kclvm_value_ref_t, -) { - let p = mut_ptr_as_ref(p); - let v = ptr_as_ref(v); - - if p.is_list() { - p.list_append_unpack(v); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_list_remove_at(p: *mut kclvm_value_ref_t, i: kclvm_size_t) { - let p = mut_ptr_as_ref(p); - p.list_remove_at(i as usize); -} - -// ---------------------------------------------------------------------------- -// values: dict -// ---------------------------------------------------------------------------- - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_len(p: *const kclvm_value_ref_t) -> kclvm_size_t { - let p = ptr_as_ref(p); - match &*p.rc.borrow() { - Value::dict_value(ref dict) => dict.values.len() as kclvm_size_t, - _ => 0, - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_clear(p: *mut kclvm_value_ref_t) { - let p = mut_ptr_as_ref(p); - p.dict_clear(); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_is_override_attr( - p: *const kclvm_value_ref_t, - key: *const kclvm_char_t, -) -> kclvm_bool_t { - let p = ptr_as_ref(p); - let key = c2str(key); - let is_override_op = matches!( - p.dict_get_attr_operator(key), - Some(ConfigEntryOperationKind::Override) - ); - let without_index = matches!(p.dict_get_insert_index(key), Some(-1) | None); - (is_override_op && without_index) as kclvm_bool_t -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_get( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, - key: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let p = ptr_as_ref(p); - let key = ptr_as_ref(key); - - match p.dict_get(key) { - Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), - None => kclvm_value_Undefined(ctx), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_has_value( - p: *const kclvm_value_ref_t, - key: *const kclvm_char_t, -) -> kclvm_bool_t { - let p = ptr_as_ref(p); - let key = c2str(key); - match p.dict_get_value(key) { - Some(_) => true as kclvm_bool_t, - None => false as kclvm_bool_t, - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_get_value( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, - key: *const kclvm_char_t, -) -> *const kclvm_value_ref_t { - let p = ptr_as_ref(p); - let key = c2str(key); - match p.dict_get_value(key) { - Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), - None => kclvm_value_Undefined(ctx), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_get_entry( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, - key: *const kclvm_char_t, -) -> *const kclvm_value_ref_t { - let p = ptr_as_ref(p); - let key = c2str(key); - match p.dict_get_entry(key) { - Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), - None => kclvm_value_Undefined(ctx), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_get_value_by_path( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, - path: *const kclvm_char_t, -) -> *const kclvm_value_ref_t { - let p = ptr_as_ref(p); - let path = c2str(path); - match p.get_by_path(path) { - Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), - None => kclvm_value_Undefined(ctx), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_set_value( - ctx: *mut kclvm_context_t, - p: *mut kclvm_value_ref_t, - key: *const kclvm_char_t, - val: *const kclvm_value_ref_t, -) { - let p = mut_ptr_as_ref(p); - let key = c2str(key); - let val = ptr_as_ref(val); - if p.is_config() { - p.dict_update_key_value(key, val.clone()); - if p.is_schema() { - let schema: ValueRef; - { - let schema_value = p.as_schema(); - let mut config_keys = schema_value.config_keys.clone(); - config_keys.push(key.to_string()); - schema = resolve_schema(mut_ptr_as_ref(ctx), p, &config_keys); - } - p.schema_update_with_schema(&schema); - } - } else { - panic!( - "failed to update the dict. An iterable of key-value pairs was expected, but got {}. Check if the syntax for updating the dictionary with the attribute '{}' is correct", - p.type_str(), - key - ); - } -} - -#[no_mangle] -#[runtime_fn] -/// Return all dict keys. -pub unsafe extern "C-unwind" fn kclvm_dict_keys( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let p = ptr_as_ref(p); - let r = p.dict_keys(); - r.into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -/// Return all dict values. -pub unsafe extern "C-unwind" fn kclvm_dict_values( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let p = ptr_as_ref(p); - let r = p.dict_values(); - r.into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_insert( - ctx: *mut kclvm_context_t, - p: *mut kclvm_value_ref_t, - key: *const kclvm_char_t, - v: *const kclvm_value_ref_t, - op: kclvm_size_t, - insert_index: kclvm_size_t, - has_insert_index: kclvm_bool_t, -) { - let p = mut_ptr_as_ref(p); - let v = ptr_as_ref(v); - p.dict_insert( - mut_ptr_as_ref(ctx), - c2str(key), - v, - ConfigEntryOperationKind::from_i32(op), - if has_insert_index != 0 { - Some(insert_index) - } else { - None - }, - ); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_merge( - ctx: *mut kclvm_context_t, - p: *mut kclvm_value_ref_t, - key: *const kclvm_char_t, - v: *const kclvm_value_ref_t, - op: kclvm_size_t, - insert_index: kclvm_size_t, - has_insert_index: kclvm_bool_t, -) { - let p = mut_ptr_as_ref(p); - let v = ptr_as_ref(v); - let key = c2str(key); - let ctx = mut_ptr_as_ref(ctx); - let attr_map = { - match &*p.rc.borrow() { - Value::dict_value(dict) => dict.attr_map.clone(), - Value::schema_value(schema) => schema.config.attr_map.clone(), - _ => panic!("invalid object '{}' in attr_map", p.type_str()), - } - }; - if attr_map.contains_key(key) { - let v = type_pack_and_check(ctx, v, vec![attr_map.get(key).unwrap()], false); - p.dict_merge( - ctx, - key, - &v, - ConfigEntryOperationKind::from_i32(op), - if has_insert_index != 0 { - Some(insert_index) - } else { - None - }, - ); - } else { - p.dict_merge( - ctx, - key, - v, - ConfigEntryOperationKind::from_i32(op), - if has_insert_index != 0 { - Some(insert_index) - } else { - None - }, - ); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_insert_value( - ctx: *mut kclvm_context_t, - p: *mut kclvm_value_ref_t, - key: *const kclvm_value_ref_t, - v: *const kclvm_value_ref_t, - op: kclvm_size_t, - insert_index: kclvm_size_t, - has_insert_index: kclvm_bool_t, -) { - let p = mut_ptr_as_ref(p); - let v = ptr_as_ref(v); - let key = ptr_as_ref(key); - let key = key.attr_str(); - p.dict_insert( - mut_ptr_as_ref(ctx), - key.as_str(), - v, - ConfigEntryOperationKind::from_i32(op), - if has_insert_index != 0 { - Some(insert_index) - } else { - None - }, - ); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_update_key_value( - p: *mut kclvm_value_ref_t, - key: *const kclvm_value_ref_t, - v: *const kclvm_value_ref_t, -) { - let p = mut_ptr_as_ref(p); - let v = ptr_as_ref(v); - let key = ptr_as_ref(key); - let key = key.attr_str(); - p.dict_update_key_value(key.as_str(), v.clone()); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_safe_insert( - ctx: *mut kclvm_context_t, - p: *mut kclvm_value_ref_t, - key: *const kclvm_char_t, - v: *const kclvm_value_ref_t, - op: kclvm_size_t, - insert_index: kclvm_size_t, - has_insert_index: kclvm_bool_t, -) { - if p.is_null() || key.is_null() || v.is_null() { - return; - } - kclvm_dict_insert(ctx, p, key, v, op, insert_index, has_insert_index); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_insert_unpack( - ctx: *mut kclvm_context_t, - p: *mut kclvm_value_ref_t, - v: *const kclvm_value_ref_t, -) { - let p = mut_ptr_as_ref(p); - let ctx = mut_ptr_as_ref(ctx); - let v = ptr_as_ref(v); - p.dict_insert_unpack(ctx, v); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_default_collection_insert_int_pointer( - p: *mut kclvm_value_ref_t, - key: *const kclvm_char_t, - ptr: *const u64, -) { - let p = mut_ptr_as_ref(p); - let key = c2str(key); - let ptr = ptr as i64; - if p.is_dict() { - let mut dict_ref_mut = p.as_dict_mut_ref(); - if !dict_ref_mut.values.contains_key(key) { - let value = ValueRef::list(None); - dict_ref_mut.values.insert(key.to_string(), value); - } - let values = dict_ref_mut.values.get_mut(key).unwrap(); - let value = ValueRef::int(ptr); - if !value.r#in(values) { - values.list_append(&value); - } - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_default_collection_insert_value( - p: *mut kclvm_value_ref_t, - key: *const kclvm_char_t, - value: *const kclvm_value_ref_t, -) { - let p = mut_ptr_as_ref(p); - let key = c2str(key); - let value = ptr_as_ref(value); - if p.is_dict() { - let mut dict_ref_mut = p.as_dict_mut_ref(); - if !dict_ref_mut.values.contains_key(key) { - let value = ValueRef::list(None); - dict_ref_mut.values.insert(key.to_string(), value); - } - let values = dict_ref_mut.values.get_mut(key).unwrap(); - if !value.r#in(values) { - values.list_append(value); - } - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_remove( - p: *mut kclvm_value_ref_t, - key: *const kclvm_char_t, -) { - let p = mut_ptr_as_ref(p); - p.dict_remove(c2str(key)); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_dict_update( - p: *mut kclvm_value_ref_t, - v: *const kclvm_value_ref_t, -) { - let p = mut_ptr_as_ref(p); - let v = ptr_as_ref(v); - p.dict_update(v); -} - -// ---------------------------------------------------------------------------- -// values: arith -// ---------------------------------------------------------------------------- - -// is true - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_is_truthy(p: *const kclvm_value_ref_t) -> kclvm_bool_t { - let p = ptr_as_ref(p); - p.is_truthy() as kclvm_bool_t -} - -// len - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_len(p: *const kclvm_value_ref_t) -> kclvm_size_t { - let p = ptr_as_ref(p); - p.len() as kclvm_size_t -} - -// compare - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_cmp_equal_to( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - if a == b { - return kclvm_value_Bool(ctx, 1); - } - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - ValueRef::bool(a.cmp_equal(b)).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_cmp_not_equal_to( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - if a == b { - return kclvm_value_Bool(ctx, 0); - } - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - ValueRef::bool(!a.cmp_equal(b)).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_cmp_less_than( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - if a == b { - return kclvm_value_Bool(ctx, 0); - } - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - ValueRef::bool(a.cmp_less_than(b)).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_cmp_less_than_or_equal( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - ValueRef::bool(a.cmp_less_than_or_equal(b)).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_cmp_greater_than( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - if a == b { - return kclvm_value_Bool(ctx, 0); - } - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - ValueRef::bool(a.cmp_greater_than(b)).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_cmp_greater_than_or_equal( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - ValueRef::bool(a.cmp_greater_than_or_equal(b)).into_raw(mut_ptr_as_ref(ctx)) -} - -// is/in - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_is( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - if a == b { - return kclvm_value_Bool(ctx, 1); - } - kclvm_value_Bool(ctx, 0) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_is_not( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - if a == b { - return kclvm_value_Bool(ctx, 0); - } - kclvm_value_Bool(ctx, 1) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_in( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - ValueRef::bool(a.r#in(b)).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_not_in( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - ValueRef::bool(a.not_in(b)).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_as( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - let ty_str = b.as_str(); - let ctx = mut_ptr_as_ref(ctx); - let value = type_pack_and_check(ctx, a, vec![ty_str.as_str()], true); - value.into_raw(ctx) -} - -// unary-xxx - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_unary_plus( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - a.unary_plus().into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_unary_minus( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - a.unary_minus().into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_unary_not( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - a.unary_not().into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_unary_l_not( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - a.unary_l_not().into_raw(mut_ptr_as_ref(ctx)) -} - -// op-xxx - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_add( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - a.bin_add(ctx, b).into_raw(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_sub( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - a.bin_sub(ctx, b).into_raw(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_mul( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - a.bin_mul(ctx, b).into_raw(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_div( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - a.bin_div(b).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_mod( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - a.bin_mod(b).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_pow( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - a.bin_pow(ctx, b).into_raw(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_floor_div( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - a.bin_floor_div(b).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_bit_lshift( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - a.bin_bit_lshift(ctx, b).into_raw(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_bit_rshift( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - a.bin_bit_rshift(ctx, b).into_raw(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_bit_and( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - a.bin_bit_and(b).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_bit_xor( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - a.bin_bit_xor(b).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_bit_or( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - a.bin_bit_or(ctx, b).into_raw(ctx) -} - -// op-aug-xxx - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_aug_add( - ctx: *mut kclvm_context_t, - a: *mut kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let a = mut_ptr_as_ref(a); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - return a.bin_aug_add(ctx, b) as *const kclvm_value_ref_t; -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_aug_sub( - ctx: *mut kclvm_context_t, - a: *mut kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let a = mut_ptr_as_ref(a); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - return a.bin_aug_sub(ctx, b) as *const kclvm_value_ref_t; -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_aug_mul( - ctx: *mut kclvm_context_t, - a: *mut kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let a = mut_ptr_as_ref(a); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - return a.bin_aug_mul(ctx, b); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_aug_div( - _ctx: *mut kclvm_context_t, - a: *mut kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let a = mut_ptr_as_ref(a); - let b = ptr_as_ref(b); - return a.bin_aug_div(b) as *const kclvm_value_ref_t; -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_aug_mod( - _ctx: *mut kclvm_context_t, - a: *mut kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let a = mut_ptr_as_ref(a); - let b = ptr_as_ref(b); - return a.bin_aug_mod(b) as *const kclvm_value_ref_t; -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_aug_pow( - ctx: *mut kclvm_context_t, - a: *mut kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let a = mut_ptr_as_ref(a); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - return a.bin_aug_pow(ctx, b) as *const kclvm_value_ref_t; -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_aug_floor_div( - _ctx: *mut kclvm_context_t, - a: *mut kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let a = mut_ptr_as_ref(a); - let b = ptr_as_ref(b); - return a.bin_aug_floor_div(b) as *const kclvm_value_ref_t; -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_aug_bit_lshift( - ctx: *mut kclvm_context_t, - a: *mut kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let a = mut_ptr_as_ref(a); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - a.bin_aug_bit_lshift(ctx, b) as *const kclvm_value_ref_t -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_aug_bit_rshift( - ctx: *mut kclvm_context_t, - a: *mut kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let a = mut_ptr_as_ref(a); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - a.bin_aug_bit_rshift(ctx, b) as *const kclvm_value_ref_t -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_aug_bit_and( - _ctx: *mut kclvm_context_t, - a: *mut kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let a = mut_ptr_as_ref(a); - let b = ptr_as_ref(b); - a.bin_aug_bit_and(b) as *const kclvm_value_ref_t -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_aug_bit_xor( - _ctx: *mut kclvm_context_t, - a: *mut kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let a = mut_ptr_as_ref(a); - let b = ptr_as_ref(b); - a.bin_aug_bit_xor(b) as *const kclvm_value_ref_t -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_op_aug_bit_or( - ctx: *mut kclvm_context_t, - a: *mut kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let a = mut_ptr_as_ref(a); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - a.bin_aug_bit_or(ctx, b) as *const kclvm_value_ref_t -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_union( - ctx: *mut kclvm_context_t, - schema: *mut kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let a = mut_ptr_as_ref(schema); - let b = ptr_as_ref(b); - let ctx = mut_ptr_as_ref(ctx); - let attr_map = match &*a.rc.borrow() { - Value::dict_value(dict) => dict.attr_map.clone(), - Value::schema_value(schema) => schema.config.attr_map.clone(), - _ => panic!("invalid object '{}' in attr_map", a.type_str()), - }; - let opts = UnionOptions { - list_override: false, - idempotent_check: false, - config_resolve: true, - }; - if b.is_config() { - let dict = b.as_dict_ref(); - for k in dict.values.keys() { - let entry = b.dict_get_entry(k).unwrap(); - a.union_entry(ctx, &entry, true, &opts); - // Has type annotation - if let Some(ty) = attr_map.get(k) { - let value = a.dict_get_value(k).unwrap(); - a.dict_update_key_value(k, type_pack_and_check(ctx, &value, vec![ty], false)); - } - } - a.clone().into_raw(ctx) - } else { - a.union_entry(ctx, b, true, &opts).into_raw(ctx) - } -} - -// logic: && || - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_logic_and( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - ValueRef::bool(a.logic_and(b)).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_logic_or( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - ValueRef::bool(a.logic_or(b)).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_subscr( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - a.bin_subscr(b).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_subscr_set( - ctx: *mut kclvm_context_t, - p: *mut kclvm_value_ref_t, - index: *const kclvm_value_ref_t, - val: *const kclvm_value_ref_t, -) { - let ctx = mut_ptr_as_ref(ctx); - let p = mut_ptr_as_ref(p); - let index = ptr_as_ref(index); - let val = ptr_as_ref(val); - p.bin_subscr_set(ctx, index, val); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_subscr_option( - ctx: *mut kclvm_context_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) -> *mut kclvm_value_ref_t { - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - a.bin_subscr_option(b).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_load_attr( - ctx: *mut kclvm_context_t, - obj: *const kclvm_value_ref_t, - key: *const kclvm_char_t, -) -> *const kclvm_value_ref_t { - let p = ptr_as_ref(obj); - let key = c2str(key); - let ctx = mut_ptr_as_ref(ctx); - p.load_attr(key).into_raw(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_load_attr_option( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, - key: *const kclvm_char_t, -) -> *const kclvm_value_ref_t { - let p_ref = ptr_as_ref(p); - if p_ref.is_truthy() { - kclvm_value_load_attr(ctx, p, key) - } else { - kclvm_value_None(ctx) - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_remove_item( - a: *mut kclvm_value_ref_t, - b: *const kclvm_value_ref_t, -) { - let a = mut_ptr_as_ref(a); - let b = ptr_as_ref(b); - if a.is_dict() { - a.dict_remove(&b.as_str()); - } else if a.is_list() { - a.list_remove(b); - } else { - panic!("only list, dict and schema can be removed item"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_slice( - ctx: *mut kclvm_context_t, - x: *const kclvm_value_ref_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, - step: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let x = ptr_as_ref(x); - let a = ptr_as_ref(a); - let b = ptr_as_ref(b); - let step = ptr_as_ref(step); - x.list_slice(a, b, step).into_raw(mut_ptr_as_ref(ctx)) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_slice_option( - ctx: *mut kclvm_context_t, - x: *const kclvm_value_ref_t, - a: *const kclvm_value_ref_t, - b: *const kclvm_value_ref_t, - step: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let value = ptr_as_ref(x); - if value.is_truthy() { - kclvm_value_slice(ctx, x, a, b, step) - } else { - kclvm_value_None(ctx) - } -} - -// ---------------------------------------------------------------------------- -// values: schema -// ---------------------------------------------------------------------------- - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_schema_backtrack_cache( - ctx: *mut kclvm_context_t, - schema: *const kclvm_value_ref_t, - cache: *mut kclvm_value_ref_t, - cal_map: *const kclvm_value_ref_t, - name: *const kclvm_char_t, - runtime_type: *const kclvm_value_ref_t, -) { - let schema = ptr_as_ref(schema); - let cache = mut_ptr_as_ref(cache); - let cal_map = ptr_as_ref(cal_map); - let name = c2str(name); - if let Some(v) = cal_map.dict_get_value(name) { - if v.len() == 1 { - if let Some(value) = schema.dict_get_value(name) { - cache.dict_update_key_value(name, value); - } - } else if let (Some(cal_map_runtime_type_list), Some(cal_map_meta_line_list)) = ( - cal_map.dict_get_value(&format!("{name}_{CAL_MAP_RUNTIME_TYPE}")), - cal_map.dict_get_value(&format!("{name}_{CAL_MAP_META_LINE}")), - ) { - if let (Some(cal_map_runtime_type), Some(cal_map_meta_line)) = ( - cal_map_runtime_type_list.list_get(-1), - cal_map_meta_line_list.list_get(-1), - ) { - let runtime_type = ptr_as_ref(runtime_type); - let ctx = mut_ptr_as_ref(ctx); - let line = ctx.panic_info.kcl_line as i64; - let cal_map_meta_line = cal_map_meta_line.as_int(); - if runtime_type == &cal_map_runtime_type && line >= cal_map_meta_line { - if let Some(value) = schema.dict_get_value(name) { - cache.dict_update_key_value(name, value); - } - } - } - } - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_schema_instances( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let ctx_ref = mut_ptr_as_ref(ctx); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - if let Some(val) = args.pop_arg_first() { - let function = val.as_function(); - let full_pkg = args.arg_0().or_else(|| kwargs.kwarg("full_pkg")); - let full_pkg = if let Some(v) = full_pkg { - v.is_truthy() - } else { - false - }; - let runtime_type = &function.runtime_type; - if ctx_ref.instances.contains_key(runtime_type) { - let mut list = ValueRef::list(None); - let instance_map = ctx_ref.instances.get(runtime_type).unwrap(); - if full_pkg { - for (_, v_list) in instance_map { - collect_schema_instances(&mut list, &v_list, runtime_type) - } - } else { - // Get the schema instances only located at the main package. - if let Some(v_list) = instance_map.get(MAIN_PKG_PATH) { - collect_schema_instances(&mut list, &v_list, runtime_type) - } - if let Some(v_list) = instance_map.get("") { - collect_schema_instances(&mut list, &v_list, runtime_type) - } - }; - list.into_raw(ctx_ref) - } else { - kclvm_value_List(ctx) - } - } else { - kclvm_value_None(ctx) - } -} - -fn collect_schema_instances(list: &mut ValueRef, v_list: &[ValueRef], runtime_type: &str) { - for v in v_list { - if v.is_schema() { - list.list_append(v) - } else if v.is_dict() { - let runtime_type = v - .get_potential_schema_type() - .unwrap_or(runtime_type.to_string()); - let names: Vec<&str> = runtime_type.rsplit('.').collect(); - let name = names[0]; - let pkgpath = names[1]; - let v = v.dict_to_schema( - name, - pkgpath, - &[], - &ValueRef::dict(None), - &ValueRef::dict(None), - None, - None, - ); - list.list_append(&v); - } - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_schema_value_check( - ctx: *mut kclvm_context_t, - schema_value: *mut kclvm_value_ref_t, - schema_config: *const kclvm_value_ref_t, - _config_meta: *const kclvm_value_ref_t, - schema_name: *const kclvm_char_t, - index_sign_value: *const kclvm_value_ref_t, - key_name: *const kclvm_char_t, - key_type: *const kclvm_char_t, - value_type: *const kclvm_char_t, - _any_other: kclvm_bool_t, -) { - let schema_value = mut_ptr_as_ref(schema_value); - let schema_config = ptr_as_ref(schema_config); - let index_sign_value = ptr_as_ref(index_sign_value); - let key_type = c2str(key_type); - let value_type = c2str(value_type); - let index_key_name = c2str(key_name); - let has_index_signature = !key_type.is_empty(); - - let ctx = mut_ptr_as_ref(ctx); - if ctx.cfg.disable_schema_check { - return; - } - let config = schema_config.as_dict_ref(); - for (key, value) in &config.values { - let no_such_attr = schema_value.dict_get_value(key).is_none(); - if has_index_signature && no_such_attr { - // Allow index signature value has different values - // related to the index signature key name. - let should_update = - if let Some(index_key_value) = schema_value.dict_get_value(index_key_name) { - index_key_value.is_str() && key == &index_key_value.as_str() - } else { - true - }; - if should_update { - let op = config - .ops - .get(key) - .unwrap_or(&ConfigEntryOperationKind::Union); - schema_value.dict_update_entry( - key.as_str(), - &index_sign_value.deep_copy(), - &ConfigEntryOperationKind::Override, - None, - ); - schema_value.dict_insert(ctx, key.as_str(), value, op.clone(), None); - let value = schema_value.dict_get_value(key).unwrap(); - schema_value.dict_update_key_value( - key.as_str(), - type_pack_and_check(ctx, &value, vec![value_type], false), - ); - } - } else if !has_index_signature && no_such_attr { - let schema_name = c2str(schema_name); - panic!("No attribute named '{key}' in the schema '{schema_name}'"); - } - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_schema_do_check_with_index_sign_attr( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, - check_fn_ptr: *const u64, - attr_name: *const kclvm_char_t, -) { - let check_fn_ptr = check_fn_ptr as u64; - let args_value = ptr_as_ref(args); - let attr_name = c2str(attr_name); - unsafe { - let check_fn: SchemaTypeFunc = transmute_copy(&check_fn_ptr); - // args_0: config_meta, args_1: config, args_2: schema, args_3: cal_map - // Schema check function closure - let config_meta = args_value.arg_i(0).unwrap(); - let config = args_value.arg_i(1).unwrap(); - let mut schema = args_value.arg_i(2).unwrap(); - let cal_map = args_value.arg_i(3).unwrap(); - let backtrack_level_map = args_value.arg_i(4).unwrap(); - let backtrack_cache = args_value.arg_i(5).unwrap(); - for (k, _) in &config.as_dict_ref().values { - // relaxed keys - if schema.attr_map_get(k).is_none() { - let value = ValueRef::str(k); - schema.dict_update_key_value(attr_name, value); - let args = &mut ValueRef::list(None); - // Schema check function closure - args.list_append(&config_meta); - args.list_append(&config); - args.list_append(&schema); - args.list_append(&cal_map); - args.list_append(&backtrack_level_map); - args.list_append(&backtrack_cache); - let args = args.clone().into_raw(mut_ptr_as_ref(ctx)); - check_fn(ctx, args, kwargs); - } - } - schema.dict_remove(attr_name); - }; -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_schema_optional_check( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, -) { - let p = ptr_as_ref(p); - let ctx = mut_ptr_as_ref(ctx); - if !ctx.cfg.disable_schema_check { - p.schema_check_attr_optional(ctx, true); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_schema_default_settings( - schema_value: *mut kclvm_value_ref_t, - _config_value: *const kclvm_value_ref_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, - runtime_type: *const kclvm_char_t, -) { - let schema_value = mut_ptr_as_ref(schema_value); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let runtime_type = c2str(runtime_type); - schema_value.set_potential_schema_type(runtime_type); - schema_value.set_schema_args(args, kwargs); -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_schema_assert( - ctx: *mut kclvm_context_t, - value: *const kclvm_value_ref_t, - msg: *const kclvm_value_ref_t, - config_meta: *const kclvm_value_ref_t, -) { - let value = ptr_as_ref(value); - let msg = ptr_as_ref(msg); - let config_meta = ptr_as_ref(config_meta); - if !value.is_truthy() { - let ctx = mut_ptr_as_ref(ctx); - ctx.set_err_type(&RuntimeErrorType::SchemaCheckFailure); - if let Some(config_meta_file) = config_meta.get_by_key(CONFIG_META_FILENAME) { - let config_meta_line = config_meta.get_by_key(CONFIG_META_LINE).unwrap(); - let config_meta_column = config_meta.get_by_key(CONFIG_META_COLUMN).unwrap(); - ctx.set_kcl_config_meta_location_info( - Some("Instance check failed"), - Some(config_meta_file.as_str().as_str()), - Some(config_meta_line.as_int() as i32), - Some(config_meta_column.as_int() as i32), - ); - } - - let arg_msg = format!( - "Check failed on the condition{}", - if msg.is_empty() { - "".to_string() - } else { - format!(": {msg}") - } - ); - ctx.set_kcl_location_info(Some(arg_msg.as_str()), None, None, None); - - panic!("{}", msg.as_str()); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_schema_value_new( - ctx: *mut kclvm_context_t, - args: *mut kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, - schema_value_or_func: *const kclvm_value_ref_t, - config: *const kclvm_value_ref_t, - config_meta: *const kclvm_value_ref_t, - pkgpath: *const kclvm_char_t, -) -> *const kclvm_value_ref_t { - let schema_value_or_func = ptr_as_ref(schema_value_or_func); - if schema_value_or_func.is_func() { - let schema_func = schema_value_or_func.as_function(); - let schema_fn_ptr = schema_func.fn_ptr; - let ctx_ref = mut_ptr_as_ref(ctx); - let now_meta_info = ctx_ref.panic_info.clone(); - if ctx_ref.cfg.debug_mode { - ctx_ref - .backtrace - .push(BacktraceFrame::from_panic_info(&ctx_ref.panic_info)); - ctx_ref.panic_info.kcl_func = schema_func.runtime_type.clone(); - } - let value = unsafe { - let org_args = ptr_as_ref(args).deep_copy(); - let schema_fn: SchemaTypeFunc = transmute_copy(&schema_fn_ptr); - let cal_map = kclvm_value_Dict(ctx); - let instance_pkgpath = kclvm_value_Str(ctx, pkgpath); - // Schema function closures - let values = [ - // is_sub_schema - kclvm_value_Bool(ctx, 0), - // Config meta - config_meta, - // Config value - config, - // Schema value - kclvm_value_Dict(ctx), - // optional_mapping - kclvm_value_Dict(ctx), - // cal order map - cal_map, - // backtrack level map - kclvm_value_Dict(ctx), - // backtrack cache - kclvm_value_Dict(ctx), - // record instance - kclvm_value_Bool(ctx, 0), - // instance pkgpath - instance_pkgpath, - ]; - for value in values { - kclvm_list_append(args, value); - } - schema_fn(ctx, args, kwargs); - // schema args - let args = org_args.into_raw(ctx_ref); - let values = [ - // is_sub_schema - kclvm_value_Bool(ctx, 1), - // Config meta - config_meta, - // Config value - config, - // Schema value - kclvm_value_Dict(ctx), - // optional_mapping - kclvm_value_Dict(ctx), - // cal order map - cal_map, - // backtrack level map - kclvm_value_Dict(ctx), - // backtrack cache - kclvm_value_Dict(ctx), - // record instance - kclvm_value_Bool(ctx, 1), - // instance pkgpath - instance_pkgpath, - ]; - for value in values { - kclvm_list_append(args, value); - } - schema_fn(ctx, args, kwargs) - }; - ctx_ref.panic_info = now_meta_info; - if ctx_ref.cfg.debug_mode { - ctx_ref.backtrace.pop(); - } - value - } else { - let config = ptr_as_ref(config); - let result = schema_value_or_func.deep_copy().union_entry( - mut_ptr_as_ref(ctx), - config, - true, - &UnionOptions::default(), - ); - result.into_raw(mut_ptr_as_ref(ctx)) - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_convert_collection_value( - ctx: *mut kclvm_context_t, - value: *const kclvm_value_ref_t, - tpe: *const kclvm_char_t, - is_in_schema: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let value = ptr_as_ref(value); - let ctx = mut_ptr_as_ref(ctx); - let tpe = c2str(tpe); - let value = type_pack_and_check(ctx, value, vec![tpe], false); - let is_in_schema = ptr_as_ref(is_in_schema); - // Schema required attribute validating. - if !is_in_schema.is_truthy() { - walk_value_mut(&value, &mut |value: &ValueRef| { - if value.is_schema() { - value.schema_check_attr_optional(ctx, true); - } - }) - } - value.into_raw(ctx) -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_schema_get_value( - ctx: *mut kclvm_context_t, - p: *const kclvm_value_ref_t, - key: *const kclvm_char_t, - config: *const kclvm_value_ref_t, - config_meta: *const kclvm_value_ref_t, - cal_map: *const kclvm_value_ref_t, - target_attr: *const kclvm_char_t, - backtrack_level_map: *mut kclvm_value_ref_t, - backtrack_cache: *mut kclvm_value_ref_t, - args: *mut kclvm_value_ref_t, - kwargs: *mut kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let schema = ptr_as_ref(p); - let key = c2str(key); - let cal_map = ptr_as_ref(cal_map); - let target_attr = c2str(target_attr); - let backtrack_level_map = mut_ptr_as_ref(backtrack_level_map); - let backtrack_cache = mut_ptr_as_ref(backtrack_cache); - let args_org = mut_ptr_as_ref(args); - let kwargs = mut_ptr_as_ref(kwargs); - let default_level = ValueRef::int(0); - let level = backtrack_level_map - .dict_get_value(key) - .unwrap_or(default_level); - let level = level.as_int(); - let is_backtracking = level > 0; - // Deal in-place modify and return it self immediately - if key == target_attr && !is_backtracking { - match schema.dict_get_value(key) { - Some(x) => return x.into_raw(mut_ptr_as_ref(ctx)), - None => return kclvm_value_Undefined(ctx), - } - } - if let Some(v) = backtrack_cache.dict_get_value(key) { - return v.into_raw(mut_ptr_as_ref(ctx)); - } - if let Some(attr_code) = cal_map.dict_get_value(key) { - let now_level = level + 1; - backtrack_level_map.dict_update_key_value(key, ValueRef::int(now_level)); - let attr_code = attr_code.as_list_ref(); - let n = attr_code.values.len(); - let index = n - now_level as usize; - if index >= n { - let value = match schema.dict_get_value(key) { - Some(x) => x, - None => ValueRef::undefined(), - }; - return value.into_raw(mut_ptr_as_ref(ctx)); - } - let fn_ptr = &attr_code.values[index]; - let fn_ptr = fn_ptr.as_int(); - // When we calculate other schema attribute values, we retain - // the row and column number information of the current schema attribute. - let ctx_ref = mut_ptr_as_ref(ctx); - let panic_info = ctx_ref.panic_info.clone(); - unsafe { - let attr_fn: SchemaTypeFunc = transmute_copy(&fn_ptr); - // args_0: config_meta, args_1: config, args_2: schema, args_3: cal_map - let config_meta = ptr_as_ref(config_meta); - let config = ptr_as_ref(config); - let mut args = ValueRef::list(None); - let args_org = args_org.as_list_ref(); - for value in &args_org.values { - args.list_append(value); - } - // Schema attr function closure - args.list_append(config_meta); - args.list_append(config); - args.list_append(schema); - args.list_append(cal_map); - args.list_append(backtrack_level_map); - args.list_append(backtrack_cache); - let args = args.into_raw(ctx_ref); - let kwargs = kwargs.clone().into_raw(ctx_ref); - attr_fn(ctx, args, kwargs); - }; - // Restore the panic info of current schema attribute. - ctx_ref.panic_info = panic_info; - backtrack_level_map.dict_update_key_value(key, ValueRef::int(level)); - let value = match schema.dict_get_value(key) { - Some(x) => x, - None => ValueRef::undefined(), - }; - backtrack_cache.dict_update_key_value(key, value); - } - match schema.dict_get_value(key) { - Some(x) => x.into_raw(mut_ptr_as_ref(ctx)), - None => kclvm_value_Undefined(ctx), - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_config_attr_map( - value: *mut kclvm_value_ref_t, - name: *const kclvm_char_t, - type_str: *const kclvm_char_t, -) { - let value = mut_ptr_as_ref(value); - let name = c2str(name); - let type_str = c2str(type_str); - value.update_attr_map(name, type_str); -} - -// ---------------------------------------------------------------------------- -// values: decorators -// ---------------------------------------------------------------------------- - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_value_Decorator( - ctx: *mut kclvm_context_t, - name: *const kclvm_char_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, - config_meta: *const kclvm_value_ref_t, - attr_name: *const kclvm_char_t, - config_value: *const kclvm_value_ref_t, - is_schema_target: *const kclvm_value_ref_t, -) -> *const kclvm_decorator_value_t { - let name = c2str(name); - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let config_meta = ptr_as_ref(config_meta); - let attr_name = c2str(attr_name); - let config_value = ptr_as_ref(config_value); - let is_schema_target = ptr_as_ref(is_schema_target); - let decorator = DecoratorValue::new(name, args, kwargs); - decorator.run( - mut_ptr_as_ref(ctx), - attr_name, - is_schema_target.as_bool(), - config_value, - config_meta, - ); - decorator.into_raw() -} - -// ---------------------------------------------------------------------------- -// values: string member functions -// ---------------------------------------------------------------------------- - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_lower( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - val.str_lower().into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_lower"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_upper( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - val.str_upper().into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_upper"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_capitalize( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - val.str_capitalize().into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_capitalize"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_chars( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - val.str_chars().into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_chars"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_count( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - if let Some(sub) = args.arg_0() { - let start = args.arg_i(1); - let end = args.arg_i(2); - val.str_count(&sub, start.as_ref(), end.as_ref()) - .into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("count() takes at least 1 argument (0 given)"); - } - } else { - panic!("invalid self value in str_count"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_endswith( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - if let Some(suffix) = args.arg_0() { - let start = args.arg_i(1); - let end = args.arg_i(2); - val.str_endswith(&suffix, start.as_ref(), end.as_ref()) - .into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("endswith() takes at least 1 argument (0 given)"); - } - } else { - panic!("invalid self value in str_endswith"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_find( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - if let Some(sub) = args.arg_0() { - let start = args.arg_i(1); - let end = args.arg_i(2); - val.str_find(&sub, start.as_ref(), end.as_ref()) - .into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("find() takes at least 1 argument (0 given)"); - } - } else { - panic!("invalid self value in str_find"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_format( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - if let Some(val) = args.pop_arg_first() { - val.str_format(args, kwargs).into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_format"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_index( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - if let Some(sub) = args.arg_0() { - let start = args.arg_i(1); - let end = args.arg_i(2); - val.str_index(&sub, start.as_ref(), end.as_ref()) - .into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("index() takes at least 1 argument (0 given)"); - } - } else { - panic!("invalid self value in str_index"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_isalnum( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - val.str_isalnum().into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_isalnum"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_isalpha( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - val.str_isalpha().into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_isalpha"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_isdigit( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - val.str_isdigit().into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_isdigit"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_islower( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - val.str_islower().into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_islower"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_isspace( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - val.str_isspace().into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_isspace"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_istitle( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - val.str_istitle().into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_istitle"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_isupper( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - val.str_isupper().into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_isupper"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_join( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - let iter = args.arg_i(0).unwrap(); - val.str_join(&iter).into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_join"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_lstrip( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - let chars = args.arg_i(0); - val.str_lstrip(chars.as_ref()).into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_lstrip"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_rstrip( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - let chars = args.arg_i(0); - val.str_rstrip(chars.as_ref()).into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_rstrip"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_replace( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - let old = args.arg_i(0).expect("expect 1 argument, found 0"); - let new = args.arg_i(1).expect("expect 2 arguments, found 1"); - let count = args.arg_i(2); - val.str_replace(&old, &new, count.as_ref()) - .into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_replace"); - } -} - -/// If the string starts with the prefix string, return string[len(prefix):]. -/// Otherwise, return a copy of the original string. -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_removeprefix( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - let prefix = args.arg_i(0).expect("expect 1 argument, found 0"); - val.str_removeprefix(&prefix).into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_removeprefix"); - } -} - -/// If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. -/// Otherwise, return a copy of the original string. -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_removesuffix( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - let suffix = args.arg_i(0).expect("expect 1 argument, found 0"); - val.str_removesuffix(&suffix).into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_removesuffix"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_rfind( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - if let Some(sub) = args.arg_0() { - let start = args.arg_i(1); - let end = args.arg_i(2); - val.str_rfind(&sub, start.as_ref(), end.as_ref()) - .into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("rfind() takes at least 1 argument (0 given)"); - } - } else { - panic!("invalid self value in str_rfind"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_rindex( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - if let Some(sub) = args.arg_0() { - let start = args.arg_i(1); - let end = args.arg_i(2); - val.str_rindex(&sub, start.as_ref(), end.as_ref()) - .into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("rindex() takes at least 1 argument (0 given)"); - } - } else { - panic!("invalid self value in str_rindex"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_rsplit( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - if let Some(val) = args.pop_arg_first() { - let sep = if let Some(sep) = args.arg_i(0) { - Some(sep) - } else { - kwargs.kwarg("sep") - }; - let maxsplit = if let Some(maxsplit) = args.arg_i(1) { - Some(maxsplit) - } else { - kwargs.kwarg("maxsplit") - }; - val.str_rsplit(sep.as_ref(), maxsplit.as_ref()) - .into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_rsplit"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_split( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - if let Some(val) = args.pop_arg_first() { - let sep = if let Some(sep) = args.arg_i(0) { - Some(sep) - } else { - kwargs.kwarg("sep") - }; - let maxsplit = if let Some(maxsplit) = args.arg_i(1) { - Some(maxsplit) - } else { - kwargs.kwarg("maxsplit") - }; - let x = val.str_split(sep.as_ref(), maxsplit.as_ref()); - x.into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_split"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_splitlines( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - if let Some(val) = args.pop_arg_first() { - if let Some(keepends) = args.arg_i(0) { - val.str_splitlines(Some(&keepends)) - .into_raw(mut_ptr_as_ref(ctx)) - } else if let Some(keepends) = kwargs.kwarg("keepends") { - val.str_splitlines(Some(&keepends)) - .into_raw(mut_ptr_as_ref(ctx)) - } else { - val.str_splitlines(None).into_raw(mut_ptr_as_ref(ctx)) - } - } else { - panic!("invalid self value in str_splitlines"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_startswith( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - if let Some(suffix) = args.arg_0() { - let start = args.arg_i(1); - let end = args.arg_i(2); - val.str_startswith(&suffix, start.as_ref(), end.as_ref()) - .into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("startswith() takes at least 1 argument (0 given)"); - } - } else { - panic!("invalid self value in str_startswith"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_strip( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - let chars = args.arg_i(0); - val.str_strip(chars.as_ref()).into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_strip"); - } -} - -#[no_mangle] -#[runtime_fn] -pub unsafe extern "C-unwind" fn kclvm_builtin_str_title( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - _kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - if let Some(val) = args.pop_arg_first() { - val.str_title().into_raw(mut_ptr_as_ref(ctx)) - } else { - panic!("invalid self value in str_title"); - } -} - -// ---------------------------------------------------------------------------- -// END -// ---------------------------------------------------------------------------- diff --git a/kclvm/runtime/src/value/val_attr.rs b/kclvm/runtime/src/value/val_attr.rs deleted file mode 100644 index 8b08dd678..000000000 --- a/kclvm/runtime/src/value/val_attr.rs +++ /dev/null @@ -1,75 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -use crate::*; - -impl ValueRef { - /// Load attribute named `key` from the self value, the attribute maybe a - /// member function or a builtin value. - pub fn load_attr(&self, key: &str) -> Self { - let p: &ValueRef = self; - // load_attr including str/dict/schema. - if p.is_dict() { - match p.dict_get_value(key) { - Some(x) => x, - None => ValueRef::undefined(), - } - } else if p.is_schema() { - let dict = p.schema_to_dict(); - match dict.dict_get_value(key) { - Some(x) => x, - None => panic!("schema '{}' attribute '{}' not found", p.type_str(), key), - } - } else if p.is_str() { - let function = match key { - "lower" => kclvm_builtin_str_lower, - "upper" => kclvm_builtin_str_upper, - "capitalize" => kclvm_builtin_str_capitalize, - "chars" => kclvm_builtin_str_chars, - "count" => kclvm_builtin_str_count, - "endswith" => kclvm_builtin_str_endswith, - "find" => kclvm_builtin_str_find, - "format" => kclvm_builtin_str_format, - "index" => kclvm_builtin_str_index, - "isalnum" => kclvm_builtin_str_isalnum, - "isalpha" => kclvm_builtin_str_isalpha, - "isdigit" => kclvm_builtin_str_isdigit, - "islower" => kclvm_builtin_str_islower, - "isspace" => kclvm_builtin_str_isspace, - "istitle" => kclvm_builtin_str_istitle, - "isupper" => kclvm_builtin_str_isupper, - "join" => kclvm_builtin_str_join, - "lstrip" => kclvm_builtin_str_lstrip, - "rstrip" => kclvm_builtin_str_rstrip, - "replace" => kclvm_builtin_str_replace, - "removeprefix" => kclvm_builtin_str_removeprefix, - "removesuffix" => kclvm_builtin_str_removesuffix, - "rfind" => kclvm_builtin_str_rfind, - "rindex" => kclvm_builtin_str_rindex, - "rsplit" => kclvm_builtin_str_rsplit, - "split" => kclvm_builtin_str_split, - "splitlines" => kclvm_builtin_str_splitlines, - "startswith" => kclvm_builtin_str_startswith, - "strip" => kclvm_builtin_str_strip, - "title" => kclvm_builtin_str_title, - _ => panic!("str object attr '{key}' not found"), - }; - let closure = ValueRef::list(Some(&[p])); - ValueRef::func(function as usize as u64, 0, closure, "", "", false) - } - // schema instance - else if p.is_func() { - let function = match key { - "instances" => kclvm_schema_instances, - _ => panic!("schema object attr '{key}' not found"), - }; - let closure = ValueRef::list(Some(&[p])); - ValueRef::func(function as usize as u64, 0, closure, "", "", false) - } else { - panic!( - "invalid value '{}' to load attribute '{}'", - p.type_str(), - key - ); - } - } -} diff --git a/kclvm/runtime/src/yaml/mod.rs b/kclvm/runtime/src/yaml/mod.rs deleted file mode 100644 index 80cd78f8c..000000000 --- a/kclvm/runtime/src/yaml/mod.rs +++ /dev/null @@ -1,191 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. -use crate::*; - -pub const YAML_STREAM_SEP: &str = "\n---\n"; -pub const JSON_STREAM_SEP: &str = "\n"; - -/// encode(data, sort_keys=False, ignore_private=False, ignore_none=False) -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_yaml_encode( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("data")) { - let s = ValueRef::str( - arg0.to_yaml_string_with_options(&args_to_opts(args, kwargs, 1)) - .as_ref(), - ); - return s.into_raw(mut_ptr_as_ref(ctx)); - } - panic!("encode_all() missing 1 required positional argument: 'data'") -} - -/// encode_all(data, sort_keys=False, ignore_private=False, ignore_none=False) -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_yaml_encode_all( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("data")) { - let opts = args_to_opts(args, kwargs, 1); - let results = arg0 - .as_list_ref() - .values - .iter() - .map(|r| r.to_yaml_string_with_options(&opts)) - .collect::>(); - let s = ValueRef::str(&results.join(YAML_STREAM_SEP)); - return s.into_raw(mut_ptr_as_ref(ctx)); - } - panic!("encode() missing 1 required positional argument: 'data'") -} - -/// decode(value) -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_yaml_decode( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("value")) { - match ValueRef::from_yaml(ctx, arg0.as_str().as_ref()) { - Ok(x) => return x.into_raw(ctx), - Err(err) => panic!("{}", err), - } - } - panic!("decode() missing 1 required positional argument: 'value'") -} - -/// decode_all(value) -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_yaml_decode_all( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("value")) { - match ValueRef::list_from_yaml_stream(ctx, arg0.as_str().as_ref()) { - Ok(x) => return x.into_raw(ctx), - Err(err) => panic!("{}", err), - } - } - panic!("decode_all() missing 1 required positional argument: 'value'") -} - -/// dump_to_file(data, sort_keys=False, ignore_private=False, ignore_none=False) -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_yaml_dump_to_file( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let data = args.arg_i(0).or(kwargs.get_by_key("data")); - let filename = args.arg_i(1).or(kwargs.get_by_key("filename")); - match (data, filename) { - (Some(data), Some(filename)) => { - let filename = filename.as_str(); - - let yaml = data.to_yaml_string_with_options(&args_to_opts(args, kwargs, 2)); - std::fs::write(&filename, yaml) - .unwrap_or_else(|e| panic!("Unable to write file '{}': {}", filename, e)); - kclvm_value_Undefined(ctx) - } - _ => { - panic!("dump_to_file() missing 2 required positional arguments: 'data' and 'filename'") - } - } -} - -/// dump_all_to_file(data, sort_keys=False, ignore_private=False, ignore_none=False) -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_yaml_dump_all_to_file( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - - let data = args.arg_i(0).or(kwargs.get_by_key("data")); - let filename = args.arg_i(1).or(kwargs.get_by_key("filename")); - match (data, filename) { - (Some(data), Some(filename)) => { - let filename = filename.as_str(); - let opts = args_to_opts(args, kwargs, 2); - let results = data - .as_list_ref() - .values - .iter() - .map(|r| r.to_yaml_string_with_options(&opts)) - .collect::>(); - - std::fs::write(filename, results.join(YAML_STREAM_SEP)).expect("Unable to write file"); - kclvm_value_Undefined(ctx) - } - _ => { - panic!( - "dump_all_to_file() missing 2 required positional arguments: 'data' and 'filename'" - ) - } - } -} - -/// validate(value: str) -> bool -#[no_mangle] -#[runtime_fn] -pub extern "C-unwind" fn kclvm_yaml_validate( - ctx: *mut kclvm_context_t, - args: *const kclvm_value_ref_t, - kwargs: *const kclvm_value_ref_t, -) -> *const kclvm_value_ref_t { - let args = ptr_as_ref(args); - let kwargs = ptr_as_ref(kwargs); - let ctx = mut_ptr_as_ref(ctx); - - if let Some(arg0) = get_call_arg(args, kwargs, 0, Some("value")) { - match ValueRef::from_yaml_stream(ctx, arg0.as_str().as_ref()) { - Ok(_) => return kclvm_value_True(ctx), - Err(_) => return kclvm_value_False(ctx), - } - } - panic!("validate() missing 1 required positional argument: 'value'") -} - -fn args_to_opts(args: &ValueRef, kwargs: &ValueRef, index: usize) -> YamlEncodeOptions { - let mut opts = YamlEncodeOptions::default(); - if let Some(sort_keys) = get_call_arg_bool(args, kwargs, index, Some("sort_keys")) { - opts.sort_keys = sort_keys; - } - if let Some(ignore_private) = get_call_arg_bool(args, kwargs, index + 1, Some("ignore_private")) - { - opts.ignore_private = ignore_private; - } - if let Some(ignore_none) = get_call_arg_bool(args, kwargs, index + 2, Some("ignore_none")) { - opts.ignore_none = ignore_none; - } - opts -} diff --git a/kclvm/sema/Cargo.lock b/kclvm/sema/Cargo.lock deleted file mode 100644 index 14fd9529f..000000000 --- a/kclvm/sema/Cargo.lock +++ /dev/null @@ -1,1778 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "ahash" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" -dependencies = [ - "getrandom", - "once_cell", - "version_check", -] - -[[package]] -name = "aho-corasick" -version = "0.7.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" -dependencies = [ - "memchr", -] - -[[package]] -name = "annotate-snippets" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78ea013094e5ea606b1c05fe35f1dd7ea1eb1ea259908d040b25bd5ec677ee5" - -[[package]] -name = "anyhow" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224afbd727c3d6e4b90103ece64b8d1b67fbb1973b1046c2281eed3f3803f800" - -[[package]] -name = "arrayvec" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" - -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi", - "libc", - "winapi", -] - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "base64" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" - -[[package]] -name = "bit-set" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e11e16035ea35e4e5997b393eacbf6f63983188f7a2ad25bfb13465f5ad59de" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "generic-array", -] - -[[package]] -name = "block-buffer" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bstr" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" -dependencies = [ - "lazy_static", - "memchr", - "regex-automata", - "serde", -] - -[[package]] -name = "bumpalo" -version = "3.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535" - -[[package]] -name = "cast" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c24dab4283a142afa2fdca129b80ad2c6284e073930f964c3a1293c225ee39a" -dependencies = [ - "rustc_version", -] - -[[package]] -name = "cc" -version = "1.0.73" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "chrono" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" -dependencies = [ - "libc", - "num-integer", - "num-traits", - "time", - "winapi", -] - -[[package]] -name = "clap" -version = "2.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c" -dependencies = [ - "bitflags", - "textwrap", - "unicode-width", -] - -[[package]] -name = "cpufeatures" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b" -dependencies = [ - "libc", -] - -[[package]] -name = "criterion" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1604dafd25fba2fe2d5895a9da139f8dc9b319a5fe5354ca137cbbce4e178d10" -dependencies = [ - "atty", - "cast", - "clap", - "criterion-plot", - "csv", - "itertools", - "lazy_static", - "num-traits", - "oorandom", - "plotters", - "rayon", - "regex", - "serde", - "serde_cbor", - "serde_derive", - "serde_json", - "tinytemplate", - "walkdir", -] - -[[package]] -name = "criterion-plot" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d00996de9f2f7559f7f4dc286073197f83e92256a59ed395f9aac01fe717da57" -dependencies = [ - "cast", - "itertools", -] - -[[package]] -name = "crossbeam-channel" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aaa7bd5fb665c6864b5f963dd9097905c54125909c7aa94c9e18507cdbe6c53" -dependencies = [ - "cfg-if 1.0.0", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" -dependencies = [ - "cfg-if 1.0.0", - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1145cf131a2c6ba0615079ab6a638f7e1973ac9c2634fcbeaaad6114246efe8c" -dependencies = [ - "autocfg", - "cfg-if 1.0.0", - "crossbeam-utils", - "lazy_static", - "memoffset", - "scopeguard", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf124c720b7686e3c2663cf54062ab0f68a88af2fb6a030e87e30bf721fcb38" -dependencies = [ - "cfg-if 1.0.0", - "lazy_static", -] - -[[package]] -name = "crypto-common" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "csv" -version = "1.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22813a6dc45b335f9bade10bf7271dc477e81113e89eb251a0bc2a8a81c536e1" -dependencies = [ - "bstr", - "csv-core", - "itoa 0.4.8", - "ryu", - "serde", -] - -[[package]] -name = "csv-core" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b2466559f260f48ad25fe6317b3c8dac77b5bdb5763ac7d9d6103530663bc90" -dependencies = [ - "memchr", -] - -[[package]] -name = "digest" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" -dependencies = [ - "generic-array", -] - -[[package]] -name = "digest" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506" -dependencies = [ - "block-buffer 0.10.2", - "crypto-common", -] - -[[package]] -name = "either" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" - -[[package]] -name = "ena" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7402b94a93c24e742487327a7cd839dc9d36fec9de9fb25b09f2dae459f36c3" -dependencies = [ - "log", -] - -[[package]] -name = "enquote" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06c36cb11dbde389f4096111698d8b567c0720e3452fd5ac3e6b4e47e1939932" -dependencies = [ - "thiserror", -] - -[[package]] -name = "fancy-regex" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d6b8560a05112eb52f04b00e5d3790c0dd75d9d980eb8a122fb23b92a623ccf" -dependencies = [ - "bit-set", - "regex", -] - -[[package]] -name = "fastrand" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf" -dependencies = [ - "instant", -] - -[[package]] -name = "fixedbitset" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "279fb028e20b3c4c320317955b77c5e0c9701f05a1d309905d6fc702cdc5053e" - -[[package]] -name = "fslock" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04412b8935272e3a9bae6f48c7bfff74c2911f60525404edfdd28e49884c3bfb" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "fuchsia-cprng" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" - -[[package]] -name = "gcc" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2" - -[[package]] -name = "generic-array" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "wasi", -] - -[[package]] -name = "glob" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" - -[[package]] -name = "half" -version = "1.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eabb4a44450da02c90444cf74558da904edde8fb4e9035a9a6a4e15445af0bd7" - -[[package]] -name = "hashbrown" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" - -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - -[[package]] -name = "indexmap" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" -dependencies = [ - "autocfg", - "hashbrown", - "rustc-rayon", -] - -[[package]] -name = "instant" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "itertools" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" - -[[package]] -name = "itoa" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" - -[[package]] -name = "jobserver" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af25a77299a7f711a01975c35a6a424eb6862092cc2d6c72c4ed6cbc56dfc1fa" -dependencies = [ - "libc", -] - -[[package]] -name = "js-sys" -version = "0.3.57" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "671a26f820db17c2a2750743f1dd03bafd15b98c9f30c7c2628c024c05d73397" -dependencies = [ - "wasm-bindgen", -] - -[[package]] -name = "kclvm-ast" -version = "0.4.5" -dependencies = [ - "kclvm-span", - "rustc_span", - "serde", - "serde_json", -] - -[[package]] -name = "kclvm-config" -version = "0.4.5" -dependencies = [ - "ahash", - "anyhow", - "chrono", - "fslock", - "glob", - "indexmap", - "kclvm-version", - "pathdiff", - "ron", - "rust-crypto", - "serde", - "serde_yaml", - "toml", -] - -[[package]] -name = "kclvm-error" -version = "0.4.5" -dependencies = [ - "annotate-snippets", - "atty", - "indexmap", - "kclvm-runtime", - "kclvm-span", - "rustc_span", - "termcolor", - "termize", - "tracing", -] - -[[package]] -name = "kclvm-lexer" -version = "0.4.5" -dependencies = [ - "kclvm-error", - "rustc_lexer", - "unic-emoji-char", -] - -[[package]] -name = "kclvm-macros" -version = "0.4.5" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "kclvm-parser" -version = "0.4.5" -dependencies = [ - "bstr", - "either", - "enquote", - "kclvm-ast", - "kclvm-config", - "kclvm-error", - "kclvm-lexer", - "kclvm-runtime", - "kclvm-sema", - "kclvm-span", - "num-bigint", - "rustc_data_structures", - "rustc_lexer", - "rustc_span", - "serde", - "serde_json", - "tracing", - "unicode_names2", -] - -[[package]] -name = "kclvm-runtime" -version = "0.4.5" -dependencies = [ - "ahash", - "base64", - "bstr", - "chrono", - "fancy-regex", - "indexmap", - "itertools", - "kclvm_runtime_internal_macros", - "libc", - "md5", - "num-integer", - "phf", - "regex", - "serde", - "serde_json", - "serde_yaml", - "sha1", - "sha2 0.9.9", - "unic-ucd-bidi", - "unic-ucd-category", - "unicode-casing", -] - -[[package]] -name = "kclvm-sema" -version = "0.4.5" -dependencies = [ - "ahash", - "bit-set", - "bitflags", - "criterion", - "fancy-regex", - "indexmap", - "kclvm-ast", - "kclvm-error", - "kclvm-parser", - "kclvm-runtime", - "kclvm-span", - "once_cell", - "petgraph", - "phf", - "unicode_names2", -] - -[[package]] -name = "kclvm-span" -version = "0.4.5" -dependencies = [ - "kclvm-macros", - "rustc_span", - "scoped-tls", -] - -[[package]] -name = "kclvm-version" -version = "0.4.5" - -[[package]] -name = "kclvm_runtime_internal_macros" -version = "0.4.5" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.123" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb691a747a7ab48abc15c5b42066eaafde10dc427e3b6ee2a1cf43db04c763bd" - -[[package]] -name = "linked-hash-map" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3" - -[[package]] -name = "lock_api" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" -dependencies = [ - "autocfg", - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6389c490849ff5bc16be905ae24bc913a9c8892e19b2341dbc175e14c341c2b8" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "matches" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" - -[[package]] -name = "md-5" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "658646b21e0b72f7866c7038ab086d3d5e1cd6271f060fd37defb241949d0582" -dependencies = [ - "digest 0.10.3", -] - -[[package]] -name = "md5" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" - -[[package]] -name = "memchr" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" - -[[package]] -name = "memmap2" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "723e3ebdcdc5c023db1df315364573789f8857c11b631a2fdfad7c00f5c046b4" -dependencies = [ - "libc", -] - -[[package]] -name = "memoffset" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num-bigint" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f" -dependencies = [ - "autocfg", - "num-integer", - "num-traits", -] - -[[package]] -name = "num-integer" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db" -dependencies = [ - "autocfg", - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_cpus" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "once_cell" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9" - -[[package]] -name = "oorandom" -version = "11.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" - -[[package]] -name = "opaque-debug" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" - -[[package]] -name = "parking_lot" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f5ec2493a61ac0506c0f4199f99070cbe83857b0337006a30f3e6719b8ef58" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "995f667a6c822200b0433ac218e05582f0e2efa1b922a3fd2fbaadc5f87bab37" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "redox_syscall", - "smallvec", - "windows-sys", -] - -[[package]] -name = "pathdiff" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" - -[[package]] -name = "petgraph" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a13a2fa9d0b63e5f22328828741e523766fff0ee9e779316902290dff3f824f" -dependencies = [ - "fixedbitset", - "indexmap", -] - -[[package]] -name = "phf" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2ac8b67553a7ca9457ce0e526948cad581819238f4a9d1ea74545851fa24f37" -dependencies = [ - "phf_macros", - "phf_shared", - "proc-macro-hack", -] - -[[package]] -name = "phf_generator" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43f3220d96e0080cc9ea234978ccd80d904eafb17be31bb0f76daaea6493082" -dependencies = [ - "phf_shared", - "rand 0.8.5", -] - -[[package]] -name = "phf_macros" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b706f5936eb50ed880ae3009395b43ed19db5bff2ebd459c95e7bf013a89ab86" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro-hack", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "phf_shared" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a68318426de33640f02be62b4ae8eb1261be2efbc337b60c54d845bf4484e0d9" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e280fbe77cc62c91527259e9442153f4688736748d24660126286329742b4c6c" - -[[package]] -name = "plotters" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a3fd9ec30b9749ce28cd91f255d569591cdf937fe280c312143e3c4bad6f2a" -dependencies = [ - "num-traits", - "plotters-backend", - "plotters-svg", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "plotters-backend" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d88417318da0eaf0fdcdb51a0ee6c3bed624333bff8f946733049380be67ac1c" - -[[package]] -name = "plotters-svg" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521fa9638fa597e1dc53e9412a4f9cefb01187ee1f7413076f9e6749e2885ba9" -dependencies = [ - "plotters-backend", -] - -[[package]] -name = "ppv-lite86" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" - -[[package]] -name = "proc-macro-hack" -version = "0.5.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" - -[[package]] -name = "proc-macro2" -version = "1.0.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "psm" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "871372391786ccec00d3c5d3d6608905b3d4db263639cfe075d3b60a736d115a" -dependencies = [ - "cc", -] - -[[package]] -name = "quote" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rand" -version = "0.3.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64ac302d8f83c0c1974bf758f6b041c6c8ada916fbb44a609158ca8b064cc76c" -dependencies = [ - "libc", - "rand 0.4.6", -] - -[[package]] -name = "rand" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293" -dependencies = [ - "fuchsia-cprng", - "libc", - "rand_core 0.3.1", - "rdrand", - "winapi", -] - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha", - "rand_core 0.6.3", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.3", -] - -[[package]] -name = "rand_core" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" -dependencies = [ - "rand_core 0.4.2", -] - -[[package]] -name = "rand_core" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" - -[[package]] -name = "rand_core" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" -dependencies = [ - "getrandom", -] - -[[package]] -name = "rayon" -version = "1.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd249e82c21598a9a426a4e00dd7adc1d640b22445ec8545feef801d1a74c221" -dependencies = [ - "autocfg", - "crossbeam-deque", - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f51245e1e62e1f1629cbfec37b5793bbabcaeb90f30e94d2ba03564687353e4" -dependencies = [ - "crossbeam-channel", - "crossbeam-deque", - "crossbeam-utils", - "num_cpus", -] - -[[package]] -name = "rdrand" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" -dependencies = [ - "rand_core 0.3.1", -] - -[[package]] -name = "redox_syscall" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" -dependencies = [ - "bitflags", -] - -[[package]] -name = "regex" -version = "1.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" - -[[package]] -name = "regex-syntax" -version = "0.6.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" - -[[package]] -name = "remove_dir_all" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" -dependencies = [ - "winapi", -] - -[[package]] -name = "ron" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b861ecaade43ac97886a512b360d01d66be9f41f3c61088b42cedf92e03d678" -dependencies = [ - "base64", - "bitflags", - "serde", -] - -[[package]] -name = "rust-crypto" -version = "0.2.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f76d05d3993fd5f4af9434e8e436db163a12a9d40e1a58a726f27a01dfd12a2a" -dependencies = [ - "gcc", - "libc", - "rand 0.3.23", - "rustc-serialize", - "time", -] - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - -[[package]] -name = "rustc-rayon" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9974ab223660e61c1b4e7b43b827379df286736ca988308ce7e16f59f2d89246" -dependencies = [ - "crossbeam-deque", - "either", - "rustc-rayon-core", -] - -[[package]] -name = "rustc-rayon-core" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "564bfd27be8db888d0fa76aa4335e7851aaed0c2c11ad1e93aeb9349f6b88500" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", - "lazy_static", - "num_cpus", -] - -[[package]] -name = "rustc-serialize" -version = "0.3.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda" - -[[package]] -name = "rustc_data_structures" -version = "0.0.0" -dependencies = [ - "arrayvec", - "bitflags", - "cfg-if 0.1.10", - "ena", - "indexmap", - "jobserver", - "libc", - "memmap2", - "parking_lot", - "rustc-hash", - "rustc-rayon", - "rustc-rayon-core", - "stable_deref_trait", - "stacker", - "tempfile", - "tracing", - "winapi", -] - -[[package]] -name = "rustc_lexer" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c86aae0c77166108c01305ee1a36a1e77289d7dc6ca0a3cd91ff4992de2d16a5" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "rustc_span" -version = "0.0.0" -dependencies = [ - "cfg-if 0.1.10", - "md-5", - "rustc_data_structures", - "scoped-tls", - "sha-1", - "sha2 0.10.2", - "tracing", - "unicode-width", -] - -[[package]] -name = "rustc_version" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" -dependencies = [ - "semver", -] - -[[package]] -name = "ryu" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" - -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "scoped-tls" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" - -[[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - -[[package]] -name = "semver" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d65bd28f48be7196d222d95b9243287f48d27aca604e08497513019ff0502cc4" - -[[package]] -name = "serde" -version = "1.0.136" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_cbor" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bef2ebfde456fb76bbcf9f59315333decc4fda0b2b44b420243c11e0f5ec1f5" -dependencies = [ - "half", - "serde", -] - -[[package]] -name = "serde_derive" -version = "1.0.136" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.86" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41feea4228a6f1cd09ec7a3593a682276702cd67b5273544757dae23c096f074" -dependencies = [ - "itoa 1.0.1", - "ryu", - "serde", -] - -[[package]] -name = "serde_yaml" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a521f2940385c165a24ee286aa8599633d162077a54bdcae2a6fd5a7bfa7a0" -dependencies = [ - "indexmap", - "ryu", - "serde", - "yaml-rust", -] - -[[package]] -name = "sha-1" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.3", -] - -[[package]] -name = "sha1" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" -dependencies = [ - "sha1_smol", -] - -[[package]] -name = "sha1_smol" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" - -[[package]] -name = "sha2" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.9.0", - "opaque-debug", -] - -[[package]] -name = "sha2" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.3", -] - -[[package]] -name = "siphasher" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bd3e3206899af3f8b12af284fafc038cc1dc2b41d1b89dd17297221c5d225de" - -[[package]] -name = "smallvec" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83" - -[[package]] -name = "stable_deref_trait" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" - -[[package]] -name = "stacker" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90939d5171a4420b3ff5fbc8954d641e7377335454c259dcb80786f3f21dc9b4" -dependencies = [ - "cc", - "cfg-if 1.0.0", - "libc", - "psm", - "winapi", -] - -[[package]] -name = "syn" -version = "1.0.91" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "synstructure" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "unicode-xid", -] - -[[package]] -name = "tempfile" -version = "3.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" -dependencies = [ - "cfg-if 1.0.0", - "fastrand", - "libc", - "redox_syscall", - "remove_dir_all", - "winapi", -] - -[[package]] -name = "termcolor" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "termize" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1706be6b564323ce7092f5f7e6b118a14c8ef7ed0e69c8c5329c914a9f101295" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "textwrap" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" -dependencies = [ - "unicode-width", -] - -[[package]] -name = "thiserror" -version = "1.0.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "854babe52e4df1653706b98fcfc05843010039b406875930a70e4d9644e5c417" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "time" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" -dependencies = [ - "libc", - "wasi", - "winapi", -] - -[[package]] -name = "tinytemplate" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "toml" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" -dependencies = [ - "serde", -] - -[[package]] -name = "tracing" -version = "0.1.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80b9fa4360528139bc96100c160b7ae879f5567f49f1782b0b02035b0358ebf3" -dependencies = [ - "cfg-if 1.0.0", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e65ce065b4b5c53e73bb28912318cb8c9e9ad3921f1d669eb0e68b4c8143a2b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tracing-core" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dfce9f3241b150f36e8e54bb561a742d5daa1a47b5dd9a5ce369fd4a4db2210" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "typenum" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" - -[[package]] -name = "unic-char-property" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" -dependencies = [ - "unic-char-range", -] - -[[package]] -name = "unic-char-range" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" - -[[package]] -name = "unic-common" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" - -[[package]] -name = "unic-emoji-char" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b07221e68897210270a38bde4babb655869637af0f69407f96053a34f76494d" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-bidi" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1d568b51222484e1f8209ce48caa6b430bf352962b877d592c29ab31fb53d8c" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-category" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b8d4591f5fcfe1bd4453baaf803c40e1b1e69ff8455c47620440b46efef91c0" -dependencies = [ - "matches", - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-version" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" -dependencies = [ - "unic-common", -] - -[[package]] -name = "unicode-casing" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "623f59e6af2a98bdafeb93fa277ac8e1e40440973001ca15cf4ae1541cd16d56" - -[[package]] -name = "unicode-width" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" - -[[package]] -name = "unicode-xid" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" - -[[package]] -name = "unicode_names2" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87d6678d7916394abad0d4b19df4d3802e1fd84abd7d701f39b75ee71b9e8cf1" - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "walkdir" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "808cf2735cd4b6866113f648b791c6adc5714537bc222d9347bb203386ffda56" -dependencies = [ - "same-file", - "winapi", - "winapi-util", -] - -[[package]] -name = "wasi" -version = "0.10.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" - -[[package]] -name = "wasm-bindgen" -version = "0.2.80" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27370197c907c55e3f1a9fbe26f44e937fe6451368324e009cba39e139dc08ad" -dependencies = [ - "cfg-if 1.0.0", - "wasm-bindgen-macro", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.80" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53e04185bfa3a779273da532f5025e33398409573f348985af9a1cbf3774d3f4" -dependencies = [ - "bumpalo", - "lazy_static", - "log", - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.80" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17cae7ff784d7e83a2fe7611cfe766ecf034111b49deb850a3dc7699c08251f5" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.80" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99ec0dc7a4756fffc231aab1b9f2f578d23cd391390ab27f952ae0c9b3ece20b" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-backend", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.80" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d554b7f530dee5964d9a9468d95c1f8b8acae4f282807e7d27d4b03099a46744" - -[[package]] -name = "web-sys" -version = "0.3.57" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b17e741662c70c8bd24ac5c5b18de314a2c26c32bf8346ee1e6f53de919c283" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" -dependencies = [ - "winapi", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-sys" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5acdd78cb4ba54c0045ac14f62d8f94a03d10047904ae2a40afa1e99d8f70825" -dependencies = [ - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17cffbe740121affb56fad0fc0e421804adf0ae00891205213b5cecd30db881d" - -[[package]] -name = "windows_i686_gnu" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2564fde759adb79129d9b4f54be42b32c89970c18ebf93124ca8870a498688ed" - -[[package]] -name = "windows_i686_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cd9d32ba70453522332c14d38814bceeb747d80b3958676007acadd7e166956" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfce6deae227ee8d356d19effc141a509cc503dfd1f850622ec4b0f84428e1f4" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d19538ccc21819d01deaf88d6a17eae6596a12e9aafdbb97916fb49896d89de9" - -[[package]] -name = "yaml-rust" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" -dependencies = [ - "linked-hash-map", -] diff --git a/kclvm/sema/Cargo.toml b/kclvm/sema/Cargo.toml deleted file mode 100644 index 6f887c33e..000000000 --- a/kclvm/sema/Cargo.toml +++ /dev/null @@ -1,43 +0,0 @@ -[package] -name = "kclvm-sema" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -serde_json = "1.0" -serde = { version = "1", features = ["derive"] } -generational-arena = "0.2.9" -phf = { version = "0.9", features = ["macros"] } -bit-set = "0.5.0" -bitflags = "1.2.1" -once_cell = "1.5.2" -fancy-regex = "0.7.1" -unicode_names2 = "0.4" -petgraph = "0.6.0" -anyhow = "1.0" -regex = "1.7.0" -lazy_static = "1.4.0" - -kclvm-primitives = { path = "../primitives" } -kclvm-ast = { path = "../ast" } -kclvm-ast-pretty = { path = "../ast_pretty" } -kclvm-runtime = { path = "../runtime" } -kclvm-error = { path = "../error" } -kclvm-span = { path = "../span" } -kclvm-utils = { path = "../utils" } -compiler_base_span = "0.1.2" -compiler_base_session = "0.1.3" -compiler_base_macros = "0.1.1" -compiler_base_error = "0.1.6" -suggestions = "0.1.1" -parking_lot = { version = "0.12.0", default-features = false } - -[dev-dependencies] -kclvm-parser = { path = "../parser" } -criterion = "0.5" - -[[bench]] -name = "my_benchmark" -harness = false diff --git a/kclvm/sema/src/advanced_resolver/mod.rs b/kclvm/sema/src/advanced_resolver/mod.rs deleted file mode 100644 index 96a51577d..000000000 --- a/kclvm/sema/src/advanced_resolver/mod.rs +++ /dev/null @@ -1,1557 +0,0 @@ -/* - - core::Namer basic_resolver - │ │ - ▼ ▼ - ┌─────────────────────┐ ┌─────────────────────┐ - │ core::GlobalState │ │ ast_node_type_map │ - └─────────────────────┘ └─────────────────────┘ - │ │ - ▼ ▼ - ┌──────────────────────────────────────────────────────────────────────────────┐ - │ advanced_resolver │ - ├──────────────────────────────────────────────────────────────────────────────┤ - │ ┌─────────────────┐ │ - │ │ ast::Expression │ │ - │ └─────────────────┘ │ - │ │ │ - │ │ resolve_local_value │ - │ ▼ │ - │ ┌─────────────────┐ │ - │ │ ast::Expression │ │ - │ └─────────────────┘ │ - │ │ │ - │ │ resolve_symbol_ref (map Expression to DefinitionSymbols) | - │ ▼ │ - │ ┌─────────────────┐ │ - │ │ ast::Expression │ │ - │ └─────────────────┘ │ - └──────────────────────────────────────────────────────────────────────────────┘ - │ - ▼ build_sema_db (collect symbol locs and analyse scope) - ┌─────────────────────┐ - │ core::GlobalState │ - └─────────────────────┘ -*/ - -use std::{cell::RefCell, rc::Rc}; - -use kclvm_error::Position; -use kclvm_primitives::IndexSet; - -use crate::{ - core::{ - global_state::GlobalState, - package::ModuleInfo, - scope::{LocalSymbolScope, LocalSymbolScopeKind, RootSymbolScope, ScopeKind, ScopeRef}, - symbol::SymbolRef, - }, - resolver::scope::{NodeKey, NodeTyMap}, -}; - -use kclvm_ast::ast::AstIndex; -use kclvm_ast::ast::Program; -use kclvm_ast::walker::MutSelfTypedResultWalker; -mod node; - -/// AdvancedResolver mainly does two tasks: -/// 1: Traverse AST to parse LocalSymbol and store it in GlobalState, while storing the parsed type in Symbol -/// 2: Establish a mapping between expressions and SymbolRef, specifically injecting symbol information into AST -/// -/// After the work of the advanced resolver is completed, the GlobalState will build the whole semantic database, -/// so that toolchain can query semantic information about the AST -pub struct AdvancedResolver<'ctx> { - pub(crate) ctx: Context<'ctx>, - pub(crate) gs: &'ctx mut GlobalState, -} - -pub struct Context<'ctx> { - pub program: &'ctx Program, - node_ty_map: Rc>, - scopes: Vec, - current_pkgpath: Option, - current_filename: Option, - schema_symbol_stack: Vec>, - start_pos: Position, - end_pos: Position, - cur_node: AstIndex, - - // whether the identifier currently being visited may be a definition - // it will only be true when visiting a l-value or parameter, - // which means advanced resolver will will create the corresponding - // ValueSymbol instead of an UnresolvedSymbol - maybe_def: bool, - // whether in schema config right value, affect lookup def - in_config_r_value: bool, - - is_type_expr: bool, -} - -impl<'ctx> Context<'ctx> { - pub fn get_node_key(&self, id: &AstIndex) -> NodeKey { - NodeKey { - pkgpath: self.current_pkgpath.clone().unwrap(), - id: id.clone(), - } - } -} - -impl<'ctx> AdvancedResolver<'ctx> { - pub fn resolve_program( - program: &'ctx Program, - gs: &'ctx mut GlobalState, - node_ty_map: Rc>, - ) -> anyhow::Result<()> { - let mut advanced_resolver = Self { - gs, - ctx: Context { - program, - node_ty_map, - scopes: vec![], - current_filename: None, - current_pkgpath: None, - schema_symbol_stack: vec![], - start_pos: Position::dummy_pos(), - end_pos: Position::dummy_pos(), - cur_node: AstIndex::default(), - maybe_def: false, - in_config_r_value: false, - is_type_expr: false, - }, - }; - // Scan all scehma symbol - for (name, modules) in advanced_resolver.ctx.program.pkgs.iter() { - advanced_resolver.scan_schemas(name, modules)?; - } - - for (name, modules) in advanced_resolver.ctx.program.pkgs.iter() { - advanced_resolver.walk_pkg(name, modules)?; - } - - advanced_resolver.gs.build_sema_db(); - advanced_resolver.gs.new_or_invalidate_pkgs.clear(); - Ok(()) - } - - fn scan_schemas(&mut self, name: &String, modules: &Vec) -> anyhow::Result<()> { - if !self.gs.new_or_invalidate_pkgs.contains(name) { - return Ok(()); - } - self.ctx.current_pkgpath = Some(name.clone()); - if let Some(pkg_info) = self.gs.get_packages().get_package_info(name) { - if modules.is_empty() { - return Ok(()); - } - if !self.ctx.scopes.is_empty() { - self.ctx.scopes.clear(); - } - - self.enter_root_scope( - name.clone(), - pkg_info.pkg_filepath.clone(), - pkg_info.kfile_paths.clone(), - ); - - let modules = self.ctx.program.get_modules_for_pkg(name); - for module in modules.iter() { - let module = module.read().expect("Failed to acquire module lock"); - self.ctx.current_filename = Some(module.filename.clone()); - self.walk_module_schemas(&module)?; - } - self.leave_scope() - } - Ok(()) - } - - fn walk_pkg(&mut self, name: &String, modules: &Vec) -> anyhow::Result<()> { - if !self.gs.new_or_invalidate_pkgs.contains(name) { - return Ok(()); - } - self.ctx.current_pkgpath = Some(name.clone()); - if let Some(_) = self.gs.get_packages().get_package_info(name) { - if modules.is_empty() { - return Ok(()); - } - if !self.ctx.scopes.is_empty() { - self.ctx.scopes.clear(); - } - - let scope_ref = self - .gs - .get_scopes_mut() - .get_root_scope(name.to_string()) - .unwrap(); - - self.ctx.scopes.push(scope_ref); - let modules = self.ctx.program.get_modules_for_pkg(name); - for module in modules.iter() { - let module = module.read().expect("Failed to acquire module lock"); - self.ctx.current_filename = Some(module.filename.clone()); - self.walk_module(&module)?; - } - self.leave_scope() - } - Ok(()) - } - - fn enter_root_scope( - &mut self, - pkgpath: String, - filename: String, - kfile_paths: IndexSet, - ) { - let package_ref = self - .gs - .get_symbols_mut() - .get_symbol_by_fully_qualified_name(&pkgpath) - .unwrap(); - - let root_scope = RootSymbolScope::new(pkgpath, filename, package_ref, kfile_paths); - let scope_ref = self.gs.get_scopes_mut().alloc_root_scope(root_scope); - self.ctx.scopes.push(scope_ref); - } - - fn enter_local_scope( - &mut self, - filepath: &str, - start: Position, - end: Position, - kind: LocalSymbolScopeKind, - ) { - let parent = *self.ctx.scopes.last().unwrap(); - let local_scope = LocalSymbolScope::new(parent, start, end, kind); - let scope_ref = self.gs.get_scopes_mut().alloc_local_scope(local_scope); - - match parent.get_kind() { - ScopeKind::Root => { - self.gs - .get_scopes_mut() - .roots - .get_mut(parent.get_id()) - .unwrap() - .add_child(filepath, scope_ref); - } - ScopeKind::Local => { - self.gs - .get_scopes_mut() - .locals - .get_mut(parent.get_id()) - .unwrap() - .add_child(scope_ref); - } - } - self.ctx.scopes.push(scope_ref); - } - - fn enter_schema_def_scope( - &mut self, - name: &str, - filepath: &str, - start: Position, - end: Position, - kind: LocalSymbolScopeKind, - ) { - let parent = *self.ctx.scopes.last().unwrap(); - let local_scope = LocalSymbolScope::new(parent, start, end, kind); - let pkg_path = self.ctx.current_pkgpath.clone().unwrap(); - let fqn_name = format!("{pkg_path}.{filepath}.{name}"); - let scope_ref = match self.gs.get_scopes().schema_scope_map.get(&fqn_name) { - Some(scope_ref) => scope_ref.clone(), - None => { - let scope_ref = self.gs.get_scopes_mut().alloc_local_scope(local_scope); - self.gs - .get_scopes_mut() - .schema_scope_map - .insert(fqn_name, scope_ref); - - match parent.get_kind() { - ScopeKind::Root => { - self.gs - .get_scopes_mut() - .roots - .get_mut(parent.get_id()) - .unwrap() - .add_child(filepath, scope_ref); - } - ScopeKind::Local => { - self.gs - .get_scopes_mut() - .locals - .get_mut(parent.get_id()) - .unwrap() - .add_child(scope_ref); - } - } - scope_ref - } - }; - self.ctx.scopes.push(scope_ref); - } - - fn leave_scope(&mut self) { - self.ctx.scopes.pop(); - } - - fn get_current_module_info(&self) -> Option<&ModuleInfo> { - self.gs - .get_packages() - .get_module_info(self.ctx.current_filename.as_ref()?) - } -} - -#[cfg(test)] -mod tests { - use crate::advanced_resolver::AdvancedResolver; - use crate::core::global_state::GlobalState; - use crate::core::symbol::SymbolKind; - use crate::namer::Namer; - use crate::resolver; - - use kclvm_ast::MAIN_PKG; - use kclvm_error::Position; - use kclvm_parser::load_program; - use kclvm_parser::ParseSession; - use std::path::Path; - use std::sync::Arc; - - #[cfg(not(target_os = "windows"))] - fn adjust_canonicalization>(p: P) -> String { - p.as_ref().display().to_string() - } - - #[cfg(target_os = "windows")] - fn adjust_canonicalization>(p: P) -> String { - const VERBATIM_PREFIX: &str = r#"\\?\"#; - let p = p.as_ref().display().to_string(); - if p.starts_with(VERBATIM_PREFIX) { - p[VERBATIM_PREFIX.len()..].to_string() - } else { - p - } - } - - #[allow(unused)] - fn print_symbols_info(gs: &GlobalState) { - let base_path = Path::new(".").canonicalize().unwrap(); - let symbols = gs.get_symbols(); - println!("vec!["); - for (key, val) in gs.sema_db.file_sema_map.iter() { - let key_path = Path::new(key) - .strip_prefix(base_path.clone()) - .unwrap_or_else(|_| Path::new(key)) - .to_str() - .unwrap() - .to_string(); - println!(" (\n \"{}\".to_string().replace(\"/\", &std::path::MAIN_SEPARATOR.to_string()),", key_path); - println!(" vec!["); - for symbol_ref in val.symbols.iter() { - let symbol = symbols.get_symbol(*symbol_ref).unwrap(); - let (start, end) = symbol.get_range(); - println!( - " ({},{},{},{},\"{}\".to_string(),SymbolKind::{:?}),", - start.line, - start.column.unwrap_or(0), - end.line, - end.column.unwrap_or(0), - symbol.get_name(), - symbol_ref.get_kind(), - ); - if let SymbolKind::Unresolved = symbol_ref.get_kind() { - let def_symbol_ref = symbol.get_definition().unwrap(); - let def_symbol = symbols.get_symbol(def_symbol_ref).unwrap(); - let (def_start, def_end) = def_symbol.get_range(); - let def_path = Path::new(&def_start.filename) - .strip_prefix(base_path.clone()) - .unwrap_or_else(|_| Path::new(&def_start.filename)) - .to_str() - .unwrap() - .to_string(); - println!( - " ({},{},{},{},\"{}\".to_string().replace(\"/\", &std::path::MAIN_SEPARATOR.to_string()),SymbolKind::{:?}),", - def_start.line, - def_start.column.unwrap_or(0), - def_end.line, - def_end.column.unwrap_or(0), - def_path, - def_symbol_ref.get_kind(), - ); - } - } - println!(" ],\n ),") - } - println!("]"); - } - - #[test] - fn test_look_up_exact_symbol() { - let sess = Arc::new(ParseSession::default()); - - let path = "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()); - let mut program = load_program(sess.clone(), &[&path], None, None) - .unwrap() - .program; - let mut gs = GlobalState::default(); - Namer::find_symbols(&program, &mut gs); - - let node_ty_map = resolver::resolve_program_with_opts( - &mut program, - resolver::Options { - merge_program: false, - type_erasure: false, - ..Default::default() - }, - None, - ) - .node_ty_map; - AdvancedResolver::resolve_program(&program, &mut gs, node_ty_map).unwrap(); - let base_path = Path::new(".").canonicalize().unwrap(); - // print_symbols_info(&gs); - let except_symbols = vec![ - ( - "src/advanced_resolver/test_data/import_test/e.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - vec![ - (1, 7, 1, 16, "UnionType".to_string(), SymbolKind::Schema), - (2, 4, 2, 5, "a".to_string(), SymbolKind::Attribute), - ], - ), - ( - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - vec![ - (1, 0, 1, 2, "_a".to_string(), SymbolKind::Value), - (2, 7, 2, 11, "Name".to_string(), SymbolKind::Schema), - (3, 4, 3, 13, "firstName".to_string(), SymbolKind::Attribute), - (4, 4, 4, 12, "lastName".to_string(), SymbolKind::Attribute), - (6, 7, 6, 13, "Person".to_string(), SymbolKind::Schema), - (7, 4, 7, 8, "name".to_string(), SymbolKind::Attribute), - (7, 10, 7, 14, "Name".to_string(), SymbolKind::Unresolved), - ( - 2, - 7, - 2, - 11, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Schema, - ), - (8, 4, 8, 7, "age".to_string(), SymbolKind::Attribute), - (10, 0, 10, 7, "_person".to_string(), SymbolKind::Value), - (10, 10, 10, 16, "Person".to_string(), SymbolKind::Unresolved), - ( - 6, - 7, - 6, - 13, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Schema, - ), - (11, 4, 11, 8, "name".to_string(), SymbolKind::Unresolved), - ( - 7, - 4, - 7, - 8, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - (11, 11, 11, 15, "Name".to_string(), SymbolKind::Unresolved), - ( - 2, - 7, - 2, - 11, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Schema, - ), - ( - 12, - 8, - 12, - 17, - "firstName".to_string(), - SymbolKind::Unresolved, - ), - ( - 3, - 4, - 3, - 13, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - ( - 13, - 8, - 13, - 16, - "lastName".to_string(), - SymbolKind::Unresolved, - ), - ( - 4, - 4, - 4, - 12, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - (15, 4, 15, 7, "age".to_string(), SymbolKind::Unresolved), - ( - 8, - 4, - 8, - 7, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - ], - ), - ( - "src/advanced_resolver/test_data/import_test/d.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - vec![ - (1, 7, 1, 13, "Parent".to_string(), SymbolKind::Schema), - (2, 4, 2, 8, "age1".to_string(), SymbolKind::Attribute), - ], - ), - ( - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - vec![ - ( - 1, - 7, - 1, - 20, - "import_test.a".to_string(), - SymbolKind::Unresolved, - ), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/a" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - ( - 2, - 7, - 2, - 20, - "import_test.b".to_string(), - SymbolKind::Unresolved, - ), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/b" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - ( - 3, - 7, - 3, - 20, - "import_test.c".to_string(), - SymbolKind::Unresolved, - ), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/c" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - ( - 4, - 7, - 4, - 20, - "import_test.d".to_string(), - SymbolKind::Unresolved, - ), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/d" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - ( - 5, - 7, - 5, - 20, - "import_test.e".to_string(), - SymbolKind::Unresolved, - ), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/e" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - ( - 6, - 24, - 6, - 25, - "import_test.f".to_string(), - SymbolKind::Unresolved, - ), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/f" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - (7, 7, 7, 10, "pkg".to_string(), SymbolKind::Unresolved), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/pkg" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - (8, 7, 8, 12, "regex".to_string(), SymbolKind::Unresolved), - ( - 1, - 0, - 1, - 0, - "".to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - (10, 7, 10, 11, "Main".to_string(), SymbolKind::Schema), - (10, 12, 10, 13, "d".to_string(), SymbolKind::Unresolved), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/d" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - (10, 14, 10, 20, "Parent".to_string(), SymbolKind::Unresolved), - ( - 1, - 7, - 1, - 13, - "src/advanced_resolver/test_data/import_test/d.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Schema, - ), - (11, 11, 11, 12, "c".to_string(), SymbolKind::Unresolved), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/c" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - ( - 11, - 13, - 11, - 24, - "TestOfMixin".to_string(), - SymbolKind::Unresolved, - ), - ( - 1, - 7, - 1, - 18, - "src/advanced_resolver/test_data/import_test/c.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Schema, - ), - (12, 4, 12, 8, "name".to_string(), SymbolKind::Attribute), - (13, 4, 13, 7, "age".to_string(), SymbolKind::Attribute), - (14, 4, 14, 10, "person".to_string(), SymbolKind::Attribute), - (14, 13, 14, 14, "a".to_string(), SymbolKind::Unresolved), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/a" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - (14, 15, 14, 21, "Person".to_string(), SymbolKind::Unresolved), - ( - 6, - 7, - 6, - 13, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Schema, - ), - ( - 15, - 4, - 15, - 19, - "list_union_type".to_string(), - SymbolKind::Attribute, - ), - (15, 23, 15, 24, "e".to_string(), SymbolKind::Unresolved), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/e" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - ( - 15, - 25, - 15, - 34, - "UnionType".to_string(), - SymbolKind::Unresolved, - ), - ( - 1, - 7, - 1, - 16, - "src/advanced_resolver/test_data/import_test/e.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Schema, - ), - ( - 16, - 4, - 16, - 19, - "dict_union_type".to_string(), - SymbolKind::Attribute, - ), - (16, 23, 16, 24, "g".to_string(), SymbolKind::Unresolved), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/f" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - ( - 16, - 25, - 16, - 34, - "UnionType".to_string(), - SymbolKind::Unresolved, - ), - ( - 1, - 7, - 1, - 16, - "src/advanced_resolver/test_data/import_test/f.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Schema, - ), - (19, 8, 19, 13, "regex".to_string(), SymbolKind::Unresolved), - ( - 1, - 0, - 1, - 0, - "".to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - (19, 14, 19, 19, "match".to_string(), SymbolKind::Unresolved), - ( - 1, - 0, - 1, - 0, - "".to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Function, - ), - (19, 20, 19, 24, "name".to_string(), SymbolKind::Unresolved), - ( - 12, - 4, - 12, - 8, - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - (19, 97, 19, 101, "name".to_string(), SymbolKind::Unresolved), - ( - 12, - 4, - 12, - 8, - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - (21, 3, 21, 4, "a".to_string(), SymbolKind::Unresolved), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/a" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - (21, 5, 21, 7, "_a".to_string(), SymbolKind::Unresolved), - ( - 1, - 0, - 1, - 2, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Value, - ), - (22, 4, 22, 6, "_c".to_string(), SymbolKind::Value), - (23, 5, 23, 6, "a".to_string(), SymbolKind::Unresolved), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/a" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - (23, 7, 23, 9, "_a".to_string(), SymbolKind::Unresolved), - ( - 1, - 0, - 1, - 2, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Value, - ), - (24, 4, 24, 6, "_c".to_string(), SymbolKind::Unresolved), - ( - 22, - 4, - 22, - 6, - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Value, - ), - (26, 4, 26, 6, "_c".to_string(), SymbolKind::Unresolved), - ( - 22, - 4, - 22, - 6, - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Value, - ), - (28, 0, 28, 1, "p".to_string(), SymbolKind::Value), - (28, 4, 28, 8, "Main".to_string(), SymbolKind::Unresolved), - ( - 10, - 7, - 10, - 11, - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Schema, - ), - (29, 4, 29, 8, "name".to_string(), SymbolKind::Unresolved), - ( - 12, - 4, - 12, - 8, - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - (29, 11, 29, 12, "a".to_string(), SymbolKind::Unresolved), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/a" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - ( - 29, - 13, - 29, - 20, - "_person".to_string(), - SymbolKind::Unresolved, - ), - ( - 10, - 0, - 10, - 7, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Value, - ), - (29, 21, 29, 25, "name".to_string(), SymbolKind::Unresolved), - ( - 7, - 4, - 7, - 8, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - ( - 29, - 26, - 29, - 35, - "firstName".to_string(), - SymbolKind::Unresolved, - ), - ( - 3, - 4, - 3, - 13, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - (29, 45, 29, 46, "a".to_string(), SymbolKind::Unresolved), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/a" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - ( - 29, - 47, - 29, - 54, - "_person".to_string(), - SymbolKind::Unresolved, - ), - ( - 10, - 0, - 10, - 7, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Value, - ), - (29, 56, 29, 60, "name".to_string(), SymbolKind::Unresolved), - ( - 7, - 4, - 7, - 8, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - ( - 29, - 61, - 29, - 69, - "lastName".to_string(), - SymbolKind::Unresolved, - ), - ( - 4, - 4, - 4, - 12, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - (30, 4, 30, 7, "age".to_string(), SymbolKind::Unresolved), - ( - 13, - 4, - 13, - 7, - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - (30, 10, 30, 11, "b".to_string(), SymbolKind::Unresolved), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/b" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - (30, 12, 30, 14, "_b".to_string(), SymbolKind::Unresolved), - ( - 1, - 0, - 1, - 2, - "src/advanced_resolver/test_data/import_test/b.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Value, - ), - (30, 17, 30, 18, "a".to_string(), SymbolKind::Unresolved), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/import_test/a" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - ( - 30, - 19, - 30, - 26, - "_person".to_string(), - SymbolKind::Unresolved, - ), - ( - 10, - 0, - 10, - 7, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Value, - ), - (30, 28, 30, 31, "age".to_string(), SymbolKind::Unresolved), - ( - 8, - 4, - 8, - 7, - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - (33, 0, 33, 6, "person".to_string(), SymbolKind::Value), - (33, 9, 33, 12, "pkg".to_string(), SymbolKind::Unresolved), - ( - 0, - 0, - 0, - 0, - "src/advanced_resolver/test_data/pkg" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Package, - ), - (33, 13, 33, 19, "Person".to_string(), SymbolKind::Unresolved), - ( - 4, - 7, - 4, - 13, - "src/advanced_resolver/test_data/pkg/pkg.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Schema, - ), - (34, 4, 34, 8, "name".to_string(), SymbolKind::Unresolved), - ( - 5, - 4, - 5, - 8, - "src/advanced_resolver/test_data/pkg/pkg.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - (34, 9, 34, 13, "name".to_string(), SymbolKind::Unresolved), - ( - 2, - 4, - 2, - 8, - "src/advanced_resolver/test_data/pkg/pkg.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - (37, 0, 37, 1, "x".to_string(), SymbolKind::Value), - (38, 16, 38, 17, "x".to_string(), SymbolKind::Unresolved), - ( - 37, - 0, - 37, - 1, - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Value, - ), - ], - ), - ( - "src/advanced_resolver/test_data/import_test/f.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - vec![ - (1, 7, 1, 16, "UnionType".to_string(), SymbolKind::Schema), - (2, 4, 2, 5, "b".to_string(), SymbolKind::Attribute), - ], - ), - ( - "src/advanced_resolver/test_data/import_test/c.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - vec![ - (1, 7, 1, 18, "TestOfMixin".to_string(), SymbolKind::Schema), - (2, 4, 2, 7, "age".to_string(), SymbolKind::Attribute), - ], - ), - ( - "src/advanced_resolver/test_data/pkg/pkg.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - vec![ - (1, 7, 1, 11, "Name".to_string(), SymbolKind::Schema), - (2, 4, 2, 8, "name".to_string(), SymbolKind::Attribute), - (4, 7, 4, 13, "Person".to_string(), SymbolKind::Schema), - (5, 4, 5, 8, "name".to_string(), SymbolKind::Attribute), - (5, 10, 5, 14, "Name".to_string(), SymbolKind::Unresolved), - ( - 1, - 7, - 1, - 11, - "src/advanced_resolver/test_data/pkg/pkg.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Schema, - ), - (5, 17, 5, 21, "Name".to_string(), SymbolKind::Unresolved), - ( - 1, - 7, - 1, - 11, - "src/advanced_resolver/test_data/pkg/pkg.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Schema, - ), - (5, 23, 5, 27, "name".to_string(), SymbolKind::Unresolved), - ( - 2, - 4, - 2, - 8, - "src/advanced_resolver/test_data/pkg/pkg.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - SymbolKind::Attribute, - ), - ], - ), - ( - "src/advanced_resolver/test_data/import_test/b.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - vec![(1, 0, 1, 2, "_b".to_string(), SymbolKind::Value)], - ), - ]; - let mut skip_def_info = false; - for (filepath, symbols) in except_symbols.iter() { - let abs_filepath = adjust_canonicalization(base_path.join(filepath)); - // symbols will be sorted according to their position in the file - // now we check all symbols - for (index, symbol_info) in symbols.iter().enumerate() { - if skip_def_info { - skip_def_info = false; - continue; - } - let (start_line, start_col, end_line, end_col, name, kind) = symbol_info; - if abs_filepath.is_empty() { - continue; - } - // test look up symbols - let inner_pos = Position { - filename: abs_filepath.clone(), - line: (start_line + end_line) / 2, - column: Some((start_col + end_col) / 2), - }; - let looked_symbol_ref = gs.look_up_exact_symbol(&inner_pos).unwrap(); - let looked_symbol = gs.get_symbols().get_symbol(looked_symbol_ref).unwrap(); - let (start, end) = looked_symbol.get_range(); - // test symbol basic infomation - assert_eq!(start.filename, abs_filepath); - assert_eq!(start.line, *start_line); - assert_eq!(start.column.unwrap_or(0), *start_col); - assert_eq!(end.line, *end_line); - assert_eq!(end.column.unwrap_or(0), *end_col); - assert_eq!(*name, looked_symbol.get_name()); - assert_eq!(looked_symbol_ref.get_kind(), *kind); - - // test find def - if SymbolKind::Unresolved == looked_symbol_ref.get_kind() { - let (start_line, start_col, end_line, end_col, path, kind) = - symbols.get(index + 1).unwrap(); - let def_ref = looked_symbol.get_definition().unwrap(); - let def = gs.get_symbols().get_symbol(def_ref).unwrap(); - let (start, end) = def.get_range(); - let def_filepath = adjust_canonicalization(base_path.join(path)); - assert_eq!(start.line, *start_line); - assert_eq!(start.column.unwrap_or(0), *start_col); - assert_eq!(end.line, *end_line); - assert_eq!(end.column.unwrap_or(0), *end_col); - if !path.is_empty() { - assert_eq!(start.filename, def_filepath); - } - assert_eq!(def_ref.get_kind(), *kind); - skip_def_info = true; - } - } - } - } - - #[test] - fn test_look_up_cloest_symbol() { - let sess = Arc::new(ParseSession::default()); - - let path = "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()); - let mut program = load_program(sess.clone(), &[&path], None, None) - .unwrap() - .program; - let mut gs = GlobalState::default(); - Namer::find_symbols(&program, &mut gs); - let node_ty_map = resolver::resolve_program(&mut program).node_ty_map; - AdvancedResolver::resolve_program(&program, &mut gs, node_ty_map).unwrap(); - let base_path = Path::new(".").canonicalize().unwrap(); - - let test_cases = vec![ - ( - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - 19_u64, - 25_u64, - Some((19, 20, 19, 24, "name".to_string(), SymbolKind::Unresolved)), - ), - ( - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - 32_u64, - 7_u64, - Some((28, 4, 28, 8, "Main".to_string(), SymbolKind::Unresolved)), - ), - ( - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - 35_u64, - 5_u64, - Some((33, 13, 33, 19, "Person".to_string(), SymbolKind::Unresolved)), - ), - ( - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - 28_u64, - 30_u64, - None, - ), - ]; - - for (filepath, line, col, symbol_info) in test_cases.iter() { - let abs_scope_file_path = adjust_canonicalization(base_path.join(filepath)); - let symbol_ref = gs.look_up_closest_symbol(&Position { - filename: abs_scope_file_path.clone(), - line: *line, - column: Some(*col), - }); - - match symbol_info { - Some((start_line, start_col, end_line, end_col, name, kind)) => { - let symbol_ref = symbol_ref.unwrap(); - let symbol = gs.get_symbols().get_symbol(symbol_ref).unwrap(); - - let (start, end) = symbol.get_range(); - assert_eq!(start.line, *start_line); - assert_eq!(start.column.unwrap_or(0), *start_col); - assert_eq!(end.line, *end_line); - assert_eq!(end.column.unwrap_or(0), *end_col); - assert_eq!(*name, symbol.get_name()); - assert_eq!(symbol_ref.get_kind(), *kind); - } - None => assert!(symbol_ref.is_none()), - } - } - } - - #[test] - fn test_look_up_scope() { - let sess = Arc::new(ParseSession::default()); - - let path = "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()); - let mut program = load_program(sess.clone(), &[&path], None, None) - .unwrap() - .program; - let mut gs = GlobalState::default(); - Namer::find_symbols(&program, &mut gs); - let node_ty_map = resolver::resolve_program(&mut program).node_ty_map; - AdvancedResolver::resolve_program(&program, &mut gs, node_ty_map).unwrap(); - let base_path = Path::new(".").canonicalize().unwrap(); - - let scope_test_cases = vec![ - // __main__.Main schema stmt scope - ( - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - 17_u64, - 26_u64, - 10_usize, - ), - // __main__.Main schema expr scope - ( - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - 30, - 6, - 6, - ), - // __main__.Main schema config entry value scope - ( - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - 30, - 20, - 7, - ), - // pkg.Person schema expr scope - ( - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - 33, - 21, - 1, - ), - // pkg.Person schema config entry value scope - ( - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - 34, - 17, - 6, - ), - // __main__ package scope - ( - "src/advanced_resolver/test_data/schema_symbols.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - 36, - 31, - 5, - ), - // import_test.a.Person expr scope - ( - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - 15, - 11, - 6, - ), - // import_test.a.Name expr scope - ( - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - 12, - 5, - 2, - ), - // import_test.a.Name config entry value scope - ( - "src/advanced_resolver/test_data/import_test/a.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()), - 12, - 21, - 8, - ), - ]; - - for (filepath, line, col, def_num) in scope_test_cases.iter() { - let abs_scope_file_path = adjust_canonicalization(base_path.join(filepath)); - let pos = Position { - filename: abs_scope_file_path.clone(), - line: *line, - column: Some(*col), - }; - let scope_ref = gs.look_up_scope(&pos).unwrap(); - let all_defs = gs.get_all_defs_in_scope(scope_ref, &pos).unwrap(); - assert_eq!(all_defs.len(), *def_num) - } - } - - #[test] - fn test_schema_def_scope() { - let sess = Arc::new(ParseSession::default()); - - let path = "src/advanced_resolver/test_data/schema_def_scope.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()); - let mut program = load_program(sess.clone(), &[&path], None, None) - .unwrap() - .program; - let mut gs = GlobalState::default(); - Namer::find_symbols(&program, &mut gs); - let node_ty_map = resolver::resolve_program(&mut program).node_ty_map; - AdvancedResolver::resolve_program(&program, &mut gs, node_ty_map).unwrap(); - let main_pkg_root_scope = gs - .get_scopes() - .get_root_scope(MAIN_PKG.to_string()) - .unwrap(); - assert_eq!( - gs.get_scopes() - .get_scope(&main_pkg_root_scope) - .unwrap() - .get_children() - .len(), - 2 - ); - } - - #[test] - fn test_schema_circle_dep() { - let sess = Arc::new(ParseSession::default()); - - let path = "src/advanced_resolver/test_data/circle_dep/circle_dep.k" - .to_string() - .replace("/", &std::path::MAIN_SEPARATOR.to_string()); - let mut program = load_program(sess.clone(), &[&path], None, None) - .unwrap() - .program; - let mut gs = GlobalState::default(); - Namer::find_symbols(&program, &mut gs); - let node_ty_map = resolver::resolve_program(&mut program).node_ty_map; - AdvancedResolver::resolve_program(&program, &mut gs, node_ty_map).unwrap(); - } -} diff --git a/kclvm/sema/src/advanced_resolver/node.rs b/kclvm/sema/src/advanced_resolver/node.rs deleted file mode 100644 index 028ecd371..000000000 --- a/kclvm/sema/src/advanced_resolver/node.rs +++ /dev/null @@ -1,2044 +0,0 @@ -use anyhow::anyhow; -use std::sync::Arc; - -use kclvm_ast::ast::{self, Stmt}; -use kclvm_ast::pos::GetPos; -use kclvm_ast::walker::MutSelfTypedResultWalker; -use kclvm_error::{diagnostic::Range, Position}; -use kclvm_primitives::{DefaultHashBuilder, IndexMap}; - -use crate::core::symbol::Symbol; -use crate::{ - core::{ - scope::{ConfigScopeContext, LocalSymbolScopeKind}, - symbol::{ - CommentOrDocSymbol, DecoratorSymbol, ExpressionSymbol, SymbolHint, SymbolHintKind, - SymbolRef, SymbolSemanticInfo, UnresolvedSymbol, ValueSymbol, - }, - }, - ty::{Parameter, Type, TypeKind, ANY_TYPE_STR, SCHEMA_MEMBER_FUNCTIONS}, -}; - -use super::AdvancedResolver; - -type ResolvedResult = anyhow::Result>; - -impl<'ctx> MutSelfTypedResultWalker<'ctx> for AdvancedResolver<'_> { - type Result = anyhow::Result>; - - fn walk_module(&mut self, module: &'ctx ast::Module) -> Self::Result { - for stmt in module.body.iter() { - self.stmt(&stmt)?; - } - for comment in module.comments.iter() { - let (start, end) = comment.get_span_pos(); - self.ctx.start_pos = start; - self.ctx.end_pos = end; - self.ctx.cur_node = comment.id.clone(); - self.walk_comment(&comment.node)?; - } - Ok(None) - } - - fn walk_expr_stmt(&mut self, expr_stmt: &'ctx ast::ExprStmt) -> Self::Result { - for expr in expr_stmt.exprs.iter() { - self.expr(&expr)?; - } - Ok(None) - } - - fn walk_unification_stmt( - &mut self, - unification_stmt: &'ctx ast::UnificationStmt, - ) -> Self::Result { - self.ctx.maybe_def = true; - self.walk_identifier_expr(&unification_stmt.target)?; - // Set schema attribute if it is in the schema stmt. - if let Some(parent_scope) = self.ctx.scopes.last() { - if let Some(parent_scope) = self.gs.get_scopes().get_scope(&parent_scope) { - let mut doc = None; - if let Some(schema_symbol) = parent_scope.get_owner() { - let schema_symbol = self - .gs - .get_symbols() - .get_symbol(schema_symbol) - .ok_or(anyhow!("schema_symbol not found1"))?; - if let Some(schema_ty) = schema_symbol.get_sema_info().ty.clone() { - if !unification_stmt.target.node.names.is_empty() { - let schema_ty = schema_ty.into_schema_type(); - if let Some(attr) = schema_ty - .attrs - .get(&unification_stmt.target.node.names[0].node) - { - doc = attr.doc.clone() - } - let attr_symbol = self - .gs - .get_symbols() - .symbols_info - .node_symbol_map - .get( - &self - .ctx - .get_node_key(&unification_stmt.target.node.names[0].id), - ) - .cloned(); - if let Some(attr_symbol) = attr_symbol { - if let Some(symbol) = self - .gs - .get_symbols_mut() - .attributes - .get_mut(attr_symbol.get_id()) - { - symbol.sema_info = SymbolSemanticInfo { - ty: self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key( - &unification_stmt.target.node.names[0].id, - )) - .map(|ty| ty.clone()), - doc, - }; - } - } - } - } - }; - } - } - self.ctx.maybe_def = false; - self.walk_schema_expr(&unification_stmt.value.node)?; - Ok(None) - } - - fn walk_type_alias_stmt(&mut self, type_alias_stmt: &'ctx ast::TypeAliasStmt) -> Self::Result { - let alias_symbol = self - .gs - .get_symbols() - .get_symbol_by_fully_qualified_name( - &(self.ctx.current_pkgpath.as_ref().unwrap().clone() - + "." - + &type_alias_stmt.type_name.node.get_name()), - ) - .ok_or(anyhow!("alias_symbol not found"))?; - if let Some(symbol) = self - .gs - .get_symbols_mut() - .type_aliases - .get_mut(alias_symbol.get_id()) - { - symbol.sema_info = SymbolSemanticInfo { - ty: self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&type_alias_stmt.type_name.id)) - .map(|ty| ty.clone()), - doc: None, - }; - } - self.walk_type_expr(Some(&type_alias_stmt.ty))?; - Ok(None) - } - - fn walk_assign_stmt(&mut self, assign_stmt: &'ctx ast::AssignStmt) -> Self::Result { - for target in &assign_stmt.targets { - self.ctx.maybe_def = true; - self.walk_target_expr_with_hint(target, assign_stmt.ty.is_none())?; - self.ctx.maybe_def = false; - } - self.walk_type_expr(assign_stmt.ty.as_ref().map(|ty| ty.as_ref()))?; - self.expr(&assign_stmt.value)?; - Ok(None) - } - - fn walk_aug_assign_stmt(&mut self, aug_assign_stmt: &'ctx ast::AugAssignStmt) -> Self::Result { - self.walk_target_expr(&aug_assign_stmt.target)?; - self.expr(&aug_assign_stmt.value)?; - Ok(None) - } - - fn walk_assert_stmt(&mut self, assert_stmt: &'ctx ast::AssertStmt) -> Self::Result { - self.expr(&assert_stmt.test)?; - if let Some(if_cond) = &assert_stmt.if_cond { - self.expr(if_cond)?; - } - if let Some(msg) = &assert_stmt.msg { - self.expr(msg)?; - } - Ok(None) - } - - fn walk_if_stmt(&mut self, if_stmt: &'ctx ast::IfStmt) -> Self::Result { - self.expr(&if_stmt.cond)?; - for stmt in if_stmt.body.iter() { - self.stmt(stmt)?; - } - for stmt in if_stmt.orelse.iter() { - self.stmt(stmt)?; - } - Ok(None) - } - - fn walk_import_stmt(&mut self, import_stmt: &'ctx ast::ImportStmt) -> Self::Result { - let ast_id = self.ctx.cur_node.clone(); - let (start_pos, end_pos) = import_stmt - .asname - .clone() - .unwrap_or(import_stmt.path.clone()) - .get_span_pos(); - - let unresolved = UnresolvedSymbol::new( - import_stmt.path.node.clone(), - start_pos, - end_pos, - None, - self.ctx.is_type_expr, - ); - let package_symbol = match self - .gs - .get_symbols() - .get_symbol_by_fully_qualified_name(&import_stmt.path.node) - { - Some(symbol) => symbol, - None => return Ok(None), - }; - let unresolved_ref = self.gs.get_symbols_mut().alloc_unresolved_symbol( - unresolved, - self.ctx.get_node_key(&ast_id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - self.gs - .get_symbols_mut() - .set_def_and_ref(package_symbol, unresolved_ref); - self.gs - .get_symbols_mut() - .symbols_info - .node_symbol_map - .insert(self.ctx.get_node_key(&ast_id), unresolved_ref); - let cur_scope = *self.ctx.scopes.last().unwrap(); - self.gs - .get_scopes_mut() - .add_ref_to_scope(cur_scope, unresolved_ref); - Ok(Some(unresolved_ref)) - } - - fn walk_schema_stmt(&mut self, schema_stmt: &'ctx ast::SchemaStmt) -> Self::Result { - let (start, end) = (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()); - let schema_ty = self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&schema_stmt.name.id)) - .ok_or(anyhow!( - "schema_ty not found when walk schema stmt {:?}", - schema_stmt - ))? - .clone(); - let schema_symbol = self - .gs - .get_symbols() - .get_type_symbol(&schema_ty, self.get_current_module_info()) - .ok_or(anyhow!("schema_symbol not found"))?; - if self - .gs - .get_symbols() - .schemas - .contains(schema_symbol.get_id()) - { - let mut schema_builtin_member = IndexMap::with_hasher(DefaultHashBuilder::default()); - for name in SCHEMA_MEMBER_FUNCTIONS.iter() { - let func_ty = Arc::new(Type::function( - Some(schema_ty.clone()), - Type::list_ref(Type::any_ref()), - &[], - "", - false, - None, - )); - let mut func_value = ValueSymbol::new( - name.to_string(), - Position::dummy_pos(), - Position::dummy_pos(), - Some(schema_symbol), - false, - ); - func_value.sema_info.ty = Some(func_ty); - let func_symbol_ref = self.gs.get_symbols_mut().alloc_value_symbol( - func_value, - self.ctx.get_node_key(&ast::AstIndex::default()), - self.ctx.current_pkgpath.clone().unwrap(), - ); - schema_builtin_member.insert(name.to_string(), func_symbol_ref); - } - self.gs - .get_symbols_mut() - .symbols_info - .schema_builtin_symbols - .insert(schema_symbol, schema_builtin_member); - self.gs - .get_symbols_mut() - .schemas - .get_mut(schema_symbol.get_id()) - .ok_or(anyhow!("schema_symbol not found"))? - .sema_info = SymbolSemanticInfo { - ty: Some(schema_ty.clone()), - doc: schema_stmt.doc.as_ref().map(|doc| doc.node.clone()), - }; - } - - self.resolve_decorator(&schema_stmt.decorators); - - let mut last_end_pos = start.clone(); - - self.enter_schema_def_scope( - &schema_ty.into_schema_type().name, - &self.ctx.current_filename.clone().unwrap(), - start, - end.clone(), - LocalSymbolScopeKind::SchemaDef, - ); - let cur_scope = *self.ctx.scopes.last().unwrap(); - self.gs - .get_scopes_mut() - .set_owner_to_scope(cur_scope, schema_symbol); - if let Some(parent) = &schema_stmt.parent_name { - self.gs - .get_symbols_mut() - .schemas - .get_mut(schema_symbol.get_id()) - .ok_or(anyhow!("schema_symbol not found"))? - .parent_schema = self.walk_identifier_expr(parent)?; - } - if let Some(for_host) = &schema_stmt.for_host_name { - self.gs - .get_symbols_mut() - .schemas - .get_mut(schema_symbol.get_id()) - .ok_or(anyhow!("schema_symbol not found"))? - .for_host = self.walk_identifier_expr(for_host)?; - } - let mut mixins = vec![]; - for mixin in schema_stmt.mixins.iter() { - if let Some(mixin) = self.walk_identifier_expr(mixin)? { - mixins.push(mixin); - } - last_end_pos = mixin.get_end_pos(); - } - self.gs - .get_symbols_mut() - .schemas - .get_mut(schema_symbol.get_id()) - .ok_or(anyhow!("schema_symbol not found"))? - .mixins = mixins; - - if let Some(args) = &schema_stmt.args { - self.walk_arguments(&args.node)?; - last_end_pos = args.get_end_pos(); - } - if let Some(index_signature) = &schema_stmt.index_signature { - if let Some(key_name) = &index_signature.node.key_name { - let (start, end) = key_name.get_span_pos(); - let value = self.gs.get_symbols_mut().alloc_value_symbol( - ValueSymbol::new( - key_name.node.clone(), - start, - end, - Some(schema_symbol), - false, - ), - self.ctx.get_node_key(&index_signature.id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - if let Some(symbol) = self.gs.get_symbols_mut().values.get_mut(value.get_id()) { - symbol.sema_info = SymbolSemanticInfo { - ty: self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&index_signature.id)) - .map(|ty| ty.clone()), - doc: None, - }; - } - - self.gs - .get_scopes_mut() - .add_def_to_scope(cur_scope, key_name.node.clone(), value); - } - self.walk_type_expr(Some(&index_signature.node.value_ty))?; - if let Some(value) = &index_signature.node.value { - self.expr(value)?; - }; - last_end_pos = index_signature.get_end_pos(); - } - - if let Some(doc) = &schema_stmt.doc { - let (start, end) = doc.get_span_pos(); - let comment_symbol = CommentOrDocSymbol::new(start, end, doc.node.clone()); - self.gs.get_symbols_mut().alloc_comment_symbol( - comment_symbol, - self.ctx.get_node_key(&self.ctx.cur_node), - self.ctx.current_pkgpath.clone().unwrap(), - ); - } - - for stmt in schema_stmt.body.iter() { - if let Some(attribute_symbol) = self.stmt(&stmt)? { - let name = self - .gs - .get_symbols() - .get_symbol(attribute_symbol) - .ok_or(anyhow!("attribute_symbol not found"))? - .get_name(); - self.gs - .get_symbols_mut() - .schemas - .get_mut(schema_symbol.get_id()) - .ok_or(anyhow!("schema_symbol not found"))? - .attributes - .insert(name, attribute_symbol); - } - last_end_pos = stmt.get_end_pos(); - } - - let has_check = !schema_stmt.checks.is_empty(); - if has_check { - self.enter_local_scope( - &self.ctx.current_filename.clone().unwrap(), - last_end_pos, - end, - LocalSymbolScopeKind::Check, - ); - } - - for check_expr in schema_stmt.checks.iter() { - self.walk_check_expr(&check_expr.node)?; - } - - if has_check { - self.leave_scope(); - } - self.leave_scope(); - - Ok(Some(schema_symbol)) - } - - fn walk_rule_stmt(&mut self, rule_stmt: &'ctx ast::RuleStmt) -> Self::Result { - let rule_ty = self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&rule_stmt.name.id)) - .ok_or(anyhow!("rule_ty not found"))? - .clone(); - let rule_symbol = self - .gs - .get_symbols() - .get_type_symbol(&rule_ty, self.get_current_module_info()) - .ok_or(anyhow!("rule_symbol not found"))?; - if let Some(symbol) = self - .gs - .get_symbols_mut() - .rules - .get_mut(rule_symbol.get_id()) - { - symbol.sema_info = SymbolSemanticInfo { - ty: self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&rule_stmt.name.id)) - .map(|ty| ty.clone()), - doc: rule_stmt.doc.as_ref().map(|doc| doc.node.clone()), - }; - } - - if let Some(for_host) = &rule_stmt.for_host_name { - self.gs - .get_symbols_mut() - .rules - .get_mut(rule_symbol.get_id()) - .ok_or(anyhow!("rule_symbol not found"))? - .for_host = self.walk_identifier_expr(for_host)?; - } - let mut parent_rules = vec![]; - for parent_rule in rule_stmt.parent_rules.iter() { - parent_rules.push( - self.walk_identifier_expr(parent_rule)? - .ok_or(anyhow!("parent_rule not found"))?, - ); - } - self.gs - .get_symbols_mut() - .rules - .get_mut(rule_symbol.get_id()) - .ok_or(anyhow!("rule_symbol not found"))? - .parent_rules = parent_rules; - self.resolve_decorator(&rule_stmt.decorators); - Ok(Some(rule_symbol)) - } - - fn walk_quant_expr(&mut self, quant_expr: &'ctx ast::QuantExpr) -> Self::Result { - let (start, end) = (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()); - self.expr(&quant_expr.target)?; - self.enter_local_scope( - &self.ctx.current_filename.as_ref().unwrap().clone(), - start, - end, - LocalSymbolScopeKind::Quant, - ); - let cur_scope = *self.ctx.scopes.last().unwrap(); - for target in quant_expr.variables.iter() { - if target.node.names.is_empty() { - continue; - } - let name = target.node.get_name(); - let (start_pos, end_pos): Range = target.get_span_pos(); - let ast_id = if target.node.names.is_empty() { - &target.id - } else { - &target.node.names.last().unwrap().id - }; - let value = self.gs.get_symbols_mut().alloc_value_symbol( - ValueSymbol::new(name.clone(), start_pos, end_pos.clone(), None, false), - self.ctx.get_node_key(&ast_id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - self.gs - .get_scopes_mut() - .add_def_to_scope(cur_scope, name, value); - let symbols = self.gs.get_symbols_mut(); - let ty = match symbols.values.get_mut(value.get_id()) { - Some(symbol) => { - let ty = self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(ast_id)) - .map(|ty| ty.clone()); - symbol.sema_info = SymbolSemanticInfo { - ty: ty.clone(), - doc: None, - }; - ty - } - None => None, - }; - if let Some(ty) = ty { - symbols.alloc_hint( - SymbolHint { - kind: SymbolHintKind::TypeHint(ty.ty_hint()), - pos: end_pos, - }, - self.ctx.current_pkgpath.clone().unwrap(), - ); - } - } - - if let Some(if_cond) = &quant_expr.if_cond { - self.expr(&if_cond)?; - } - self.expr(&quant_expr.test)?; - self.leave_scope(); - Ok(None) - } - - fn walk_schema_attr(&mut self, schema_attr: &'ctx ast::SchemaAttr) -> Self::Result { - let attr_symbol = *self - .gs - .get_symbols() - .symbols_info - .node_symbol_map - .get(&self.ctx.get_node_key(&schema_attr.name.id)) - .ok_or(anyhow!("attr_symbol not found"))?; - let parent_scope = *self.ctx.scopes.last().unwrap(); - let parent_scope = self.gs.get_scopes().get_scope(&parent_scope).unwrap(); - let mut doc = None; - if let Some(schema_symbol) = parent_scope.get_owner() { - let schema_symbol = self - .gs - .get_symbols() - .get_symbol(schema_symbol) - .ok_or(anyhow!("schema_symbol not found"))?; - if let Some(schema_ty) = schema_symbol.get_sema_info().ty.clone() { - let schema_ty = schema_ty.into_schema_type(); - if let Some(attr) = schema_ty.attrs.get(&schema_attr.name.node) { - doc = attr.doc.clone() - } - } - }; - - if let Some(symbol) = self - .gs - .get_symbols_mut() - .attributes - .get_mut(attr_symbol.get_id()) - { - symbol.sema_info = SymbolSemanticInfo { - ty: self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&schema_attr.name.id)) - .map(|ty| ty.clone()), - doc, - }; - }; - - self.walk_type_expr(Some(&schema_attr.ty))?; - if let Some(value) = &schema_attr.value { - self.expr(value)?; - } - - self.resolve_decorator(&schema_attr.decorators); - let cur_scope = *self.ctx.scopes.last().unwrap(); - let name = self - .gs - .get_symbols() - .get_symbol(attr_symbol) - .ok_or(anyhow!("attribute_symbol not found"))? - .get_name(); - self.gs - .get_scopes_mut() - .add_def_to_scope(cur_scope, name, attr_symbol); - Ok(Some(attr_symbol)) - } - - /// if else -> sup([body, orelse]) - fn walk_if_expr(&mut self, if_expr: &'ctx ast::IfExpr) -> Self::Result { - self.expr(&if_expr.cond)?; - self.expr(&if_expr.body)?; - self.expr(&if_expr.orelse)?; - Ok(None) - } - - fn walk_unary_expr(&mut self, unary_expr: &'ctx ast::UnaryExpr) -> Self::Result { - self.expr(&unary_expr.operand)?; - Ok(None) - } - - fn walk_binary_expr(&mut self, binary_expr: &'ctx ast::BinaryExpr) -> Self::Result { - self.expr(&binary_expr.left)?; - self.expr(&binary_expr.right)?; - Ok(None) - } - - fn walk_selector_expr(&mut self, selector_expr: &'ctx ast::SelectorExpr) -> Self::Result { - self.expr(&selector_expr.value)?; - let mut parent_ty = match self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&selector_expr.value.id)) - { - Some(ty) => ty.clone(), - None => return Ok(None), - }; - for name in &selector_expr.attr.node.names { - let def_symbol_ref = match self.gs.get_symbols().get_type_attribute( - &parent_ty, - &name.node, - self.get_current_module_info(), - ) { - Some(symbol) => symbol, - None => return Ok(None), - }; - - let (start_pos, end_pos): Range = name.get_span_pos(); - let ast_id = name.id.clone(); - let unresolved = UnresolvedSymbol::new( - name.node.clone(), - start_pos, - end_pos, - None, - self.ctx.is_type_expr, - ); - let unresolved_ref = self.gs.get_symbols_mut().alloc_unresolved_symbol( - unresolved, - self.ctx.get_node_key(&ast_id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - - self.gs - .get_symbols_mut() - .set_def_and_ref(def_symbol_ref, unresolved_ref); - - let cur_scope = *self.ctx.scopes.last().unwrap(); - self.gs - .get_scopes_mut() - .add_ref_to_scope(cur_scope, unresolved_ref); - - parent_ty = match self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&name.id)) - { - Some(ty) => ty.clone(), - None => return Ok(None), - }; - } - Ok(None) - } - - fn walk_call_expr(&mut self, call_expr: &'ctx ast::CallExpr) -> Self::Result { - let start = call_expr.func.get_end_pos(); - let end = self.ctx.end_pos.clone(); - let func_symbol = self.expr(&call_expr.func)?; - let call_ty = self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&call_expr.func.id)) - .map(|ty| ty.clone()); - - if let Some(ty) = call_ty { - match &ty.kind { - TypeKind::Schema(schema_ty) => { - if !schema_ty.is_instance { - self.enter_local_scope( - &self.ctx.current_filename.as_ref().unwrap().clone(), - start, - end, - LocalSymbolScopeKind::Config, - ); - - if let Some(owner) = func_symbol { - let cur_scope = self.ctx.scopes.last().unwrap(); - self.gs - .get_scopes_mut() - .set_owner_to_scope(*cur_scope, owner); - } - self.do_arguments_symbol_resolve_with_hint( - &call_expr.args, - &call_expr.keywords, - &schema_ty.func.params, - true, - )?; - - self.leave_scope(); - } - } - TypeKind::Function(func_ty) => { - self.enter_local_scope( - &self.ctx.current_filename.as_ref().unwrap().clone(), - start, - end, - LocalSymbolScopeKind::Callable, - ); - - if let Some(owner) = func_symbol { - let cur_scope = self.ctx.scopes.last().unwrap(); - self.gs - .get_scopes_mut() - .set_owner_to_scope(*cur_scope, owner); - } - - self.do_arguments_symbol_resolve_with_hint( - &call_expr.args, - &call_expr.keywords, - &func_ty.params, - true, - )?; - self.leave_scope(); - } - _ => {} - } - } - - Ok(None) - } - - fn walk_subscript(&mut self, subscript: &'ctx ast::Subscript) -> Self::Result { - self.expr(&subscript.value)?; - if let Some(index) = &subscript.index { - self.expr(index)?; - } else { - for expr in [&subscript.lower, &subscript.upper, &subscript.step] - .iter() - .copied() - .flatten() - { - self.expr(expr)?; - } - } - Ok(None) - } - - fn walk_paren_expr(&mut self, paren_expr: &'ctx ast::ParenExpr) -> Self::Result { - self.expr(&paren_expr.expr)?; - Ok(None) - } - - fn walk_list_expr(&mut self, list_expr: &'ctx ast::ListExpr) -> Self::Result { - for expr in list_expr.elts.iter() { - self.expr(expr)?; - } - Ok(None) - } - - fn walk_list_comp(&mut self, list_comp: &'ctx ast::ListComp) -> Self::Result { - let start = list_comp.elt.get_pos(); - let end = match list_comp.generators.last() { - Some(last) => last.get_end_pos(), - None => list_comp.elt.get_end_pos(), - }; - self.enter_local_scope( - &self.ctx.current_filename.clone().unwrap(), - start, - end, - LocalSymbolScopeKind::List, - ); - for comp_clause in &list_comp.generators { - self.walk_comp_clause(&comp_clause.node)?; - } - self.expr(&list_comp.elt)?; - self.leave_scope(); - Ok(None) - } - - fn walk_dict_comp(&mut self, dict_comp: &'ctx ast::DictComp) -> Self::Result { - let (start, key) = match dict_comp.entry.key.as_ref() { - Some(key) => (key.get_pos(), Some(key)), - None => (dict_comp.entry.value.get_pos(), None), - }; - - let end = match dict_comp.generators.last() { - Some(last) => last.get_end_pos(), - None => dict_comp.entry.value.get_end_pos(), - }; - self.enter_local_scope( - &self.ctx.current_filename.clone().unwrap(), - start, - end, - LocalSymbolScopeKind::Dict, - ); - for comp_clause in &dict_comp.generators { - self.walk_comp_clause(&comp_clause.node)?; - } - if let Some(key) = key { - self.expr(key)?; - } - self.expr(&dict_comp.entry.value)?; - self.leave_scope(); - Ok(None) - } - - fn walk_list_if_item_expr( - &mut self, - list_if_item_expr: &'ctx ast::ListIfItemExpr, - ) -> Self::Result { - self.expr(&list_if_item_expr.if_cond)?; - if let Some(orelse) = &list_if_item_expr.orelse { - self.expr(orelse)?; - } - for expr in list_if_item_expr.exprs.iter() { - self.expr(expr)?; - } - Ok(None) - } - - fn walk_starred_expr(&mut self, starred_expr: &'ctx ast::StarredExpr) -> Self::Result { - self.expr(&starred_expr.value)?; - Ok(None) - } - - fn walk_config_if_entry_expr( - &mut self, - config_if_entry_expr: &'ctx ast::ConfigIfEntryExpr, - ) -> Self::Result { - self.expr(&config_if_entry_expr.if_cond)?; - self.walk_config_entries(&config_if_entry_expr.items)?; - if let Some(expr) = config_if_entry_expr.orelse.as_ref() { - self.expr(expr)?; - } - Ok(None) - } - - fn walk_comp_clause(&mut self, comp_clause: &'ctx ast::CompClause) -> Self::Result { - self.expr(&comp_clause.iter)?; - for target in comp_clause.targets.iter() { - self.ctx.maybe_def = true; - self.walk_identifier_expr_with_hint(target, true)?; - self.ctx.maybe_def = false; - } - for if_expr in comp_clause.ifs.iter() { - self.expr(if_expr)?; - } - Ok(None) - } - - fn walk_schema_expr(&mut self, schema_expr: &'ctx ast::SchemaExpr) -> Self::Result { - self.walk_identifier_expr(&schema_expr.name)?; - let schema_ty = self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&schema_expr.name.id)) - .ok_or(anyhow!( - "schema_ty not found when walk schema expr {:?}", - schema_expr - ))? - .clone(); - match schema_ty.kind { - TypeKind::Schema(_) => { - self.expr(&schema_expr.config)?; - self.do_arguments_symbol_resolve(&schema_expr.args, &schema_expr.kwargs)?; - } - _ => { - // Invalid schema type, nothing todo - } - } - Ok(None) - } - - fn walk_config_expr(&mut self, config_expr: &'ctx ast::ConfigExpr) -> Self::Result { - self.walk_config_entries(&config_expr.items)?; - Ok(None) - } - - fn walk_check_expr(&mut self, check_expr: &'ctx ast::CheckExpr) -> Self::Result { - if let Some(msg) = &check_expr.msg { - self.expr(msg)?; - } - if let Some(if_cond) = &check_expr.if_cond { - self.expr(if_cond)?; - } - self.expr(&check_expr.test)?; - Ok(None) - } - - fn walk_lambda_expr(&mut self, lambda_expr: &'ctx ast::LambdaExpr) -> Self::Result { - let (start, end) = (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()); - self.enter_local_scope( - &self.ctx.current_filename.clone().unwrap(), - start, - end, - LocalSymbolScopeKind::Lambda, - ); - if let Some(args) = &lambda_expr.args { - self.walk_arguments(&args.node)?; - } - if let Some(ret_annotation_ty) = &lambda_expr.return_ty { - self.walk_type_expr(Some(&ret_annotation_ty))?; - } - for stmt in lambda_expr.body.iter() { - self.stmt(&stmt)?; - } - self.leave_scope(); - Ok(None) - } - - fn walk_keyword(&mut self, keyword: &'ctx ast::Keyword) -> Self::Result { - self.ctx.maybe_def = true; - self.walk_identifier_expr(&keyword.arg)?; - self.ctx.maybe_def = false; - if let Some(value) = &keyword.value { - self.expr(&value)?; - } - Ok(None) - } - - fn walk_arguments(&mut self, arguments: &'ctx ast::Arguments) -> Self::Result { - for (i, arg) in arguments.args.iter().enumerate() { - let ty = arguments.get_arg_type_node(i); - self.walk_type_expr(ty)?; - self.ctx.maybe_def = true; - self.walk_identifier_expr(arg)?; - self.ctx.maybe_def = false; - - if let Some(val) = &arguments.defaults[i] { - self.expr(val)?; - } - } - Ok(None) - } - - fn walk_compare(&mut self, compare: &'ctx ast::Compare) -> Self::Result { - self.expr(&compare.left)?; - for comparator in compare.comparators.iter() { - self.expr(&comparator)?; - } - Ok(None) - } - - fn walk_identifier(&mut self, identifier: &'ctx ast::Identifier) -> Self::Result { - let symbol_ref = self.resolve_names(&identifier.names, self.ctx.maybe_def)?; - Ok(symbol_ref) - } - - fn walk_target(&mut self, target: &'ctx ast::Target) -> Self::Result { - let symbol_ref = self.resolve_target(&target, self.ctx.maybe_def)?; - Ok(symbol_ref) - } - - fn walk_number_lit(&mut self, _number_lit: &'ctx ast::NumberLit) -> Self::Result { - Ok(None) - } - - fn walk_string_lit(&mut self, _string_lit: &'ctx ast::StringLit) -> Self::Result { - Ok(None) - } - - fn walk_name_constant_lit( - &mut self, - _name_constant_lit: &'ctx ast::NameConstantLit, - ) -> Self::Result { - Ok(None) - } - - fn walk_joined_string(&mut self, joined_string: &'ctx ast::JoinedString) -> Self::Result { - self.ctx.maybe_def = false; - for expr in joined_string.values.iter() { - self.expr(expr)?; - } - Ok(None) - } - - fn walk_formatted_value(&mut self, formatted_value: &'ctx ast::FormattedValue) -> Self::Result { - self.expr(&formatted_value.value)?; - Ok(None) - } - - fn walk_comment(&mut self, comment: &'ctx ast::Comment) -> Self::Result { - let (start, end) = (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()); - let comment_symbol = CommentOrDocSymbol::new(start, end, comment.text.clone()); - Ok(self.gs.get_symbols_mut().alloc_comment_symbol( - comment_symbol, - self.ctx.get_node_key(&self.ctx.cur_node), - self.ctx.current_pkgpath.clone().unwrap(), - )) - } - - fn walk_missing_expr(&mut self, _missing_expr: &'ctx ast::MissingExpr) -> Self::Result { - Ok(None) - } -} - -impl<'ctx> AdvancedResolver<'_> { - #[inline] - pub fn expr(&mut self, expr: &'ctx ast::NodeRef) -> ResolvedResult { - if matches!( - &expr.node, - ast::Expr::Identifier(_) - | ast::Expr::Config(_) - | ast::Expr::Schema(_) - | ast::Expr::ConfigIfEntry(_) - | ast::Expr::Quant(_) - | ast::Expr::Lambda(_) - | ast::Expr::Call(_) - ) { - let (start, end) = expr.get_span_pos(); - self.ctx.start_pos = start; - self.ctx.end_pos = end; - } - self.ctx.cur_node = expr.id.clone(); - - if let Some(expr_ty) = self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&expr.id)) - { - match &expr_ty.kind { - TypeKind::Schema(_) => { - let schema_symbol = self - .gs - .get_symbols() - .get_type_symbol(&expr_ty, self.get_current_module_info()) - .ok_or(anyhow!("schema_symbol not found"))?; - self.ctx.schema_symbol_stack.push(Some(schema_symbol)); - } - _ => { - self.ctx.schema_symbol_stack.push(None); - } - } - } - - let expr_symbol = self.walk_expr(&expr.node); - self.ctx.schema_symbol_stack.pop(); - - match expr_symbol { - Ok(None) => match self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&expr.id)) - { - Some(ty) => match expr.node { - ast::Expr::Missing(_) - | ast::Expr::Binary(_) - | ast::Expr::CompClause(_) - | ast::Expr::Keyword(_) - | ast::Expr::Arguments(_) - | ast::Expr::Compare(_) => return Ok(None), - _ => { - let (_, end) = expr.get_span_pos(); - let mut expr_symbol = ExpressionSymbol::new( - format!("@{}", expr.node.get_expr_name()), - end.clone(), - end, - None, - ); - expr_symbol.sema_info.ty = if matches!(&expr.node, | ast::Expr::Call(_)) { - if let TypeKind::Function(func_ty) = &ty.kind { - Some(func_ty.return_ty.clone()) - } else { - Some(ty.clone()) - } - } else { - Some(ty.clone()) - }; - - Ok(self.gs.get_symbols_mut().alloc_expression_symbol( - expr_symbol, - self.ctx.get_node_key(&expr.id), - self.ctx.current_pkgpath.clone().unwrap(), - )) - } - }, - None => Ok(None), - }, - res => res, - } - } - - #[inline] - pub fn stmt(&mut self, stmt: &'ctx ast::NodeRef) -> ResolvedResult { - let (start, end) = stmt.get_span_pos(); - self.ctx.start_pos = start; - self.ctx.end_pos = end; - self.ctx.cur_node = stmt.id.clone(); - let result = self.walk_stmt(&stmt.node); - result - } - - fn resolve_names(&mut self, names: &[ast::Node], maybe_def: bool) -> ResolvedResult { - let first_name = names.get(0).unwrap(); - let cur_scope = *self.ctx.scopes.last().unwrap(); - - let mut first_symbol = self.gs.look_up_symbol( - &first_name.node, - cur_scope, - self.get_current_module_info(), - maybe_def, - !self.ctx.in_config_r_value, - ); - if first_symbol.is_none() { - // Maybe import package symbol - let module_info = self.get_current_module_info().unwrap(); - - let import_info = module_info.get_import_info(&first_name.node); - if import_info.is_some() && !maybe_def { - first_symbol = self - .gs - .get_symbols() - .get_symbol_by_fully_qualified_name(&import_info.unwrap().fully_qualified_name); - } - - if let Some(first_symbol) = first_symbol { - if self - .gs - .get_symbols() - .get_symbol(first_symbol) - .ok_or(anyhow!("first name symbol not found"))? - .get_sema_info() - .ty - .is_none() - { - if let Some(ty) = self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&first_name.id)) - { - self.gs - .get_symbols_mut() - .set_symbol_type(first_symbol, ty.clone()); - } - } - } - } - match first_symbol { - Some(symbol_ref) => { - let mut ret_symbol = symbol_ref.clone(); - let (start_pos, end_pos): Range = first_name.get_span_pos(); - let def_symbol = self - .gs - .get_symbols() - .get_symbol(symbol_ref) - .ok_or(anyhow!("first name symbol not found"))?; - let (def_start_pos, def_end_pos) = def_symbol.get_range(); - - let cur_scope = *self.ctx.scopes.last().unwrap(); - let ast_id = first_name.id.clone(); - let mut first_unresolved = UnresolvedSymbol::new( - first_name.node.clone(), - start_pos.clone(), - end_pos.clone(), - None, - self.ctx.is_type_expr, - ); - let name = def_symbol.get_name(); - first_unresolved.def = Some(symbol_ref); - let first_unresolved_ref = self.gs.get_symbols_mut().alloc_unresolved_symbol( - first_unresolved, - self.ctx.get_node_key(&ast_id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - - match cur_scope.get_kind() { - crate::core::scope::ScopeKind::Local => { - let local_scope = self - .gs - .get_scopes() - .try_get_local_scope(&cur_scope) - .unwrap(); - match local_scope.get_kind() { - LocalSymbolScopeKind::Config => { - if let crate::core::symbol::SymbolKind::Attribute = - symbol_ref.get_kind() - { - if maybe_def { - self.gs.get_scopes_mut().add_def_to_scope( - cur_scope, - name, - first_unresolved_ref, - ); - ret_symbol = first_unresolved_ref; - } - } - } - _ => {} - } - } - _ => {} - } - - if def_start_pos != start_pos || def_end_pos != end_pos { - self.gs - .get_symbols_mut() - .set_def_and_ref(symbol_ref, first_unresolved_ref); - - let cur_scope = *self.ctx.scopes.last().unwrap(); - self.gs - .get_scopes_mut() - .add_ref_to_scope(cur_scope, first_unresolved_ref); - } - - if names.len() > 1 { - let mut parent_ty = match self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&first_name.id)) - { - Some(ty) => ty.clone(), - None => return Ok(None), - }; - - for index in 1..names.len() { - let name = names.get(index).unwrap(); - let def_symbol_ref = match self.gs.get_symbols().get_type_attribute( - &parent_ty, - &name.node, - self.get_current_module_info(), - ) { - Some(symbol) => symbol, - None => return Ok(None), - }; - - let (start_pos, end_pos): Range = name.get_span_pos(); - let ast_id = name.id.clone(); - let mut unresolved = UnresolvedSymbol::new( - name.node.clone(), - start_pos, - end_pos, - None, - self.ctx.is_type_expr, - ); - - unresolved.sema_info = SymbolSemanticInfo { - ty: self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&name.id)) - .map(|ty| ty.clone()), - doc: None, - }; - - let unresolved_ref = self.gs.get_symbols_mut().alloc_unresolved_symbol( - unresolved, - self.ctx.get_node_key(&ast_id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - - self.gs - .get_symbols_mut() - .set_def_and_ref(def_symbol_ref, unresolved_ref); - - let cur_scope = *self.ctx.scopes.last().unwrap(); - self.gs - .get_scopes_mut() - .add_ref_to_scope(cur_scope, unresolved_ref); - - parent_ty = match self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&name.id)) - { - Some(ty) => ty.clone(), - None => return Ok(None), - }; - if index == names.len() - 1 { - return Ok(Some(unresolved_ref)); - } - } - } - Ok(Some(ret_symbol)) - } - None => { - if maybe_def { - let (start_pos, end_pos): Range = first_name.get_span_pos(); - let ast_id = first_name.id.clone(); - let first_value = self.gs.get_symbols_mut().alloc_value_symbol( - ValueSymbol::new(first_name.node.clone(), start_pos, end_pos, None, false), - self.ctx.get_node_key(&ast_id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - self.gs.get_scopes_mut().add_def_to_scope( - cur_scope, - first_name.node.clone(), - first_value, - ); - - if let Some(symbol) = self - .gs - .get_symbols_mut() - .values - .get_mut(first_value.get_id()) - { - symbol.sema_info = SymbolSemanticInfo { - ty: self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&first_name.id)) - .map(|ty| ty.clone()), - doc: None, - }; - } - - for index in 1..names.len() { - let name = names.get(index).unwrap(); - let (start_pos, end_pos): Range = name.get_span_pos(); - let ast_id = name.id.clone(); - let value = self.gs.get_symbols_mut().alloc_value_symbol( - ValueSymbol::new(name.node.clone(), start_pos, end_pos, None, false), - self.ctx.get_node_key(&ast_id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - - self.gs.get_scopes_mut().add_def_to_scope( - cur_scope, - name.node.clone(), - value, - ); - - if let Some(symbol) = - self.gs.get_symbols_mut().values.get_mut(value.get_id()) - { - symbol.sema_info = SymbolSemanticInfo { - ty: self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&name.id)) - .map(|ty| ty.clone()), - doc: None, - }; - } - if index == names.len() - 1 { - return Ok(Some(value)); - } - } - } - Ok(None) - } - } - } - - fn resolve_target(&mut self, target: &'ctx ast::Target, maybe_def: bool) -> ResolvedResult { - let first_name = &target.name; - let cur_scope = *self.ctx.scopes.last().unwrap(); - - let first_symbol = self.gs.look_up_symbol( - &first_name.node, - cur_scope, - self.get_current_module_info(), - true, - !self.ctx.in_config_r_value, - ); - match first_symbol { - Some(symbol_ref) => { - let (start_pos, end_pos): Range = first_name.get_span_pos(); - let (def_start_pos, def_end_pos) = self - .gs - .get_symbols() - .get_symbol(symbol_ref) - .ok_or(anyhow!("first name symbol not found"))? - .get_range(); - - // Get an unresolved symbol - if def_start_pos != start_pos || def_end_pos != end_pos { - let ast_id = first_name.id.clone(); - let mut first_unresolved = UnresolvedSymbol::new( - first_name.node.clone(), - start_pos, - end_pos, - None, - self.ctx.is_type_expr, - ); - first_unresolved.def = Some(symbol_ref); - let first_unresolved_ref = self.gs.get_symbols_mut().alloc_unresolved_symbol( - first_unresolved, - self.ctx.get_node_key(&ast_id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - let cur_scope = *self.ctx.scopes.last().unwrap(); - self.gs - .get_scopes_mut() - .add_ref_to_scope(cur_scope, first_unresolved_ref); - } - if !target.paths.is_empty() { - let mut parent_ty = match self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&first_name.id)) - { - Some(ty) => ty.clone(), - None => return Ok(None), - }; - - for (index, path) in target.paths.iter().enumerate() { - match path { - ast::MemberOrIndex::Member(member) => { - let name = member; - let def_symbol_ref = match self.gs.get_symbols().get_type_attribute( - &parent_ty, - &name.node, - self.get_current_module_info(), - ) { - Some(symbol) => symbol, - None => return Ok(None), - }; - - let (start_pos, end_pos): Range = name.get_span_pos(); - let ast_id = name.id.clone(); - let mut unresolved = UnresolvedSymbol::new( - name.node.clone(), - start_pos, - end_pos, - None, - self.ctx.is_type_expr, - ); - unresolved.def = Some(def_symbol_ref); - unresolved.sema_info = SymbolSemanticInfo { - ty: self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&name.id)) - .map(|ty| ty.clone()), - doc: None, - }; - - let unresolved_ref = - self.gs.get_symbols_mut().alloc_unresolved_symbol( - unresolved, - self.ctx.get_node_key(&ast_id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - - let cur_scope = *self.ctx.scopes.last().unwrap(); - self.gs - .get_scopes_mut() - .add_ref_to_scope(cur_scope, unresolved_ref); - - parent_ty = match self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&name.id)) - { - Some(ty) => ty.clone(), - None => return Ok(None), - }; - if index == target.paths.len() - 1 { - return Ok(Some(unresolved_ref)); - } - } - ast::MemberOrIndex::Index(index_expr) => { - let last_maybe_def = self.ctx.maybe_def; - self.ctx.maybe_def = false; - let symbol = self.expr(index_expr); - parent_ty = match self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&index_expr.id)) - { - Some(ty) => ty.clone(), - None => return Ok(None), - }; - self.ctx.maybe_def = last_maybe_def; - if index == target.paths.len() { - return symbol; - } - } - } - } - } - Ok(Some(symbol_ref)) - } - None => { - if maybe_def { - let (start_pos, end_pos): Range = first_name.get_span_pos(); - let ast_id = first_name.id.clone(); - let first_value = self.gs.get_symbols_mut().alloc_value_symbol( - ValueSymbol::new(first_name.node.clone(), start_pos, end_pos, None, false), - self.ctx.get_node_key(&ast_id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - self.gs.get_scopes_mut().add_def_to_scope( - cur_scope, - first_name.node.clone(), - first_value, - ); - - if let Some(symbol) = self - .gs - .get_symbols_mut() - .values - .get_mut(first_value.get_id()) - { - symbol.sema_info = SymbolSemanticInfo { - ty: self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&first_name.id)) - .map(|ty| ty.clone()), - doc: None, - }; - } - - for (index, path) in target.paths.iter().enumerate() { - match path { - ast::MemberOrIndex::Member(member) => { - let name = member; - let (start_pos, end_pos): Range = name.get_span_pos(); - let ast_id = name.id.clone(); - let value = self.gs.get_symbols_mut().alloc_value_symbol( - ValueSymbol::new( - name.node.clone(), - start_pos, - end_pos, - None, - false, - ), - self.ctx.get_node_key(&ast_id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - - self.gs.get_scopes_mut().add_def_to_scope( - cur_scope, - name.node.clone(), - value, - ); - - if let Some(symbol) = - self.gs.get_symbols_mut().values.get_mut(value.get_id()) - { - symbol.sema_info = SymbolSemanticInfo { - ty: self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&name.id)) - .map(|ty| ty.clone()), - doc: None, - }; - } - if index == target.paths.len() { - return Ok(Some(value)); - } - } - ast::MemberOrIndex::Index(index_expr) => { - let last_maybe_def = self.ctx.maybe_def; - self.ctx.maybe_def = false; - let symbol = self.expr(index_expr); - self.ctx.maybe_def = last_maybe_def; - if index == target.paths.len() { - return symbol; - } - } - } - } - } - Ok(None) - } - } - } - - #[inline] - pub fn walk_target_expr(&mut self, target: &'ctx ast::NodeRef) -> ResolvedResult { - self.walk_target_expr_with_hint(target, false) - } - - pub fn walk_target_expr_with_hint( - &mut self, - target: &'ctx ast::NodeRef, - with_hint: bool, - ) -> ResolvedResult { - let symbol_ref = if let Some(identifier_symbol) = self - .gs - .get_symbols() - .symbols_info - .node_symbol_map - .get(&self.ctx.get_node_key(&&target.id)) - .map(|symbol_ref| *symbol_ref) - { - let symbols = self.gs.get_symbols_mut(); - - if let Some(symbol) = symbols.values.get_mut(identifier_symbol.get_id()) { - let id = if let Some(last) = target.node.paths.last() { - last.id() - } else { - target.node.name.id.clone() - }; - let ty = self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&id)) - .map(|ty| ty.clone()); - - symbol.sema_info = SymbolSemanticInfo { - ty: ty.clone(), - doc: None, - }; - if with_hint & ty.is_some() { - symbols.alloc_hint( - SymbolHint { - kind: SymbolHintKind::TypeHint(ty.unwrap().ty_hint()), - pos: target.get_end_pos(), - }, - self.ctx.current_pkgpath.clone().unwrap(), - ); - } - } - - let cur_scope = *self.ctx.scopes.last().unwrap(); - match cur_scope.kind { - crate::core::scope::ScopeKind::Local => { - self.gs.get_scopes_mut().add_def_to_scope( - cur_scope, - target.node.get_name().to_string(), - identifier_symbol, - ); - } - crate::core::scope::ScopeKind::Root => {} - } - identifier_symbol - } else { - match self.resolve_target(&target.node, self.ctx.maybe_def)? { - Some(symbol) => symbol, - None => return Ok(None), - } - }; - - Ok(Some(symbol_ref)) - } - - #[inline] - pub fn walk_identifier_expr( - &mut self, - identifier: &'ctx ast::NodeRef, - ) -> ResolvedResult { - self.walk_identifier_expr_with_hint(identifier, false) - } - - pub fn walk_identifier_expr_with_hint( - &mut self, - identifier: &'ctx ast::NodeRef, - with_hint: bool, - ) -> ResolvedResult { - let symbol_ref = if let Some(identifier_symbol) = self - .gs - .get_symbols() - .symbols_info - .node_symbol_map - .get(&self.ctx.get_node_key(&&identifier.id)) - .map(|symbol_ref| *symbol_ref) - { - let symbols = self.gs.get_symbols_mut(); - - if let Some(symbol) = symbols.values.get_mut(identifier_symbol.get_id()) { - let id = if identifier.node.names.is_empty() { - &identifier.id - } else { - &identifier.node.names.last().unwrap().id - }; - let ty = self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&id)) - .map(|ty| ty.clone()); - - symbol.sema_info = SymbolSemanticInfo { - ty: ty.clone(), - doc: None, - }; - if with_hint & ty.is_some() { - symbols.alloc_hint( - SymbolHint { - kind: SymbolHintKind::TypeHint(ty.unwrap().ty_hint()), - pos: identifier.get_end_pos(), - }, - self.ctx.current_pkgpath.clone().unwrap(), - ); - } - } - - if self.ctx.maybe_def && identifier.node.names.len() > 0 { - let cur_scope = *self.ctx.scopes.last().unwrap(); - match cur_scope.kind { - crate::core::scope::ScopeKind::Local => { - self.gs.get_scopes_mut().add_def_to_scope( - cur_scope, - identifier.node.names.last().unwrap().node.clone(), - identifier_symbol, - ); - } - crate::core::scope::ScopeKind::Root => {} - } - } - identifier_symbol - } else { - match self.resolve_names(&identifier.node.names, self.ctx.maybe_def)? { - Some(symbol) => symbol, - None => return Ok(None), - } - }; - - Ok(Some(symbol_ref)) - } - - pub fn walk_type_expr( - &mut self, - ty_node: Option<&'ctx ast::Node>, - ) -> ResolvedResult { - self.ctx.is_type_expr = true; - if let Some(ty_node) = ty_node { - match &ty_node.node { - ast::Type::Any => { - let (start, end) = ty_node.get_span_pos(); - let mut type_symbol = - UnresolvedSymbol::new(ANY_TYPE_STR.to_owned(), start, end, None, true); - - type_symbol.sema_info.ty = Some(Arc::new(Type::ANY)); - self.gs.get_symbols_mut().alloc_unresolved_symbol( - type_symbol, - self.ctx.get_node_key(&ty_node.id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - } - ast::Type::Named(identifier) => { - self.walk_identifier(identifier)?; - } - ast::Type::Basic(_) => {} - ast::Type::List(list_type) => { - self.walk_type_expr(list_type.inner_type.as_ref().map(|ty| ty.as_ref()))?; - } - ast::Type::Dict(dict_type) => { - self.walk_type_expr(dict_type.key_type.as_ref().map(|ty| ty.as_ref()))?; - self.walk_type_expr(dict_type.value_type.as_ref().map(|ty| ty.as_ref()))?; - } - ast::Type::Union(union_type) => { - for elem_ty in union_type.type_elements.iter() { - self.walk_type_expr(Some(elem_ty))?; - } - } - ast::Type::Literal(_) => {} - ast::Type::Function(func_type) => { - if let Some(params_ty) = &func_type.params_ty { - for param_ty in params_ty.iter() { - self.walk_type_expr(Some(param_ty))?; - } - } - if let Some(ret_ty) = &func_type.ret_ty { - self.walk_type_expr(Some(&ret_ty))?; - } - } - } - } - - if let Some(ty_node) = ty_node { - match self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&ty_node.id)) - { - Some(ty) => { - let (_, end) = ty_node.get_span_pos(); - let mut expr_symbol = - ExpressionSymbol::new(format!("@{}", ty.ty_hint()), end.clone(), end, None); - - expr_symbol.sema_info.ty = Some(ty.clone()); - self.gs.get_symbols_mut().alloc_expression_symbol( - expr_symbol, - self.ctx.get_node_key(&ty_node.id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - } - None => {} - } - } - self.ctx.is_type_expr = false; - Ok(None) - } - - pub fn do_arguments_symbol_resolve( - &mut self, - args: &'ctx [ast::NodeRef], - kwargs: &'ctx [ast::NodeRef], - ) -> anyhow::Result<()> { - for arg in args.iter() { - self.expr(arg)?; - } - for kw in kwargs.iter() { - if let Some(value) = &kw.node.value { - self.expr(value)?; - } - let (start_pos, end_pos): Range = kw.node.arg.get_span_pos(); - let value = self.gs.get_symbols_mut().alloc_value_symbol( - ValueSymbol::new(kw.node.arg.node.get_name(), start_pos, end_pos, None, false), - self.ctx.get_node_key(&kw.id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - - if let Some(value) = self.gs.get_symbols_mut().values.get_mut(value.get_id()) { - value.sema_info = SymbolSemanticInfo { - ty: self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&kw.id)) - .map(|ty| ty.clone()), - doc: None, - }; - } - } - Ok(()) - } - - pub fn do_arguments_symbol_resolve_with_hint( - &mut self, - args: &'ctx [ast::NodeRef], - kwargs: &'ctx [ast::NodeRef], - params: &[Parameter], - with_hint: bool, - ) -> anyhow::Result<()> { - if params.is_empty() { - self.do_arguments_symbol_resolve(args, kwargs)?; - } else { - for (arg, param) in args.iter().zip(params.iter()) { - self.expr(arg)?; - - if with_hint { - let symbol_data = self.gs.get_symbols_mut(); - let id = match &arg.node { - ast::Expr::Identifier(id) => id.names.last().unwrap().id.clone(), - _ => arg.id.clone(), - }; - match symbol_data - .symbols_info - .node_symbol_map - .get(&self.ctx.get_node_key(&id)) - { - Some(arg_ref) => match arg_ref.get_kind() { - crate::core::symbol::SymbolKind::Unresolved => { - let mut has_hint = false; - if let Some(unresolved) = - symbol_data.unresolved.get(arg_ref.get_id()) - { - if let Some(def) = unresolved.def { - if let Some(def) = symbol_data.get_symbol(def) { - if def.get_name() != param.name { - has_hint = true; - } - } - } - } - if has_hint { - symbol_data.alloc_hint( - SymbolHint { - kind: SymbolHintKind::VarHint(param.name.clone()), - pos: arg.get_pos(), - }, - self.ctx.current_pkgpath.clone().unwrap(), - ); - } - } - _ => { - symbol_data.alloc_hint( - SymbolHint { - kind: SymbolHintKind::VarHint(param.name.clone()), - pos: arg.get_pos(), - }, - self.ctx.current_pkgpath.clone().unwrap(), - ); - } - }, - None => { - symbol_data.alloc_hint( - SymbolHint { - kind: SymbolHintKind::VarHint(param.name.clone()), - pos: arg.get_pos(), - }, - self.ctx.current_pkgpath.clone().unwrap(), - ); - } - } - } - } - - for kw in kwargs.iter() { - if let Some(value) = &kw.node.value { - self.expr(value)?; - } - let (start_pos, end_pos): Range = kw.node.arg.get_span_pos(); - let value = self.gs.get_symbols_mut().alloc_value_symbol( - ValueSymbol::new(kw.node.arg.node.get_name(), start_pos, end_pos, None, false), - self.ctx.get_node_key(&kw.id), - self.ctx.current_pkgpath.clone().unwrap(), - ); - - if let Some(value) = self.gs.get_symbols_mut().values.get_mut(value.get_id()) { - value.sema_info = SymbolSemanticInfo { - ty: self - .ctx - .node_ty_map - .borrow() - .get(&self.ctx.get_node_key(&kw.id)) - .map(|ty| ty.clone()), - doc: None, - }; - } - } - } - Ok(()) - } - - pub(crate) fn walk_config_entries( - &mut self, - entries: &'ctx [ast::NodeRef], - ) -> anyhow::Result<()> { - let (start, end) = (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()); - - let schema_symbol = self.ctx.schema_symbol_stack.last().unwrap_or(&None).clone(); - let kind = LocalSymbolScopeKind::Config; - - self.enter_local_scope( - &self.ctx.current_filename.as_ref().unwrap().clone(), - start, - end, - kind, - ); - - if let Some(owner) = schema_symbol { - let cur_scope = self.ctx.scopes.last().unwrap(); - self.gs - .get_scopes_mut() - .set_owner_to_scope(*cur_scope, owner); - } - - let mut entries_range = vec![]; - for entry in entries.iter() { - entries_range.push(( - entry.node.key.clone().map(|k| k.get_span_pos()), - entry.node.value.get_span_pos(), - )); - self.ctx.in_config_r_value = true; - self.expr(&entry.node.value)?; - self.ctx.in_config_r_value = false; - - if let Some(key) = &entry.node.key { - self.ctx.maybe_def = true; - if let Some(symbol_ref) = self.expr(key)? { - if let Some(config_key_symbol) = - self.gs.get_symbols().unresolved.get(symbol_ref.get_id()) - { - if let Some(def_ref) = config_key_symbol.get_definition() { - if let Some(def_symbol) = self.gs.get_symbols().get_symbol(def_ref) { - let ty = def_symbol.get_sema_info().ty.clone(); - let symbols = self.gs.get_symbols_mut(); - if let Some(ty) = ty { - symbols.alloc_hint( - SymbolHint { - kind: SymbolHintKind::KeyTypeHint(ty.ty_hint()), - pos: key.get_end_pos(), - }, - self.ctx.current_pkgpath.clone().unwrap(), - ); - } - } - } - } - } - self.ctx.maybe_def = false; - } - } - - let cur_scope = self.ctx.scopes.last().unwrap(); - self.gs - .get_scopes_mut() - .config_scope_context - .insert(cur_scope.get_id(), ConfigScopeContext { entries_range }); - self.leave_scope(); - Ok(()) - } - - pub(crate) fn resolve_decorator(&mut self, decorators: &'ctx [ast::NodeRef]) { - for decorator in decorators { - let func_ident = &decorator.node.func; - let (start, end) = func_ident.get_span_pos(); - if let kclvm_ast::ast::Expr::Identifier(id) = &func_ident.node { - let decorator_symbol = DecoratorSymbol::new(start, end, id.get_name()); - self.gs.get_symbols_mut().alloc_decorator_symbol( - decorator_symbol, - self.ctx.get_node_key(&self.ctx.cur_node), - self.ctx.current_pkgpath.clone().unwrap(), - ); - } - } - } - - pub(crate) fn walk_module_schemas(&mut self, module: &'ctx ast::Module) -> anyhow::Result<()> { - for stmt in module.body.iter() { - if matches!(stmt.node, Stmt::Schema(_)) { - self.stmt(stmt)?; - } - } - Ok(()) - } -} diff --git a/kclvm/sema/src/builtin/mod.rs b/kclvm/sema/src/builtin/mod.rs deleted file mode 100644 index b2b93aa4c..000000000 --- a/kclvm/sema/src/builtin/mod.rs +++ /dev/null @@ -1,588 +0,0 @@ -//! This package mainly contains the type definitions of built-in system libraries, -//! functions, decorators and member methods. -pub mod decorator; -pub mod option; -pub mod string; -pub mod system_module; - -use std::sync::Arc; - -use kclvm_error::diagnostic::dummy_range; -use kclvm_primitives::IndexMap; -use once_cell::sync::Lazy; - -use crate::ty::{Parameter, Type}; -pub use decorator::BUILTIN_DECORATORS; -pub use string::STRING_MEMBER_FUNCTIONS; -pub use system_module::*; - -pub const KCL_BUILTIN_FUNCTION_MANGLE_PREFIX: &str = "kclvm_builtin"; -pub const KCL_SYSTEM_MODULE_MANGLE_PREFIX: &str = "kclvm_"; -pub const BUILTIN_FUNCTION_PREFIX: &str = "$builtin"; - -macro_rules! register_builtin { - ($($name:ident => $ty:expr)*) => ( - // Builtin function map. - pub const BUILTIN_FUNCTIONS: Lazy> = Lazy::new(|| { - let mut builtin_mapping = IndexMap::default(); - $( builtin_mapping.insert(stringify!($name).to_string(), $ty); )* - builtin_mapping - }); - pub static BUILTIN_FUNCTION_NAMES: &[&str] = &[ - $( stringify!($name), )* - ]; - ) -} - -register_builtin! { - option => Type::function( - None, - Arc::new(Type::ANY), - &[ - Parameter { - name: "key".to_string(), - ty: Arc::new(Type::STR), - has_default: false, - default_value: None, - range: dummy_range(), - }, - Parameter { - name: "type".to_string(), - ty: Arc::new(Type::STR), - has_default: true, - default_value: None, - range: dummy_range(), - }, - Parameter { - name: "required".to_string(), - ty: Arc::new(Type::BOOL), - has_default: true, - default_value: None, - range: dummy_range(), - }, - Parameter { - name: "default".to_string(), - ty: Arc::new(Type::ANY), - has_default: true, - default_value: None, - range: dummy_range(), - }, - Parameter { - name: "help".to_string(), - ty: Arc::new(Type::STR), - has_default: true, - default_value: None, - range: dummy_range(), - }, - ], - "Return the top level argument by the key", - false, - Some(1), - ) - print => Type::function( - None, - Arc::new(Type::NONE), - &[], - r#"Prints the values to a stream, or to the system stdout by default. -Optional keyword arguments: -sep: string inserted between values, default a space. -end: string appended after the last value, default a newline."#, - true, - None, - ) - multiplyof => Type::function( - None, - Arc::new(Type::BOOL), - &[ - Parameter { - name: "a".to_string(), - ty: Arc::new(Type::INT), - has_default: false, - default_value: None, - range: dummy_range(), - }, - Parameter { - name: "b".to_string(), - ty: Arc::new(Type::INT), - has_default: false, - default_value: None, - range: dummy_range(), - }, - ], - "Check if the modular result of a and b is 0.", - false, - None, - ) - isunique => Type::function( - None, - Arc::new(Type::BOOL), - &[ - Parameter { - name: "inval".to_string(), - ty: Type::list_ref(Arc::new(Type::ANY)), - has_default: false, - default_value: None, - range: dummy_range(), - }, - ], - "Check if a list has duplicated elements", - false, - None, - ) - isnullish => Type::function( - None, - Arc::new(Type::BOOL), - &[ - Parameter { - name: "inval".to_string(), - ty: Type::any_ref(), - has_default: false, - default_value: None, - range: dummy_range(), - }, - ], - "Return `True` if the input value is `None` or `Undefined`, and `False` otherwise.", - false, - None, - ) - len => Type::function( - None, - Arc::new(Type::INT), - &[ - Parameter { - name: "inval".to_string(), - ty: Type::iterable(), - has_default: false,default_value: None, - range: dummy_range(), - }, - ], - "Return the length of a value.", - false, - None, - ) - abs => Type::function( - None, - Arc::new(Type::ANY), - &[ - Parameter { - name: "inval".to_string(), - ty: Arc::new(Type::ANY), - has_default: false, - default_value: None, - range: dummy_range(), - }, - ], - "Return the absolute value of the argument.", - false, - None, - ) - all_true => Type::function( - None, - Arc::new(Type::BOOL), - &[ - Parameter { - name: "inval".to_string(), - ty: Type::list_ref(Arc::new(Type::ANY)), - has_default: false, - default_value: None, - range: dummy_range(), - }, - ], - r#"Return True if bool(x) is True for all values x in the iterable. - -If the iterable is empty, return True."#, - false, - None, - ) - any_true => Type::function( - None, - Arc::new(Type::BOOL), - &[ - Parameter { - name: "inval".to_string(), - ty: Type::list_ref(Arc::new(Type::ANY)), - has_default: false, - default_value: None, - range: dummy_range(), - }, - ], - r#"Return True if bool(x) is True for any x in the iterable. - -If the iterable is empty, return False."#, - false, - None, - ) - hex => Type::function( - None, - Arc::new(Type::STR), - &[ - Parameter { - name: "number".to_string(), - ty: Arc::new(Type::INT), - has_default: false, - default_value: None, - range: dummy_range(), - }, - ], - "Return the hexadecimal representation of an integer.", - false, - None, - ) - bin => Type::function( - None, - Arc::new(Type::STR), - &[ - Parameter { - name: "number".to_string(), - ty: Arc::new(Type::INT), - has_default: false, - default_value: None, - range: dummy_range(), - }, - ], - "Return the binary representation of an integer.", - false, - None, - ) - oct => Type::function( - None, - Arc::new(Type::STR), - &[ - Parameter { - name: "number".to_string(), - ty: Arc::new(Type::INT), - has_default: false, - default_value: None, - range: dummy_range(), - }, - ], - "Return the octal representation of an integer.", - false, - None, - ) - ord => Type::function( - None, - Arc::new(Type::INT), - &[ - Parameter { - name: "c".to_string(), - ty: Arc::new(Type::STR), - has_default: false, - default_value: None, - range: dummy_range(), - }, - ], - "Return the Unicode code point for a one-character string.", - false, - None, - ) - sorted => Type::function( - None, - Type::list_ref(Arc::new(Type::ANY)), - &[ - Parameter { - name: "inval".to_string(), - ty: Type::iterable(), - has_default: false, - default_value: None, - range: dummy_range(), - }, - Parameter { - name: "reverse".to_string(), - ty: Arc::new(Type::BOOL), - has_default: true,default_value: None, - range: dummy_range(), - }, - ], - r#"Return a new list containing all items from the iterable in ascending order. - -A custom key function can be supplied to customize the sort order, and the reverse -flag can be set to request the result in descending order."#, - false, - Some(1), - ) - range => Type::function( - None, - Type::list_ref(Arc::new(Type::INT)), - &[ - Parameter { - name: "start".to_string(), - ty: Arc::new(Type::INT), - has_default: true, - default_value: None, - range: dummy_range(), - }, - Parameter { - name: "stop".to_string(), - ty: Arc::new(Type::INT), - has_default: true, - default_value: None, - range: dummy_range(), - }, - Parameter { - name: "step".to_string(), - ty: Arc::new(Type::INT), - has_default: true, - default_value: None, - range: dummy_range(), - }, - ], - r#"Return the range of a value."#, - false, - None, - ) - max => Type::function( - None, - Arc::new(Type::ANY), - &[], - r#"With a single iterable argument, return its biggest item. -The default keyword-only argument specifies an object to return -if the provided iterable is empty. With two or more arguments, -return the largest argument."#, - true, - None, - ) - min => Type::function( - None, - Arc::new(Type::ANY), - &[], - r#"With a single iterable argument, return its smallest item. -The default keyword-only argument specifies an object to return -if the provided iterable is empty. With two or more arguments, -return the smallest argument."#, - true, - None, - ) - sum => Type::function( - None, - Arc::new(Type::ANY), - &[ - Parameter { - name: "iterable".to_string(), - ty: Type::list_ref(Arc::new(Type::ANY)), - has_default: false, - default_value: None, - range: dummy_range(), - }, - Parameter { - name: "start".to_string(), - ty: Arc::new(Type::ANY), - has_default: true, - default_value: None, - range: dummy_range(), - }, - ], - r#"When the iterable is empty, return the start value. This function is -intended specifically for use with numeric values and may reject -non-numeric types."#, - false, - None, - ) - pow => Type::function( - None, - Type::number(), - &[ - Parameter { - name: "x".to_string(), - ty: Type::number(), - has_default: false, - default_value: None, - range: dummy_range(), - }, - Parameter { - name: "y".to_string(), - ty: Type::number(), - has_default: false, - default_value: None, - range: dummy_range(), - }, - Parameter { - name: "z".to_string(), - ty: Type::number(), - has_default: true, - default_value: None, - range: dummy_range(), - }, - ], - r#"Equivalent to `x ** y` (with two arguments) or `x ** y % z` (with three arguments) - -Some types, such as ints, are able to use a more efficient algorithm when -invoked using the three argument form."#, - false, - None, - ) - round => Type::function( - None, - Type::number(), - &[ - Parameter { - name: "number".to_string(), - ty: Type::number(), - has_default: false, - default_value: None, - range: dummy_range(), - }, - Parameter { - name: "ndigits".to_string(), - ty: Arc::new(Type::INT), - has_default: true, - default_value: None, - range: dummy_range(), - }, - ], - r#"Round a number to a given precision in decimal digits. - -The return value is an integer if ndigits is omitted or None. -Otherwise the return value has the same type as the number. -ndigits may be negative."#, - false, - None, - ) - zip => Type::function( - None, - Type::list_ref(Arc::new(Type::ANY)), - &[], - r#"Return a zip object whose next method returns -a tuple where the i-th element comes from the i-th iterable -argument."#, - true, - None, - ) - int => Type::function( - None, - Arc::new(Type::INT), - &[ - Parameter { - name: "number".to_string(), - ty: Arc::new(Type::ANY), - has_default: false, - default_value: None, - range: dummy_range(), - }, - Parameter { - name: "base".to_string(), - ty: Arc::new(Type::INT), - has_default: true, - default_value: None, - range: dummy_range(), - }, - ], - r#"Convert a number or string to an integer, or return 0 if no arguments -are given. For floating point numbers, this truncates towards zero."#, - false, - None, - ) - float => Type::function( - None, - Arc::new(Type::FLOAT), - &[ - Parameter { - name: "number".to_string(), - ty: Arc::new(Type::ANY), - has_default: false, - default_value: None, - range: dummy_range(), - }, - ], - r#"Convert a string or number to a floating point number, if possible."#, - false, - None, - ) - bool => Type::function( - None, - Arc::new(Type::BOOL), - &[ - Parameter { - name: "x".to_string(), - ty: Arc::new(Type::ANY), - has_default: true, - default_value: None, - range: dummy_range(), - }, - ], - r#"Returns True when the argument x is true, False otherwise. -The builtin `True` and `False` are the only two instances of the class bool. -The class bool is a subclass of the class int, and cannot be subclassed."#, - false, - None, - ) - str => Type::function( - None, - Arc::new(Type::STR), - &[ - Parameter { - name: "x".to_string(), - ty: Arc::new(Type::ANY), - has_default: true, - default_value: None, - range: dummy_range(), - }, - ], - r#"Create a new string object from the given object. -If encoding or errors is specified, then the object must -expose a data buffer that will be decoded using the -given encoding and error handler."#, - false, - None, - ) - list => Type::function( - None, - Type::list_ref(Arc::new(Type::ANY)), - &[ - Parameter { - name: "x".to_string(), - ty: Arc::new(Type::ANY), - has_default: true, - default_value: None, - range: dummy_range(), - }, - ], - r#"Built-in list function, which can convert other data types or construct a list. - -If no argument is given, the constructor creates a new empty list. -The argument must be an iterable if specified."#, - false, - None, - ) - dict => Type::function( - None, - Type::dict_ref(Arc::new(Type::ANY), Arc::new(Type::ANY)), - &[ - Parameter { - name: "x".to_string(), - ty: Arc::new(Type::ANY), - has_default: true, - default_value: None, - range: dummy_range(), - }, - ], - r#"Built-in dict function. - -If no argument is given, the constructor creates a new empty dict."#, - true, - None, - ) - typeof => Type::function( - None, - Arc::new(Type::STR), - &[ - Parameter { - name: "x".to_string(), - ty: Arc::new(Type::ANY), - has_default: false, - default_value: None, - range: dummy_range(), - }, - Parameter { - name: "full_name".to_string(), - ty: Arc::new(Type::BOOL), - has_default: true, - default_value: None, - range: dummy_range(), - }, - ], - r#"Return the type of the object"#, - false, - None, - ) -} diff --git a/kclvm/sema/src/core/scope.rs b/kclvm/sema/src/core/scope.rs deleted file mode 100644 index 8882884a6..000000000 --- a/kclvm/sema/src/core/scope.rs +++ /dev/null @@ -1,745 +0,0 @@ -use std::collections::{HashMap, HashSet}; - -use kclvm_ast::pos::ContainsPos; -use kclvm_error::{diagnostic::Range, Position}; -use kclvm_primitives::{IndexMap, IndexSet}; -use serde::Serialize; - -use crate::core::symbol::SymbolRef; - -use super::{package::ModuleInfo, symbol::SymbolData}; - -pub trait Scope { - type SymbolData; - fn get_filename(&self) -> &str; - fn get_parent(&self) -> Option; - fn get_children(&self) -> Vec; - - fn contains_pos(&self, pos: &Position) -> bool; - fn get_range(&self) -> Option<(Position, Position)>; - - fn get_owner(&self) -> Option; - fn look_up_def( - &self, - name: &str, - scope_data: &ScopeData, - symbol_data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - // lookup in local scope - local: bool, - // lookup in scope owner - get_def_from_owner: bool, - ) -> Option; - - /// Get all defs within current scope and parent scope - fn get_all_defs( - &self, - scope_data: &ScopeData, - symbol_data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - maybe_in_key: bool, - get_def_from_owner: bool, - ) -> HashMap; - - /// Get all defs within current scope - fn get_defs_within_scope( - &self, - scope_data: &ScopeData, - symbol_data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - maybe_in_key: bool, - get_def_from_owner: bool, - ) -> HashMap; - - fn dump(&self, scope_data: &ScopeData, symbol_data: &Self::SymbolData) -> Option; -} - -#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Serialize)] -pub enum ScopeKind { - Local, - Root, -} - -#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] -pub struct ScopeRef { - pub(crate) id: generational_arena::Index, - pub(crate) kind: ScopeKind, -} - -impl Serialize for ScopeRef { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - let (index, generation) = self.id.into_raw_parts(); - let data = SerializableScopeRef { - i: index as u64, - g: generation, - kind: self.kind.clone(), - }; - data.serialize(serializer) - } -} - -#[derive(Debug, Clone, Serialize)] - -struct SerializableScopeRef { - i: u64, - g: u64, - kind: ScopeKind, -} - -impl ScopeRef { - pub fn get_id(&self) -> generational_arena::Index { - self.id - } - - pub fn get_kind(&self) -> ScopeKind { - self.kind - } -} - -#[derive(Default, Debug, Clone)] -pub struct ScopeData { - /// map pkgpath to root_scope - pub(crate) root_map: IndexMap, - /// map schema fully qualified name to schema local scope - pub(crate) schema_scope_map: IndexMap, - pub(crate) locals: generational_arena::Arena, - pub(crate) roots: generational_arena::Arena, - pub(crate) config_scope_context: IndexMap, -} - -/// Determine the position of pos in the config scope for completion in lsp. -/// Refer to gopls `compLitInfo`: https://github.com/golang/tools/blob/28ba9914c6b79f6cf3a56cc477398f7fd686c84d/gopls/internal/golang/completion/completion.go#L298 -/// But the semantics are different. Complete item in: -/// Go: left = keys + right right = all def in scope and parent scope -/// kcl: left = keys if in schema, right = all def in left and parent scope -#[derive(Default, Debug, Clone)] -pub struct ConfigScopeContext { - pub entries_range: Vec<(Option, Range)>, -} - -impl ConfigScopeContext { - pub fn in_entry(&self, pos: &Position) -> bool { - self.entries_range.iter().any(|(key, value)| { - let start = if key.is_some() { - key.clone().unwrap().0 - } else { - value.0.clone() - }; - start.less_equal(pos) && pos.less_equal(&value.1) - }) - } - - pub fn maybe_in_key(&self, pos: &Position) -> bool { - !self.in_right_value(pos) - } - - pub fn in_right_value(&self, pos: &Position) -> bool { - self.entries_range - .iter() - .any(|(_, value)| value.contains_pos(pos)) - } -} - -impl ScopeData { - #[inline] - pub fn get_root_scope_map(&self) -> &IndexMap { - &self.root_map - } - - pub fn get_scope(&self, scope: &ScopeRef) -> Option<&dyn Scope> { - match scope.get_kind() { - ScopeKind::Local => { - Some(self.locals.get(scope.get_id())? as &dyn Scope) - } - ScopeKind::Root => { - Some(self.roots.get(scope.get_id())? as &dyn Scope) - } - } - } - - pub fn remove_scope(&mut self, scope: &ScopeRef) { - match scope.get_kind() { - ScopeKind::Local => { - self.locals.remove(scope.get_id()); - } - ScopeKind::Root => { - self.roots.remove(scope.get_id()); - } - } - } - - pub fn try_get_local_scope(&self, scope: &ScopeRef) -> Option<&LocalSymbolScope> { - match scope.get_kind() { - ScopeKind::Local => Some(self.locals.get(scope.get_id())?), - ScopeKind::Root => None, - } - } - - pub fn get_root_scope(&self, name: String) -> Option { - self.root_map.get(&name).copied() - } - - pub fn add_def_to_scope(&mut self, scope: ScopeRef, name: String, symbol: SymbolRef) { - match scope.get_kind() { - ScopeKind::Local => { - if let Some(local) = self.locals.get_mut(scope.get_id()) { - local.defs.insert(name, symbol); - } - } - ScopeKind::Root => { - unreachable!("never add symbol to root scope after namer pass") - } - } - } - - pub fn add_ref_to_scope(&mut self, scope: ScopeRef, symbol: SymbolRef) { - match scope.get_kind() { - ScopeKind::Local => { - if let Some(local) = self.locals.get_mut(scope.get_id()) { - local.refs.push(symbol); - } - } - ScopeKind::Root => { - if let Some(root) = self.roots.get_mut(scope.get_id()) { - root.refs.push(symbol); - } - } - } - } - - pub fn set_owner_to_scope(&mut self, scope: ScopeRef, owner: SymbolRef) { - match scope.get_kind() { - ScopeKind::Local => { - if let Some(local) = self.locals.get_mut(scope.get_id()) { - local.owner = Some(owner); - } - } - ScopeKind::Root => { - if let Some(root) = self.roots.get_mut(scope.get_id()) { - root.owner = owner; - } - } - } - } - - pub fn alloc_root_scope(&mut self, root: RootSymbolScope) -> ScopeRef { - let filepath = root.pkgpath.clone(); - let id = self.roots.insert(root); - let scope_ref = ScopeRef { - id, - kind: ScopeKind::Root, - }; - self.root_map.insert(filepath, scope_ref); - scope_ref - } - - pub fn alloc_local_scope(&mut self, local: LocalSymbolScope) -> ScopeRef { - let id = self.locals.insert(local); - ScopeRef { - id, - kind: ScopeKind::Local, - } - } - - pub fn clear_cache(&mut self, invalidate_pkgs: &HashSet) { - for invalidate_pkg in invalidate_pkgs { - if let Some(scope_ref) = self.root_map.swap_remove(invalidate_pkg) { - self.clear_scope_and_child(scope_ref); - self.roots.remove(scope_ref.get_id()); - } - self.schema_scope_map - .retain(|key, _| !key.starts_with(invalidate_pkg)); - } - } - - pub fn clear_scope_and_child(&mut self, scope_ref: ScopeRef) { - if let Some(scope) = self.get_scope(&scope_ref) { - for c in scope.get_children() { - self.clear_scope_and_child(c) - } - } - self.remove_scope(&scope_ref) - } - - pub fn set_config_scope_ctx(&mut self, scope: ScopeRef, ctx: ConfigScopeContext) { - self.config_scope_context.insert(scope.get_id(), ctx); - } - - pub fn get_config_scope_ctx(&self, scope: ScopeRef) -> Option { - self.config_scope_context.get(&scope.get_id()).cloned() - } -} - -#[derive(Debug, Clone)] -pub struct RootSymbolScope { - pub(crate) pkgpath: String, - - pub(crate) filename: String, - - pub(crate) kfile_path: IndexSet, - - /// PackageSymbol of this scope - pub(crate) owner: SymbolRef, - - /// map filepath to children - pub(crate) children: IndexMap>, - - pub(crate) refs: Vec, -} - -impl Scope for RootSymbolScope { - type SymbolData = SymbolData; - fn get_filename(&self) -> &str { - &self.filename - } - - fn get_children(&self) -> Vec { - let mut children = vec![]; - for scopes in self.children.values() { - children.append(&mut scopes.clone()) - } - children - } - - fn get_parent(&self) -> Option { - None - } - - fn contains_pos(&self, pos: &Position) -> bool { - self.kfile_path.contains(&pos.filename) - } - fn get_owner(&self) -> Option { - Some(self.owner) - } - - fn look_up_def( - &self, - name: &str, - _scope_data: &ScopeData, - symbol_data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - _local: bool, - _owner: bool, - ) -> Option { - let package_symbol = symbol_data.get_symbol(self.owner)?; - - package_symbol.get_attribute(name, symbol_data, module_info) - } - - fn get_all_defs( - &self, - _scope_data: &ScopeData, - symbol_data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - _maybe_in_key: bool, - _owner: bool, - ) -> HashMap { - let mut all_defs_map = HashMap::new(); - if let Some(owner) = symbol_data.get_symbol(self.owner) { - let all_defs = owner.get_all_attributes(symbol_data, module_info); - - for def_ref in all_defs { - if let Some(def) = symbol_data.get_symbol(def_ref) { - all_defs_map.insert(def.get_name(), def_ref); - } - } - } - all_defs_map - } - - fn dump(&self, scope_data: &ScopeData, symbol_data: &Self::SymbolData) -> Option { - let mut output = String::from(""); - output.push_str("{\n\"scope_kind\": \"Root\",\n"); - output.push_str(&format!("\n\"pkgpath\": \"{}\",\n", self.pkgpath)); - let owner_symbol = symbol_data.get_symbol(self.owner)?; - output.push_str(&format!( - "\"owner\": {},\n", - owner_symbol.full_dump(symbol_data)? - )); - output.push_str("\"refs\": [\n"); - for (index, symbol) in self.refs.iter().enumerate() { - let symbol = symbol_data.get_symbol(*symbol)?; - output.push_str(&format!("{}", symbol.full_dump(symbol_data)?)); - if index + 1 < self.refs.len() { - output.push_str(",\n") - } - } - output.push_str("\n],\n"); - output.push_str("\"children\": {\n"); - for (index, (key, scopes)) in self.children.iter().enumerate() { - output.push_str(&format!("\"{}\": [\n", key)); - for (index, scope) in scopes.iter().enumerate() { - let scope = scope_data.get_scope(scope)?; - output.push_str(&format!("{}", scope.dump(scope_data, symbol_data)?)); - if index + 1 < scopes.len() { - output.push_str(",\n"); - } - } - output.push_str("\n]"); - if index + 1 < self.children.len() { - output.push_str(",\n"); - } - } - output.push_str("\n}\n}"); - - let val: serde_json::Value = serde_json::from_str(&output).unwrap(); - Some(serde_json::to_string_pretty(&val).ok()?) - } - - fn get_range(&self) -> Option<(Position, Position)> { - None - } - - fn get_defs_within_scope( - &self, - scope_data: &ScopeData, - symbol_data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - maybe_in_key: bool, - owner: bool, - ) -> HashMap { - // get defs within root scope equal to get all defs - self.get_all_defs(scope_data, symbol_data, module_info, maybe_in_key, owner) - } -} - -impl RootSymbolScope { - pub fn new( - pkgpath: String, - filename: String, - owner: SymbolRef, - kfile_path: IndexSet, - ) -> Self { - Self { - pkgpath, - kfile_path, - filename, - owner, - children: IndexMap::default(), - refs: vec![], - } - } - - pub fn add_child(&mut self, filepath: &str, child: ScopeRef) { - if self.children.contains_key(filepath) { - self.children.get_mut(filepath).unwrap().push(child); - } else { - self.children.insert(filepath.to_string(), vec![child]); - } - } -} - -#[derive(Debug, Clone)] -pub struct LocalSymbolScope { - pub(crate) parent: ScopeRef, - pub(crate) owner: Option, - pub(crate) children: Vec, - pub(crate) defs: IndexMap, - pub(crate) refs: Vec, - - pub(crate) start: Position, - pub(crate) end: Position, - pub(crate) kind: LocalSymbolScopeKind, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum LocalSymbolScopeKind { - List, - Dict, - Quant, - Lambda, - SchemaDef, - Config, - Check, - Callable, -} - -impl Scope for LocalSymbolScope { - type SymbolData = SymbolData; - - fn get_filename(&self) -> &str { - &self.start.filename - } - - fn get_children(&self) -> Vec { - self.children.clone() - } - - fn get_parent(&self) -> Option { - Some(self.parent) - } - - fn contains_pos(&self, pos: &Position) -> bool { - self.start.filename == pos.filename - && self.start.less_equal(pos) - && pos.less_equal(&self.end) - } - - fn get_owner(&self) -> Option { - self.owner.clone() - } - - fn look_up_def( - &self, - name: &str, - scope_data: &ScopeData, - symbol_data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - local: bool, - get_def_from_owner: bool, - ) -> Option { - match self.defs.get(name) { - Some(symbol_ref) => return Some(*symbol_ref), - None => { - // Try to get the attributes in the schema's protocol and mixin, and get the schema attr by `get_def_from_owner` - if let LocalSymbolScopeKind::SchemaDef = self.kind { - if let Some(owner) = self.owner.as_ref() { - if let Some(owner_schema) = symbol_data.get_schema_symbol(*owner) { - let attrs = - owner_schema.get_protocol_and_mixin_attrs(symbol_data, module_info); - for attr in attrs { - if let Some(symbol) = symbol_data.get_symbol(attr) { - if symbol.get_name() == name { - return Some(attr); - } - } - } - } - } - } - - match (local, get_def_from_owner) { - // Search in the current scope and owner - (true, true) => { - if let Some(owner) = self.owner.as_ref() { - let owner_symbol = symbol_data.get_symbol(*owner)?; - if let Some(symbol_ref) = - owner_symbol.get_attribute(name, symbol_data, module_info) - { - return Some(symbol_ref); - } - } - None - } - // Search only in the current scope - (true, false) => None, - // Search in the current scope, parent scope and owner - (false, true) => { - if let Some(owner) = self.owner.as_ref() { - let owner_symbol = symbol_data.get_symbol(*owner)?; - if let Some(symbol_ref) = - owner_symbol.get_attribute(name, symbol_data, module_info) - { - return Some(symbol_ref); - } - }; - - let parent = scope_data.get_scope(&self.parent)?; - return parent.look_up_def( - name, - scope_data, - symbol_data, - module_info, - local, - get_def_from_owner, - ); - } - // Search in the current and parent scope - (false, false) => { - let parent = scope_data.get_scope(&self.parent)?; - return parent.look_up_def( - name, - scope_data, - symbol_data, - module_info, - local, - get_def_from_owner, - ); - } - } - } - } - } - - fn get_all_defs( - &self, - scope_data: &ScopeData, - symbol_data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - maybe_in_key: bool, - owner: bool, - ) -> HashMap { - let mut all_defs_map = HashMap::new(); - if owner { - if let Some(owner) = self.owner { - if let Some(owner) = symbol_data.get_symbol(owner) { - for def_ref in owner.get_all_attributes(symbol_data, module_info) { - if let Some(def) = symbol_data.get_symbol(def_ref) { - let name = def.get_name(); - if !all_defs_map.contains_key(&name) { - all_defs_map.insert(name, def_ref); - } - } - } - } - } - } - // In Config, available definitions only contain keys of schema attr,i.e., `left` values in schema expr. - // but right value in schema expr, available definitions contain all def in left parent definitions. - // ``` - // b = "bar" - // foo = Foo{ - // bar: b - // } - // ```` - // At position of `bar`, only get def from keys of Foo - // At position of seconde `b`, get def from left([bar]) and parent scope - if maybe_in_key { - return all_defs_map; - } - - for def_ref in self.defs.values() { - if let Some(def) = symbol_data.get_symbol(*def_ref) { - all_defs_map.insert(def.get_name(), *def_ref); - } - } - - if let Some(parent) = scope_data.get_scope(&self.parent) { - for (name, def_ref) in - parent.get_all_defs(scope_data, symbol_data, module_info, false, owner) - { - if !all_defs_map.contains_key(&name) { - all_defs_map.insert(name, def_ref); - } - } - } - all_defs_map - } - - fn dump(&self, scope_data: &ScopeData, symbol_data: &Self::SymbolData) -> Option { - let mut output = String::from(""); - output.push_str("{\n\"scope_kind\": \"Local\",\n"); - output.push_str(&format!( - "\"range\": \"{}:{}", - self.start.filename, self.start.line - )); - if let Some(start_col) = self.start.column { - output.push_str(&format!(":{}", start_col)); - } - - output.push_str(&format!(" to {}", self.end.line)); - if let Some(end_col) = self.end.column { - output.push_str(&format!(":{}", end_col)); - } - output.push_str("\",\n"); - if let Some(owner) = self.owner.as_ref() { - let owner_symbol = symbol_data.get_symbol(*owner)?; - output.push_str(&format!( - "\"owner\": {},\n", - owner_symbol.full_dump(symbol_data)? - )); - } - output.push_str("\"defs\": {\n"); - for (index, (key, symbol)) in self.defs.iter().enumerate() { - let symbol = symbol_data.get_symbol(*symbol)?; - output.push_str(&format!("\"{}\": {}", key, symbol.full_dump(symbol_data)?)); - if index + 1 < self.defs.len() { - output.push_str(",\n") - } - } - output.push_str("\n},\n"); - output.push_str("\"refs\": [\n"); - for (index, symbol) in self.refs.iter().enumerate() { - let symbol = symbol_data.get_symbol(*symbol)?; - output.push_str(&format!("{}", symbol.full_dump(symbol_data)?)); - if index + 1 < self.refs.len() { - output.push_str(",\n") - } - } - output.push_str("\n],"); - output.push_str("\n\"children\": [\n"); - for (index, scope) in self.children.iter().enumerate() { - let scope = scope_data.get_scope(scope)?; - output.push_str(&format!("{}", scope.dump(scope_data, symbol_data)?)); - if index + 1 < self.children.len() { - output.push_str(",\n") - } - } - output.push_str("\n]\n}"); - Some(output) - } - - fn get_range(&self) -> Option<(Position, Position)> { - Some((self.start.clone(), self.end.clone())) - } - - fn get_defs_within_scope( - &self, - _scope_data: &ScopeData, - symbol_data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - _maybe_in_key: bool, - owner: bool, - ) -> HashMap { - let mut all_defs_map = HashMap::new(); - if owner { - if let Some(owner) = self.owner { - if let Some(owner) = symbol_data.get_symbol(owner) { - for def_ref in owner.get_all_attributes(symbol_data, module_info) { - if let Some(def) = symbol_data.get_symbol(def_ref) { - let name = def.get_name(); - if !all_defs_map.contains_key(&name) { - all_defs_map.insert(name, def_ref); - } - } - } - } - } - } - - for def_ref in self.defs.values() { - if let Some(def) = symbol_data.get_symbol(*def_ref) { - all_defs_map.insert(def.get_name(), *def_ref); - } - } - all_defs_map - } -} - -impl LocalSymbolScope { - pub fn new( - parent: ScopeRef, - start: Position, - end: Position, - kind: LocalSymbolScopeKind, - ) -> Self { - Self { - parent, - owner: None, - children: vec![], - defs: IndexMap::default(), - refs: vec![], - start, - end, - kind, - } - } - - #[inline] - pub fn get_kind(&self) -> &LocalSymbolScopeKind { - &self.kind - } - - #[inline] - pub fn add_child(&mut self, child: ScopeRef) { - self.children.push(child) - } - - #[inline] - pub fn set_owner(&mut self, owner: SymbolRef) { - self.owner = Some(owner) - } -} diff --git a/kclvm/sema/src/core/symbol.rs b/kclvm/sema/src/core/symbol.rs deleted file mode 100644 index ac7cc8edf..000000000 --- a/kclvm/sema/src/core/symbol.rs +++ /dev/null @@ -1,2651 +0,0 @@ -use std::{ - collections::{HashMap, HashSet}, - sync::Arc, -}; - -use generational_arena::Arena; -use kclvm_primitives::{IndexMap, IndexSet}; - -use kclvm_error::{diagnostic::Range, Position}; -use serde::Serialize; - -use super::package::ModuleInfo; -use crate::{ - resolver::scope::NodeKey, - ty::{Type, TypeKind, TypeRef}, -}; - -pub trait Symbol { - type SymbolData; - type SemanticInfo; - type SymbolHint; - - fn get_sema_info(&self) -> &Self::SemanticInfo; - fn is_global(&self) -> bool; - fn get_range(&self) -> Range; - fn get_owner(&self) -> Option; - fn get_definition(&self) -> Option; - fn get_references(&self) -> HashSet; - fn get_name(&self) -> String; - fn get_id(&self) -> Option; - fn get_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Option; - fn has_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> bool; - - fn get_all_attributes( - &self, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Vec; - - fn simple_dump(&self) -> String; - - fn full_dump(&self, data: &Self::SymbolData) -> Option; -} - -pub type KCLSymbol = - dyn Symbol; -#[derive(Debug, Clone, Default)] -pub struct SymbolSemanticInfo { - pub ty: Option>, - pub doc: Option, -} - -pub(crate) const BUILTIN_STR_PACKAGE: &'static str = "@str"; -pub(crate) const BUILTIN_FUNCTION_PACKAGE: &'static str = "@builtin"; - -#[derive(Default, Debug, Clone)] -pub struct SymbolData { - pub(crate) values: Arena, - pub(crate) packages: Arena, - pub(crate) attributes: Arena, - pub(crate) schemas: Arena, - pub(crate) type_aliases: Arena, - pub(crate) unresolved: Arena, - pub(crate) rules: Arena, - pub(crate) exprs: Arena, - pub(crate) comments: Arena, - pub(crate) decorators: Arena, - pub(crate) functions: Arena, - pub(crate) hints: HashMap>, - - pub(crate) symbols_info: SymbolDB, -} - -#[derive(Default, Debug, Clone)] -pub struct SymbolDB { - pub(crate) symbol_pos_set: IndexSet, - pub(crate) global_builtin_symbols: IndexMap, - pub(crate) fully_qualified_name_map: IndexMap, - pub(crate) schema_builtin_symbols: IndexMap>, - pub(crate) node_symbol_map: IndexMap, - pub(crate) symbol_node_map: IndexMap, - pub(crate) pkg_symbol_map: IndexMap>, -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct SymbolHint { - pub kind: SymbolHintKind, - pub pos: Position, -} - -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub enum SymbolHintKind { - TypeHint(String), - VarHint(String), - KeyTypeHint(String), -} - -impl SymbolData { - pub fn get_all_schemas(&self) -> &Arena { - &self.schemas - } - - pub fn get_package_symbol(&self, id: SymbolRef) -> Option<&PackageSymbol> { - if matches!(id.get_kind(), SymbolKind::Package) { - self.packages.get(id.get_id()) - } else { - None - } - } - - pub fn get_value_symbol(&self, id: SymbolRef) -> Option<&ValueSymbol> { - if matches!(id.get_kind(), SymbolKind::Value) { - self.values.get(id.get_id()) - } else { - None - } - } - - pub fn get_attribute_symbol(&self, id: SymbolRef) -> Option<&AttributeSymbol> { - if matches!(id.get_kind(), SymbolKind::Attribute) { - self.attributes.get(id.get_id()) - } else { - None - } - } - - pub fn get_type_alias_symbol(&self, id: SymbolRef) -> Option<&TypeAliasSymbol> { - if matches!(id.get_kind(), SymbolKind::TypeAlias) { - self.type_aliases.get(id.get_id()) - } else { - None - } - } - - pub fn get_schema_symbol(&self, id: SymbolRef) -> Option<&SchemaSymbol> { - if matches!(id.get_kind(), SymbolKind::Schema) { - self.schemas.get(id.get_id()) - } else { - None - } - } - - pub fn get_rule_symbol(&self, id: SymbolRef) -> Option<&RuleSymbol> { - if matches!(id.get_kind(), SymbolKind::Rule) { - self.rules.get(id.get_id()) - } else { - None - } - } - - pub fn get_attr_symbol(&self, id: SymbolRef) -> Option<&AttributeSymbol> { - if matches!(id.get_kind(), SymbolKind::Attribute) { - self.attributes.get(id.get_id()) - } else { - None - } - } - - pub fn get_function_symbol(&self, id: SymbolRef) -> Option<&FunctionSymbol> { - if matches!(id.get_kind(), SymbolKind::Function) { - self.functions.get(id.get_id()) - } else { - None - } - } - - pub fn get_unresolved_symbol(&self, id: SymbolRef) -> Option<&UnresolvedSymbol> { - if matches!(id.get_kind(), SymbolKind::Unresolved) { - self.unresolved.get(id.get_id()) - } else { - None - } - } - - pub fn get_symbol(&self, id: SymbolRef) -> Option<&KCLSymbol> { - match id.get_kind() { - SymbolKind::Schema => self - .schemas - .get(id.get_id()) - .map(|symbol| symbol as &KCLSymbol), - SymbolKind::Attribute => self - .attributes - .get(id.get_id()) - .map(|symbol| symbol as &KCLSymbol), - SymbolKind::Value => self - .values - .get(id.get_id()) - .map(|symbol| symbol as &KCLSymbol), - SymbolKind::Package => self - .packages - .get(id.get_id()) - .map(|symbol| symbol as &KCLSymbol), - SymbolKind::TypeAlias => self - .type_aliases - .get(id.get_id()) - .map(|symbol| symbol as &KCLSymbol), - SymbolKind::Unresolved => self - .unresolved - .get(id.get_id()) - .map(|symbol| symbol as &KCLSymbol), - SymbolKind::Rule => self - .rules - .get(id.get_id()) - .map(|symbol| symbol as &KCLSymbol), - SymbolKind::Expression => self - .exprs - .get(id.get_id()) - .map(|symbol| symbol as &KCLSymbol), - SymbolKind::Comment => self - .comments - .get(id.get_id()) - .map(|symbol| symbol as &KCLSymbol), - SymbolKind::Decorator => self - .decorators - .get(id.get_id()) - .map(|symbol| symbol as &KCLSymbol), - SymbolKind::Function => self - .functions - .get(id.get_id()) - .map(|symbol| symbol as &KCLSymbol), - } - } - - pub fn remove_symbol(&mut self, id: &SymbolRef) { - if let Some(symbol) = self.get_symbol(id.clone()) { - self.symbols_info - .symbol_pos_set - .swap_remove(&symbol.get_range().1); - } - match id.get_kind() { - SymbolKind::Schema => { - self.schemas.remove(id.get_id()); - self.symbols_info.schema_builtin_symbols.swap_remove(id); - } - SymbolKind::Attribute => { - self.attributes.remove(id.get_id()); - } - SymbolKind::Value => { - self.values.remove(id.get_id()); - } - SymbolKind::Package => { - self.packages.remove(id.get_id()); - } - SymbolKind::TypeAlias => { - self.type_aliases.remove(id.get_id()); - } - SymbolKind::Unresolved => { - self.unresolved.remove(id.get_id()); - } - SymbolKind::Rule => { - self.rules.remove(id.get_id()); - } - SymbolKind::Expression => { - self.exprs.remove(id.get_id()); - } - SymbolKind::Comment => { - self.comments.remove(id.get_id()); - } - SymbolKind::Decorator => { - self.decorators.remove(id.get_id()); - } - SymbolKind::Function => { - self.functions.remove(id.get_id()); - } - } - } - - pub fn set_symbol_type(&mut self, id: SymbolRef, ty: TypeRef) { - match id.get_kind() { - SymbolKind::Schema => { - self.schemas.get_mut(id.get_id()).map(|symbol| { - symbol.sema_info.ty = Some(ty); - symbol - }); - } - SymbolKind::Attribute => { - self.attributes.get_mut(id.get_id()).map(|symbol| { - symbol.sema_info.ty = Some(ty); - symbol - }); - } - SymbolKind::Value => { - self.values.get_mut(id.get_id()).map(|symbol| { - symbol.sema_info.ty = Some(ty); - symbol - }); - } - SymbolKind::Package => { - self.packages.get_mut(id.get_id()).map(|symbol| { - symbol.sema_info.ty = Some(ty); - symbol - }); - } - SymbolKind::TypeAlias => { - self.type_aliases.get_mut(id.get_id()).map(|symbol| { - symbol.sema_info.ty = Some(ty); - symbol - }); - } - SymbolKind::Unresolved => { - self.unresolved.get_mut(id.get_id()).map(|symbol| { - symbol.sema_info.ty = Some(ty); - symbol - }); - } - SymbolKind::Rule => { - self.rules.get_mut(id.get_id()).map(|symbol| { - symbol.sema_info.ty = Some(ty); - symbol - }); - } - SymbolKind::Expression => { - self.exprs.get_mut(id.get_id()).map(|symbol| { - symbol.sema_info.ty = Some(ty); - symbol - }); - } - SymbolKind::Comment => { - self.comments.get_mut(id.get_id()).map(|symbol| { - symbol.sema_info.ty = Some(ty); - symbol - }); - } - SymbolKind::Decorator => { - self.decorators.get_mut(id.get_id()).map(|symbol| { - symbol.sema_info.ty = Some(ty); - symbol - }); - } - SymbolKind::Function => { - self.functions.get_mut(id.get_id()).map(|symbol| { - symbol.sema_info.ty = Some(ty); - symbol - }); - } - } - } - - pub fn get_type_symbol( - &self, - ty: &Type, - module_info: Option<&ModuleInfo>, - ) -> Option { - match &ty.kind { - //TODO: builtin ty symbol,now we just return none - TypeKind::None => None, - TypeKind::Any => None, - TypeKind::Void => None, - TypeKind::Bool => None, - TypeKind::BoolLit(_) => None, - TypeKind::Int => None, - TypeKind::IntLit(_) => None, - TypeKind::Float => None, - TypeKind::FloatLit(_) => None, - TypeKind::Str => self.get_symbol_by_fully_qualified_name(BUILTIN_STR_PACKAGE), - TypeKind::StrLit(_) => self.get_symbol_by_fully_qualified_name(BUILTIN_STR_PACKAGE), - TypeKind::List(_) => None, - TypeKind::Dict(_) => None, - TypeKind::NumberMultiplier(_) => None, - TypeKind::Function(_) => None, - TypeKind::Union(types) => { - if types - .iter() - .all(|ut| matches!(&ut.kind, TypeKind::StrLit(_) | TypeKind::Str)) - { - self.get_symbol_by_fully_qualified_name(BUILTIN_STR_PACKAGE) - } else { - None - } - } - TypeKind::Schema(schema_ty) => { - let fully_qualified_ty_name = schema_ty.pkgpath.clone() + "." + &schema_ty.name; - - self.get_symbol_by_fully_qualified_name(&fully_qualified_ty_name) - } - TypeKind::Module(module_ty) => { - self.get_symbol_by_fully_qualified_name(&module_ty.pkgpath) - } - TypeKind::Named(name) => { - let splits: Vec<&str> = name.rsplitn(2, '.').collect(); - let len = splits.len(); - let pkgname = splits[len - 1]; - - let pkgpath: &String = &module_info?.get_import_info(pkgname)?.fully_qualified_name; - let fully_qualified_ty_name = if name.contains('.') { - name.replacen(&pkgname, pkgpath, 1) - } else { - kclvm_ast::MAIN_PKG.to_string() + name - }; - - self.get_symbol_by_fully_qualified_name(&fully_qualified_ty_name) - } - } - } - - pub fn get_type_all_attribute( - &self, - ty: &Type, - name: &str, - module_info: Option<&ModuleInfo>, - ) -> Vec { - match &ty.kind { - //TODO: builtin ty symbol,now we just return none - TypeKind::None => vec![], - TypeKind::Any => vec![], - TypeKind::Void => vec![], - TypeKind::Bool => vec![], - TypeKind::BoolLit(_) => vec![], - TypeKind::Int => vec![], - TypeKind::IntLit(_) => vec![], - TypeKind::Float => vec![], - TypeKind::FloatLit(_) => vec![], - TypeKind::Str | TypeKind::StrLit(_) => { - let mut result = vec![]; - if let Some(symbol_ref) = self.get_type_symbol(ty, module_info) { - if let Some(symbol) = self.get_symbol(symbol_ref) { - result = symbol.get_all_attributes(self, module_info); - } - } - result - } - TypeKind::List(_) => vec![], - TypeKind::Dict(_) => vec![], - TypeKind::NumberMultiplier(_) => vec![], - TypeKind::Function(_) => vec![], - TypeKind::Union(tys) => { - let mut result = vec![]; - for ty in tys.iter() { - result.append(&mut self.get_type_all_attribute(ty, name, module_info)); - } - result - } - TypeKind::Schema(_) => { - let mut result = vec![]; - if let Some(symbol_ref) = self.get_type_symbol(ty, module_info) { - if let Some(symbol) = self.get_symbol(symbol_ref) { - result = symbol.get_all_attributes(self, module_info); - } - } - result - } - TypeKind::Module(_) => { - let mut result = vec![]; - if let Some(symbol_ref) = self.get_type_symbol(ty, module_info) { - if let Some(symbol) = self.get_symbol(symbol_ref) { - result = symbol.get_all_attributes(self, module_info); - } - } - result - } - TypeKind::Named(_) => { - let mut result = vec![]; - if let Some(symbol_ref) = self.get_type_symbol(ty, module_info) { - if let Some(symbol) = self.get_symbol(symbol_ref) { - result = symbol.get_all_attributes(self, module_info); - } - } - result - } - } - } - - pub fn get_type_attribute( - &self, - ty: &Type, - name: &str, - module_info: Option<&ModuleInfo>, - ) -> Option { - match &ty.kind { - TypeKind::None => None, - TypeKind::Any => None, - TypeKind::Void => None, - TypeKind::Bool => None, - TypeKind::BoolLit(_) => None, - TypeKind::Int => None, - TypeKind::IntLit(_) => None, - TypeKind::Float => None, - TypeKind::FloatLit(_) => None, - TypeKind::Str => self - .get_symbol(self.get_type_symbol(ty, module_info)?)? - .get_attribute(name, self, module_info), - TypeKind::StrLit(_) => self - .get_symbol(self.get_type_symbol(ty, module_info)?)? - .get_attribute(name, self, module_info), - TypeKind::List(_) => None, - TypeKind::Dict(_) => None, - TypeKind::NumberMultiplier(_) => None, - TypeKind::Function(_) => None, - TypeKind::Union(tys) => { - for ty in tys.iter() { - if let Some(symbol_ref) = self.get_type_attribute(ty, name, module_info) { - return Some(symbol_ref); - } - } - None - } - TypeKind::Schema(_) => self - .get_symbol(self.get_type_symbol(ty, module_info)?)? - .get_attribute(name, self, module_info), - TypeKind::Module(_) => self - .get_symbol(self.get_type_symbol(ty, module_info)?)? - .get_attribute(name, self, module_info), - TypeKind::Named(_) => self - .get_symbol(self.get_type_symbol(ty, module_info)?)? - .get_attribute(name, self, module_info), - } - } - - pub fn get_symbol_by_fully_qualified_name(&self, fqn: &str) -> Option { - self.symbols_info.fully_qualified_name_map.get(fqn).cloned() - } - - pub fn get_fully_qualified_name(&self, symbol_ref: SymbolRef) -> Option { - match symbol_ref.get_kind() { - SymbolKind::Unresolved => None, - _ => { - let symbol = self.get_symbol(symbol_ref)?; - let owner = symbol.get_owner(); - if let Some(owner) = owner { - Some(self.get_fully_qualified_name(owner)? + "." + &symbol.get_name()) - } else { - Some(symbol.get_name()) - } - } - } - } - - pub fn build_fully_qualified_name_map(&mut self) { - for (id, _) in self.packages.iter() { - let symbol_ref = SymbolRef { - id, - kind: SymbolKind::Package, - }; - self.symbols_info.fully_qualified_name_map.insert( - self.get_fully_qualified_name(symbol_ref).unwrap(), - symbol_ref, - ); - } - - for (id, _) in self.schemas.iter() { - let symbol_ref = SymbolRef { - id, - kind: SymbolKind::Schema, - }; - self.symbols_info.fully_qualified_name_map.insert( - self.get_fully_qualified_name(symbol_ref).unwrap(), - symbol_ref, - ); - } - - for (id, _) in self.type_aliases.iter() { - let symbol_ref = SymbolRef { - id, - kind: SymbolKind::TypeAlias, - }; - self.symbols_info.fully_qualified_name_map.insert( - self.get_fully_qualified_name(symbol_ref).unwrap(), - symbol_ref, - ); - } - - for (id, _) in self.attributes.iter() { - let symbol_ref = SymbolRef { - id, - kind: SymbolKind::Attribute, - }; - self.symbols_info.fully_qualified_name_map.insert( - self.get_fully_qualified_name(symbol_ref).unwrap(), - symbol_ref, - ); - } - - for (id, _) in self.rules.iter() { - let symbol_ref = SymbolRef { - id, - kind: SymbolKind::Rule, - }; - self.symbols_info.fully_qualified_name_map.insert( - self.get_fully_qualified_name(symbol_ref).unwrap(), - symbol_ref, - ); - } - - for (id, _) in self.values.iter() { - let symbol_ref = SymbolRef { - id, - kind: SymbolKind::Value, - }; - self.symbols_info.fully_qualified_name_map.insert( - self.get_fully_qualified_name(symbol_ref).unwrap(), - symbol_ref, - ); - } - - for (id, _) in self.functions.iter() { - let symbol_ref = SymbolRef { - id, - kind: SymbolKind::Function, - }; - self.symbols_info.fully_qualified_name_map.insert( - self.get_fully_qualified_name(symbol_ref).unwrap(), - symbol_ref, - ); - } - } - - pub fn insert_package_symbol(&mut self, symbol_ref: SymbolRef, pkg_name: String) { - if !self.symbols_info.pkg_symbol_map.contains_key(&pkg_name) { - self.symbols_info - .pkg_symbol_map - .insert(pkg_name.clone(), IndexSet::default()); - } - - self.symbols_info - .pkg_symbol_map - .get_mut(&pkg_name) - .unwrap() - .insert(symbol_ref); - } - - pub fn alloc_package_symbol(&mut self, pkg: PackageSymbol, pkg_name: String) -> SymbolRef { - let symbol_id = self.packages.insert(pkg); - let symbol_ref = SymbolRef { - id: symbol_id, - kind: SymbolKind::Package, - }; - self.packages.get_mut(symbol_id).unwrap().id = Some(symbol_ref); - self.insert_package_symbol(symbol_ref, pkg_name); - symbol_ref - } - - pub fn alloc_schema_symbol( - &mut self, - schema: SchemaSymbol, - node_key: NodeKey, - pkg_name: String, - ) -> SymbolRef { - self.symbols_info.symbol_pos_set.insert(schema.end.clone()); - let symbol_id = self.schemas.insert(schema); - let symbol_ref = SymbolRef { - id: symbol_id, - kind: SymbolKind::Schema, - }; - self.symbols_info - .node_symbol_map - .insert(node_key.clone(), symbol_ref); - self.symbols_info - .symbol_node_map - .insert(symbol_ref, node_key); - self.schemas.get_mut(symbol_id).unwrap().id = Some(symbol_ref); - self.insert_package_symbol(symbol_ref, pkg_name); - symbol_ref - } - - pub fn alloc_unresolved_symbol( - &mut self, - unresolved: UnresolvedSymbol, - node_key: NodeKey, - pkg_name: String, - ) -> SymbolRef { - self.symbols_info - .symbol_pos_set - .insert(unresolved.end.clone()); - let symbol_id = self.unresolved.insert(unresolved); - let symbol_ref = SymbolRef { - id: symbol_id, - kind: SymbolKind::Unresolved, - }; - self.symbols_info - .node_symbol_map - .insert(node_key.clone(), symbol_ref); - self.symbols_info - .symbol_node_map - .insert(symbol_ref, node_key); - self.unresolved.get_mut(symbol_id).unwrap().id = Some(symbol_ref); - self.insert_package_symbol(symbol_ref, pkg_name); - symbol_ref - } - - pub fn alloc_type_alias_symbol( - &mut self, - alias: TypeAliasSymbol, - node_key: NodeKey, - pkg_name: String, - ) -> SymbolRef { - self.symbols_info.symbol_pos_set.insert(alias.end.clone()); - let symbol_id = self.type_aliases.insert(alias); - let symbol_ref = SymbolRef { - id: symbol_id, - kind: SymbolKind::TypeAlias, - }; - self.symbols_info - .node_symbol_map - .insert(node_key.clone(), symbol_ref); - self.symbols_info - .symbol_node_map - .insert(symbol_ref, node_key); - self.type_aliases.get_mut(symbol_id).unwrap().id = Some(symbol_ref); - self.insert_package_symbol(symbol_ref, pkg_name); - symbol_ref - } - - pub fn alloc_rule_symbol( - &mut self, - rule: RuleSymbol, - node_key: NodeKey, - pkg_name: String, - ) -> SymbolRef { - self.symbols_info.symbol_pos_set.insert(rule.end.clone()); - let symbol_id = self.rules.insert(rule); - let symbol_ref = SymbolRef { - id: symbol_id, - kind: SymbolKind::Rule, - }; - self.symbols_info - .node_symbol_map - .insert(node_key.clone(), symbol_ref); - self.symbols_info - .symbol_node_map - .insert(symbol_ref, node_key); - self.rules.get_mut(symbol_id).unwrap().id = Some(symbol_ref); - self.insert_package_symbol(symbol_ref, pkg_name); - symbol_ref - } - - pub fn alloc_attribute_symbol( - &mut self, - attribute: AttributeSymbol, - node_key: NodeKey, - pkg_name: String, - ) -> SymbolRef { - self.symbols_info - .symbol_pos_set - .insert(attribute.end.clone()); - let symbol_id = self.attributes.insert(attribute); - let symbol_ref = SymbolRef { - id: symbol_id, - kind: SymbolKind::Attribute, - }; - self.symbols_info - .node_symbol_map - .insert(node_key.clone(), symbol_ref); - self.symbols_info - .symbol_node_map - .insert(symbol_ref, node_key); - self.attributes.get_mut(symbol_id).unwrap().id = Some(symbol_ref); - self.insert_package_symbol(symbol_ref, pkg_name); - symbol_ref - } - - pub fn alloc_value_symbol( - &mut self, - value: ValueSymbol, - node_key: NodeKey, - pkg_name: String, - ) -> SymbolRef { - self.symbols_info.symbol_pos_set.insert(value.end.clone()); - let symbol_id = self.values.insert(value); - let symbol_ref = SymbolRef { - id: symbol_id, - kind: SymbolKind::Value, - }; - self.symbols_info - .node_symbol_map - .insert(node_key.clone(), symbol_ref); - self.symbols_info - .symbol_node_map - .insert(symbol_ref, node_key); - self.values.get_mut(symbol_id).unwrap().id = Some(symbol_ref); - self.insert_package_symbol(symbol_ref, pkg_name); - symbol_ref - } - - pub fn alloc_expression_symbol( - &mut self, - expr: ExpressionSymbol, - node_key: NodeKey, - pkg_name: String, - ) -> Option { - if self.symbols_info.symbol_pos_set.contains(&expr.end) { - return None; - } - self.symbols_info.symbol_pos_set.insert(expr.end.clone()); - let symbol_id = self.exprs.insert(expr); - let symbol_ref = SymbolRef { - id: symbol_id, - kind: SymbolKind::Expression, - }; - self.symbols_info - .node_symbol_map - .insert(node_key.clone(), symbol_ref); - self.symbols_info - .symbol_node_map - .insert(symbol_ref, node_key); - self.exprs.get_mut(symbol_id).unwrap().id = Some(symbol_ref); - self.insert_package_symbol(symbol_ref, pkg_name); - Some(symbol_ref) - } - - pub fn alloc_comment_symbol( - &mut self, - comment: CommentOrDocSymbol, - node_key: NodeKey, - pkg_name: String, - ) -> Option { - let symbol_id = self.comments.insert(comment); - let symbol_ref = SymbolRef { - id: symbol_id, - kind: SymbolKind::Comment, - }; - self.symbols_info - .node_symbol_map - .insert(node_key.clone(), symbol_ref); - self.symbols_info - .symbol_node_map - .insert(symbol_ref, node_key); - self.comments.get_mut(symbol_id).unwrap().id = Some(symbol_ref); - self.insert_package_symbol(symbol_ref, pkg_name); - Some(symbol_ref) - } - - pub fn alloc_decorator_symbol( - &mut self, - decorator: DecoratorSymbol, - node_key: NodeKey, - pkg_name: String, - ) -> Option { - let symbol_id = self.decorators.insert(decorator); - let symbol_ref = SymbolRef { - id: symbol_id, - kind: SymbolKind::Decorator, - }; - self.symbols_info - .node_symbol_map - .insert(node_key.clone(), symbol_ref); - self.symbols_info - .symbol_node_map - .insert(symbol_ref, node_key); - self.decorators.get_mut(symbol_id).unwrap().id = Some(symbol_ref); - self.insert_package_symbol(symbol_ref, pkg_name); - Some(symbol_ref) - } - - pub fn alloc_function_symbol( - &mut self, - func: FunctionSymbol, - node_key: NodeKey, - pkg_name: String, - ) -> SymbolRef { - self.symbols_info.symbol_pos_set.insert(func.end.clone()); - let symbol_id = self.functions.insert(func); - let symbol_ref = SymbolRef { - id: symbol_id, - kind: SymbolKind::Function, - }; - self.symbols_info - .node_symbol_map - .insert(node_key.clone(), symbol_ref); - self.symbols_info - .symbol_node_map - .insert(symbol_ref, node_key); - self.functions.get_mut(symbol_id).unwrap().id = Some(symbol_ref); - self.insert_package_symbol(symbol_ref, pkg_name); - symbol_ref - } - - pub fn alloc_hint(&mut self, hint: SymbolHint, pkg_name: String) { - match self.hints.get_mut(&pkg_name) { - Some(hints) => hints.push(hint), - None => { - self.hints.insert(pkg_name, vec![hint]); - } - } - } - - #[inline] - pub fn get_node_symbol_map(&self) -> &IndexMap { - &self.symbols_info.node_symbol_map - } - - #[inline] - pub fn get_node_symbol_map_mut(&mut self) -> &mut IndexMap { - &mut self.symbols_info.node_symbol_map - } - - #[inline] - pub fn get_symbol_node_map(&self) -> &IndexMap { - &self.symbols_info.symbol_node_map - } - - #[inline] - pub fn get_symbol_node_map_mut(&mut self) -> &mut IndexMap { - &mut self.symbols_info.symbol_node_map - } - - #[inline] - pub fn get_fully_qualified_name_map(&self) -> &IndexMap { - &self.symbols_info.fully_qualified_name_map - } - - #[inline] - pub fn get_builtin_symbols(&self) -> &IndexMap { - &self.symbols_info.global_builtin_symbols - } - - pub fn clear_cache(&mut self, invalidate_pkgs: &HashSet) { - let mut to_remove: Vec = Vec::new(); - - for invalidate_pkg in invalidate_pkgs { - if let Some(symbols) = self.symbols_info.pkg_symbol_map.get(invalidate_pkg) { - to_remove.extend(symbols.iter().cloned()); - } - self.hints.remove(invalidate_pkg); - } - for symbol in to_remove { - self.remove_symbol(&symbol); - if let Some(node_id) = self.get_symbol_node_map_mut().swap_remove(&symbol) { - self.get_node_symbol_map_mut().swap_remove(&node_id); - } - } - } - - pub fn set_def_and_ref(&mut self, def: SymbolRef, r#ref: SymbolRef) { - self.set_def(def, r#ref); - self.set_ref(def, r#ref); - } - - pub fn set_def(&mut self, def: SymbolRef, r#ref: SymbolRef) { - match r#ref.get_kind() { - SymbolKind::Unresolved => { - self.unresolved.get_mut(r#ref.get_id()).unwrap().def = Some(def) - } - _ => {} - } - } - - pub fn set_ref(&mut self, def: SymbolRef, r#ref: SymbolRef) { - match def.get_kind() { - SymbolKind::Schema => { - self.schemas - .get_mut(def.get_id()) - .unwrap() - .r#ref - .insert(r#ref); - } - - SymbolKind::Attribute => { - self.attributes - .get_mut(def.get_id()) - .unwrap() - .r#ref - .insert(r#ref); - } - SymbolKind::Value => { - self.values - .get_mut(def.get_id()) - .unwrap() - .r#ref - .insert(r#ref); - } - SymbolKind::Function => { - self.functions - .get_mut(def.get_id()) - .unwrap() - .r#ref - .insert(r#ref); - } - SymbolKind::Package => { - self.packages - .get_mut(def.get_id()) - .unwrap() - .r#ref - .insert(r#ref); - } - SymbolKind::TypeAlias => { - self.type_aliases - .get_mut(def.get_id()) - .unwrap() - .r#ref - .insert(r#ref); - } - SymbolKind::Rule => { - self.rules - .get_mut(def.get_id()) - .unwrap() - .r#ref - .insert(r#ref); - } - _ => {} - }; - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)] -pub enum SymbolKind { - Schema, - Attribute, - Value, - Function, - Package, - TypeAlias, - Unresolved, - Rule, - Expression, - Comment, - Decorator, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct SymbolRef { - pub(crate) id: generational_arena::Index, - pub(crate) kind: SymbolKind, -} - -impl Serialize for SymbolRef { - fn serialize(&self, serializer: S) -> Result - where - S: serde::Serializer, - { - let (index, generation) = self.id.into_raw_parts(); - let data = SerializableSymbolRef { - i: index as u64, - g: generation, - kind: self.kind.clone(), - }; - data.serialize(serializer) - } -} - -#[derive(Debug, Clone, Serialize)] - -struct SerializableSymbolRef { - i: u64, - g: u64, - kind: SymbolKind, -} - -impl SymbolRef { - #[inline] - pub fn get_kind(&self) -> SymbolKind { - self.kind - } - #[inline] - pub fn get_id(&self) -> generational_arena::Index { - self.id - } -} -#[allow(unused)] -#[derive(Debug, Clone)] -pub struct SchemaSymbol { - pub(crate) id: Option, - pub(crate) name: String, - pub(crate) start: Position, - pub(crate) end: Position, - pub(crate) owner: SymbolRef, - pub(crate) sema_info: SymbolSemanticInfo, - pub(crate) r#ref: HashSet, - - pub(crate) parent_schema: Option, - pub(crate) for_host: Option, - pub(crate) mixins: Vec, - pub(crate) attributes: IndexMap, -} - -impl Symbol for SchemaSymbol { - type SymbolData = SymbolData; - type SemanticInfo = SymbolSemanticInfo; - type SymbolHint = SymbolHint; - - fn is_global(&self) -> bool { - true - } - fn get_range(&self) -> Range { - (self.start.clone(), self.end.clone()) - } - - fn get_owner(&self) -> Option { - Some(self.owner) - } - - fn get_definition(&self) -> Option { - self.id.clone() - } - - fn get_name(&self) -> String { - self.name.clone() - } - - fn get_id(&self) -> Option { - self.id.clone() - } - - fn get_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Option { - match self.attributes.get(name) { - Some(attribute) => Some(*attribute), - None => { - if let Some(for_host) = self.for_host { - if let Some(attribute) = - data.get_symbol(for_host)? - .get_attribute(name, data, module_info) - { - return Some(attribute); - } - } - - for mixin in self.mixins.iter() { - if let Some(attribute) = - data.get_symbol(*mixin)? - .get_attribute(name, data, module_info) - { - return Some(attribute); - } - } - - if let Some(_) = self.parent_schema { - let mut parents = vec![]; - parents.push(self.id.unwrap()); - self.get_parents(data, &mut parents); - if parents.len() > 1 { - for parent_schema in &parents[1..] { - if let Some(parent_schema) = data.get_schema_symbol(*parent_schema) { - let parent_attr = parent_schema.get_self_attr(data, module_info); - for attr in parent_attr { - if let Some(attribute) = data.get_symbol(attr) { - if attribute.get_name() == name { - return Some(attr); - } - } - } - } - } - } - } - None - } - } - } - - fn get_all_attributes( - &self, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Vec { - let mut result = self.get_self_attr(data, module_info); - if let Some(_) = self.parent_schema { - let mut parents = vec![]; - parents.push(self.id.unwrap()); - self.get_parents(data, &mut parents); - if parents.len() > 1 { - for parent in &parents[1..] { - if let Some(schema_symbol) = data.get_schema_symbol(*parent) { - result.append(&mut schema_symbol.get_self_attr(data, module_info)) - } - } - } - } - result - } - - fn has_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> bool { - self.get_attribute(name, data, module_info).is_some() - } - - fn simple_dump(&self) -> String { - let mut output = "{\n".to_string(); - output.push_str("\"kind\": \"SchemaSymbol\",\n"); - output.push_str(&format!("\"name\":\"{}\",\n", self.name)); - output.push_str(&format!( - "\"range\": \"{}:{}", - self.start.filename, self.start.line - )); - if let Some(start_col) = self.start.column { - output.push_str(&format!(":{}", start_col)); - } - - output.push_str(&format!(" to {}", self.end.line)); - if let Some(end_col) = self.end.column { - output.push_str(&format!(":{}", end_col)); - } - output.push_str("\"\n}"); - output - } - - fn full_dump(&self, data: &Self::SymbolData) -> Option { - let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); - output.push_str("\"additional_info\": {\n"); - let owner_symbol = data.get_symbol(self.owner)?; - output.push_str(&format!("\"owner\": {},\n", owner_symbol.simple_dump())); - if let Some(parent_schema) = self.parent_schema.as_ref() { - let parent_schema_symbol = data.get_symbol(*parent_schema)?; - output.push_str(&format!( - "\"parent_schema\": {},\n", - parent_schema_symbol.simple_dump() - )); - } - if let Some(parent_schema) = self.for_host.as_ref() { - let host_symbol = data.get_symbol(*parent_schema)?; - output.push_str(&format!("\"for_host\": {},\n", host_symbol.simple_dump())); - } - output.push_str("\"mixins\": [\n"); - for (index, mixin) in self.mixins.iter().enumerate() { - let mixin_symbol = data.get_symbol(*mixin)?; - output.push_str(&format!("{}", mixin_symbol.simple_dump())); - if index + 1 < self.mixins.len() { - output.push_str(",\n") - } - } - output.push_str("\n],\n"); - output.push_str("\"attributes\": {\n"); - for (index, (key, attribute)) in self.attributes.iter().enumerate() { - let attribute_symbol = data.get_symbol(*attribute)?; - output.push_str(&format!("\"{}\": {}", key, attribute_symbol.simple_dump())); - if index + 1 < self.attributes.len() { - output.push_str(",\n") - } - } - output.push_str("\n}\n}\n}"); - Some(output) - } - - fn get_sema_info(&self) -> &Self::SemanticInfo { - &self.sema_info - } - - fn get_references(&self) -> HashSet { - self.r#ref.clone() - } -} - -impl SchemaSymbol { - pub fn new(name: String, start: Position, end: Position, owner: SymbolRef) -> Self { - Self { - id: None, - name, - start, - end, - owner, - parent_schema: None, - for_host: None, - sema_info: SymbolSemanticInfo::default(), - mixins: Vec::default(), - attributes: IndexMap::default(), - r#ref: HashSet::default(), - } - } - - pub fn get_parents(&self, data: &SymbolData, parents: &mut Vec) { - if let Some(parent_schema_ref) = self.parent_schema { - if let Some(parent_schema) = data.get_symbol(parent_schema_ref) { - if let Some(schema_def) = parent_schema.get_definition() { - if let Some(parent_schema) = data.get_schema_symbol(schema_def) { - // circular reference - if !parents.contains(&schema_def) { - parents.push(schema_def); - parent_schema.get_parents(data, parents); - } - } - } - } - } - } - - pub fn get_protocol_and_mixin_attrs( - &self, - data: &SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Vec { - let mut result = vec![]; - if let Some(for_host) = self.for_host { - if let Some(for_host) = data.get_symbol(for_host) { - result.append(&mut for_host.get_all_attributes(data, module_info)) - } - } - for mixin in self.mixins.iter() { - if let Some(mixin) = data.get_symbol(*mixin) { - result.append(&mut mixin.get_all_attributes(data, module_info)) - } - } - - result - } - - pub fn get_self_attr( - &self, - data: &SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Vec { - let mut result = vec![]; - for attribute in self.attributes.values() { - result.push(*attribute); - } - result.extend(self.get_protocol_and_mixin_attrs(data, module_info)); - result - } -} - -#[allow(unused)] -#[derive(Debug, Clone)] -pub struct ValueSymbol { - pub(crate) id: Option, - pub(crate) name: String, - pub(crate) start: Position, - pub(crate) end: Position, - pub(crate) owner: Option, - pub(crate) sema_info: SymbolSemanticInfo, - pub(crate) r#ref: HashSet, - pub(crate) is_global: bool, -} - -impl Symbol for ValueSymbol { - type SymbolData = SymbolData; - type SemanticInfo = SymbolSemanticInfo; - type SymbolHint = SymbolHint; - - fn is_global(&self) -> bool { - self.is_global - } - - fn get_range(&self) -> Range { - (self.start.clone(), self.end.clone()) - } - - fn get_owner(&self) -> Option { - self.owner.clone() - } - - fn get_definition(&self) -> Option { - self.id.clone() - } - - fn get_name(&self) -> String { - self.name.clone() - } - - fn get_id(&self) -> Option { - self.id.clone() - } - - fn get_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Option { - data.get_type_attribute(self.sema_info.ty.as_ref()?, name, module_info) - } - - fn get_all_attributes( - &self, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Vec { - let mut result = vec![]; - if let Some(ty) = self.sema_info.ty.as_ref() { - if let Some(symbol_ref) = data.get_type_symbol(ty, module_info) { - if let Some(symbol) = data.get_symbol(symbol_ref) { - result.append(&mut symbol.get_all_attributes(data, module_info)) - } - } - } - - result - } - - fn has_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> bool { - self.get_attribute(name, data, module_info).is_some() - } - - fn simple_dump(&self) -> String { - let mut output = "{\n".to_string(); - output.push_str("\"kind\": \"ValueSymbol\",\n"); - output.push_str(&format!("\"name\":\"{}\",\n", self.name)); - output.push_str(&format!( - "\"range\": \"{}:{}", - self.start.filename, self.start.line - )); - if let Some(start_col) = self.start.column { - output.push_str(&format!(":{}", start_col)); - } - - output.push_str(&format!(" to {}", self.end.line)); - if let Some(end_col) = self.end.column { - output.push_str(&format!(":{}", end_col)); - } - output.push_str("\"\n}"); - output - } - - fn full_dump(&self, data: &Self::SymbolData) -> Option { - let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); - output.push_str("\"additional_info\": {\n"); - if let Some(owner) = self.owner.as_ref() { - let owner_symbol = data.get_symbol(*owner)?; - output.push_str(&format!("\"owner\": {}\n", owner_symbol.simple_dump())); - } - output.push_str("\n}\n}"); - Some(output) - } - - fn get_sema_info(&self) -> &Self::SemanticInfo { - &self.sema_info - } - - fn get_references(&self) -> HashSet { - self.r#ref.clone() - } -} - -impl ValueSymbol { - pub fn new( - name: String, - start: Position, - end: Position, - owner: Option, - is_global: bool, - ) -> Self { - Self { - id: None, - name, - start, - end, - owner, - sema_info: SymbolSemanticInfo::default(), - is_global, - r#ref: HashSet::default(), - } - } -} - -#[allow(unused)] -#[derive(Debug, Clone)] -pub struct AttributeSymbol { - pub(crate) id: Option, - pub(crate) name: String, - pub(crate) start: Position, - pub(crate) end: Position, - pub(crate) owner: SymbolRef, - pub(crate) sema_info: SymbolSemanticInfo, - pub(crate) is_optional: bool, - pub(crate) r#ref: HashSet, - pub(crate) default_value: Option, -} - -impl Symbol for AttributeSymbol { - type SymbolData = SymbolData; - type SemanticInfo = SymbolSemanticInfo; - type SymbolHint = SymbolHint; - - fn is_global(&self) -> bool { - true - } - fn get_range(&self) -> Range { - (self.start.clone(), self.end.clone()) - } - - fn get_owner(&self) -> Option { - Some(self.owner) - } - - fn get_definition(&self) -> Option { - self.id.clone() - } - - fn get_name(&self) -> String { - self.name.clone() - } - - fn get_id(&self) -> Option { - self.id.clone() - } - - fn get_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Option { - let ty = self.sema_info.ty.as_ref()?; - data.get_type_attribute(ty, name, module_info) - } - - fn get_all_attributes( - &self, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Vec { - let mut result = vec![]; - if module_info.is_none() { - return result; - } - if let Some(ty) = self.sema_info.ty.as_ref() { - if let Some(symbol_ref) = data.get_type_symbol(ty, module_info) { - if let Some(symbol) = data.get_symbol(symbol_ref) { - result.append(&mut symbol.get_all_attributes(data, module_info)) - } - } - } - - result - } - - fn has_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> bool { - self.get_attribute(name, data, module_info).is_some() - } - - fn simple_dump(&self) -> String { - let mut output = "{\n".to_string(); - output.push_str("\"kind\": \"AttributeSymbol\",\n"); - output.push_str(&format!("\"name\":\"{}\",\n", self.name)); - output.push_str(&format!( - "\"range\": \"{}:{}", - self.start.filename, self.start.line - )); - if let Some(start_col) = self.start.column { - output.push_str(&format!(":{}", start_col)); - } - - output.push_str(&format!(" to {}", self.end.line)); - if let Some(end_col) = self.end.column { - output.push_str(&format!(":{}", end_col)); - } - output.push_str("\"\n}"); - output - } - - fn full_dump(&self, data: &Self::SymbolData) -> Option { - let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); - output.push_str("\"additional_info\": {\n"); - let owner_symbol = data.get_symbol(self.owner)?; - output.push_str(&format!("\"owner\": {}\n", owner_symbol.simple_dump())); - output.push_str("\n}\n}"); - Some(output) - } - - fn get_sema_info(&self) -> &Self::SemanticInfo { - &self.sema_info - } - - fn get_references(&self) -> HashSet { - self.r#ref.clone() - } -} - -impl AttributeSymbol { - pub fn new( - name: String, - start: Position, - end: Position, - owner: SymbolRef, - is_optional: bool, - default_value: Option, - ) -> Self { - Self { - id: None, - name, - start, - end, - sema_info: SymbolSemanticInfo::default(), - owner, - is_optional, - r#ref: HashSet::default(), - default_value, - } - } - - pub fn is_optional(&self) -> bool { - self.is_optional - } - - pub fn get_default_value(&self) -> Option { - self.default_value.clone() - } -} -#[allow(unused)] -#[derive(Debug, Clone)] -pub struct PackageSymbol { - pub(crate) id: Option, - pub(crate) name: String, - pub(crate) members: IndexMap, - pub(crate) start: Position, - pub(crate) end: Position, - pub(crate) sema_info: SymbolSemanticInfo, - pub(crate) r#ref: HashSet, -} - -impl Symbol for PackageSymbol { - type SymbolData = SymbolData; - type SemanticInfo = SymbolSemanticInfo; - type SymbolHint = SymbolHint; - - fn is_global(&self) -> bool { - true - } - fn get_range(&self) -> Range { - (self.start.clone(), self.end.clone()) - } - - fn get_owner(&self) -> Option { - None - } - - fn get_definition(&self) -> Option { - self.id.clone() - } - - fn get_name(&self) -> String { - self.name.clone() - } - - fn get_id(&self) -> Option { - self.id.clone() - } - - fn get_attribute( - &self, - name: &str, - _data: &Self::SymbolData, - _module_info: Option<&ModuleInfo>, - ) -> Option { - self.members.get(name).cloned() - } - - fn get_all_attributes( - &self, - _data: &Self::SymbolData, - _module_info: Option<&ModuleInfo>, - ) -> Vec { - let mut result = vec![]; - for member in self.members.values() { - result.push(*member); - } - result - } - - fn has_attribute( - &self, - name: &str, - _data: &Self::SymbolData, - _module_info: Option<&ModuleInfo>, - ) -> bool { - self.members.contains_key(name) - } - - fn simple_dump(&self) -> String { - let mut output = "{\n".to_string(); - output.push_str("\"kind\": \"PackageSymbol\",\n"); - output.push_str(&format!("\"name\":\"{}\",\n", self.name)); - output.push_str(&format!( - "\"range\": \"{}:{}", - self.start.filename, self.start.line - )); - if let Some(start_col) = self.start.column { - output.push_str(&format!(":{}", start_col)); - } - - output.push_str(&format!(" to {}", self.end.line)); - if let Some(end_col) = self.end.column { - output.push_str(&format!(":{}", end_col)); - } - output.push_str("\"\n}"); - output - } - - fn full_dump(&self, data: &Self::SymbolData) -> Option { - let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); - output.push_str("\"additional_info\": {\n"); - output.push_str("\"members\": {\n"); - for (index, (key, member)) in self.members.iter().enumerate() { - let member_symbol = data.get_symbol(*member)?; - output.push_str(&format!("\"{}\": {}", key, member_symbol.simple_dump())); - if index + 1 < self.members.len() { - output.push_str(",\n"); - } - } - output.push_str("\n}\n}\n}"); - Some(output) - } - - fn get_sema_info(&self) -> &Self::SemanticInfo { - &self.sema_info - } - - fn get_references(&self) -> HashSet { - self.r#ref.clone() - } -} - -impl PackageSymbol { - pub fn new(name: String, start: Position, end: Position) -> Self { - Self { - id: None, - name, - start, - end, - sema_info: SymbolSemanticInfo::default(), - members: IndexMap::default(), - r#ref: HashSet::default(), - } - } -} -#[allow(unused)] -#[derive(Debug, Clone)] -pub struct TypeAliasSymbol { - pub(crate) id: Option, - pub(crate) name: String, - pub(crate) start: Position, - pub(crate) end: Position, - pub(crate) owner: SymbolRef, - pub(crate) sema_info: SymbolSemanticInfo, - pub(crate) r#ref: HashSet, -} - -impl Symbol for TypeAliasSymbol { - type SymbolData = SymbolData; - type SemanticInfo = SymbolSemanticInfo; - type SymbolHint = SymbolHint; - - fn is_global(&self) -> bool { - true - } - fn get_range(&self) -> Range { - (self.start.clone(), self.end.clone()) - } - - fn get_owner(&self) -> Option { - Some(self.owner) - } - - fn get_definition(&self) -> Option { - self.id.clone() - } - - fn get_name(&self) -> String { - self.name.clone() - } - - fn get_id(&self) -> Option { - self.id.clone() - } - - fn get_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Option { - let ty = self.sema_info.ty.as_ref()?; - data.get_type_attribute(ty, name, module_info) - } - - fn get_all_attributes( - &self, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Vec { - let mut result = vec![]; - if let Some(ty) = self.sema_info.ty.as_ref() { - if let Some(symbol_ref) = data.get_type_symbol(ty, module_info) { - if let Some(symbol) = data.get_symbol(symbol_ref) { - result.append(&mut symbol.get_all_attributes(data, module_info)) - } - } - } - result - } - - fn has_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> bool { - self.get_attribute(name, data, module_info).is_some() - } - - fn simple_dump(&self) -> String { - let mut output = "{\n".to_string(); - output.push_str("\"kind\": \"TypeAliasSymbol\",\n"); - output.push_str(&format!("\"name\":\"{}\",\n", self.name)); - output.push_str(&format!( - "\"range\": \"{}:{}", - self.start.filename, self.start.line - )); - if let Some(start_col) = self.start.column { - output.push_str(&format!(":{}", start_col)); - } - - output.push_str(&format!(" to {}", self.end.line)); - if let Some(end_col) = self.end.column { - output.push_str(&format!(":{}", end_col)); - } - output.push_str("\"\n}"); - output - } - - fn full_dump(&self, data: &Self::SymbolData) -> Option { - let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); - output.push_str("\"additional_info\": {\n"); - let owner_symbol = data.get_symbol(self.owner)?; - output.push_str(&format!( - "\"owner\": {}\n}}\n}}", - owner_symbol.simple_dump() - )); - Some(output) - } - - fn get_sema_info(&self) -> &Self::SemanticInfo { - &self.sema_info - } - - fn get_references(&self) -> HashSet { - self.r#ref.clone() - } -} - -impl TypeAliasSymbol { - pub fn new(name: String, start: Position, end: Position, owner: SymbolRef) -> Self { - Self { - id: None, - name, - start, - end, - sema_info: SymbolSemanticInfo::default(), - owner, - r#ref: HashSet::default(), - } - } -} -#[allow(unused)] -#[derive(Debug, Clone)] -pub struct RuleSymbol { - pub(crate) id: Option, - pub(crate) name: String, - pub(crate) start: Position, - pub(crate) end: Position, - pub(crate) owner: SymbolRef, - pub(crate) sema_info: SymbolSemanticInfo, - - pub(crate) parent_rules: Vec, - pub(crate) for_host: Option, - pub(crate) r#ref: HashSet, -} - -impl Symbol for RuleSymbol { - type SymbolData = SymbolData; - type SemanticInfo = SymbolSemanticInfo; - type SymbolHint = SymbolHint; - - fn is_global(&self) -> bool { - true - } - fn get_range(&self) -> Range { - (self.start.clone(), self.end.clone()) - } - - fn get_owner(&self) -> Option { - Some(self.owner) - } - - fn get_definition(&self) -> Option { - self.id.clone() - } - - fn get_name(&self) -> String { - self.name.clone() - } - - fn get_id(&self) -> Option { - self.id.clone() - } - - fn get_attribute( - &self, - _name: &str, - _data: &Self::SymbolData, - _module_info: Option<&ModuleInfo>, - ) -> Option { - None - } - - fn get_all_attributes( - &self, - _data: &Self::SymbolData, - _module_info: Option<&ModuleInfo>, - ) -> Vec { - vec![] - } - - fn has_attribute( - &self, - _name: &str, - _data: &Self::SymbolData, - _module_info: Option<&ModuleInfo>, - ) -> bool { - false - } - - fn simple_dump(&self) -> String { - let mut output = "{\n".to_string(); - output.push_str("\"kind\": \"RuleSymbol\",\n"); - output.push_str(&format!("\"name\":\"{}\",\n", self.name)); - output.push_str(&format!( - "\"range\": \"{}:{}", - self.start.filename, self.start.line - )); - if let Some(start_col) = self.start.column { - output.push_str(&format!(":{}", start_col)); - } - - output.push_str(&format!(" to {}", self.end.line)); - if let Some(end_col) = self.end.column { - output.push_str(&format!(":{}", end_col)); - } - output.push_str("\"\n}"); - output - } - - fn full_dump(&self, data: &Self::SymbolData) -> Option { - let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); - output.push_str("\"additional_info\": {\n"); - let owner_symbol = data.get_symbol(self.owner)?; - output.push_str(&format!("\"owner\": {},\n", owner_symbol.simple_dump())); - - if let Some(parent_schema) = self.for_host.as_ref() { - let host_symbol = data.get_symbol(*parent_schema)?; - output.push_str(&format!("\"for_host\": {},\n", host_symbol.simple_dump())); - } - output.push_str("\"parent_rules\": [\n"); - for (index, parent_rule) in self.parent_rules.iter().enumerate() { - let parent_symbol = data.get_symbol(*parent_rule)?; - output.push_str(&format!("{}", parent_symbol.simple_dump())); - if index + 1 < self.parent_rules.len() { - output.push_str(",\n") - } - } - output.push_str("\n]\n}\n}"); - - Some(output) - } - - fn get_sema_info(&self) -> &Self::SemanticInfo { - &self.sema_info - } - - fn get_references(&self) -> HashSet { - self.r#ref.clone() - } -} - -impl RuleSymbol { - pub fn new(name: String, start: Position, end: Position, owner: SymbolRef) -> Self { - Self { - id: None, - name, - start, - end, - owner, - sema_info: SymbolSemanticInfo::default(), - parent_rules: vec![], - for_host: None, - r#ref: HashSet::default(), - } - } -} -#[allow(unused)] -#[derive(Debug, Clone)] -pub struct UnresolvedSymbol { - pub(crate) id: Option, - pub(crate) def: Option, - pub(crate) name: String, - pub(crate) start: Position, - pub(crate) end: Position, - pub(crate) owner: Option, - pub(crate) sema_info: SymbolSemanticInfo, - pub(crate) is_type: bool, - pub(crate) r#ref: HashSet, -} - -impl Symbol for UnresolvedSymbol { - type SymbolData = SymbolData; - type SemanticInfo = SymbolSemanticInfo; - type SymbolHint = SymbolHint; - - fn is_global(&self) -> bool { - false - } - fn get_range(&self) -> Range { - (self.start.clone(), self.end.clone()) - } - - fn get_owner(&self) -> Option { - self.owner.clone() - } - - fn get_definition(&self) -> Option { - self.def.clone() - } - - fn get_name(&self) -> String { - self.name.clone() - } - - fn get_id(&self) -> Option { - self.id.clone() - } - - fn get_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Option { - if self.is_type() { - None - } else { - data.get_symbol(self.def?)? - .get_attribute(name, data, module_info) - } - } - - fn get_all_attributes( - &self, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Vec { - if !self.is_type() { - if let Some(def) = self.def { - if let Some(def_symbol) = data.get_symbol(def) { - return def_symbol.get_all_attributes(data, module_info); - } - } - } - - vec![] - } - - fn has_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> bool { - self.get_attribute(name, data, module_info).is_some() - } - - fn get_sema_info(&self) -> &Self::SemanticInfo { - &self.sema_info - } - - fn simple_dump(&self) -> String { - let mut output = "{\n".to_string(); - output.push_str("\"kind\": \"UnresolvedSymbol\",\n"); - output.push_str(&format!("\"name\":\"{}\",\n", self.name)); - output.push_str(&format!( - "\"range\": \"{}:{}", - self.start.filename, self.start.line - )); - if let Some(start_col) = self.start.column { - output.push_str(&format!(":{}", start_col)); - } - - output.push_str(&format!(" to {}", self.end.line)); - if let Some(end_col) = self.end.column { - output.push_str(&format!(":{}", end_col)); - } - output.push_str("\"\n}"); - output - } - - fn full_dump(&self, data: &Self::SymbolData) -> Option { - let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); - output.push_str("\"additional_info\": {\n"); - if let Some(def) = self.def.as_ref() { - let def_symbol = data.get_symbol(*def)?; - output.push_str(&format!("\"def\": {}\n", def_symbol.simple_dump())); - } - output.push_str("\n}\n}"); - Some(output) - } - - fn get_references(&self) -> HashSet { - self.r#ref.clone() - } -} - -impl UnresolvedSymbol { - pub fn new( - name: String, - start: Position, - end: Position, - owner: Option, - is_type: bool, - ) -> Self { - Self { - id: None, - def: None, - name, - start, - end, - sema_info: SymbolSemanticInfo::default(), - owner, - is_type, - r#ref: HashSet::default(), - } - } - - pub fn get_fully_qualified_name(&self, module_info: &ModuleInfo) -> String { - let names: Vec<_> = self.name.split('.').collect(); - let pkg_path = if names.len() == 1 { - kclvm_ast::MAIN_PKG.to_string() - } else { - let pkg_alias = names.first().unwrap(); - let import_info = module_info.get_import_info(*pkg_alias); - match import_info { - Some(info) => info.fully_qualified_name.clone(), - None => kclvm_ast::MAIN_PKG.to_string(), - } - }; - - pkg_path + "." + names.last().unwrap() - } - - pub fn is_type(&self) -> bool { - self.is_type - } -} - -#[derive(Debug, Clone)] -pub struct ExpressionSymbol { - pub(crate) id: Option, - pub(crate) start: Position, - pub(crate) end: Position, - pub(crate) owner: Option, - pub(crate) name: String, - - pub(crate) sema_info: SymbolSemanticInfo, - pub(crate) r#ref: HashSet, -} - -impl Symbol for ExpressionSymbol { - type SymbolData = SymbolData; - type SemanticInfo = SymbolSemanticInfo; - type SymbolHint = SymbolHint; - - fn is_global(&self) -> bool { - false - } - fn get_range(&self) -> Range { - (self.start.clone(), self.end.clone()) - } - - fn get_owner(&self) -> Option { - self.owner.clone() - } - - fn get_definition(&self) -> Option { - self.id - } - - fn get_name(&self) -> String { - self.name.clone() - } - - fn get_id(&self) -> Option { - self.id.clone() - } - - fn get_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Option { - data.get_type_attribute(self.sema_info.ty.as_ref()?, name, module_info) - } - - fn get_all_attributes( - &self, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Vec { - let mut result = vec![]; - if let Some(ty) = self.sema_info.ty.as_ref() { - if let Some(symbol_ref) = data.get_type_symbol(ty, module_info) { - if let Some(symbol) = data.get_symbol(symbol_ref) { - result.append(&mut symbol.get_all_attributes(data, module_info)) - } - } - } - - result - } - - fn has_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> bool { - self.get_attribute(name, data, module_info).is_some() - } - - fn get_sema_info(&self) -> &Self::SemanticInfo { - &self.sema_info - } - - fn simple_dump(&self) -> String { - let mut output = "{\n".to_string(); - output.push_str("\"kind\": \"ExpressionSymbol\",\n"); - output.push_str(&format!( - "\"range\": \"{}:{}", - self.start.filename, self.start.line - )); - if let Some(start_col) = self.start.column { - output.push_str(&format!(":{}", start_col)); - } - - output.push_str(&format!(" to {}", self.end.line)); - if let Some(end_col) = self.end.column { - output.push_str(&format!(":{}", end_col)); - } - output.push_str("\"\n}"); - output - } - - fn full_dump(&self, data: &Self::SymbolData) -> Option { - let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); - output.push_str("\"additional_info\": {\n"); - if let Some(owner) = self.owner.as_ref() { - let owner_symbol = data.get_symbol(*owner)?; - output.push_str(&format!("\"owner\": {}\n", owner_symbol.simple_dump())); - } - output.push_str("\n}\n}"); - Some(output) - } - - fn get_references(&self) -> HashSet { - self.r#ref.clone() - } -} - -impl ExpressionSymbol { - pub fn new(name: String, start: Position, end: Position, owner: Option) -> Self { - Self { - id: None, - name, - start, - end, - sema_info: SymbolSemanticInfo::default(), - owner, - r#ref: HashSet::default(), - } - } -} - -#[derive(Debug, Clone)] -pub struct CommentOrDocSymbol { - pub(crate) id: Option, - pub(crate) start: Position, - pub(crate) end: Position, - pub(crate) content: String, - pub(crate) sema_info: SymbolSemanticInfo, - pub(crate) r#ref: HashSet, -} - -impl Symbol for CommentOrDocSymbol { - type SymbolData = SymbolData; - type SemanticInfo = SymbolSemanticInfo; - type SymbolHint = SymbolHint; - - fn get_sema_info(&self) -> &Self::SemanticInfo { - &self.sema_info - } - - fn is_global(&self) -> bool { - true - } - - fn get_range(&self) -> Range { - (self.start.clone(), self.end.clone()) - } - - fn get_owner(&self) -> Option { - None - } - - fn get_definition(&self) -> Option { - self.id - } - - fn get_name(&self) -> String { - self.name() - } - - fn get_id(&self) -> Option { - self.id.clone() - } - - fn get_attribute( - &self, - _name: &str, - _data: &Self::SymbolData, - _module_info: Option<&ModuleInfo>, - ) -> Option { - None - } - - fn has_attribute( - &self, - _name: &str, - _data: &Self::SymbolData, - _module_info: Option<&ModuleInfo>, - ) -> bool { - false - } - - fn get_all_attributes( - &self, - _data: &Self::SymbolData, - _module_info: Option<&ModuleInfo>, - ) -> Vec { - vec![] - } - - fn simple_dump(&self) -> String { - let mut output = "{\n".to_string(); - output.push_str("\"kind\": \"CommentSymbol\",\n"); - output.push_str(&format!( - "\"range\": \"{}:{}", - self.start.filename, self.start.line - )); - if let Some(start_col) = self.start.column { - output.push_str(&format!(":{}", start_col)); - } - - output.push_str(&format!(" to {}", self.end.line)); - if let Some(end_col) = self.end.column { - output.push_str(&format!(":{}", end_col)); - } - output.push_str(&format!("content :{}", self.name())); - output.push_str("\"\n}"); - output - } - - fn full_dump(&self, _data: &Self::SymbolData) -> Option { - Some(self.simple_dump()) - } - - fn get_references(&self) -> HashSet { - self.r#ref.clone() - } -} - -impl CommentOrDocSymbol { - pub fn new(start: Position, end: Position, content: String) -> Self { - Self { - id: None, - start, - end, - content, - sema_info: SymbolSemanticInfo::default(), - r#ref: HashSet::default(), - } - } - - pub fn name(&self) -> String { - format!("# {}", self.content) - } -} - -#[derive(Debug, Clone)] -pub struct DecoratorSymbol { - pub(crate) id: Option, - pub(crate) start: Position, - pub(crate) end: Position, - pub(crate) name: String, - pub(crate) sema_info: SymbolSemanticInfo, - pub(crate) r#ref: HashSet, -} - -impl Symbol for DecoratorSymbol { - type SymbolData = SymbolData; - type SemanticInfo = SymbolSemanticInfo; - type SymbolHint = SymbolHint; - - fn get_sema_info(&self) -> &Self::SemanticInfo { - &self.sema_info - } - - fn is_global(&self) -> bool { - true - } - - fn get_range(&self) -> Range { - (self.start.clone(), self.end.clone()) - } - - fn get_owner(&self) -> Option { - None - } - - fn get_definition(&self) -> Option { - self.id - } - - fn get_name(&self) -> String { - self.name() - } - - fn get_id(&self) -> Option { - self.id.clone() - } - - fn get_attribute( - &self, - _name: &str, - _data: &Self::SymbolData, - _module_info: Option<&ModuleInfo>, - ) -> Option { - None - } - - fn has_attribute( - &self, - _name: &str, - _data: &Self::SymbolData, - _module_info: Option<&ModuleInfo>, - ) -> bool { - false - } - - fn get_all_attributes( - &self, - _data: &Self::SymbolData, - _module_info: Option<&ModuleInfo>, - ) -> Vec { - vec![] - } - - fn simple_dump(&self) -> String { - let mut output = "{\n".to_string(); - output.push_str("\"kind\": \"CommentSymbol\",\n"); - output.push_str(&format!( - "\"range\": \"{}:{}", - self.start.filename, self.start.line - )); - if let Some(start_col) = self.start.column { - output.push_str(&format!(":{}", start_col)); - } - - output.push_str(&format!(" to {}", self.end.line)); - if let Some(end_col) = self.end.column { - output.push_str(&format!(":{}", end_col)); - } - output.push_str(&format!("name :{}", self.name())); - output.push_str("\"\n}"); - output - } - - fn full_dump(&self, _data: &Self::SymbolData) -> Option { - Some(self.simple_dump()) - } - - fn get_references(&self) -> HashSet { - self.r#ref.clone() - } -} - -impl DecoratorSymbol { - pub fn new(start: Position, end: Position, name: String) -> Self { - Self { - id: None, - start, - end, - name, - sema_info: SymbolSemanticInfo::default(), - r#ref: HashSet::default(), - } - } - - pub fn name(&self) -> String { - self.name.clone() - } -} - -#[derive(Debug, Clone)] -pub struct FunctionSymbol { - pub(crate) id: Option, - pub(crate) name: String, - pub(crate) start: Position, - pub(crate) end: Position, - pub(crate) owner: Option, - pub(crate) sema_info: SymbolSemanticInfo, - pub(crate) is_global: bool, - pub(crate) r#ref: HashSet, -} - -impl Symbol for FunctionSymbol { - type SymbolData = SymbolData; - type SemanticInfo = SymbolSemanticInfo; - type SymbolHint = SymbolHint; - - fn is_global(&self) -> bool { - self.is_global - } - - fn get_range(&self) -> Range { - (self.start.clone(), self.end.clone()) - } - - fn get_owner(&self) -> Option { - self.owner.clone() - } - - fn get_definition(&self) -> Option { - self.id.clone() - } - - fn get_name(&self) -> String { - self.name.clone() - } - - fn get_id(&self) -> Option { - self.id.clone() - } - - fn get_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Option { - data.get_type_attribute(self.sema_info.ty.as_ref()?, name, module_info) - } - - fn get_all_attributes( - &self, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> Vec { - let mut result = vec![]; - if let Some(ty) = self.sema_info.ty.as_ref() { - if let Some(symbol_ref) = data.get_type_symbol(ty, module_info) { - if let Some(symbol) = data.get_symbol(symbol_ref) { - result.append(&mut symbol.get_all_attributes(data, module_info)) - } - } - } - - result - } - - fn has_attribute( - &self, - name: &str, - data: &Self::SymbolData, - module_info: Option<&ModuleInfo>, - ) -> bool { - self.get_attribute(name, data, module_info).is_some() - } - - fn get_sema_info(&self) -> &Self::SemanticInfo { - &self.sema_info - } - - fn simple_dump(&self) -> String { - let mut output = "{\n".to_string(); - output.push_str("\"kind\": \"FunctionSymbol\",\n"); - output.push_str(&format!("\"name\":\"{}\",\n", self.name)); - output.push_str(&format!( - "\"range\": \"{}:{}", - self.start.filename, self.start.line - )); - if let Some(start_col) = self.start.column { - output.push_str(&format!(":{}", start_col)); - } - - output.push_str(&format!(" to {}", self.end.line)); - if let Some(end_col) = self.end.column { - output.push_str(&format!(":{}", end_col)); - } - output.push_str("\"\n}"); - output - } - - fn full_dump(&self, data: &Self::SymbolData) -> Option { - let mut output = format!("{{\n\"simple_info\": {},\n", self.simple_dump()); - output.push_str("\"additional_info\": {\n"); - if let Some(owner) = self.owner.as_ref() { - let owner_symbol = data.get_symbol(*owner)?; - output.push_str(&format!("\"owner\": {}\n", owner_symbol.simple_dump())); - } - output.push_str("\n}\n}"); - Some(output) - } - - fn get_references(&self) -> HashSet { - self.r#ref.clone() - } -} - -impl FunctionSymbol { - pub fn new( - name: String, - start: Position, - end: Position, - owner: Option, - is_global: bool, - ) -> Self { - Self { - id: None, - name, - start, - end, - owner, - sema_info: SymbolSemanticInfo::default(), - is_global, - r#ref: HashSet::default(), - } - } -} diff --git a/kclvm/sema/src/lint/mod.rs b/kclvm/sema/src/lint/mod.rs deleted file mode 100644 index 9ae492ce3..000000000 --- a/kclvm/sema/src/lint/mod.rs +++ /dev/null @@ -1,402 +0,0 @@ -//! The design and implementation of KCL Lint refer to the [rust-lang/rustc](https://github.com/rust-lang/rust) lint and follow Apache License Version 2.0 -//! -//! This file is the implementation of KCLLint, which is used to perform some additional checks on KCL code. -//! The main structures of the file are Lint, LintPass, CombinedLintPass and Linter. -//! For details see the: https://github.com/kcl-lang/kcl/issues/109 -//! -//! File dependencies: -//! mode -> combinedlintpass -> lints_def -> lintpass -> lint -//! -//! mode.rs: Definition of `Linter`, the entry for lint check -//! combinedlintpass.rs: `CombinedLintPass` collects all the lints defined in the lints_def.rs -//! lints_def.rs: Defined the various lints and the corresponding lintpasses implementation -//! lintpass.rs: Definition of `Lintpass` -//! lint.rs: Definition of `Lint` -//! -//! Steps to define a new lint: -//! 1. Define a static instance of the `Lint` structure in lints_def.rs,e.g., -//! -//! ```ignore -//! pub static IMPORT_POSITION: &Lint = &Lint { -//! ... -//! } -//! ``` -//! -//! 2. Define a lintpass, which is used to implement the checking process,e.g., -//! -//! ```ignore -//! declare_lint_pass!(ImportPosition => [IMPORT_POSITION]); -//! ``` -//! -//! The `ImportPosition` is the defined LintPass structure and the `IMPORT_POSITION` is the `Lint` structure -//! defined in step 1. Here is a `LintArray`, which means that multiple lint checks can be implemented -//! in a single lintpass. -//! -//! 3. Implement the lintpass check process, e.g., -//! -//! ```ignore -//! impl LintPass for ImportPosition { -//! fn check_module(&mut self, handler: &mut Handler, ctx: &mut LintContext,module: &ast::Module){ -//! ... -//! } -//! } -//! ``` -//! -//! 4. Add the `check_*` methods in lintpass to the macro `lint_methods`, or skip it if it exists -//! -//! ```ignore -//! macro_rules! lint_methods { -//! ($macro:path, $args:tt) => ( -//! $macro!($args, [ -//! fn check_module(module: &ast::Module); -//! ]); -//! ) -//! } -//! ``` -//! -//! 5. Add the new lintpass to the macro `default_lint_passes` in lintpass.rs , noting that `:` is preceded and followed by -//! the name of the lintpass. e.g., -//! -//! ```ignore -//! macro_rules! default_lint_passes { -//! ($macro:path, $args:tt) => { -//! $macro!( -//! $args, -//! [ -//! ImportPosition: ImportPosition, -//! ] -//! ); -//! }; -//! } -//! ``` -//! -//! 6. If new `check_*` method was added in step 4, it needs to override the walk_* method in Linter. -//! In addition to calling the self.pass.check_* function, the original walk method in MutSelfWalker -//! should be copied here so that it can continue to traverse the child nodes. - -use crate::resolver::{scope::Scope, Resolver}; -use kclvm_ast::pos::GetPos; -use kclvm_error::{Handler, Position}; -mod combinedlintpass; -mod lint; -mod lintpass; -mod lints_def; -use kclvm_ast::ast; -use kclvm_ast::walker::MutSelfWalker; - -pub use self::{combinedlintpass::CombinedLintPass, lint::LintContext, lintpass::LintPass}; - -/// The struct `Linter` is used to traverse the AST and call the `check_*` method defined in `CombinedLintPass`. -pub struct Linter { - pub pass: T, - pub handler: Handler, - pub ctx: LintContext, -} - -impl LintContext { - pub fn dummy_ctx() -> Self { - LintContext { - filename: "".to_string(), - start_pos: Position::dummy_pos(), - end_pos: Position::dummy_pos(), - } - } -} - -impl Linter { - pub fn new() -> Self { - Linter:: { - pass: CombinedLintPass::new(), - handler: Handler::default(), - ctx: LintContext::dummy_ctx(), - } - } - pub fn walk_scope(&mut self, scope: &Scope) { - self.pass - .check_scope(&mut self.handler, &mut self.ctx, scope); - } -} - -impl Resolver<'_> { - /// Iterate the module and run lint checks, generating diagnostics and save them in `lint.handler` - pub fn lint_check_module(&mut self, module: &ast::Module) { - self.linter.ctx.filename = module.filename.clone(); - self.linter.walk_module(module); - } - /// Recursively iterate the scope and its child scope, run lint checks, generating diagnostics and save them in `lint.handler` - pub fn lint_check_scope(&mut self, scope: &Scope) { - self.linter.walk_scope(scope); - for children in &scope.children { - self.lint_check_scope(&children.borrow().clone()) - } - } - - /// Iterate the resolver.scope_map and run lint checks, generating diagnostics and save them in `lint.handler` - pub fn lint_check_scope_map(&mut self) { - let scope_map = self.scope_map.clone(); - for (_, scope) in scope_map.iter() { - self.lint_check_scope(&scope.borrow()) - } - } -} - -macro_rules! walk_set_list { - ($walker: expr, $method: ident, $list: expr) => { - for elem in &$list { - set_pos!($walker, elem); - $walker.$method(&elem.node) - } - }; -} - -macro_rules! walk_set_if { - ($walker: expr, $method: ident, $value: expr) => { - match &$value { - Some(v) => { - set_pos!($walker, &v); - $walker.$method(&v.node); - } - None => (), - } - }; -} - -macro_rules! set_pos { - ($walker: expr, $value: expr) => { - $walker.set_pos(&$value.get_pos(), &$value.get_end_pos()); - }; -} - -impl Linter { - fn set_pos(&mut self, start_pos: &Position, end_pos: &Position) { - self.ctx.start_pos = start_pos.clone(); - self.ctx.end_pos = end_pos.clone(); - } -} - -impl MutSelfWalker for Linter { - fn walk_module(&mut self, module: &ast::Module) { - self.pass - .check_module(&mut self.handler, &mut self.ctx, module); - walk_set_list!(self, walk_stmt, module.body); - } - - fn walk_expr_stmt(&mut self, expr_stmt: &ast::ExprStmt) { - for expr in &expr_stmt.exprs { - set_pos!(self, &expr); - self.walk_expr(&expr.node) - } - } - - fn walk_type_alias_stmt(&mut self, type_alias_stmt: &ast::TypeAliasStmt) { - set_pos!(self, &type_alias_stmt.type_name); - self.walk_identifier(&type_alias_stmt.type_name.node); - } - fn walk_unification_stmt(&mut self, unification_stmt: &ast::UnificationStmt) { - set_pos!(self, &unification_stmt.target); - self.walk_identifier(&unification_stmt.target.node); - set_pos!(self, &unification_stmt.value); - self.walk_schema_expr(&unification_stmt.value.node); - } - fn walk_assign_stmt(&mut self, assign_stmt: &ast::AssignStmt) { - for target in &assign_stmt.targets { - set_pos!(self, &target); - self.walk_target(&target.node) - } - set_pos!(self, &assign_stmt.value); - self.walk_expr(&assign_stmt.value.node); - } - fn walk_aug_assign_stmt(&mut self, aug_assign_stmt: &ast::AugAssignStmt) { - set_pos!(self, &aug_assign_stmt.target); - self.walk_target(&aug_assign_stmt.target.node); - set_pos!(self, &aug_assign_stmt.value); - self.walk_expr(&aug_assign_stmt.value.node); - } - fn walk_assert_stmt(&mut self, assert_stmt: &ast::AssertStmt) { - set_pos!(self, &assert_stmt.test); - self.walk_expr(&assert_stmt.test.node); - walk_set_if!(self, walk_expr, assert_stmt.if_cond); - walk_set_if!(self, walk_expr, assert_stmt.msg); - } - fn walk_if_stmt(&mut self, if_stmt: &ast::IfStmt) { - set_pos!(self, &if_stmt.cond); - self.walk_expr(&if_stmt.cond.node); - walk_set_list!(self, walk_stmt, if_stmt.body); - walk_set_list!(self, walk_stmt, if_stmt.orelse); - } - fn walk_import_stmt(&mut self, import_stmt: &ast::ImportStmt) { - // Nothing to do. - let _ = import_stmt; - } - fn walk_schema_attr(&mut self, schema_attr: &ast::SchemaAttr) { - walk_set_list!(self, walk_call_expr, schema_attr.decorators); - walk_set_if!(self, walk_expr, schema_attr.value); - } - fn walk_schema_stmt(&mut self, schema_stmt: &ast::SchemaStmt) { - walk_set_if!(self, walk_identifier, schema_stmt.parent_name); - walk_set_if!(self, walk_identifier, schema_stmt.for_host_name); - walk_set_if!(self, walk_arguments, schema_stmt.args); - if let Some(schema_index_signature) = &schema_stmt.index_signature { - let value = &schema_index_signature.node.value; - walk_set_if!(self, walk_expr, value); - } - walk_set_list!(self, walk_identifier, schema_stmt.mixins); - walk_set_list!(self, walk_call_expr, schema_stmt.decorators); - walk_set_list!(self, walk_check_expr, schema_stmt.checks); - walk_set_list!(self, walk_stmt, schema_stmt.body); - } - fn walk_rule_stmt(&mut self, rule_stmt: &ast::RuleStmt) { - walk_set_list!(self, walk_identifier, rule_stmt.parent_rules); - walk_set_list!(self, walk_call_expr, rule_stmt.decorators); - walk_set_list!(self, walk_check_expr, rule_stmt.checks); - walk_set_if!(self, walk_arguments, rule_stmt.args); - walk_set_if!(self, walk_identifier, rule_stmt.for_host_name); - } - fn walk_quant_expr(&mut self, quant_expr: &ast::QuantExpr) { - set_pos!(self, &quant_expr.target); - self.walk_expr(&quant_expr.target.node); - walk_set_list!(self, walk_identifier, quant_expr.variables); - set_pos!(self, &quant_expr.test); - self.walk_expr(&quant_expr.test.node); - walk_set_if!(self, walk_expr, quant_expr.if_cond); - } - fn walk_if_expr(&mut self, if_expr: &ast::IfExpr) { - set_pos!(self, &if_expr.cond); - self.walk_expr(&if_expr.cond.node); - set_pos!(self, &if_expr.body); - self.walk_expr(&if_expr.body.node); - set_pos!(self, &if_expr.orelse); - self.walk_expr(&if_expr.orelse.node); - } - fn walk_unary_expr(&mut self, unary_expr: &ast::UnaryExpr) { - set_pos!(self, &unary_expr.operand); - self.walk_expr(&unary_expr.operand.node); - } - fn walk_binary_expr(&mut self, binary_expr: &ast::BinaryExpr) { - set_pos!(self, &binary_expr.left); - self.walk_expr(&binary_expr.left.node); - set_pos!(self, &binary_expr.right); - self.walk_expr(&binary_expr.right.node); - } - fn walk_selector_expr(&mut self, selector_expr: &ast::SelectorExpr) { - set_pos!(self, &selector_expr.value); - self.walk_expr(&selector_expr.value.node); - set_pos!(self, &selector_expr.attr); - self.walk_identifier(&selector_expr.attr.node); - } - fn walk_call_expr(&mut self, call_expr: &ast::CallExpr) { - set_pos!(self, &call_expr.func); - self.walk_expr(&call_expr.func.node); - walk_set_list!(self, walk_expr, call_expr.args); - walk_set_list!(self, walk_keyword, call_expr.keywords); - } - fn walk_subscript(&mut self, subscript: &ast::Subscript) { - set_pos!(self, &subscript.value); - self.walk_expr(&subscript.value.node); - walk_set_if!(self, walk_expr, subscript.index); - walk_set_if!(self, walk_expr, subscript.lower); - walk_set_if!(self, walk_expr, subscript.upper); - walk_set_if!(self, walk_expr, subscript.step); - } - fn walk_paren_expr(&mut self, paren_expr: &ast::ParenExpr) { - set_pos!(self, &paren_expr.expr); - self.walk_expr(&paren_expr.expr.node); - } - fn walk_list_expr(&mut self, list_expr: &ast::ListExpr) { - walk_set_list!(self, walk_expr, list_expr.elts); - } - fn walk_list_comp(&mut self, list_comp: &ast::ListComp) { - set_pos!(self, &list_comp.elt); - self.walk_expr(&list_comp.elt.node); - walk_set_list!(self, walk_comp_clause, list_comp.generators); - } - fn walk_list_if_item_expr(&mut self, list_if_item_expr: &ast::ListIfItemExpr) { - set_pos!(self, &list_if_item_expr.if_cond); - self.walk_expr(&list_if_item_expr.if_cond.node); - walk_set_list!(self, walk_expr, list_if_item_expr.exprs); - walk_set_if!(self, walk_expr, list_if_item_expr.orelse); - } - fn walk_starred_expr(&mut self, starred_expr: &ast::StarredExpr) { - set_pos!(self, &starred_expr.value); - self.walk_expr(&starred_expr.value.node); - } - fn walk_dict_comp(&mut self, dict_comp: &ast::DictComp) { - if let Some(key) = &dict_comp.entry.key { - set_pos!(self, &key); - self.walk_expr(&key.node); - } - set_pos!(self, &dict_comp.entry.value); - self.walk_expr(&dict_comp.entry.value.node); - walk_set_list!(self, walk_comp_clause, dict_comp.generators); - } - fn walk_config_if_entry_expr(&mut self, config_if_entry_expr: &ast::ConfigIfEntryExpr) { - set_pos!(self, &config_if_entry_expr.if_cond); - self.walk_expr(&config_if_entry_expr.if_cond.node); - for config_entry in &config_if_entry_expr.items { - walk_set_if!(self, walk_expr, config_entry.node.key); - set_pos!(self, &config_entry.node.value); - self.walk_expr(&config_entry.node.value.node); - } - walk_set_if!(self, walk_expr, config_if_entry_expr.orelse); - } - fn walk_comp_clause(&mut self, comp_clause: &ast::CompClause) { - walk_set_list!(self, walk_identifier, comp_clause.targets); - set_pos!(self, &comp_clause.iter); - self.walk_expr(&comp_clause.iter.node); - walk_set_list!(self, walk_expr, comp_clause.ifs); - } - fn walk_schema_expr(&mut self, schema_expr: &ast::SchemaExpr) { - set_pos!(self, &schema_expr.name); - self.walk_identifier(&schema_expr.name.node); - walk_set_list!(self, walk_expr, schema_expr.args); - walk_set_list!(self, walk_keyword, schema_expr.kwargs); - set_pos!(self, &schema_expr.config); - self.walk_expr(&schema_expr.config.node); - } - fn walk_config_expr(&mut self, config_expr: &ast::ConfigExpr) { - for config_entry in &config_expr.items { - walk_set_if!(self, walk_expr, config_entry.node.key); - set_pos!(self, &config_entry.node.value); - self.walk_expr(&config_entry.node.value.node); - } - } - fn walk_check_expr(&mut self, check_expr: &ast::CheckExpr) { - set_pos!(self, &check_expr.test); - self.walk_expr(&check_expr.test.node); - walk_set_if!(self, walk_expr, check_expr.if_cond); - walk_set_if!(self, walk_expr, check_expr.msg); - } - fn walk_lambda_expr(&mut self, lambda_expr: &ast::LambdaExpr) { - walk_set_if!(self, walk_arguments, lambda_expr.args); - walk_set_list!(self, walk_stmt, lambda_expr.body); - } - fn walk_keyword(&mut self, keyword: &ast::Keyword) { - set_pos!(self, &keyword.arg); - self.walk_identifier(&keyword.arg.node); - if let Some(v) = &keyword.value { - set_pos!(self, &v); - self.walk_expr(&v.node) - } - } - fn walk_arguments(&mut self, arguments: &ast::Arguments) { - walk_set_list!(self, walk_identifier, arguments.args); - for default in &arguments.defaults { - if let Some(d) = default { - set_pos!(self, d); - self.walk_expr(&d.node) - } - } - } - fn walk_compare(&mut self, compare: &ast::Compare) { - set_pos!(self, &compare.left); - self.walk_expr(&compare.left.node); - walk_set_list!(self, walk_expr, compare.comparators); - } - fn walk_joined_string(&mut self, joined_string: &ast::JoinedString) { - walk_set_list!(self, walk_expr, joined_string.values); - } - fn walk_formatted_value(&mut self, formatted_value: &ast::FormattedValue) { - set_pos!(self, &formatted_value.value); - self.walk_expr(&formatted_value.value.node); - } -} diff --git a/kclvm/sema/src/namer/mod.rs b/kclvm/sema/src/namer/mod.rs deleted file mode 100644 index 1db8bb3ca..000000000 --- a/kclvm/sema/src/namer/mod.rs +++ /dev/null @@ -1,373 +0,0 @@ -/* - ┌─────────────────────────────────────────────────────────────────────────────────────────────────┐ - │ namer │ - ├─────────────────────────────────────────────────────────────────────────────────────────────────┤ - │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ - │ │ ast::Expression │ │ ast::Expression │ │ ast::Expression │ │ - │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ - │ │ │ │ │ - │ │ find_symbols │ find_symbols │ find_symbols │ - │ ▼ ▼ ▼ │ - │ ┌─────────────────────────┐ ┌─────────────────────────┐ ┌─────────────────────────┐ │ - │ │ core::SymbolRef │ │ core::SymbolRef │ │ core::SymbolRef │ │ - │ └─────────────────────────┘ └─────────────────────────┘ └─────────────────────────┘ │ - │ │ │ │ │ - │ │ │ │ │ - │ └───────────────────────────────┼───────────────────────────────┘ │ - │ │ │ - │ │ merge findSymbols results │ - │ ▼ │ - │ ┌─────────────────────────┐ │ - │ │ core::SymbolRef │ │ - │ └─────────────────────────┘ │ - │ │ │ - │ │ define_symbols(FQN) │ - │ ■ │ - │ (mutates GlobalState) | - │ │ - └─────────────────────────────────────────────────────────────────────────────────────────────────┘ - - The early stage of the namer will be based on file level , which collects global symbols defined in the file, - and then merges the symbols based on FQN to obtain a unique GlobalState - - Based on file level, it means that we can easily perform incremental compilation in the future - - Now we just run namer pass serially - -*/ - -use std::path::Path; -use std::sync::Arc; - -use crate::builtin::{ - get_system_member_function_ty, get_system_module_members, BUILTIN_FUNCTIONS, - STANDARD_SYSTEM_MODULES, STRING_MEMBER_FUNCTIONS, -}; -use crate::core::global_state::GlobalState; -use crate::core::package::{ModuleInfo, PackageInfo}; -use crate::core::symbol::{ - FunctionSymbol, PackageSymbol, SymbolRef, BUILTIN_FUNCTION_PACKAGE, BUILTIN_STR_PACKAGE, -}; -use crate::resolver::scope::NodeKey; -use kclvm_ast::ast::AstIndex; -use kclvm_ast::ast::Program; -use kclvm_ast::walker::MutSelfTypedResultWalker; -use kclvm_error::Position; -use kclvm_primitives::IndexSet; -mod node; - -pub const BUILTIN_SYMBOL_PKG_PATH: &str = "@builtin"; - -pub struct Namer<'ctx> { - gs: &'ctx mut GlobalState, - ctx: NamerContext<'ctx>, -} - -struct NamerContext<'ctx> { - pub program: &'ctx Program, - pub current_package_info: Option, - pub current_module_info: Option, - pub owner_symbols: Vec, - pub value_fully_qualified_name_set: IndexSet, -} - -impl<'ctx> NamerContext<'ctx> { - pub fn get_node_key(&self, id: &AstIndex) -> NodeKey { - NodeKey { - pkgpath: self - .current_package_info - .clone() - .unwrap() - .fully_qualified_name, - id: id.clone(), - } - } -} - -impl<'ctx> Namer<'ctx> { - fn new(program: &'ctx Program, gs: &'ctx mut GlobalState) -> Self { - Self { - ctx: NamerContext { - program, - current_package_info: None, - current_module_info: None, - owner_symbols: Vec::default(), - value_fully_qualified_name_set: IndexSet::default(), - }, - gs, - } - } - - // serial namer pass - pub fn find_symbols(program: &'ctx Program, gs: &'ctx mut GlobalState) { - let has_init_builtin = gs.ctx.has_init_builtin; - gs.ctx.has_init_builtin = true; - let mut namer = Self::new(program, gs); - namer.ctx.current_package_info = Some(PackageInfo::new( - BUILTIN_SYMBOL_PKG_PATH.to_string(), - "".to_string(), - true, - )); - if !has_init_builtin { - namer.init_builtin_symbols(); - } - - namer - .gs - .get_packages_mut() - .add_package(namer.ctx.current_package_info.take().unwrap()); - - for (name, modules) in namer.ctx.program.pkgs.iter() { - namer.walk_pkg(name, modules); - } - - namer.define_symbols(); - } - - fn walk_pkg(&mut self, name: &String, modules: &Vec) { - // new pkgs or invalidate pkg - if self.gs.get_packages().get_package_info(name).is_some() - && !self.gs.new_or_invalidate_pkgs.contains(name) - { - return; - } - - // add new pkgs to invalidate pkgs - self.gs.new_or_invalidate_pkgs.insert(name.clone()); - - { - if modules.is_empty() { - return; - } - self.ctx.value_fully_qualified_name_set.clear(); - let mut real_path = Path::new(&self.ctx.program.root) - .join(name.replace('.', &std::path::MAIN_SEPARATOR.to_string())) - .to_str() - .unwrap() - .to_string(); - if name == kclvm_ast::MAIN_PKG { - real_path = self.ctx.program.root.clone() - } - let pkg_pos = Position { - filename: real_path.clone(), - line: 0, - column: None, - }; - - let pkg_symbol = PackageSymbol::new(name.clone(), pkg_pos.clone(), pkg_pos); - let symbol_ref = self - .gs - .get_symbols_mut() - .alloc_package_symbol(pkg_symbol, name.to_string()); - self.ctx.owner_symbols.push(symbol_ref); - - self.ctx.current_package_info = - Some(PackageInfo::new(name.to_string(), real_path, false)); - } - - let modules = self.ctx.program.get_modules_for_pkg(name); - for module in modules.iter() { - let module = module.read().expect("Failed to acquire module lock"); - self.ctx - .current_package_info - .as_mut() - .unwrap() - .kfile_paths - .insert(module.filename.clone()); - self.ctx.current_module_info = - Some(ModuleInfo::new(module.filename.clone(), name.to_string())); - self.walk_module(&module); - self.gs - .get_packages_mut() - .add_module_info(self.ctx.current_module_info.take().unwrap()); - } - - self.ctx.owner_symbols.pop(); - self.gs - .get_packages_mut() - .add_package(self.ctx.current_package_info.take().unwrap()) - } - - fn init_builtin_symbols(&mut self) { - //add global built functions - for (name, builtin_func) in BUILTIN_FUNCTIONS.iter() { - let mut func_symbol = FunctionSymbol::new( - name.to_string(), - Position::dummy_pos(), - Position::dummy_pos(), - None, - true, - ); - - func_symbol.sema_info.ty = Some(Arc::new(builtin_func.clone())); - func_symbol.sema_info.doc = builtin_func.ty_doc(); - let symbol_ref = self.gs.get_symbols_mut().alloc_function_symbol( - func_symbol, - self.ctx.get_node_key(&AstIndex::default()), - BUILTIN_FUNCTION_PACKAGE.to_string(), - ); - self.gs - .get_symbols_mut() - .symbols_info - .global_builtin_symbols - .insert(name.to_string(), symbol_ref); - } - - //add system modules - for system_pkg_name in STANDARD_SYSTEM_MODULES { - let package_symbol_ref = self.gs.get_symbols_mut().alloc_package_symbol( - PackageSymbol::new( - system_pkg_name.to_string(), - Position::dummy_pos(), - Position::dummy_pos(), - ), - system_pkg_name.to_string(), - ); - for func_name in get_system_module_members(system_pkg_name) { - let func_ty = get_system_member_function_ty(*system_pkg_name, func_name); - let mut func_symbol = FunctionSymbol::new( - func_name.to_string(), - Position::dummy_pos(), - Position::dummy_pos(), - Some(package_symbol_ref), - false, - ); - - func_symbol.sema_info.ty = Some(func_ty.clone()); - func_symbol.sema_info.doc = func_ty.ty_doc(); - let func_symbol_ref = self.gs.get_symbols_mut().alloc_function_symbol( - func_symbol, - self.ctx.get_node_key(&AstIndex::default()), - system_pkg_name.to_string(), - ); - self.gs - .get_symbols_mut() - .packages - .get_mut(package_symbol_ref.get_id()) - .unwrap() - .members - .insert(func_name.to_string(), func_symbol_ref); - } - } - - //add string builtin function - let package_symbol_ref = self.gs.get_symbols_mut().alloc_package_symbol( - PackageSymbol::new( - BUILTIN_STR_PACKAGE.to_string(), - Position::dummy_pos(), - Position::dummy_pos(), - ), - BUILTIN_STR_PACKAGE.to_string(), - ); - for (name, builtin_func) in STRING_MEMBER_FUNCTIONS.iter() { - let mut func_symbol = FunctionSymbol::new( - name.to_string(), - Position::dummy_pos(), - Position::dummy_pos(), - Some(package_symbol_ref), - true, - ); - - func_symbol.sema_info.ty = Some(Arc::new(builtin_func.clone())); - func_symbol.sema_info.doc = builtin_func.ty_doc(); - let symbol_ref = self.gs.get_symbols_mut().alloc_function_symbol( - func_symbol, - self.ctx.get_node_key(&AstIndex::default()), - BUILTIN_STR_PACKAGE.to_string(), - ); - self.gs - .get_symbols_mut() - .packages - .get_mut(package_symbol_ref.get_id()) - .unwrap() - .members - .insert(name.to_string(), symbol_ref); - } - } - - fn define_symbols(&mut self) { - self.gs.get_symbols_mut().build_fully_qualified_name_map(); - } -} - -#[cfg(test)] -mod tests { - use super::Namer; - use crate::core::global_state::GlobalState; - use crate::core::symbol::SymbolKind; - use kclvm_parser::load_program; - use kclvm_parser::ParseSession; - use std::sync::Arc; - - #[test] - fn test_find_symbols() { - let sess = Arc::new(ParseSession::default()); - let program = load_program( - sess.clone(), - &["./src/namer/test_data/schema_symbols.k"], - None, - None, - ) - .unwrap() - .program; - let mut gs = GlobalState::default(); - Namer::find_symbols(&program, &mut gs); - - let symbols = gs.get_symbols(); - - let excepts_symbols = vec![ - // package - ("import_test.a", SymbolKind::Package), - ("import_test.b", SymbolKind::Package), - ("import_test.c", SymbolKind::Package), - ("import_test.d", SymbolKind::Package), - ("import_test.e", SymbolKind::Package), - ("import_test.f", SymbolKind::Package), - ("__main__", SymbolKind::Package), - ("pkg", SymbolKind::Package), - // schema - ("import_test.f.UnionType", SymbolKind::Schema), - ("import_test.a.Person", SymbolKind::Schema), - ("import_test.c.TestOfMixin", SymbolKind::Schema), - ("import_test.d.Parent", SymbolKind::Schema), - ("import_test.e.UnionType", SymbolKind::Schema), - ("pkg.Name", SymbolKind::Schema), - ("pkg.Person", SymbolKind::Schema), - ("__main__.Main", SymbolKind::Schema), - // attribute - ("import_test.f.UnionType.b", SymbolKind::Attribute), - ("import_test.a.Person.name", SymbolKind::Attribute), - ("import_test.a.Person.age", SymbolKind::Attribute), - ("pkg.Name.name", SymbolKind::Attribute), - ("pkg.Person.name", SymbolKind::Attribute), - ("import_test.c.TestOfMixin.age", SymbolKind::Attribute), - ("import_test.d.Parent.age1", SymbolKind::Attribute), - ("import_test.e.UnionType.a", SymbolKind::Attribute), - ("__main__.Main.name", SymbolKind::Attribute), - ("__main__.Main.age", SymbolKind::Attribute), - ("__main__.Main.person", SymbolKind::Attribute), - ("__main__.Main.list_union_type", SymbolKind::Attribute), - ("__main__.Main.dict_union_type", SymbolKind::Attribute), - // value - ("__main__.p", SymbolKind::Value), - ("__main__.person", SymbolKind::Value), - ("__main__._c", SymbolKind::Value), - ("import_test.a._a", SymbolKind::Value), - ("import_test.b._b", SymbolKind::Value), - ]; - - for (fqn, kind) in excepts_symbols { - assert!(symbols - .symbols_info - .fully_qualified_name_map - .contains_key(fqn)); - assert_eq!( - symbols - .get_symbol_by_fully_qualified_name(fqn) - .unwrap() - .get_kind(), - kind - ); - } - } -} diff --git a/kclvm/sema/src/namer/node.rs b/kclvm/sema/src/namer/node.rs deleted file mode 100644 index 92b0dfc86..000000000 --- a/kclvm/sema/src/namer/node.rs +++ /dev/null @@ -1,429 +0,0 @@ -use crate::core::package::ImportInfo; -use crate::core::symbol::{ - AttributeSymbol, RuleSymbol, SchemaSymbol, SymbolKind, SymbolRef, TypeAliasSymbol, ValueSymbol, -}; - -use super::Namer; -use kclvm_ast::ast; -use kclvm_ast::pos::GetPos; -use kclvm_ast::walker::MutSelfTypedResultWalker; -use kclvm_ast_pretty::{print_ast_node, ASTNode}; -use kclvm_error::diagnostic::Range; - -impl<'ctx> MutSelfTypedResultWalker<'ctx> for Namer<'_> { - type Result = Option>; - fn walk_module(&mut self, module: &'ctx ast::Module) -> Self::Result { - let owner = *self.ctx.owner_symbols.last().unwrap(); - for stmt_node in module.body.iter() { - let symbol_refs = self.walk_stmt(&stmt_node.node); - - if let Some(symbol_refs) = symbol_refs { - for symbol_ref in symbol_refs { - let full_name = self - .gs - .get_symbols() - .get_fully_qualified_name(symbol_ref) - .unwrap(); - let name = full_name.split(".").last().unwrap().to_string(); - - let package_symbol = self - .gs - .get_symbols_mut() - .packages - .get_mut(owner.get_id()) - .unwrap(); - - if !package_symbol.members.contains_key(&name) { - package_symbol.members.insert(name, symbol_ref); - } - } - } - } - - None - } - - fn walk_expr_stmt(&mut self, _expr_stmt: &'ctx ast::ExprStmt) -> Self::Result { - None - } - - fn walk_unification_stmt( - &mut self, - unification_stmt: &'ctx ast::UnificationStmt, - ) -> Self::Result { - let (start_pos, end_pos): Range = unification_stmt.target.get_span_pos(); - let owner = self.ctx.owner_symbols.last().unwrap().clone(); - if unification_stmt.target.node.names.len() == 1 { - let owner_fully_qualified_name = self - .gs - .get_symbols() - .get_fully_qualified_name(owner) - .unwrap(); - let value_name = unification_stmt.target.node.get_name(); - if self.gs.get_symbols().get_schema_symbol(owner).is_some() { - let attribute_ref = self.gs.get_symbols_mut().alloc_attribute_symbol( - AttributeSymbol::new(value_name, start_pos, end_pos, owner, false, None), - self.ctx - .get_node_key(&unification_stmt.target.node.names[0].id), - self.ctx - .current_package_info - .clone() - .unwrap() - .fully_qualified_name, - ); - Some(vec![attribute_ref]) - } else { - let value_fully_qualified_name = owner_fully_qualified_name + "." + &value_name; - if !self - .ctx - .value_fully_qualified_name_set - .contains(&value_fully_qualified_name) - { - let value_ref = self.gs.get_symbols_mut().alloc_value_symbol( - ValueSymbol::new(value_name, start_pos, end_pos, Some(owner), true), - self.ctx.get_node_key(&unification_stmt.target.id), - self.ctx - .current_package_info - .clone() - .unwrap() - .fully_qualified_name, - ); - self.ctx - .value_fully_qualified_name_set - .insert(value_fully_qualified_name); - Some(vec![value_ref]) - } else { - None - } - } - } else { - None - } - } - - fn walk_type_alias_stmt(&mut self, type_alias_stmt: &'ctx ast::TypeAliasStmt) -> Self::Result { - let (start_pos, end_pos): Range = type_alias_stmt.type_name.get_span_pos(); - let owner = self.ctx.owner_symbols.last().unwrap().clone(); - let type_alias_ref = self.gs.get_symbols_mut().alloc_type_alias_symbol( - TypeAliasSymbol::new( - type_alias_stmt.type_name.node.get_name(), - start_pos, - end_pos, - owner, - ), - self.ctx.get_node_key(&type_alias_stmt.type_name.id), - self.ctx - .current_package_info - .clone() - .unwrap() - .fully_qualified_name, - ); - Some(vec![type_alias_ref]) - } - - fn walk_assign_stmt(&mut self, assign_stmt: &'ctx ast::AssignStmt) -> Self::Result { - let mut value_symbols = vec![]; - for target in assign_stmt.targets.iter() { - let (start_pos, end_pos): Range = target.get_span_pos(); - let owner = self.ctx.owner_symbols.last().unwrap().clone(); - if target.node.paths.is_empty() { - let owner_fully_qualified_name = self - .gs - .get_symbols() - .get_fully_qualified_name(owner) - .unwrap(); - let value_name = target.node.get_name(); - let value_fully_qualified_name = owner_fully_qualified_name + "." + &value_name; - if !self - .ctx - .value_fully_qualified_name_set - .contains(&value_fully_qualified_name) - { - let value_ref = self.gs.get_symbols_mut().alloc_value_symbol( - ValueSymbol::new( - value_name.to_string(), - start_pos, - end_pos, - Some(owner), - true, - ), - self.ctx.get_node_key(&target.id), - self.ctx - .current_package_info - .clone() - .unwrap() - .fully_qualified_name, - ); - self.ctx - .value_fully_qualified_name_set - .insert(value_fully_qualified_name); - value_symbols.push(value_ref) - } - } - } - Some(value_symbols) - } - - fn walk_aug_assign_stmt(&mut self, _aug_assign_stmt: &'ctx ast::AugAssignStmt) -> Self::Result { - None - } - - fn walk_assert_stmt(&mut self, _assert_stmt: &'ctx ast::AssertStmt) -> Self::Result { - None - } - - fn walk_if_stmt(&mut self, if_stmt: &'ctx ast::IfStmt) -> Self::Result { - let mut all_symbols = vec![]; - for stmt in if_stmt.body.iter() { - let mut symbols = self.walk_stmt(&stmt.node); - if let Some(symbols) = &mut symbols { - all_symbols.append(symbols); - } - } - for stmt in if_stmt.orelse.iter() { - let mut symbols = self.walk_stmt(&stmt.node); - if let Some(symbols) = &mut symbols { - all_symbols.append(symbols); - } - } - Some(all_symbols) - } - - fn walk_import_stmt(&mut self, import_stmt: &'ctx ast::ImportStmt) -> Self::Result { - self.ctx - .current_module_info - .as_mut() - .unwrap() - .add_import_info(ImportInfo::new( - import_stmt.name.clone(), - import_stmt.path.node.clone(), - )); - - None - } - - fn walk_schema_stmt(&mut self, schema_stmt: &'ctx ast::SchemaStmt) -> Self::Result { - let (start_pos, end_pos): Range = schema_stmt.name.get_span_pos(); - let owner = self.ctx.owner_symbols.last().unwrap(); - let shcema_ref = self.gs.get_symbols_mut().alloc_schema_symbol( - SchemaSymbol::new(schema_stmt.name.node.clone(), start_pos, end_pos, *owner), - self.ctx.get_node_key(&schema_stmt.name.id), - self.ctx - .current_package_info - .clone() - .unwrap() - .fully_qualified_name, - ); - self.ctx.owner_symbols.push(shcema_ref); - - for stmt in schema_stmt.body.iter() { - let symbol_refs = self.walk_stmt(&stmt.node); - if let Some(symbol_refs) = symbol_refs { - for symbol_ref in symbol_refs { - if matches!(&symbol_ref.get_kind(), SymbolKind::Attribute) { - let full_attribute_name = self - .gs - .get_symbols() - .get_fully_qualified_name(symbol_ref) - .unwrap(); - self.ctx - .value_fully_qualified_name_set - .insert(full_attribute_name.clone()); - let attribute_name = - full_attribute_name.split(".").last().unwrap().to_string(); - - let schema_symbol = self - .gs - .get_symbols_mut() - .schemas - .get_mut(shcema_ref.get_id()) - .unwrap(); - if !schema_symbol.attributes.contains_key(&attribute_name) { - schema_symbol.attributes.insert(attribute_name, symbol_ref); - } - } - } - } - } - self.ctx.owner_symbols.pop(); - Some(vec![shcema_ref]) - } - - fn walk_rule_stmt(&mut self, rule_stmt: &'ctx ast::RuleStmt) -> Self::Result { - let (start_pos, end_pos): Range = rule_stmt.name.get_span_pos(); - let owner = self.ctx.owner_symbols.last().unwrap().clone(); - let rule_ref = self.gs.get_symbols_mut().alloc_rule_symbol( - RuleSymbol::new(rule_stmt.name.node.clone(), start_pos, end_pos, owner), - self.ctx.get_node_key(&rule_stmt.name.id), - self.ctx - .current_package_info - .clone() - .unwrap() - .fully_qualified_name, - ); - Some(vec![rule_ref]) - } - - fn walk_quant_expr(&mut self, _quant_expr: &'ctx ast::QuantExpr) -> Self::Result { - None - } - - fn walk_schema_attr(&mut self, schema_attr: &'ctx ast::SchemaAttr) -> Self::Result { - let (start_pos, end_pos): Range = schema_attr.name.get_span_pos(); - let owner = self.ctx.owner_symbols.last().unwrap().clone(); - let default_value = schema_attr - .value - .as_ref() - .map(|v| print_ast_node(ASTNode::Expr(v))); - let attribute_ref = self.gs.get_symbols_mut().alloc_attribute_symbol( - AttributeSymbol::new( - schema_attr.name.node.clone(), - start_pos, - end_pos, - owner, - schema_attr.is_optional, - default_value, - ), - self.ctx.get_node_key(&schema_attr.name.id), - self.ctx - .current_package_info - .clone() - .unwrap() - .fully_qualified_name, - ); - Some(vec![attribute_ref]) - } - - /// if else -> sup([body, orelse]) - fn walk_if_expr(&mut self, _if_expr: &'ctx ast::IfExpr) -> Self::Result { - None - } - - fn walk_unary_expr(&mut self, _unary_expr: &'ctx ast::UnaryExpr) -> Self::Result { - None - } - - fn walk_binary_expr(&mut self, _binary_expr: &'ctx ast::BinaryExpr) -> Self::Result { - None - } - - fn walk_selector_expr(&mut self, _selector_expr: &'ctx ast::SelectorExpr) -> Self::Result { - None - } - - fn walk_call_expr(&mut self, _call_expr: &'ctx ast::CallExpr) -> Self::Result { - None - } - - fn walk_subscript(&mut self, _subscript: &'ctx ast::Subscript) -> Self::Result { - None - } - - fn walk_paren_expr(&mut self, _paren_expr: &'ctx ast::ParenExpr) -> Self::Result { - None - } - - fn walk_list_expr(&mut self, _list_expr: &'ctx ast::ListExpr) -> Self::Result { - None - } - - fn walk_list_comp(&mut self, _list_comp: &'ctx ast::ListComp) -> Self::Result { - None - } - - fn walk_dict_comp(&mut self, _dict_comp: &'ctx ast::DictComp) -> Self::Result { - None - } - - fn walk_list_if_item_expr( - &mut self, - _list_if_item_expr: &'ctx ast::ListIfItemExpr, - ) -> Self::Result { - None - } - - fn walk_starred_expr(&mut self, _starred_expr: &'ctx ast::StarredExpr) -> Self::Result { - None - } - - fn walk_config_if_entry_expr( - &mut self, - _config_if_entry_expr: &'ctx ast::ConfigIfEntryExpr, - ) -> Self::Result { - None - } - - fn walk_comp_clause(&mut self, _comp_clause: &'ctx ast::CompClause) -> Self::Result { - None - } - - fn walk_schema_expr(&mut self, _schema_expr: &'ctx ast::SchemaExpr) -> Self::Result { - None - } - - fn walk_config_expr(&mut self, _config_expr: &'ctx ast::ConfigExpr) -> Self::Result { - None - } - - fn walk_check_expr(&mut self, _check_expr: &'ctx ast::CheckExpr) -> Self::Result { - None - } - - fn walk_lambda_expr(&mut self, _lambda_expr: &'ctx ast::LambdaExpr) -> Self::Result { - None - } - - fn walk_keyword(&mut self, _keyword: &'ctx ast::Keyword) -> Self::Result { - None - } - - fn walk_arguments(&mut self, _arguments: &'ctx ast::Arguments) -> Self::Result { - None - } - - fn walk_compare(&mut self, _compare: &'ctx ast::Compare) -> Self::Result { - None - } - - fn walk_identifier(&mut self, _identifier: &'ctx ast::Identifier) -> Self::Result { - None - } - - fn walk_target(&mut self, _target: &'ctx ast::Target) -> Self::Result { - None - } - - fn walk_number_lit(&mut self, _number_lit: &'ctx ast::NumberLit) -> Self::Result { - None - } - - fn walk_string_lit(&mut self, _string_lit: &'ctx ast::StringLit) -> Self::Result { - None - } - - fn walk_name_constant_lit( - &mut self, - _name_constant_lit: &'ctx ast::NameConstantLit, - ) -> Self::Result { - None - } - - fn walk_joined_string(&mut self, _joined_string: &'ctx ast::JoinedString) -> Self::Result { - None - } - - fn walk_formatted_value( - &mut self, - _formatted_value: &'ctx ast::FormattedValue, - ) -> Self::Result { - None - } - - fn walk_comment(&mut self, _comment: &'ctx ast::Comment) -> Self::Result { - None - } - - fn walk_missing_expr(&mut self, _missing_expr: &'ctx ast::MissingExpr) -> Self::Result { - None - } -} diff --git a/kclvm/sema/src/pre_process/config.rs b/kclvm/sema/src/pre_process/config.rs deleted file mode 100644 index 153b36fa7..000000000 --- a/kclvm/sema/src/pre_process/config.rs +++ /dev/null @@ -1,366 +0,0 @@ -use crate::info::is_private_field; -use kclvm_ast::walker::MutSelfMutWalker; -use kclvm_ast::{ast, walk_if_mut}; -use kclvm_primitives::{IndexMap, IndexSet}; - -const NAME_NONE_BUCKET_KEY: &str = "$name_none"; - -#[derive(Debug, Default)] -struct ConfigNestAttrTransformer; - -impl ConfigNestAttrTransformer { - pub fn walk_config_entry(&mut self, config_entry: &mut Box>) { - if let Some(key) = config_entry.node.key.as_mut() { - if let ast::Expr::Identifier(identifier) = &mut key.node { - // desuger config expr, e.g., desuger - // ``` - // foo = Foo { - // bar.baz : xxx - // } - // ``` - // to: - // ``` - // foo = Foo { - // bar : Bar { - // baz : xxx - // } - // } - // ``` - if identifier.names.len() > 1 { - let mut names = identifier.names.clone(); - let names = &mut names[1..]; - names.reverse(); - identifier.names = vec![identifier.names[0].clone()]; - key.filename = identifier.names[0].filename.clone(); - key.line = identifier.names[0].line; - key.column = identifier.names[0].column; - key.end_line = identifier.names[0].end_line; - key.end_column = identifier.names[0].end_column; - - let mut value = config_entry.node.value.clone(); - for (i, name) in names.iter().enumerate() { - let is_last_item = i == 0; - let name_node = ast::Identifier { - names: vec![name.clone()], - pkgpath: "".to_string(), - ctx: ast::ExprContext::Load, - }; - let entry_value = ast::ConfigEntry { - key: Some(Box::new(ast::Node::new( - ast::Expr::Identifier(name_node), - name.filename.clone(), - name.line, - name.column, - name.end_line, - name.end_column, - ))), - value: value.clone(), - operation: if is_last_item { - config_entry.node.operation.clone() - } else { - ast::ConfigEntryOperation::Union - }, - }; - let config_expr = ast::ConfigExpr { - items: vec![Box::new(ast::Node::new( - entry_value, - config_entry.filename.clone(), - name.line, - name.column, - config_entry.end_line, - config_entry.end_column, - ))], - }; - value = Box::new(ast::Node::new( - ast::Expr::Config(config_expr), - value.filename.clone(), - name.line, - name.column, - value.end_line, - value.end_column, - )) - } - config_entry.node.value = value; - config_entry.node.operation = ast::ConfigEntryOperation::Union; - } - } - } - } -} - -impl<'ctx> MutSelfMutWalker<'ctx> for ConfigNestAttrTransformer { - fn walk_config_expr(&mut self, config_expr: &'ctx mut ast::ConfigExpr) { - for config_entry in config_expr.items.iter_mut() { - self.walk_config_entry(config_entry); - self.walk_expr(&mut config_entry.node.value.node); - } - } - fn walk_config_if_entry_expr( - &mut self, - config_if_entry_expr: &'ctx mut ast::ConfigIfEntryExpr, - ) { - for config_entry in config_if_entry_expr.items.iter_mut() { - self.walk_config_entry(config_entry); - self.walk_expr(&mut config_entry.node.value.node); - } - walk_if_mut!(self, walk_expr, config_if_entry_expr.orelse); - } -} - -#[derive(Debug, Default)] -struct ConfigMergeTransformer {} - -#[derive(Debug)] -enum ConfigMergeKind { - Override, - Union, -} - -impl ConfigMergeTransformer { - pub fn merge(&mut self, program: &mut ast::Program) { - // {name: (filename, module index in main package, statement index in the module body, kind)} - // module index is to prevent same filename in main package - let mut name_declaration_mapping: IndexMap< - String, - Vec<(String, usize, usize, ConfigMergeKind)>, - > = IndexMap::default(); - // 1. Collect merged config - let modules = program.get_modules_for_pkg(kclvm_ast::MAIN_PKG); - for (module_id, module) in modules.iter().enumerate() { - let mut module = module.write().expect("Failed to acquire module lock"); - let filename = module.filename.to_string(); - for (i, stmt) in module.body.iter_mut().enumerate() { - match &mut stmt.node { - ast::Stmt::Unification(unification_stmt) - if !unification_stmt.target.node.names.is_empty() => - { - let name = &unification_stmt.target.node.names[0].node; - match name_declaration_mapping.get_mut(name) { - Some(declarations) => declarations.push(( - filename.clone(), - module_id, - i, - ConfigMergeKind::Union, - )), - None => { - name_declaration_mapping.insert( - name.to_string(), - vec![(filename.clone(), module_id, i, ConfigMergeKind::Union)], - ); - } - } - } - ast::Stmt::Assign(assign_stmt) => { - if let ast::Expr::Schema(_) = assign_stmt.value.node { - for target in &assign_stmt.targets { - if target.node.paths.is_empty() { - let name = &target.node.name.node; - match name_declaration_mapping.get_mut(name) { - Some(declarations) => { - // A hidden var is mutable. - if is_private_field(name) { - declarations.clear(); - declarations.push(( - filename.clone(), - module_id, - i, - ConfigMergeKind::Override, - )) - } - } - None => { - name_declaration_mapping.insert( - name.to_string(), - vec![( - filename.clone(), - module_id, - i, - ConfigMergeKind::Override, - )], - ); - } - } - } - } - } - } - _ => {} - } - } - } - // 2. Merge config - for (_, index_list) in &name_declaration_mapping { - let index_len = index_list.len(); - if index_len > 1 { - let (filename, merged_id, merged_index, merged_kind) = index_list.last().unwrap(); - let mut items: Vec> = vec![]; - for (merged_filename, merged_id, index, kind) in index_list { - let modules = program.get_modules_for_pkg(kclvm_ast::MAIN_PKG); - for (module_id, module) in modules.iter().enumerate() { - let mut module = module.write().expect("Failed to acquire module lock"); - if &module.filename == merged_filename && module_id == *merged_id { - let stmt = module.body.get_mut(*index).unwrap(); - match &mut stmt.node { - ast::Stmt::Unification(unification_stmt) - if matches!(kind, ConfigMergeKind::Union) => - { - if let ast::Expr::Config(config_expr) = - &mut unification_stmt.value.node.config.node - { - let mut config_items = config_expr.items.clone(); - items.append(&mut config_items); - } - } - ast::Stmt::Assign(assign_stmt) - if matches!(kind, ConfigMergeKind::Override) => - { - if let ast::Expr::Schema(schema_expr) = - &mut assign_stmt.value.node - { - if let ast::Expr::Config(config_expr) = - &mut schema_expr.config.node - { - let mut config_items = config_expr.items.clone(); - items.append(&mut config_items); - } - } - } - _ => { - bug!("mismatch ast node and config merge kind: {:?}", kind) - } - } - } - } - } - for (module_id, module) in modules.iter().enumerate() { - let mut module = module.write().expect("Failed to acquire module lock"); - if &module.filename == filename && module_id == *merged_id { - if let Some(stmt) = module.body.get_mut(*merged_index) { - match &mut stmt.node { - ast::Stmt::Unification(unification_stmt) - if matches!(merged_kind, ConfigMergeKind::Union) => - { - if let ast::Expr::Config(config_expr) = - &mut unification_stmt.value.node.config.node - { - config_expr.items = unify_config_entries(&items); - } - } - ast::Stmt::Assign(assign_stmt) - if matches!(merged_kind, ConfigMergeKind::Override) => - { - if let ast::Expr::Schema(schema_expr) = - &mut assign_stmt.value.node - { - if let ast::Expr::Config(config_expr) = - &mut schema_expr.config.node - { - config_expr.items = unify_config_entries(&items); - } - } - } - _ => bug!( - "mismatch ast node and config merge kind: {:?}", - merged_kind - ), - } - } - break; - } - } - } - } - // 3. Delete redundant config. - for (i, module) in modules.iter().enumerate() { - let mut module = module.write().expect("Failed to acquire module lock"); - let mut delete_index_set: IndexSet = IndexSet::default(); - for (_, index_list) in &name_declaration_mapping { - let index_len = index_list.len(); - if index_len > 1 { - for (filename, module_id, index, _) in &index_list[..index_len - 1] { - // Use module filename and index to prevent the same compile filenames - // in the main package. - if &module.filename == filename && i == *module_id { - delete_index_set.insert(*index); - } - } - } - } - let mut body: Vec<(usize, &ast::NodeRef)> = - module.body.iter().enumerate().collect(); - body.retain(|(idx, _)| !delete_index_set.contains(idx)); - module.body = body - .iter() - .map(|(_, stmt)| (*stmt).clone()) - .collect::>>(); - } - } -} - -/// Unify config entries. -fn unify_config_entries( - entries: &[ast::NodeRef], -) -> Vec> { - // Using bucket map to check unique/merge option and store values - let mut bucket: IndexMap>> = Default::default(); - for entry in entries { - let name = match &entry.node.key { - Some(key) => match &key.node { - ast::Expr::Identifier(identifier) => identifier.get_name(), - ast::Expr::StringLit(string_lit) => string_lit.value.clone(), - _ => NAME_NONE_BUCKET_KEY.to_string(), - }, - None => NAME_NONE_BUCKET_KEY.to_string(), - }; - let entry = entry.clone(); - match bucket.get_mut(&name) { - Some(values) => { - // If the attribute operation is override, clear all previous entries and override - // with current entry. - if let ast::ConfigEntryOperation::Override = entry.node.operation { - values.clear(); - } - values.push(entry); - } - None => { - let values = vec![entry]; - bucket.insert(name, values); - } - } - } - let mut entries = vec![]; - for (_, items) in bucket.iter_mut() { - entries.append(items); - } - // Unify config entries recursively. - for entry in &mut entries { - match &mut entry.node.value.node { - ast::Expr::Schema(item_schema_expr) => { - if let ast::Expr::Config(item_config_expr) = &mut item_schema_expr.config.node { - item_config_expr.items = unify_config_entries(&item_config_expr.items); - } - } - ast::Expr::Config(item_config_expr) => { - item_config_expr.items = unify_config_entries(&item_config_expr.items); - } - _ => {} - } - } - entries -} - -/// Merge program for multiple file config. -#[inline] -pub fn merge_program(program: &mut ast::Program) { - let mut merger = ConfigMergeTransformer::default(); - merger.merge(program); -} - -/// Fix AST config expr nest attribute declarations. -/// -/// Examples -/// -------- -/// {a.b.c = 1} -> {a: {b: {c = 1}}} -pub fn fix_config_expr_nest_attr(module: &mut ast::Module) { - ConfigNestAttrTransformer::default().walk_module(module); -} diff --git a/kclvm/sema/src/pre_process/mod.rs b/kclvm/sema/src/pre_process/mod.rs deleted file mode 100644 index 482316b00..000000000 --- a/kclvm/sema/src/pre_process/mod.rs +++ /dev/null @@ -1,55 +0,0 @@ -mod config; -mod identifier; -mod lit_ty_default_value; -mod multi_assign; - -use kclvm_ast::ast; -use kclvm_primitives::IndexMap; - -#[cfg(test)] -mod tests; - -pub use config::{fix_config_expr_nest_attr, merge_program}; -pub use identifier::{fix_qualified_identifier, fix_raw_identifier_prefix}; -pub use lit_ty_default_value::fix_lit_ty_default_value; -pub use multi_assign::transform_multi_assign; - -use crate::resolver::Options; - -/// Pre-process AST program. -pub fn pre_process_program(program: &mut ast::Program, opts: &Options) { - for (pkgpath, modules) in program.pkgs.iter() { - let mut import_names = IndexMap::default(); - if pkgpath == kclvm_ast::MAIN_PKG { - for module in modules.iter() { - let module = program - .get_module(module) - .expect("Failed to acquire module lock") - .expect(&format!("module {:?} not found in program", module)); - for stmt in &module.body { - if let ast::Stmt::Import(import_stmt) = &stmt.node { - import_names - .insert(import_stmt.name.clone(), import_stmt.path.node.clone()); - } - } - } - } - for module in modules.iter() { - let mut module = program - .get_module_mut(module) - .expect("Failed to acquire module lock") - .expect(&format!("module {:?} not found in program", module)); - if pkgpath != kclvm_ast::MAIN_PKG { - import_names.clear(); - } - // First we should transform the raw identifier to avoid raw identifier that happens to be a package path. - fix_raw_identifier_prefix(&mut module); - fix_qualified_identifier(&mut module, &mut import_names); - fix_config_expr_nest_attr(&mut module); - fix_lit_ty_default_value(&mut module); - } - } - if opts.merge_program { - merge_program(program); - } -} diff --git a/kclvm/sema/src/pre_process/tests.rs b/kclvm/sema/src/pre_process/tests.rs deleted file mode 100644 index 1cc0eb88f..000000000 --- a/kclvm/sema/src/pre_process/tests.rs +++ /dev/null @@ -1,354 +0,0 @@ -use std::sync::Arc; - -use super::*; -use kclvm_ast::path::get_attr_paths_from_config_expr; -use kclvm_parser::{load_program, parse_file_force_errors, ParseSession}; -use kclvm_primitives::IndexMap; - -#[test] -fn test_fix_qualified_identifier() { - let mut module = - parse_file_force_errors("./src/pre_process/test_data/qualified_identifier.k", None) - .unwrap(); - fix_qualified_identifier(&mut module, &mut IndexMap::default()); - if let ast::Stmt::Assign(assign_stmt) = &module.body[1].node { - if let ast::Expr::Identifier(identifier) = &assign_stmt.value.node { - assert_eq!(identifier.pkgpath, "pkg") - } else { - panic!("invalid assign statement value") - } - } else { - panic!("invalid assign statement") - } -} - -#[test] -fn test_fix_lit_ty_default_value() { - let mut module = - parse_file_force_errors("./src/pre_process/test_data/lit_ty_default_val.k", None).unwrap(); - fix_lit_ty_default_value(&mut module); - if let ast::Stmt::Schema(schema_stmt) = &module.body[0].node { - if let ast::Stmt::SchemaAttr(schema_attr) = &schema_stmt.body[0].node { - assert_eq!( - schema_attr.value.as_ref().unwrap().node, - ast::Expr::StringLit(ast::StringLit { - is_long_string: false, - raw_value: "\"val\"".to_string(), - value: "val".to_string(), - }) - ) - } else { - panic!("invalid schema attr value") - } - if let ast::Stmt::SchemaAttr(schema_attr) = &schema_stmt.body[1].node { - assert_eq!( - schema_attr.value.as_ref().unwrap().node, - ast::Expr::NumberLit(ast::NumberLit { - value: ast::NumberLitValue::Int(1), - binary_suffix: None, - }) - ) - } else { - panic!("invalid schema attr value") - } - if let ast::Stmt::SchemaAttr(schema_attr) = &schema_stmt.body[2].node { - assert_eq!( - schema_attr.value.as_ref().unwrap().node, - ast::Expr::NumberLit(ast::NumberLit { - value: ast::NumberLitValue::Int(1), - binary_suffix: Some(ast::NumberBinarySuffix::Ki), - }) - ) - } else { - panic!("invalid schema attr value") - } - if let ast::Stmt::SchemaAttr(schema_attr) = &schema_stmt.body[3].node { - assert_eq!( - schema_attr.value.as_ref().unwrap().node, - ast::Expr::NumberLit(ast::NumberLit { - value: ast::NumberLitValue::Float(2.0), - binary_suffix: None, - }) - ) - } else { - panic!("invalid schema attr value") - } - if let ast::Stmt::SchemaAttr(schema_attr) = &schema_stmt.body[4].node { - assert_eq!( - schema_attr.value.as_ref().unwrap().node, - ast::Expr::NameConstantLit(ast::NameConstantLit { - value: ast::NameConstant::True, - }) - ) - } else { - panic!("invalid schema attr value") - } - if let ast::Stmt::SchemaAttr(schema_attr) = &schema_stmt.body[5].node { - assert_eq!( - schema_attr.value.as_ref().unwrap().node, - ast::Expr::NameConstantLit(ast::NameConstantLit { - value: ast::NameConstant::False, - }) - ) - } else { - panic!("invalid schema attr value") - } - } else { - panic!("invalid schema statement") - } -} - -#[test] -fn test_fix_raw_identifier_prefix() { - let mut module = - parse_file_force_errors("./src/pre_process/test_data/raw_identifier.k", None).unwrap(); - if let ast::Stmt::Assign(assign_stmt) = &module.body[0].node { - assert_eq!(assign_stmt.targets[0].node.name.node, "$schema") - } else { - panic!("invalid assign statement") - } - fix_raw_identifier_prefix(&mut module); - if let ast::Stmt::Assign(assign_stmt) = &module.body[0].node { - assert_eq!(assign_stmt.targets[0].node.name.node, "schema") - } else { - panic!("invalid assign statement") - } - if let ast::Stmt::Schema(schema_stmt) = &module.body[1].node { - if let ast::Stmt::SchemaAttr(attr) = &schema_stmt.body[0].node { - assert_eq!(attr.name.node, "name"); - } else { - panic!("invalid schema attr") - } - if let ast::Stmt::SchemaAttr(attr) = &schema_stmt.body[1].node { - assert_eq!(attr.name.node, "$name"); - } else { - panic!("invalid schema attr") - } - } else { - panic!("invalid schema statement") - } -} - -#[test] -fn test_transform_multi_assign() { - let targets = ["a", "b", "c", "d"]; - let mut module = - parse_file_force_errors("./src/pre_process/test_data/multi_assign.k", None).unwrap(); - if let ast::Stmt::Assign(assign_stmt) = &module.body[1].node { - assert_eq!(assign_stmt.targets.len(), targets.len()); - for (i, target) in targets.iter().enumerate() { - assert_eq!(assign_stmt.targets[i].node.get_name(), *target); - } - } else { - panic!("invalid assign statement") - } - transform_multi_assign(&mut module); - for (i, target) in targets.iter().enumerate() { - if let ast::Stmt::Assign(assign_stmt) = &module.body[i + 1].node { - assert_eq!(assign_stmt.targets.len(), 1); - assert_eq!(assign_stmt.targets[0].node.get_name(), *target); - } else { - panic!("invalid assign statement") - } - } -} - -#[test] -fn test_config_merge() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess, - &[ - "./src/pre_process/test_data/config_merge/def.k", - "./src/pre_process/test_data/config_merge/config1.k", - "./src/pre_process/test_data/config_merge/config2.k", - "./src/pre_process/test_data/config_merge/config2.k", - ], - None, - None, - ) - .unwrap() - .program; - merge_program(&mut program); - let modules = program.pkgs.get(kclvm_ast::MAIN_PKG).unwrap(); - assert_eq!(modules.len(), 3); - // Test the module merge result - let module = modules.last().unwrap(); - let module = program - .get_module(module) - .expect("Failed to acquire module lock") - .expect(&format!("module {:?} not found in program", module)); - if let ast::Stmt::Unification(unification) = &module.body[0].node { - let schema = &unification.value.node; - if let ast::Expr::Config(config) = &schema.config.node { - // 2 contains `name` in `config1.k`, `age` in `config2.k`. - // person: Person { - // name = "Alice" - // age = 18 - // } - assert_eq!(config.items.len(), 2); - assert_eq!( - get_attr_paths_from_config_expr(config), - vec!["name".to_string(), "age".to_string()] - ); - } else { - panic!( - "test failed, expect config expression, got {:?}", - schema.config - ) - } - } else { - panic!( - "test failed, expect unification statement, got {:?}", - module.body[0] - ) - } -} - -#[test] -fn test_config_override() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess, - &["./src/pre_process/test_data/config_override.k"], - None, - None, - ) - .unwrap() - .program; - merge_program(&mut program); - let modules = program.pkgs.get(kclvm_ast::MAIN_PKG).unwrap(); - assert_eq!(modules.len(), 1); - // Test the module merge result - let module = modules.first().unwrap(); - let module = program - .get_module(module) - .expect("Failed to acquire module lock") - .expect(&format!("module {:?} not found in program", module)); - if let ast::Stmt::Unification(unification) = &module.body[2].node { - let schema = &unification.value.node; - if let ast::Expr::Config(config) = &schema.config.node { - // key = Config { - // data.key: "value1" - // } - assert_eq!(config.items.len(), 1); - assert_eq!( - get_attr_paths_from_config_expr(config), - vec!["key".to_string(), "key.data.key".to_string()] - ); - } else { - panic!( - "test failed, expect config expression, got {:?}", - schema.config - ) - } - } else { - panic!( - "test failed, expect unification statement, got {:?}", - module.body[2] - ) - } -} - -#[test] -fn test_skip_merge_program() { - let sess = Arc::new(ParseSession::default()); - let program = load_program( - sess, - &[ - "./src/pre_process/test_data/config_merge/def.k", - "./src/pre_process/test_data/config_merge/config1.k", - "./src/pre_process/test_data/config_merge/config2.k", - ], - None, - None, - ) - .unwrap() - .program; - // skip merge program and save raw config ast node - // merge_program(&mut program); - let modules = program.pkgs.get(kclvm_ast::MAIN_PKG).unwrap(); - assert_eq!(modules.len(), 3); - let config1 = &modules[1]; - let config2 = &modules[1]; - let config1 = program - .get_module(config1) - .expect("Failed to acquire module lock") - .expect(&format!("module {:?} not found in program", config1)); - let config2 = program - .get_module(config2) - .expect("Failed to acquire module lock") - .expect(&format!("module {:?} not found in program", config2)); - if let ast::Stmt::Unification(unification) = &config1.body[0].node { - let schema = &unification.value.node; - if let ast::Expr::Config(config) = &schema.config.node { - assert_eq!(config.items.len(), 1); - } else { - panic!( - "test failed, expect config expression, got {:?}", - schema.config - ) - } - } else { - panic!( - "test failed, expect unification statement, got {:?}", - config1.body[0] - ) - } - - if let ast::Stmt::Unification(unification) = &config2.body[0].node { - let schema = &unification.value.node; - if let ast::Expr::Config(config) = &schema.config.node { - assert_eq!(config.items.len(), 1); - } else { - panic!( - "test failed, expect config expression, got {:?}", - schema.config - ) - } - } else { - panic!( - "test failed, expect unification statement, got {:?}", - config2.body[0] - ) - } -} - -#[test] -fn test_list_type_validation() { - let code = r#" - schema Resource: - kind: str - apiGroup: str - metadata: any - spec: any - - resource = Resource{ - kind = "Pod" - apiGroup = "core" - metadata = { - name = "test" - } - } - - resource2 = Resource{ - kind = "Pod" - apiGroup = "core" - metadata = { - name = "test" - } - } - - otherResource = { - name = "test" - } - - resourceList: [Resource] = [resource, resource2, otherResource] - "#; - - let result = parse_file_force_errors("test_list_type_validation.k", Some(code.to_string())); - assert!( - result.is_err(), - "Expected an evaluation error, but the code passed." - ); -} diff --git a/kclvm/sema/src/resolver/calculation.rs b/kclvm/sema/src/resolver/calculation.rs deleted file mode 100644 index fff27b38b..000000000 --- a/kclvm/sema/src/resolver/calculation.rs +++ /dev/null @@ -1,333 +0,0 @@ -use std::sync::Arc; - -use crate::resolver::Resolver; -use crate::ty::{ - has_any_type, is_upper_bound, sup, Type, TypeInferMethods, TypeKind, TypeRef, ZERO_LIT_TYPES, -}; -use kclvm_ast::ast; -use kclvm_error::diagnostic::Range; -use kclvm_primitives::{DefaultHashBuilder, IndexMap}; - -const DIV_OR_MOD_ZERO_MSG: &str = "integer division or modulo by zero"; - -impl<'ctx> Resolver<'ctx> { - /// Binary operator calculation table. - /// - /// Arithmetic (int or float; result has type float unless both operands have type int) - /// number + number # addition - /// number - number # subtraction - /// number * number # multiplication - /// number / number # real division (result is always a float) - /// number // number # floored division - /// number % number # remainder of floored division - /// number ^ number # bitwise XOR - /// number << number # bitwise left shift - /// number >> number # bitwise right shift - /// - /// Concatenation - /// string + string - /// list + list - /// - /// Repetition (string/list) - /// int * sequence - /// sequence * int - /// - /// Union - /// int | int - /// list | list - /// dict | dict - /// schema | schema - /// schema | dict - /// - /// Add: number + number, str + str, list + list - /// Sub: number - number - /// Mul: number * number, int * list, list * int, int * str, str * int - /// Div: number / number - /// FloorDiv: number // number - /// Mod: number % number - /// Pow: number ** number - /// LShift: int >> int - /// RShift: int << int - /// BitOr: int | int, list | list, dict | dict, schema | schema, schema | dict - /// BitXOr: int ^ int - /// BitAdd int & int - /// - /// And: any_type and any_type -> bool - /// Or: any_type1 or any_type1 -> sup([any_type1, any_type2]) - pub fn binary( - &mut self, - left: TypeRef, - right: TypeRef, - op: &ast::BinOp, - range: Range, - ) -> TypeRef { - let t1 = self - .ctx - .ty_ctx - .literal_union_type_to_variable_type(left.clone()); - let t2 = self - .ctx - .ty_ctx - .literal_union_type_to_variable_type(right.clone()); - if has_any_type(&[t1.clone(), t2.clone()]) { - return self.any_ty(); - } - let number_binary = |left: &TypeRef, right: &TypeRef| { - if left.is_float() || right.is_float() { - Arc::new(Type::FLOAT) - } else { - Arc::new(Type::INT) - } - }; - let (result, return_ty) = match op { - ast::BinOp::Add => { - if t1.is_number() && t2.is_number() { - (true, number_binary(&t1, &t2)) - } else if t1.is_str() && t2.is_str() { - (true, self.str_ty()) - } else if t1.is_list() && t2.is_list() { - ( - true, - Type::list_ref(sup(&[t1.list_item_ty(), t2.list_item_ty()])), - ) - } else { - (false, self.any_ty()) - } - } - ast::BinOp::Sub | ast::BinOp::Pow => { - if t1.is_number() && t2.is_number() { - (true, number_binary(&t1, &t2)) - } else { - (false, self.any_ty()) - } - } - ast::BinOp::Mul => { - if t1.is_number() && t2.is_number() { - (true, number_binary(&t1, &t2)) - } else if t1.is_int() - && self - .ctx - .ty_ctx - .is_mul_val_type_or_mul_val_union_type(t2.clone()) - { - (true, t2) - } else if self - .ctx - .ty_ctx - .is_mul_val_type_or_mul_val_union_type(t1.clone()) - && t2.is_int() - { - (true, t1) - } else { - (false, self.any_ty()) - } - } - ast::BinOp::Div | ast::BinOp::FloorDiv => { - if t1.is_number() && t2.is_number() { - if ZERO_LIT_TYPES.contains(&t2) { - self.handler - .add_type_error(DIV_OR_MOD_ZERO_MSG, range.clone()); - } - (true, number_binary(&t1, &t2)) - } else { - (false, self.any_ty()) - } - } - ast::BinOp::Mod => { - if t1.is_number() && t2.is_number() { - if ZERO_LIT_TYPES.contains(&t2) { - self.handler - .add_type_error(DIV_OR_MOD_ZERO_MSG, range.clone()); - } - (true, self.int_ty()) - } else { - (false, self.any_ty()) - } - } - ast::BinOp::LShift | ast::BinOp::RShift | ast::BinOp::BitXor | ast::BinOp::BitAnd => { - if t1.is_int() && t2.is_int() { - (true, self.int_ty()) - } else { - (false, self.any_ty()) - } - } - ast::BinOp::BitOr => { - if t1.is_int() && t2.is_int() { - (true, self.int_ty()) - } else if t1.is_none() { - (true, t2) - } else if t2.is_none() { - (true, t1) - } else if t1.is_list() && t2.is_list() { - ( - true, - Type::list_ref(sup(&[t1.list_item_ty(), t2.list_item_ty()])), - ) - } else if let (TypeKind::Dict(t1_dict_ty), TypeKind::Dict(t2_dict_ty)) = - (&t1.kind, &t2.kind) - { - let mut attrs = IndexMap::with_hasher(DefaultHashBuilder::default()); - for (k, v) in &t1_dict_ty.attrs { - attrs.insert(k.to_string(), v.clone()); - } - for (k, v) in &t2_dict_ty.attrs { - attrs.insert(k.to_string(), v.clone()); - } - ( - true, - Arc::new(Type::dict_with_attrs( - sup(&[t1_dict_ty.key_ty.clone(), t2_dict_ty.key_ty.clone()]), - sup(&[t1_dict_ty.val_ty.clone(), t2_dict_ty.val_ty.clone()]), - attrs, - )), - ) - } else if t1.is_schema() && (t2.is_schema() || t2.is_dict()) { - (true, t1) - } else { - (false, self.any_ty()) - } - } - ast::BinOp::And => (true, self.bool_ty()), - ast::BinOp::Or => (true, sup(&[t1, t2])), - ast::BinOp::As => { - if !is_upper_bound( - self.ctx.ty_ctx.infer_to_variable_type(t1.clone()), - t2.clone(), - ) { - self.handler.add_type_error( - &format!( - "Conversion of type '{}' to type '{}' may be a mistake because neither type sufficiently overlaps with the other", - t1.full_ty_str(), - t2.full_ty_str() - ), - range.clone(), - ); - } - (true, t2) - } - }; - - if !result { - self.handler.add_type_error( - &format!( - "unsupported operand type(s) for {}: '{}' and '{}'", - op.symbol(), - left.ty_str(), - right.ty_str() - ), - range, - ); - } - return_ty - } - - /// Unary operator calculation table - /// - /// + number unary positive (int, float) - /// - number unary negation (int, float) - /// ~ number unary bitwise inversion (int) - /// not x logical negation (any type) - pub fn unary(&mut self, ty: TypeRef, op: &ast::UnaryOp, range: Range) -> TypeRef { - if has_any_type(&[ty.clone()]) { - return self.any_ty(); - } - let var_ty = self - .ctx - .ty_ctx - .literal_union_type_to_variable_type(ty.clone()); - let result = match op { - ast::UnaryOp::UAdd | ast::UnaryOp::USub => var_ty.is_number(), - ast::UnaryOp::Invert => var_ty.is_int() || var_ty.is_bool(), - ast::UnaryOp::Not => true, - }; - if result { - var_ty - } else { - self.handler.add_type_error( - &format!( - "bad operand type for unary {}: '{}'", - op.symbol(), - ty.ty_str(), - ), - range, - ); - self.any_ty() - } - } - - /// Compare operator calculation table - /// - /// int # mathematical 1 < 2 - /// float # as defined by IEEE 754 1.0 < 2.0 - /// list/config/schema # lexicographical [1] == [2] - /// iterable # 1 in [1, 2, 3], "s" in "ss", "key" in Schema - /// relation # a is True, b is Undefined - pub fn compare( - &mut self, - left: TypeRef, - right: TypeRef, - op: &ast::CmpOp, - range: Range, - ) -> TypeRef { - let t1 = self.ctx.ty_ctx.literal_union_type_to_variable_type(left); - let t2 = self.ctx.ty_ctx.literal_union_type_to_variable_type(right); - if has_any_type(&[t1.clone(), t2.clone()]) { - return self.any_ty(); - } - if self - .ctx - .ty_ctx - .is_number_bool_type_or_number_bool_union_type(t1.clone()) - && self - .ctx - .ty_ctx - .is_number_bool_type_or_number_bool_union_type(t2.clone()) - && !matches!(op, ast::CmpOp::In | ast::CmpOp::NotIn) - { - return self.bool_ty(); - } - if self - .ctx - .ty_ctx - .is_primitive_type_or_primitive_union_type(t1.clone()) - && self - .ctx - .ty_ctx - .is_primitive_type_or_primitive_union_type(t2.clone()) - && matches!(op, ast::CmpOp::Eq | ast::CmpOp::NotEq) - { - return self.bool_ty(); - } - if matches!(op, ast::CmpOp::Eq) && t1.is_list() && t2.is_list() { - return self.bool_ty(); - } - if matches!(op, ast::CmpOp::Eq) && t1.is_dict_or_schema() && t2.is_dict_or_schema() { - return self.bool_ty(); - } - if matches!(op, ast::CmpOp::In | ast::CmpOp::NotIn) && t2.is_iterable() { - return self.bool_ty(); - } - if (t1.is_none() || t2.is_none()) - && matches!( - op, - ast::CmpOp::Eq - | ast::CmpOp::NotEq - | ast::CmpOp::Is - | ast::CmpOp::IsNot - | ast::CmpOp::Not - ) - { - return self.bool_ty(); - } - self.handler.add_type_error( - &format!( - "unsupported operand type(s) for {}: '{}' and '{}'", - op.symbol(), - t1.ty_str(), - t2.ty_str(), - ), - range, - ); - self.any_ty() - } -} diff --git a/kclvm/sema/src/resolver/config.rs b/kclvm/sema/src/resolver/config.rs deleted file mode 100644 index a7fc4a688..000000000 --- a/kclvm/sema/src/resolver/config.rs +++ /dev/null @@ -1,880 +0,0 @@ -use std::{collections::HashSet, sync::Arc}; - -use super::{ - scope::{ScopeKind, ScopeObject, ScopeObjectKind}, - Resolver, -}; -use crate::ty::{sup, DictType, TypeInferMethods, TypeRef}; -use crate::ty::{Attr, SchemaType}; -use crate::ty::{Type, TypeKind}; -use kclvm_ast::ast; -use kclvm_ast::pos::GetPos; -use kclvm_error::{diagnostic::Range, ErrorKind, Message, Position, Style}; -use kclvm_primitives::IndexMap; - -/// Config Expr type check state. -/// -/// e.g. -/// ```no_check -/// schema Person: -/// name: str -/// -/// person = Person { -/// name: 1 # Type error, expect str, got int(1) -/// } -/// ``` -pub enum SwitchConfigContextState { - KeepConfigUnchanged = 0, - SwitchConfigOnce = 1, -} - -impl<'ctx> Resolver<'_> { - #[inline] - pub(crate) fn new_config_expr_context_item( - &mut self, - name: &str, - ty: TypeRef, - start: Position, - end: Position, - ) -> ScopeObject { - ScopeObject { - name: name.to_string(), - start, - end, - ty, - kind: ScopeObjectKind::Attribute, - doc: None, - } - } - - /// Finds the items needed to switch the context by name 'key_name' - /// - /// At present, only when the top item of the stack is 'KCLSchemaTypeObject' or 'KCLDictTypeObject', - /// it will return the next item (the attribute named 'key_name' in 'KCLSchemaTypeObject' - /// or the value of 'key_name' in 'KCLDictTypeObject') needed to be pushed. - /// If the top item of the stack is not 'KCLSchemaTypeObject' or 'KCLDictTypeObject', - /// it will return 'None'. - /// - /// Args: - /// key_name: The name of the item needed to be pushed onto the 'config_expr_context' stack - /// - /// Returns: - /// The item needed to be pushed onto the 'config_expr_context' stack - pub(crate) fn find_schema_attr_obj_from_schema_expr_stack( - &mut self, - key_name: &str, - ) -> Option { - if key_name.is_empty() { - None - } else { - match self.ctx.config_expr_context.last() { - Some(obj) => { - let obj = obj.clone(); - match obj { - Some(obj) => match &obj.ty.kind { - TypeKind::List(elem_type) => Some(self.new_config_expr_context_item( - key_name, - elem_type.clone(), - obj.start.clone(), - obj.end.clone(), - )), - TypeKind::Dict(DictType { - key_ty: _, val_ty, .. - }) => Some(self.new_config_expr_context_item( - key_name, - val_ty.clone(), - obj.start.clone(), - obj.end.clone(), - )), - TypeKind::Schema(schema_ty) => { - match schema_ty.get_obj_of_attr(key_name) { - Some(attr_ty_obj) => { - let ty = match &attr_ty_obj.ty.kind { - TypeKind::Schema(schema_ty) => { - let runtime_type = - kclvm_runtime::schema_runtime_type( - &schema_ty.name, - &schema_ty.pkgpath, - ); - if let Some(runtime_scehma_ty) = - self.ctx.schema_mapping.get(&runtime_type) - { - Arc::new(Type::schema( - runtime_scehma_ty.borrow().clone(), - )) - } else { - attr_ty_obj.ty.clone() - } - } - _ => attr_ty_obj.ty.clone(), - }; - Some(self.new_config_expr_context_item( - key_name, - ty, - attr_ty_obj.range.0.clone(), - attr_ty_obj.range.1.clone(), - )) - } - None => match &schema_ty.index_signature { - Some(index_signature) => { - Some(self.new_config_expr_context_item( - key_name, - index_signature.val_ty.clone(), - obj.start.clone(), - obj.end.clone(), - )) - } - None => None, - }, - } - } - TypeKind::Union(types) => { - let mut possible_types = vec![]; - for ty in types { - match &ty.kind { - TypeKind::Schema(schema_ty) => { - match schema_ty.get_obj_of_attr(key_name) { - Some(attr_ty_obj) => { - possible_types.push(attr_ty_obj.ty.clone()); - } - None => match &schema_ty.index_signature { - Some(index_signature) => { - possible_types - .push(index_signature.val_ty.clone()); - } - None => continue, - }, - } - } - TypeKind::Dict(DictType { val_ty, .. }) => { - possible_types.push(val_ty.clone()); - } - _ => continue, - } - } - - Some(self.new_config_expr_context_item( - key_name, - crate::ty::sup(&possible_types).into(), - obj.start.clone(), - obj.end.clone(), - )) - } - _ => None, - }, - None => None, - } - } - None => None, - } - } - } - - /// Switch the context in 'config_expr_context' stack by AST nodes 'Identifier', 'Subscript' or 'Literal' - /// - /// Args: - /// key: AST nodes 'Identifier', 'Subscript' or 'Literal' - /// - /// Returns: - /// push stack times - pub(crate) fn switch_config_expr_context_by_key( - &mut self, - key: &'ctx Option>, - ) -> usize { - match key { - Some(key) => { - let names: Vec = match &key.node { - ast::Expr::Identifier(identifier) => identifier.get_names(), - ast::Expr::Subscript(subscript) => { - if let ast::Expr::Identifier(identifier) = &subscript.value.node { - if let Some(index) = &subscript.index { - if matches!(index.node, ast::Expr::NumberLit(_)) { - identifier.get_names() - } else { - return SwitchConfigContextState::KeepConfigUnchanged as usize; - } - } else { - return SwitchConfigContextState::KeepConfigUnchanged as usize; - } - } else { - return SwitchConfigContextState::KeepConfigUnchanged as usize; - } - } - ast::Expr::StringLit(string_lit) => vec![string_lit.value.clone()], - // There may be a valid configuration key for joined string and missing expressions here, - // and we will restore it to a null value to avoid unfriendly error messages. - ast::Expr::JoinedString(_) | ast::Expr::Missing(_) => vec!["".to_string()], - _ => return SwitchConfigContextState::KeepConfigUnchanged as usize, - }; - self.switch_config_expr_context_by_names(&names) - } - // Double star expression - None => SwitchConfigContextState::KeepConfigUnchanged as usize, - } - } - - /// Switch the context in 'config_expr_context' stack by the list index `[]` - /// - /// Returns: - /// push stack times - #[inline] - pub(crate) fn switch_list_expr_context(&mut self) -> usize { - self.switch_config_expr_context_by_names(&["[]".to_string()]) - } - - /// Switch the context in 'config_expr_context' stack by name - /// - /// find the next item that needs to be pushed into the stack, - /// according to name and the top context of the stack, and push the item into the stack. - /// - /// Args: - /// name: the name of item to be pushed - /// - /// Returns: - /// push stack times - pub(crate) fn switch_config_expr_context_by_name(&mut self, name: &str) -> usize { - let ctx_obj = self.find_schema_attr_obj_from_schema_expr_stack(name); - self.switch_config_expr_context(ctx_obj) as usize - } - - /// Push method for the 'config_expr_context' stack - /// - /// Args: - /// config_ctx_obj: the item needed to be pushed - /// - /// Returns: - /// push stack times - pub(crate) fn switch_config_expr_context( - &mut self, - config_ctx_obj: Option, - ) -> SwitchConfigContextState { - self.ctx.config_expr_context.push(config_ctx_obj); - SwitchConfigContextState::SwitchConfigOnce - } - - /// Pop method for the 'config_expr_context' stack - /// - /// Returns: - /// the item popped from stack. - #[inline] - pub(crate) fn restore_config_expr_context(&mut self) -> Option { - match self.ctx.config_expr_context.pop() { - Some(obj) => obj, - None => None, - } - } - - /// Pop all method for the 'config_expr_context' stack - /// - /// Args: - /// stack_depth: 'stack_depth' is the number of stacks that need to be popped - /// clear_all: 'clear_all' is True to clear all the items of the stack - /// - pub(crate) fn clear_config_expr_context(&mut self, stack_depth: usize, clear_all: bool) { - if clear_all { - self.ctx.config_expr_context.clear() - } else { - for _ in 0..stack_depth { - self.restore_config_expr_context(); - } - } - } - - /// Switch the context in 'config_expr_context' stack by names - /// - /// Traverse all name in 'names', find the next item that needs to be pushed into the stack, - /// according to name and the top context of the stack, and push the item into the stack. - /// - /// Args: - /// names: A list of string containing the names of items to be pushed - /// - /// Returns: - /// push stack times - pub(crate) fn switch_config_expr_context_by_names(&mut self, names: &[String]) -> usize { - let mut stack_depth = 0; - for name in names { - stack_depth += self.switch_config_expr_context_by_name(name); - } - stack_depth - } - - /// Check whether the key of config expr meets the constraints of schema attributes such as final, defined. - /// - /// Args: - /// name: the name of key - /// key: the ast node of key - /// check_rules: the constraints, such as 'check_defined' - pub(crate) fn check_config_expr_by_key_name( - &mut self, - name: &str, - key: &'ctx ast::NodeRef, - ) { - if !name.is_empty() { - if let Some(Some(obj)) = self.ctx.config_expr_context.last() { - let ty = obj.ty.clone(); - self.must_check_config_attr(name, &ty, &key.get_span_pos(), None); - } - } - } - - fn check_config_value_recursively(&mut self, value_ty: &TypeRef, value_span: &Range) { - match &value_ty.kind { - TypeKind::Dict(DictType { - key_ty: _, - val_ty: _, - attrs, - }) => { - for (key, attr) in attrs { - self.check_attr_recursively(&key, &attr.ty, &attr.range, value_span); - } - } - TypeKind::Schema(schema_ty) => { - for (key, attr) in &schema_ty.attrs { - self.check_attr_recursively(&key, &attr.ty, &attr.range, value_span); - } - } - _ => {} - } - } - - fn check_attr_recursively( - &mut self, - key: &str, - attr_ty: &TypeRef, - attr_span: &Range, - value_span: &Range, - ) { - if !key.is_empty() { - if let Some(Some(obj)) = self.ctx.config_expr_context.last() { - let ty = obj.ty.clone(); - self.must_check_config_attr(key, &ty, value_span, Some(attr_span)); - } - let stack_depth = self.switch_config_expr_context_by_name(key); - if let Some(Some(obj)) = self.ctx.config_expr_context.last() { - let ty = obj.ty.clone(); - self.attr_must_assignable_to( - attr_ty.clone(), - ty, - value_span.clone(), - Some(obj.get_span_pos()), - Some(attr_span.clone()), - ); - } - self.check_config_value_recursively(attr_ty, value_span); - self.clear_config_expr_context(stack_depth, false); - } - } - - /// Check the key-value in 'ConfigExpr', such as check_defined and check_type - /// - /// Notes: - /// If the top item of the 'config_expr_context' stack is 'None', the check will be skipped. - /// - /// Args: - /// key: the key of 'ConfigExpr'. - /// value: the value of 'ConfigExpr'. - /// check_rules: Some checks on the key individually,such as check_defined. - pub(crate) fn check_config_entry( - &mut self, - key: &'ctx Option>, - value: &'ctx ast::NodeRef, - ) -> Option { - if let Some(key) = key { - if let Some(Some(_)) = self.ctx.config_expr_context.last() { - let names: Vec = match &key.node { - ast::Expr::Identifier(identifier) => identifier.get_names(), - ast::Expr::Subscript(subscript) => { - if let ast::Expr::Identifier(identifier) = &subscript.value.node { - if let Some(index) = &subscript.index { - if matches!(index.node, ast::Expr::NumberLit(_)) { - identifier.get_names() - } else if let ast::Expr::Unary(unary_expr) = &index.node { - // Negative index constant - if matches!(unary_expr.operand.node, ast::Expr::NumberLit(_)) { - identifier.get_names() - } else { - return None; - } - } else { - return None; - } - } else { - return None; - } - } else { - return None; - } - } - ast::Expr::StringLit(string_lit) => vec![string_lit.value.clone()], - _ => return None, - }; - let mut stack_depth = 0; - for name in &names { - self.check_config_expr_by_key_name(name, key); - stack_depth += self.switch_config_expr_context_by_name(name); - } - let mut val_ty = self.expr(value); - - let return_ty = Some(val_ty.clone()); - - for _ in 0..names.len() - 1 { - val_ty = Type::dict_ref(self.str_ty(), val_ty); - } - if let Some(Some(obj_last)) = self.ctx.config_expr_context.last() { - let ty = obj_last.ty.clone(); - self.must_assignable_to( - val_ty, - ty, - key.get_span_pos(), - Some(obj_last.get_span_pos()), - ); - } - self.clear_config_expr_context(stack_depth, false); - return return_ty; - } - } else { - // For double star expression, we can recursively check nested configuration properties at compile time. - let value_ty = self.expr(value); - self.check_config_value_recursively(&value_ty, &value.get_span_pos()); - return Some(value_ty); - } - None - } - - #[inline] - pub(crate) fn get_config_attr_err_suggestion_from_schema( - &self, - attr: &str, - schema_ty: &SchemaType, - ) -> (Vec, String) { - self.get_config_attr_err_suggestion(attr, schema_ty.attrs.keys()) - } - - pub(crate) fn get_config_attr_err_suggestion( - &self, - attr: &str, - keys: I, - ) -> (Vec, String) - where - T: AsRef, - I: IntoIterator, - { - let mut suggestion = String::new(); - // Calculate the closest miss attributes. - let suggs = suggestions::provide_suggestions(attr, keys); - if suggs.len() > 0 { - suggestion = format!(", did you mean '{:?}'?", suggs); - } - (suggs, suggestion) - } - - /// Check config attr has been defined. - pub(crate) fn must_check_config_attr( - &mut self, - attr: &str, - ty: &TypeRef, - range: &Range, - attr_range: Option<&Range>, - ) { - if let TypeKind::Schema(schema_ty) = &ty.kind { - self.check_config_attr(attr, schema_ty, range, attr_range); - } else if let TypeKind::Union(types) = &ty.kind { - let mut schema_names = vec![]; - let mut total_suggs = vec![]; - for ty in types { - match &ty.kind { - TypeKind::Schema(schema_ty) => { - if schema_ty.get_obj_of_attr(attr).is_none() - && !schema_ty.is_mixin - && schema_ty.index_signature.is_none() - { - let mut suggs = - suggestions::provide_suggestions(attr, schema_ty.attrs.keys()); - total_suggs.append(&mut suggs); - schema_names.push(schema_ty.name.clone()); - } else { - // If there is a schema attribute that meets the condition, the type check passes - return; - } - } - TypeKind::Dict(..) => return, - _ => continue, - } - } - if !schema_names.is_empty() { - let mut msgs = vec![Message { - range: range.clone(), - style: Style::LineAndColumn, - message: format!( - "Cannot add member '{}' to '{}'{}", - attr, - if schema_names.len() > 1 { - format!("schemas {:?}", schema_names) - } else { - format!("schema {}", schema_names[0]) - }, - if total_suggs.is_empty() { - "".to_string() - } else { - format!(", did you mean '{:?}'?", total_suggs) - }, - ), - note: None, - suggested_replacement: Some(total_suggs), - }]; - if let Some(attr_range) = attr_range { - msgs.push(Message { - range: attr_range.clone(), - style: Style::LineAndColumn, - message: "config attribute is defined here".to_string(), - note: None, - suggested_replacement: None, - }); - } - self.handler.add_error(ErrorKind::CompileError, &msgs); - } - } - } - - /// Check config attr has been defined. - pub(crate) fn check_config_attr( - &mut self, - attr: &str, - schema_ty: &SchemaType, - range: &Range, - attr_range: Option<&Range>, - ) { - let runtime_type = kclvm_runtime::schema_runtime_type(&schema_ty.name, &schema_ty.pkgpath); - match self.ctx.schema_mapping.get(&runtime_type) { - Some(schema_mapping_ty) => { - let schema_ty = schema_mapping_ty.clone(); - let schema_ty_ref = schema_ty.borrow(); - self.check_config_attr_without_schema_mapping( - attr, - &schema_ty_ref, - range, - attr_range, - ); - } - None => { - self.check_config_attr_without_schema_mapping(attr, schema_ty, range, attr_range); - } - }; - } - - fn check_config_attr_without_schema_mapping( - &mut self, - attr: &str, - schema_ty: &SchemaType, - range: &Range, - attr_range: Option<&Range>, - ) { - if schema_ty.get_obj_of_attr(attr).is_none() - && !schema_ty.is_mixin - && schema_ty.index_signature.is_none() - { - let (suggs, msg) = self.get_config_attr_err_suggestion_from_schema(attr, schema_ty); - self.add_config_attr_error(attr, schema_ty, range, attr_range, suggs, msg); - } - if let Some(index_signature) = &schema_ty.index_signature { - // Here we need to check whether the key of the index signature is a string literal type or a string literal union types - if !index_signature.any_other { - match &index_signature.key_ty.kind { - TypeKind::StrLit(name) => { - if name != attr { - let (suggs, msg) = self.get_config_attr_err_suggestion(attr, &[name]); - self.add_config_attr_error( - attr, schema_ty, range, attr_range, suggs, msg, - ); - } - } - TypeKind::Union(types) => { - let mut keys: HashSet = HashSet::default(); - for ty in types { - if let TypeKind::StrLit(name) = &ty.kind { - keys.insert(name.clone()); - } - } - if !keys.contains(attr) { - let (suggs, msg) = self.get_config_attr_err_suggestion(attr, &keys); - self.add_config_attr_error( - attr, schema_ty, range, attr_range, suggs, msg, - ); - } - } - _ => {} - } - } - } - } - - fn add_config_attr_error( - &mut self, - attr: &str, - schema_ty: &SchemaType, - range: &Range, - attr_range: Option<&Range>, - suggs: Vec, - msg: String, - ) { - let mut msgs = vec![Message { - range: range.clone(), - style: Style::LineAndColumn, - message: format!( - "Cannot add member '{}' to schema '{}'{}", - attr, schema_ty.name, msg, - ), - note: None, - suggested_replacement: Some(suggs), - }]; - if let Some(attr_range) = attr_range { - msgs.push(Message { - range: attr_range.clone(), - style: Style::LineAndColumn, - message: "config attribute is defined here".to_string(), - note: None, - suggested_replacement: None, - }); - } - self.handler.add_error(ErrorKind::CompileError, &msgs); - } - - /// Schema load atr - pub(crate) fn schema_load_attr( - &mut self, - schema_ty: &SchemaType, - attr: &str, - ) -> (bool, TypeRef) { - let runtime_type = kclvm_runtime::schema_runtime_type(&schema_ty.name, &schema_ty.pkgpath); - match self.ctx.schema_mapping.get(&runtime_type) { - Some(schema_mapping_ty) => { - let schema_ty = schema_mapping_ty.borrow(); - match schema_ty.get_type_of_attr(attr) { - Some(ty) => (true, ty), - None => { - if schema_ty.is_mixin || schema_ty.index_signature.is_some() { - (true, self.any_ty()) - } else { - (false, self.any_ty()) - } - } - } - } - None => match schema_ty.get_type_of_attr(attr) { - Some(ty) => (true, ty), - None => { - if schema_ty.is_mixin || schema_ty.index_signature.is_some() { - (true, self.any_ty()) - } else { - (false, self.any_ty()) - } - } - }, - } - } - - pub(crate) fn walk_config_entries( - &mut self, - entries: &'ctx [ast::NodeRef], - ) -> TypeRef { - let (start, end) = match entries.len() { - 0 => (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()), - 1 => entries[0].get_span_pos(), - _ => ( - entries.first().unwrap().get_pos(), - entries.last().unwrap().get_end_pos(), - ), - }; - self.enter_scope(start, end, ScopeKind::Config); - let mut key_types: Vec = vec![]; - let mut val_types: Vec = vec![]; - let mut attrs: IndexMap = Default::default(); - for item in entries { - let key = &item.node.key; - let value = &item.node.value; - let op = &item.node.operation; - let mut stack_depth: usize = 0; - let value_ty = self.check_config_entry(key, value); - stack_depth += self.switch_config_expr_context_by_key(key); - let val_ty = match key { - Some(key) => match &key.node { - ast::Expr::Identifier(identifier) => { - let mut val_ty = value_ty.unwrap_or_else(|| self.expr(value)); - - for _ in 0..identifier.names.len() - 1 { - val_ty = Type::dict_ref(self.str_ty(), val_ty.clone()); - } - let key_ty = if identifier.names.len() == 1 { - let name = &identifier.names[0].node; - let key_ty = if self.ctx.local_vars.contains(name) { - // set key context expected schema as None - self.ctx.config_expr_context.push(None); - let key_ty = self.expr(key); - self.ctx.config_expr_context.pop(); - key_ty - } else { - Arc::new(Type::str_lit(name)) - }; - self.check_attr_ty(&key_ty, key.get_span_pos()); - let ty = if let Some(attr) = attrs.get(name) { - sup(&[attr.ty.clone(), val_ty.clone()]) - } else { - val_ty.clone() - }; - attrs.insert( - name.to_string(), - Attr { - ty: self.ctx.ty_ctx.infer_to_variable_type(ty.clone()), - range: key.get_span_pos(), - }, - ); - self.insert_object( - name, - ScopeObject { - name: name.to_string(), - start: key.get_pos(), - end: key.get_end_pos(), - ty, - kind: ScopeObjectKind::Attribute, - doc: None, - }, - ); - key_ty - } else { - self.str_ty() - }; - key_types.push(key_ty); - val_types.push(val_ty.clone()); - val_ty - } - ast::Expr::Subscript(subscript) if subscript.has_name_and_constant_index() => { - let val_ty = value_ty.unwrap_or_else(|| self.expr(value)); - key_types.push(self.str_ty()); - if matches!(op, ast::ConfigEntryOperation::Insert) { - val_types.push(val_ty.clone()); - } else { - val_types.push(Type::list_ref(val_ty.clone())); - } - val_ty - } - _ => { - // set key context expected schema as None - self.ctx.config_expr_context.push(None); - let key_ty = self.expr(key); - self.ctx.config_expr_context.pop(); - let val_ty = value_ty.unwrap_or_else(|| self.expr(value)); - self.check_attr_ty(&key_ty, key.get_span_pos()); - if let ast::Expr::StringLit(string_lit) = &key.node { - let ty = if let Some(attr) = attrs.get(&string_lit.value) { - sup(&[attr.ty.clone(), val_ty.clone()]) - } else { - val_ty.clone() - }; - attrs.insert( - string_lit.value.clone(), - Attr { - ty: self.ctx.ty_ctx.infer_to_variable_type(ty.clone()), - range: key.get_span_pos(), - }, - ); - self.insert_object( - &string_lit.value, - ScopeObject { - name: string_lit.value.clone(), - start: key.get_pos(), - end: key.get_end_pos(), - ty, - kind: ScopeObjectKind::Attribute, - doc: None, - }, - ); - } - key_types.push(key_ty); - val_types.push(val_ty.clone()); - val_ty - } - }, - None => { - let val_ty = value_ty.unwrap_or_else(|| self.expr(value)); - match &val_ty.kind { - TypeKind::None | TypeKind::Any => { - val_types.push(val_ty.clone()); - } - TypeKind::Dict(DictType { - key_ty, - val_ty, - attrs: merged_attrs, - }) => { - key_types.push(key_ty.clone()); - val_types.push(val_ty.clone()); - for (key, value) in merged_attrs { - attrs.insert(key.to_string(), value.clone()); - } - } - TypeKind::Schema(schema_ty) => { - key_types.push(schema_ty.key_ty()); - val_types.push(schema_ty.val_ty()); - for (key, attr) in &schema_ty.attrs { - attrs.insert( - key.to_string(), - Attr { - ty: attr.ty.clone(), - range: attr.range.clone(), - }, - ); - } - } - TypeKind::Union(types) - if self - .ctx - .ty_ctx - .is_config_type_or_config_union_type(val_ty.clone()) => - { - key_types.push(sup(&types - .iter() - .map(|ty| ty.config_key_ty()) - .collect::>())); - val_types.push(sup(&types - .iter() - .map(|ty| ty.config_val_ty()) - .collect::>())); - } - _ => { - self.handler.add_compile_error( - &format!( - "only dict and schema can be used ** unpack, got '{}'", - val_ty.ty_str() - ), - value.get_span_pos(), - ); - } - } - val_ty - } - }; - if matches!(op, ast::ConfigEntryOperation::Insert) - && !val_ty.is_any() - && !val_ty.is_list() - { - self.handler.add_error( - ErrorKind::IllegalAttributeError, - &[Message { - range: value.get_span_pos(), - style: Style::LineAndColumn, - message: format!( - "only list type can in inserted, got '{}'", - val_ty.ty_str() - ), - note: None, - suggested_replacement: None, - }], - ); - } - self.clear_config_expr_context(stack_depth, false); - } - self.leave_scope(); - let key_ty = sup(&key_types); - let val_ty = sup(&val_types); - Type::dict_ref_with_attrs(key_ty, val_ty, attrs) - } -} diff --git a/kclvm/sema/src/resolver/mod.rs b/kclvm/sema/src/resolver/mod.rs deleted file mode 100644 index d64cb5701..000000000 --- a/kclvm/sema/src/resolver/mod.rs +++ /dev/null @@ -1,253 +0,0 @@ -mod arg; -mod attr; -mod calculation; -mod config; -pub mod doc; -mod format; -pub mod global; -mod import; -mod r#loop; -mod node; -mod para; -mod schema; -pub mod scope; -pub(crate) mod ty; -mod ty_alias; -mod ty_erasure; -mod var; - -#[cfg(test)] -mod tests; - -use kclvm_error::diagnostic::Range; -use kclvm_primitives::{IndexMap, IndexSet}; -use std::sync::Arc; -use std::{cell::RefCell, rc::Rc}; - -use crate::lint::{CombinedLintPass, Linter}; -use crate::pre_process::pre_process_program; -use crate::resolver::scope::ScopeObject; -use crate::resolver::ty_alias::type_alias_pass; -use crate::resolver::ty_erasure::type_func_erasure_pass; -use crate::ty::TypeContext; -use crate::{resolver::scope::Scope, ty::SchemaType}; -use kclvm_ast::ast::Program; -use kclvm_error::*; - -use self::scope::{builtin_scope, KCLScopeCache, NodeTyMap, ProgramScope}; - -/// Resolver is responsible for program semantic checking, mainly -/// including type checking and contract model checking. -pub struct Resolver<'ctx> { - pub program: &'ctx Program, - pub scope_map: IndexMap>>, - pub scope: Rc>, - pub scope_level: usize, - pub node_ty_map: Rc>, - pub builtin_scope: Rc>, - pub ctx: Context, - pub options: Options, - pub handler: Handler, - pub linter: Linter, -} - -impl<'ctx> Resolver<'ctx> { - pub fn new(program: &'ctx Program, options: Options) -> Self { - let builtin_scope = Rc::new(RefCell::new(builtin_scope())); - let scope = Rc::clone(&builtin_scope); - Resolver { - program, - scope_map: IndexMap::default(), - builtin_scope, - scope, - scope_level: 0, - node_ty_map: Rc::new(RefCell::new(IndexMap::default())), - ctx: Context::default(), - options, - handler: Handler::default(), - linter: Linter::::new(), - } - } - - /// The check main function. - pub(crate) fn check(&mut self, pkgpath: &str) { - self.check_import(pkgpath); - self.init_global_types(); - match self - .program - .pkgs - .get(pkgpath) - .or(self.program.pkgs_not_imported.get(pkgpath)) - { - Some(modules) => { - for module in modules { - let module = self - .program - .get_module(module) - .expect("Failed to acquire module lock") - .expect(&format!("module {:?} not found in program", module)); - self.ctx.filename = module.filename.to_string(); - if let scope::ScopeKind::Package(files) = &mut self.scope.borrow_mut().kind { - files.insert(module.filename.to_string()); - } - for stmt in &module.body { - self.stmt(&stmt); - } - if self.options.lint_check { - self.lint_check_module(&module); - } - } - } - None => {} - } - } - - pub(crate) fn check_and_lint_all_pkgs(&mut self) -> ProgramScope { - self.check(kclvm_ast::MAIN_PKG); - self.lint_check_scope_map(); - let mut handler = self.handler.clone(); - for diag in &self.linter.handler.diagnostics { - handler.diagnostics.insert(diag.clone()); - } - - for pkg in self.program.pkgs_not_imported.keys() { - if !self.scope_map.contains_key(pkg) { - self.check(pkg); - } - } - - let mut scope_map = self.scope_map.clone(); - for invalid_pkg_scope in &self.ctx.invalid_pkg_scope { - scope_map.swap_remove(invalid_pkg_scope); - } - let scope = ProgramScope { - scope_map, - import_names: self.ctx.import_names.clone(), - node_ty_map: self.node_ty_map.clone(), - handler, - schema_mapping: self.ctx.schema_mapping.clone(), - }; - scope - } -} - -/// Resolve context -#[derive(Debug, Default)] -pub struct Context { - /// What source file are we in. - pub filename: String, - /// What package path are we in. - pub pkgpath: String, - /// What schema are we in. - pub schema: Option>>, - /// Global schemas name and type mapping. - pub schema_mapping: IndexMap>>, - /// For loop local vars. - pub local_vars: Vec, - /// Import pkgpath and name - pub import_names: IndexMap>, - /// Global names at top level of the program. - pub global_names: IndexMap>, - /// Are we resolving the left value. - pub l_value: bool, - /// Are we resolving the statement start position. - pub start_pos: Position, - /// Are we resolving the statement end position. - pub end_pos: Position, - /// Is in lambda expression. - pub in_lambda_expr: Vec, - /// Current schema expr type stack - pub config_expr_context: Vec>, - /// Type context. - pub ty_ctx: TypeContext, - /// Type alias mapping - pub type_alias_mapping: IndexMap>, - /// invalid pkg scope, remove when after resolve - pub invalid_pkg_scope: IndexSet, -} - -/// Resolve options. -/// - lint_check: whether to run lint passes -/// - resolve_val: whether to resolve and print their AST to value for some nodes. -#[derive(Clone, Debug)] -pub struct Options { - pub lint_check: bool, - pub resolve_val: bool, - pub merge_program: bool, - pub type_erasure: bool, -} - -impl Default for Options { - fn default() -> Self { - Self { - lint_check: true, - resolve_val: false, - merge_program: true, - type_erasure: true, - } - } -} - -/// Resolve program with default options. -#[inline] -pub fn resolve_program(program: &mut Program) -> ProgramScope { - resolve_program_with_opts(program, Options::default(), None) -} - -/// Resolve program with options. See [Options] -pub fn resolve_program_with_opts( - program: &mut Program, - opts: Options, - cached_scope: Option, -) -> ProgramScope { - pre_process_program(program, &opts); - let mut resolver = Resolver::new(program, opts.clone()); - resolver.resolve_import(); - if let Some(cached_scope) = cached_scope.as_ref() { - if let Some(mut cached_scope) = cached_scope.try_write() { - cached_scope.invalidate_pkgs.clear(); - cached_scope.update(program); - resolver.scope_map = cached_scope.scope_map.clone(); - resolver.ctx.schema_mapping = cached_scope.schema_mapping.clone(); - cached_scope - .invalidate_pkgs - .insert(kclvm_ast::MAIN_PKG.to_string()); - for pkg in &cached_scope.invalidate_pkgs { - resolver.scope_map.swap_remove(pkg); - } - let mut nodes = vec![]; - for node in cached_scope.node_ty_map.keys() { - if cached_scope.invalidate_pkgs.contains(&node.pkgpath) { - nodes.push(node.clone()); - } - } - for node in nodes { - cached_scope.node_ty_map.swap_remove(&node); - } - resolver.node_ty_map = Rc::new(RefCell::new(cached_scope.node_ty_map.clone())); - } - } - let scope = resolver.check_and_lint_all_pkgs(); - - if let Some(cached_scope) = cached_scope.as_ref() { - if let Some(mut cached_scope) = cached_scope.try_write() { - cached_scope.update(program); - cached_scope.scope_map = scope.scope_map.clone(); - cached_scope.node_ty_map = scope.node_ty_map.borrow().clone(); - cached_scope.scope_map.swap_remove(kclvm_ast::MAIN_PKG); - cached_scope.schema_mapping = resolver.ctx.schema_mapping; - cached_scope - .invalidate_pkgs - .insert(kclvm_ast::MAIN_PKG.to_string()); - cached_scope.invalidate_pkg_modules = None; - } - } - if opts.type_erasure { - let type_alias_mapping = resolver.ctx.type_alias_mapping.clone(); - // Erase all the function type to a named type "function" - type_func_erasure_pass(program); - // Erase types with their type alias - type_alias_pass(program, type_alias_mapping); - } - scope -} diff --git a/kclvm/sema/src/resolver/node.rs b/kclvm/sema/src/resolver/node.rs deleted file mode 100644 index 9af4acae0..000000000 --- a/kclvm/sema/src/resolver/node.rs +++ /dev/null @@ -1,1344 +0,0 @@ -use kclvm_ast::ast; -use kclvm_ast::pos::GetPos; -use kclvm_ast::walker::MutSelfTypedResultWalker; -use kclvm_ast_pretty::{print_ast_node, ASTNode}; -use kclvm_error::*; -use kclvm_primitives::IndexMap; -use std::sync::Arc; - -use crate::info::is_private_field; -use crate::ty::{ - sup, DictType, FunctionType, Parameter, Type, TypeInferMethods, TypeKind, TypeRef, - RESERVED_TYPE_IDENTIFIERS, -}; - -use super::doc::extract_doc_from_body; -use super::format::VALID_FORMAT_SPEC_SET; -use super::scope::{ScopeKind, ScopeObject, ScopeObjectKind}; -use super::ty::ty_str_replace_pkgpath; -use super::Resolver; -/// ResolvedResult denotes the result, when the result is error, -/// put the message string into the diagnostic vector. -pub type ResolvedResult = TypeRef; - -impl<'ctx> MutSelfTypedResultWalker<'ctx> for Resolver<'_> { - type Result = ResolvedResult; - - fn walk_module(&mut self, module: &'ctx ast::Module) -> Self::Result { - self.stmts(&module.body) - } - - fn walk_expr_stmt(&mut self, expr_stmt: &'ctx ast::ExprStmt) -> Self::Result { - let expr_types = self.exprs(&expr_stmt.exprs); - if let Some(last) = expr_types.last() { - let ty = last.clone(); - if expr_types.len() > 1 { - self.handler.add_compile_error( - "expression statement can only have one expression", - expr_stmt.exprs[1].get_span_pos(), - ); - } - ty - } else { - bug!("invalid expr statement exprs"); - } - } - - fn walk_unification_stmt( - &mut self, - unification_stmt: &'ctx ast::UnificationStmt, - ) -> Self::Result { - let names = &unification_stmt.target.node.names; - if names.len() > 1 { - self.handler.add_compile_error( - "unification identifier can not be selected", - unification_stmt.target.get_span_pos(), - ); - } - let (start, end) = unification_stmt.value.get_span_pos(); - if names.is_empty() { - self.handler.add_compile_error( - "missing target in the unification statement", - unification_stmt.value.get_span_pos(), - ); - return self.any_ty(); - } - self.ctx.l_value = true; - let expected_ty = self.walk_identifier_expr(&unification_stmt.target); - self.ctx.l_value = false; - let obj = - self.new_config_expr_context_item(&names[0].node, expected_ty.clone(), start, end); - let init_stack_depth = self.switch_config_expr_context(Some(obj)); - let ty = self.walk_schema_expr(&unification_stmt.value.node); - self.clear_config_expr_context(init_stack_depth as usize, false); - self.must_assignable_to( - ty.clone(), - expected_ty.clone(), - unification_stmt.target.get_span_pos(), - None, - ); - if !ty.is_any() && expected_ty.is_any() { - self.set_infer_type_to_scope(&names[0].node, ty, &names[0]); - } - expected_ty - } - - fn walk_type_alias_stmt(&mut self, type_alias_stmt: &'ctx ast::TypeAliasStmt) -> Self::Result { - let (start, end) = type_alias_stmt.type_name.get_span_pos(); - let mut ty = self - .parse_ty_with_scope(Some(&type_alias_stmt.ty), (start.clone(), end.clone())) - .as_ref() - .clone(); - if let TypeKind::Schema(schema_ty) = &mut ty.kind { - schema_ty.is_instance = false; - } - ty.is_type_alias = true; - let ty = Arc::new(ty); - let ty_str = ty.into_type_annotation_str(); - let name = type_alias_stmt.type_name.node.get_name(); - let mut mapping = IndexMap::default(); - mapping.insert(ty_str.clone(), "".to_string()); - self.ctx.import_names.insert(name.to_string(), mapping); - self.add_type_alias(&name, &ty_str); - if RESERVED_TYPE_IDENTIFIERS.contains(&name.as_str()) { - self.handler.add_type_error( - &format!( - "type alias '{}' cannot be the same as the built-in types ({:?})", - name, RESERVED_TYPE_IDENTIFIERS - ), - type_alias_stmt.type_name.get_span_pos(), - ); - } - self.insert_object( - &name, - ScopeObject { - name: name.clone(), - start, - end, - ty: ty.clone(), - kind: ScopeObjectKind::TypeAlias, - doc: None, - }, - ); - self.node_ty_map.borrow_mut().insert( - self.get_node_key(type_alias_stmt.type_name.id.clone()), - ty.clone(), - ); - ty - } - - fn walk_assign_stmt(&mut self, assign_stmt: &'ctx ast::AssignStmt) -> Self::Result { - self.ctx.local_vars.clear(); - let mut value_ty = self.any_ty(); - let start = if assign_stmt.targets.is_empty() { - assign_stmt.value.get_pos() - } else { - assign_stmt.targets[0].get_pos() - }; - let end = assign_stmt.value.get_end_pos(); - let is_config = matches!(assign_stmt.value.node, ast::Expr::Schema(_)); - for target in &assign_stmt.targets { - let name = &target.node.name.node; - // Add global names. - if (is_private_field(name) || is_config || !self.contains_global_name(name)) - && self.scope_level == 0 - { - self.insert_global_name(name, &target.get_span_pos()); - } - if target.node.paths.is_empty() { - self.ctx.l_value = true; - let expected_ty = self.walk_target_expr(target); - self.ctx.l_value = false; - match &expected_ty.kind { - TypeKind::Schema(ty) => { - let obj = self.new_config_expr_context_item( - &ty.name, - expected_ty.clone(), - start.clone(), - end.clone(), - ); - let init_stack_depth = self.switch_config_expr_context(Some(obj)); - value_ty = self.expr(&assign_stmt.value); - self.clear_config_expr_context(init_stack_depth as usize, false) - } - TypeKind::List(_) | TypeKind::Dict(_) | TypeKind::Union(_) => { - let obj = self.new_config_expr_context_item( - "[]", - expected_ty.clone(), - start.clone(), - end.clone(), - ); - let init_stack_depth = self.switch_config_expr_context(Some(obj)); - value_ty = self.expr(&assign_stmt.value); - self.check_assignment_type_annotation(assign_stmt, value_ty.clone()); - self.clear_config_expr_context(init_stack_depth as usize, false) - } - _ => { - value_ty = self.expr(&assign_stmt.value); - // Check type annotation if exists. - self.check_assignment_type_annotation(assign_stmt, value_ty.clone()); - } - } - self.must_assignable_to( - value_ty.clone(), - expected_ty.clone(), - target.get_span_pos(), - None, - ); - let upgrade_schema_type = - self.upgrade_dict_to_schema(value_ty.clone(), expected_ty.clone()); - self.node_ty_map.borrow_mut().insert( - self.get_node_key(assign_stmt.value.id.clone()), - upgrade_schema_type.clone(), - ); - - if !value_ty.is_any() && expected_ty.is_any() && assign_stmt.ty.is_none() { - // When the type is inferred and paths of target are empty, set the type to - // the whole AST node `target` and the first name of node `target.node.name` - self.set_infer_type_to_scope(name, value_ty.clone(), &target); - self.set_infer_type_to_scope(name, value_ty.clone(), &target.node.name); - if let Some(schema_ty) = &self.ctx.schema { - let mut schema_ty = schema_ty.borrow_mut(); - schema_ty.set_type_of_attr( - name, - self.ctx.ty_ctx.infer_to_variable_type(value_ty.clone()), - ); - } - } - } else { - self.lookup_type_from_scope(name, target.get_span_pos()); - self.ctx.l_value = true; - let expected_ty = self.walk_target_expr(target); - self.ctx.l_value = false; - value_ty = self.expr(&assign_stmt.value); - // Check type annotation if exists. - self.check_assignment_type_annotation(assign_stmt, value_ty.clone()); - self.must_assignable_to( - value_ty.clone(), - expected_ty.clone(), - target.get_span_pos(), - None, - ); - let upgrade_schema_type = - self.upgrade_dict_to_schema(value_ty.clone(), expected_ty.clone()); - self.node_ty_map.borrow_mut().insert( - self.get_node_key(assign_stmt.value.id.clone()), - upgrade_schema_type.clone(), - ); - } - } - value_ty - } - - fn walk_aug_assign_stmt(&mut self, aug_assign_stmt: &'ctx ast::AugAssignStmt) -> Self::Result { - self.ctx.l_value = false; - let is_config = matches!(aug_assign_stmt.value.node, ast::Expr::Schema(_)); - let name = &aug_assign_stmt.target.node.name.node; - // Add global names. - if is_private_field(name) || is_config || !self.contains_global_name(name) { - if self.scope_level == 0 { - self.insert_global_name(name, &aug_assign_stmt.target.get_span_pos()); - } - } else { - let mut msgs = vec![Message { - range: aug_assign_stmt.target.get_span_pos(), - style: Style::LineAndColumn, - message: format!("Immutable variable '{}' is modified during compiling", name), - note: None, - suggested_replacement: None, - }]; - if let Some(pos) = self.get_global_name_pos(name) { - msgs.push(Message { - range: pos.clone(), - style: Style::LineAndColumn, - message: format!("The variable '{}' is declared here firstly", name), - note: Some(format!( - "change the variable name to '_{}' to make it mutable", - name - )), - suggested_replacement: None, - }) - } - self.handler.add_error(ErrorKind::ImmutableError, &msgs); - } - - let left_ty = self.walk_target_expr(&aug_assign_stmt.target); - let right_ty = self.expr(&aug_assign_stmt.value); - let op = match aug_assign_stmt.op.clone().try_into() { - Ok(op) => op, - Err(msg) => bug!("{}", msg), - }; - let new_target_ty = self.binary( - left_ty, - right_ty, - &op, - aug_assign_stmt.target.get_span_pos(), - ); - self.ctx.l_value = true; - let expected_ty = self.walk_target_expr(&aug_assign_stmt.target); - self.must_assignable_to( - new_target_ty.clone(), - expected_ty, - aug_assign_stmt.target.get_span_pos(), - None, - ); - self.ctx.l_value = false; - new_target_ty - } - - fn walk_assert_stmt(&mut self, assert_stmt: &'ctx ast::AssertStmt) -> Self::Result { - self.expr(&assert_stmt.test); - self.expr_or_any_type(&assert_stmt.if_cond); - if let Some(msg) = &assert_stmt.msg { - self.must_be_type(msg, self.str_ty()); - } - self.any_ty() - } - - fn walk_if_stmt(&mut self, if_stmt: &'ctx ast::IfStmt) -> Self::Result { - self.expr(&if_stmt.cond); - let if_ty = self.stmts(&if_stmt.body); - let orelse_ty = self.stmts(&if_stmt.orelse); - sup(&[if_ty, orelse_ty]) - } - - fn walk_import_stmt(&mut self, _import_stmt: &'ctx ast::ImportStmt) -> Self::Result { - // Nothing to do. - self.any_ty() - } - - fn walk_schema_stmt(&mut self, schema_stmt: &'ctx ast::SchemaStmt) -> Self::Result { - self.resolve_schema_stmt(schema_stmt) - } - - fn walk_rule_stmt(&mut self, rule_stmt: &'ctx ast::RuleStmt) -> Self::Result { - self.resolve_rule_stmt(rule_stmt) - } - - fn walk_quant_expr(&mut self, quant_expr: &'ctx ast::QuantExpr) -> Self::Result { - let iter_ty = self.expr(&quant_expr.target); - let (start, mut end) = quant_expr.test.get_span_pos(); - if let Some(if_cond) = &quant_expr.if_cond { - end = if_cond.get_end_pos(); - } - self.enter_scope(start, end, ScopeKind::Loop); - let (mut key_name, mut val_name) = (None, None); - for (i, target) in quant_expr.variables.iter().enumerate() { - if target.node.names.is_empty() { - continue; - } - if target.node.names.len() > 1 { - self.handler.add_compile_error( - "loop variables can only be ordinary identifiers", - target.get_span_pos(), - ); - } - let name = &target.node.names[0]; - if i == 0 { - key_name = Some(name); - } else if i == 1 { - val_name = Some(name) - } else { - self.handler.add_compile_error( - &format!( - "the number of loop variables is {}, which can only be 1 or 2", - quant_expr.variables.len() - ), - target.get_span_pos(), - ); - break; - } - self.ctx.local_vars.push(name.node.to_string()); - let (start, end) = target.get_span_pos(); - self.insert_object( - &name.node, - ScopeObject { - name: name.node.to_string(), - start, - end, - ty: self.any_ty(), - kind: ScopeObjectKind::Variable, - doc: None, - }, - ); - } - self.do_loop_type_check( - key_name, - val_name, - iter_ty.clone(), - quant_expr.target.get_span_pos(), - ); - self.expr_or_any_type(&quant_expr.if_cond); - let item_ty = self.expr(&quant_expr.test); - self.leave_scope(); - match &quant_expr.op { - ast::QuantOperation::All | ast::QuantOperation::Any => self.bool_ty(), - ast::QuantOperation::Filter => iter_ty, - ast::QuantOperation::Map => Arc::new(Type::list(item_ty)), - } - } - - fn walk_schema_attr(&mut self, schema_attr: &'ctx ast::SchemaAttr) -> Self::Result { - self.ctx.local_vars.clear(); - let (start, end) = schema_attr.name.get_span_pos(); - let name = if schema_attr.is_ident_attr() && schema_attr.name.node.contains('.') { - self.handler.add_compile_error( - "schema attribute can not be selected", - schema_attr.name.get_span_pos(), - ); - schema_attr.name.node.split('.').collect::>()[0] - } else { - &schema_attr.name.node - }; - let schema = self.ctx.schema.as_ref().unwrap(); - let expected_ty = schema - .borrow() - .get_type_of_attr(name) - .map_or(self.any_ty(), |ty| ty); - - self.node_ty_map.borrow_mut().insert( - self.get_node_key(schema_attr.name.id.clone()), - expected_ty.clone(), - ); - - let doc_str = schema - .borrow() - .attrs - .get(name) - .map(|attr| attr.doc.clone()) - .flatten(); - - self.insert_object( - name, - ScopeObject { - name: name.to_string(), - start, - end, - ty: expected_ty.clone(), - kind: ScopeObjectKind::Attribute, - doc: doc_str, - }, - ); - if let Some(value) = &schema_attr.value { - let value_ty = if let TypeKind::Schema(ty) = &expected_ty.kind { - let (start, end) = value.get_span_pos(); - let obj = - self.new_config_expr_context_item(&ty.name, expected_ty.clone(), start, end); - let init_stack_depth = self.switch_config_expr_context(Some(obj)); - let value_ty = self.expr(value); - self.clear_config_expr_context(init_stack_depth as usize, false); - value_ty - } else { - self.expr(value) - }; - match &schema_attr.op { - Some(bin_or_aug) => match bin_or_aug { - // Union - ast::AugOp::BitOr => { - let op = ast::BinOp::BitOr; - let value_ty = self.binary( - value_ty, - expected_ty.clone(), - &op, - schema_attr.name.get_span_pos(), - ); - self.must_assignable_to( - value_ty, - expected_ty, - schema_attr.name.get_span_pos(), - None, - ); - } - // Assign - _ => self.must_assignable_to( - value_ty, - expected_ty, - schema_attr.name.get_span_pos(), - None, - ), - }, - // Default is Assign - None => self.must_assignable_to( - value_ty, - expected_ty, - schema_attr.name.get_span_pos(), - None, - ), - } - } - self.any_ty() - } - - /// if else -> sup([body, orelse]) - fn walk_if_expr(&mut self, if_expr: &'ctx ast::IfExpr) -> Self::Result { - self.expr(&if_expr.cond); - let body_ty = self.expr(&if_expr.body); - let orelse_ty = self.expr(&if_expr.orelse); - sup(&[body_ty, orelse_ty]) - } - - fn walk_unary_expr(&mut self, unary_expr: &'ctx ast::UnaryExpr) -> Self::Result { - let operand_ty = self.expr(&unary_expr.operand); - self.unary( - operand_ty, - &unary_expr.op, - unary_expr.operand.get_span_pos(), - ) - } - - fn walk_binary_expr(&mut self, binary_expr: &'ctx ast::BinaryExpr) -> Self::Result { - let left_ty = self.expr(&binary_expr.left); - let mut right_ty = self.expr(&binary_expr.right); - let range = (binary_expr.left.get_pos(), binary_expr.right.get_end_pos()); - match &binary_expr.op { - ast::BinOp::As => { - if let ast::Expr::Identifier(identifier) = &binary_expr.right.node { - right_ty = self.parse_ty_str_with_scope( - &identifier.get_name(), - binary_expr.right.get_span_pos(), - ); - if right_ty.is_schema() { - let mut schema_ty = right_ty.into_schema_type(); - schema_ty.is_instance = true; - right_ty = Arc::new(Type::schema(schema_ty)); - } - let ty_annotation_str = right_ty.into_type_annotation_str(); - self.add_type_alias( - &identifier.get_name(), - &ty_str_replace_pkgpath(&ty_annotation_str, &self.ctx.pkgpath), - ); - } else { - self.handler - .add_compile_error("keyword 'as' right operand must be a type", range); - return left_ty; - } - self.binary(left_ty, right_ty, &binary_expr.op, range) - } - _ => self.binary(left_ty, right_ty, &binary_expr.op, range), - } - } - - fn walk_selector_expr(&mut self, selector_expr: &'ctx ast::SelectorExpr) -> Self::Result { - let mut value_ty = self.expr(&selector_expr.value); - if value_ty.is_module() && selector_expr.has_question { - let attr = selector_expr.attr.node.get_name(); - - self.handler.add_compile_error_with_suggestions( - &format!( - "For the module type, the use of '?.{}' is unnecessary and it can be modified as '.{}'", - attr, - attr - ), - (selector_expr.value.get_end_pos(), selector_expr.attr.get_pos()), - Some(vec![".".to_string()]) - ); - } - - self.node_ty_map.borrow_mut().insert( - self.get_node_key(selector_expr.attr.id.clone()), - value_ty.clone(), - ); - - for name in &selector_expr.attr.node.names { - value_ty = self.load_attr( - value_ty.clone(), - &name.node, - selector_expr.attr.get_span_pos(), - ); - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(name.id.clone()), value_ty.clone()); - } - - if let TypeKind::Function(func) = &value_ty.kind { - self.insert_object( - &selector_expr.attr.node.get_name(), - ScopeObject { - name: selector_expr.attr.node.get_name(), - start: selector_expr.attr.get_pos(), - end: selector_expr.attr.get_end_pos(), - ty: value_ty.clone(), - kind: ScopeObjectKind::FunctionCall, - doc: Some(func.doc.clone()), - }, - ) - } - - value_ty - } - - fn walk_call_expr(&mut self, call_expr: &'ctx ast::CallExpr) -> Self::Result { - let call_ty = self.expr(&call_expr.func); - let range = call_expr.func.get_span_pos(); - if call_ty.is_any() { - self.do_arguments_type_check( - &call_expr.func, - &call_expr.args, - &call_expr.keywords, - &FunctionType::variadic_func(), - ); - self.any_ty() - } else if let TypeKind::Function(func_ty) = &call_ty.kind { - self.do_arguments_type_check( - &call_expr.func, - &call_expr.args, - &call_expr.keywords, - &func_ty, - ); - func_ty.return_ty.clone() - } else if let TypeKind::Schema(schema_ty) = &call_ty.kind { - if schema_ty.is_instance { - self.handler.add_compile_error( - &format!("schema '{}' instance is not callable", call_ty.ty_str()), - range, - ); - self.any_ty() - } else { - self.do_arguments_type_check( - &call_expr.func, - &call_expr.args, - &call_expr.keywords, - &schema_ty.func, - ); - let mut return_ty = schema_ty.clone(); - return_ty.is_instance = true; - Arc::new(Type::schema(return_ty)) - } - } else { - self.handler.add_compile_error( - &format!("'{}' object is not callable", call_ty.ty_str()), - range, - ); - self.any_ty() - } - } - - fn walk_subscript(&mut self, subscript: &'ctx ast::Subscript) -> Self::Result { - let value_ty = self.expr(&subscript.value); - let range = subscript.value.get_span_pos(); - self.subscript( - value_ty, - &subscript.index, - &subscript.lower, - &subscript.upper, - &subscript.step, - range, - ) - } - - fn walk_paren_expr(&mut self, paren_expr: &'ctx ast::ParenExpr) -> Self::Result { - self.expr(&paren_expr.expr) - } - - fn walk_list_expr(&mut self, list_expr: &'ctx ast::ListExpr) -> Self::Result { - let stack_depth = self.switch_list_expr_context(); - let item_type = sup(&self.exprs(&list_expr.elts).to_vec()); - self.clear_config_expr_context(stack_depth, false); - Type::list_ref(item_type) - } - - fn walk_list_comp(&mut self, list_comp: &'ctx ast::ListComp) -> Self::Result { - let start = list_comp.elt.get_pos(); - let stack_depth = self.switch_list_expr_context(); - let end = match list_comp.generators.last() { - Some(last) => last.get_end_pos(), - None => list_comp.elt.get_end_pos(), - }; - self.enter_scope(start.clone(), end, ScopeKind::Loop); - for comp_clause in &list_comp.generators { - self.walk_comp_clause(&comp_clause.node); - } - if let ast::Expr::Starred(_) = list_comp.elt.node { - self.handler.add_compile_error( - "list unpacking cannot be used in list comprehension", - list_comp.elt.get_span_pos(), - ); - } - let item_ty = self.expr(&list_comp.elt); - self.leave_scope(); - self.clear_config_expr_context(stack_depth, false); - Type::list_ref(item_ty) - } - - fn walk_dict_comp(&mut self, dict_comp: &'ctx ast::DictComp) -> Self::Result { - if dict_comp.entry.key.is_none() { - self.handler.add_compile_error( - "dict unpacking cannot be used in dict comprehension", - dict_comp.entry.value.get_span_pos(), - ); - let start = dict_comp.entry.value.get_pos(); - let end = match dict_comp.generators.last() { - Some(last) => last.get_end_pos(), - None => dict_comp.entry.value.get_end_pos(), - }; - self.enter_scope(start.clone(), end, ScopeKind::Loop); - for comp_clause in &dict_comp.generators { - self.walk_comp_clause(&comp_clause.node); - } - let stack_depth = self.switch_config_expr_context_by_key(&dict_comp.entry.key); - let val_ty = self.expr(&dict_comp.entry.value); - let key_ty = match &val_ty.kind { - TypeKind::None | TypeKind::Any => val_ty.clone(), - TypeKind::Dict(DictType { key_ty, .. }) => key_ty.clone(), - TypeKind::Schema(schema_ty) => schema_ty.key_ty().clone(), - TypeKind::Union(types) - if self - .ctx - .ty_ctx - .is_config_type_or_config_union_type(val_ty.clone()) => - { - sup(&types - .iter() - .map(|ty| ty.config_key_ty()) - .collect::>()) - } - _ => { - self.handler.add_compile_error( - &format!( - "only dict and schema can be used ** unpack, got '{}'", - val_ty.ty_str() - ), - dict_comp.entry.value.get_span_pos(), - ); - self.any_ty() - } - }; - self.clear_config_expr_context(stack_depth, false); - self.leave_scope(); - Type::dict_ref(key_ty, val_ty) - } else { - let key = dict_comp.entry.key.as_ref().unwrap(); - let end = match dict_comp.generators.last() { - Some(last) => last.get_end_pos(), - None => dict_comp.entry.value.get_end_pos(), - }; - let start = key.get_pos(); - self.enter_scope(start.clone(), end, ScopeKind::Loop); - for comp_clause in &dict_comp.generators { - self.walk_comp_clause(&comp_clause.node); - } - let key_ty = self.expr(key); - self.check_attr_ty(&key_ty, key.get_span_pos()); - let stack_depth = self.switch_config_expr_context_by_key(&dict_comp.entry.key); - let val_ty = self.expr(&dict_comp.entry.value); - self.clear_config_expr_context(stack_depth, false); - self.leave_scope(); - Type::dict_ref(key_ty, val_ty) - } - } - - fn walk_list_if_item_expr( - &mut self, - list_if_item_expr: &'ctx ast::ListIfItemExpr, - ) -> Self::Result { - self.expr(&list_if_item_expr.if_cond); - let mut or_else_ty = self.expr_or_any_type(&list_if_item_expr.orelse); - // `orelse` node maybe a list unpack node, use its item type instead. - if let TypeKind::List(item_ty) = &or_else_ty.kind { - or_else_ty = item_ty.clone(); - } - let exprs_ty = sup(&self.exprs(&list_if_item_expr.exprs).to_vec()); - sup(&[or_else_ty, exprs_ty]) - } - - fn walk_starred_expr(&mut self, starred_expr: &'ctx ast::StarredExpr) -> Self::Result { - let value_ty = self.expr(&starred_expr.value); - fn starred_ty_walk_fn(ty: &TypeRef) -> (TypeRef, bool) { - match &ty.kind { - TypeKind::None | TypeKind::Any => (ty.clone(), true), - TypeKind::List(item_ty) => (item_ty.clone(), true), - TypeKind::Dict(DictType { key_ty, .. }) => (key_ty.clone(), true), - TypeKind::Schema(schema_ty) => (schema_ty.key_ty(), true), - TypeKind::Union(types) => { - let results = types - .iter() - .map(starred_ty_walk_fn) - .collect::>(); - ( - sup(&results - .iter() - .map(|(ty, _)| ty) - .cloned() - .collect::>()), - results.iter().all(|(_, r)| *r), - ) - } - _ => (Arc::new(Type::ANY), false), - } - } - let (ty, result) = starred_ty_walk_fn(&value_ty); - if !result { - self.handler.add_compile_error( - &format!( - "only list, dict, schema object can be used * unpacked, got {}", - ty.ty_str() - ), - starred_expr.value.get_span_pos(), - ); - } - ty - } - - fn walk_config_if_entry_expr( - &mut self, - config_if_entry_expr: &'ctx ast::ConfigIfEntryExpr, - ) -> Self::Result { - self.expr(&config_if_entry_expr.if_cond); - let dict_ty = self.walk_config_entries(&config_if_entry_expr.items); - if let Some(orelse) = &config_if_entry_expr.orelse { - let or_else_ty = self.expr(orelse); - sup(&[dict_ty, or_else_ty]) - } else { - dict_ty - } - } - - fn walk_comp_clause(&mut self, comp_clause: &'ctx ast::CompClause) -> Self::Result { - let iter_ty = self.expr(&comp_clause.iter); - let (mut key_name, mut val_name) = (None, None); - let mut prev_target_pos = None; - for (i, target) in comp_clause.targets.iter().enumerate() { - if target.node.names.is_empty() { - continue; - } - if target.node.names.len() > 1 { - self.handler.add_compile_error( - "loop variables can only be ordinary identifiers", - target.get_span_pos(), - ); - } - let name = &target.node.names[0]; - if i == 0 { - key_name = Some(name); - } else if i == 1 { - val_name = Some(name); - } else { - let previous_pos = if let Some(prev_pos) = prev_target_pos { - prev_pos - } else { - target.get_end_pos() - }; - self.handler.add_compile_error_with_suggestions( - &format!( - "the number of loop variables is {}, which can only be 1 or 2", - comp_clause.targets.len() - ), - (previous_pos, target.get_end_pos()), - Some(vec![]), - ); - break; - } - self.ctx.local_vars.push(name.node.to_string()); - let (start, end) = target.get_span_pos(); - self.insert_object( - &name.node, - ScopeObject { - name: name.node.to_string(), - start, - end, - ty: self.any_ty(), - kind: ScopeObjectKind::Variable, - doc: None, - }, - ); - prev_target_pos = Some(target.get_end_pos()); - } - if iter_ty.is_any() { - self.exprs(&comp_clause.ifs); - iter_ty - } else { - self.do_loop_type_check(key_name, val_name, iter_ty, comp_clause.iter.get_span_pos()); - self.exprs(&comp_clause.ifs); - self.any_ty() - } - } - - fn walk_schema_expr(&mut self, schema_expr: &'ctx ast::SchemaExpr) -> Self::Result { - let def_ty = self.walk_identifier_expr(&schema_expr.name); - if !matches!(&schema_expr.config.node, ast::Expr::Config(_)) { - self.handler.add_compile_error( - "Invalid schema config expr, expect config entries, e.g., {k1 = v1, k2 = v2}", - schema_expr.config.get_span_pos(), - ); - } - let mut range = schema_expr.name.get_span_pos(); - let ret_ty = match &def_ty.kind { - TypeKind::Dict(DictType { .. }) => { - let obj = self.new_config_expr_context_item( - "", - def_ty.clone(), - Position::dummy_pos(), - Position::dummy_pos(), - ); - let init_stack_depth = self.switch_config_expr_context(Some(obj)); - let config_ty = self.expr(&schema_expr.config); - self.clear_config_expr_context(init_stack_depth as usize, false); - self.binary(def_ty.clone(), config_ty, &ast::BinOp::BitOr, range) - } - TypeKind::Schema(schema_ty) => { - if !schema_ty.is_instance { - let name = schema_expr.name.node.get_name(); - if !self.ctx.local_vars.contains(&name) { - let ty_annotation_str = ty_str_replace_pkgpath( - &def_ty.into_type_annotation_str(), - &self.ctx.pkgpath, - ); - self.add_type_alias(&name, &ty_annotation_str); - } - } - let obj = self.new_config_expr_context_item( - &schema_ty.name, - def_ty.clone(), - Position::dummy_pos(), - Position::dummy_pos(), - ); - let init_stack_depth = self.switch_config_expr_context(Some(obj)); - self.expr(&schema_expr.config); - self.node_ty_map.borrow_mut().insert( - self.get_node_key(schema_expr.config.id.clone()), - def_ty.clone(), - ); - self.clear_config_expr_context(init_stack_depth as usize, false); - if schema_ty.is_instance { - if !schema_expr.args.is_empty() || !schema_expr.kwargs.is_empty() { - self.handler.add_compile_error( - "Arguments cannot be used in the schema modification expression", - range, - ); - } - } else { - let func = Box::new(ast::Node::node_with_pos( - ast::Expr::Identifier(schema_expr.name.node.clone()), - schema_expr.name.pos(), - )); - self.do_arguments_type_check( - &func, - &schema_expr.args, - &schema_expr.kwargs, - &schema_ty.func, - ); - } - self.any_ty() - } - TypeKind::Any => { - return self.any_ty(); - } - _ => { - range.0.filename = self.ctx.filename.clone(); - range.1.filename = self.ctx.filename.clone(); - self.handler.add_compile_error( - &format!("Invalid schema type '{}'", def_ty.ty_str()), - range, - ); - return self.any_ty(); - } - }; - let mut def_ty_clone = def_ty.as_ref().clone(); - if let TypeKind::Schema(schema_ty) = &mut def_ty_clone.kind { - schema_ty.is_instance = true; - } - if def_ty_clone.is_schema() { - Arc::new(def_ty_clone) - } else { - ret_ty - } - } - - fn walk_config_expr(&mut self, config_expr: &'ctx ast::ConfigExpr) -> Self::Result { - self.walk_config_entries(&config_expr.items) - } - - fn walk_check_expr(&mut self, check_expr: &'ctx ast::CheckExpr) -> Self::Result { - if let Some(msg) = &check_expr.msg { - self.must_be_type(msg, self.str_ty()); - } - // Check type in if_cond expression - self.expr_or_any_type(&check_expr.if_cond); - self.expr(&check_expr.test) - } - - fn walk_lambda_expr(&mut self, lambda_expr: &'ctx ast::LambdaExpr) -> Self::Result { - let mut ret_ty = self.any_ty(); - let mut params = vec![]; - self.do_parameters_check(&lambda_expr.args); - if let Some(args) = &lambda_expr.args { - for (i, arg) in args.node.args.iter().enumerate() { - let name = arg.node.get_name(); - let arg_ty = args.node.get_arg_type_node(i); - let range = match arg_ty { - Some(arg_type_node) => arg_type_node.get_span_pos(), - None => arg.get_span_pos(), - }; - let ty = self.parse_ty_with_scope(arg_ty, range); - - // If the arguments type of a lambda is a schema type, - // It should be marked as an schema instance type. - let ty = if let TypeKind::Schema(sty) = &ty.kind { - let mut arg_ty = sty.clone(); - arg_ty.is_instance = true; - Arc::new(Type::schema(arg_ty)) - } else { - ty.clone() - }; - if let Some(name) = arg.node.names.last() { - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(name.id.clone()), ty.clone()); - } - - let value = &args.node.defaults[i]; - params.push(Parameter { - name, - ty: ty.clone(), - has_default: value.is_some(), - default_value: value.as_ref().map(|v| print_ast_node(ASTNode::Expr(v))), - range: args.node.args[i].get_span_pos(), - }); - self.expr_or_any_type(value); - } - } - let (start, end) = (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()); - if let Some(ret_annotation_ty) = &lambda_expr.return_ty { - ret_ty = - self.parse_ty_with_scope(Some(&ret_annotation_ty), (start.clone(), end.clone())); - } - self.enter_scope(start.clone(), end.clone(), ScopeKind::Lambda); - self.ctx.in_lambda_expr.push(true); - // Lambda parameters - for param in ¶ms { - self.insert_object( - ¶m.name, - ScopeObject { - name: param.name.clone(), - start: start.clone(), - end: end.clone(), - ty: param.ty.clone(), - kind: ScopeObjectKind::Parameter, - doc: None, - }, - ) - } - if let Some(stmt) = lambda_expr.body.last() { - if !matches!( - stmt.node, - ast::Stmt::Expr(_) - | ast::Stmt::Assign(_) - | ast::Stmt::AugAssign(_) - | ast::Stmt::Assert(_) - ) { - self.handler.add_compile_error( - "The last statement of the lambda body must be a expression e.g., x, 1, etc.", - stmt.get_span_pos(), - ); - } - } - // Walk lambda body statements except the last statement. - if lambda_expr.body.len() > 1 { - self.stmts(&lambda_expr.body[..lambda_expr.body.len() - 1]); - } - // Upgrade return value type to schema if return type is schema - let real_ret_ty = if let Some(stmt) = lambda_expr.body.last() { - if let ast::Stmt::Expr(expr_stmt) = &stmt.node { - if let Some(expr) = expr_stmt.exprs.last() { - self.upgrade_type_for_expr( - ret_ty.clone(), - expr, - expr.get_span_pos(), - lambda_expr.return_ty.as_ref().map(|ty| ty.get_span_pos()), - ) - } else { - let real_ret_ty = self.stmt(stmt); - self.must_assignable_to( - real_ret_ty.clone(), - ret_ty.clone(), - (start, end), - None, - ); - real_ret_ty - } - } else { - let real_ret_ty = self.stmt(stmt); - self.must_assignable_to(real_ret_ty.clone(), ret_ty.clone(), (start, end), None); - real_ret_ty - } - } else { - self.any_ty() - }; - // Leave the lambda scope. - self.leave_scope(); - self.ctx.in_lambda_expr.pop(); - - if !real_ret_ty.is_any() && ret_ty.is_any() && lambda_expr.return_ty.is_none() { - ret_ty = real_ret_ty; - } - let doc = extract_doc_from_body(&lambda_expr.body); - Arc::new(Type::function( - None, - ret_ty, - ¶ms, - &doc.unwrap_or_default(), - false, - None, - )) - } - - fn walk_keyword(&mut self, keyword: &'ctx ast::Keyword) -> Self::Result { - self.walk_identifier_expr(&keyword.arg); - self.expr_or_any_type(&keyword.value) - } - - fn walk_arguments(&mut self, arguments: &'ctx ast::Arguments) -> Self::Result { - for (i, arg) in arguments.args.iter().enumerate() { - let ty = arguments.get_arg_type_node(i); - let ty = self.parse_ty_with_scope(ty, arg.get_span_pos()); - if let Some(name) = arg.node.names.last() { - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(name.id.clone()), ty.clone()); - } - let value = &arguments.defaults[i]; - self.expr_or_any_type(value); - } - self.any_ty() - } - - fn walk_compare(&mut self, compare: &'ctx ast::Compare) -> Self::Result { - let t1 = self.expr(&compare.left); - let t2 = self.expr(&compare.comparators[0]); - self.compare( - t1.clone(), - t2.clone(), - &compare.ops[0], - (compare.left.get_pos(), compare.comparators[0].get_end_pos()), - ); - for i in 1..compare.comparators.len() - 1 { - let op = &compare.ops[i + 1]; - let t2 = self.expr(&compare.comparators[i]); - self.compare( - t1.clone(), - t2.clone(), - op, - compare.comparators[i].get_span_pos(), - ); - } - self.bool_ty() - } - - fn walk_identifier(&mut self, identifier: &'ctx ast::Identifier) -> Self::Result { - let tys = self.resolve_var( - &identifier.get_names(), - &identifier.pkgpath, - (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()), - ); - for (index, name) in identifier.names.iter().enumerate() { - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(name.id.clone()), tys[index].clone()); - } - tys.last().unwrap().clone() - } - - fn walk_target(&mut self, target: &'ctx ast::Target) -> Self::Result { - let tys = self.resolve_target( - &target, - (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()), - ); - if let Some(ty) = tys.first() { - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(target.name.id.clone()), ty.clone()); - } - for (index, name) in target.paths.iter().enumerate() { - self.node_ty_map.borrow_mut().insert( - self.get_node_key(name.id()), - tys.get(index + 1).unwrap_or(&self.any_ty()).clone(), - ); - } - let target_ty = tys.last().unwrap_or(&self.any_ty()).clone(); - target_ty - } - - fn walk_number_lit(&mut self, number_lit: &'ctx ast::NumberLit) -> Self::Result { - match &number_lit.binary_suffix { - Some(binary_suffix) => { - let raw_value = match number_lit.value { - ast::NumberLitValue::Int(int_val) => int_val, - ast::NumberLitValue::Float(float_val) => { - self.handler.add_compile_error( - "float literal can not be followed the unit suffix", - (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()), - ); - float_val as i64 - } - }; - let binary_suffix_str: String = binary_suffix.value(); - let value = kclvm_runtime::units::cal_num(raw_value, &binary_suffix_str); - Arc::new(Type::number_multiplier( - value, - raw_value, - &binary_suffix_str, - )) - } - None => match number_lit.value { - ast::NumberLitValue::Int(int_val) => Arc::new(Type::int_lit(int_val)), - ast::NumberLitValue::Float(float_val) => Arc::new(Type::float_lit(float_val)), - }, - } - } - - fn walk_string_lit(&mut self, string_lit: &'ctx ast::StringLit) -> Self::Result { - Arc::new(Type::str_lit(&string_lit.value)) - } - - fn walk_name_constant_lit( - &mut self, - name_constant_lit: &'ctx ast::NameConstantLit, - ) -> Self::Result { - match &name_constant_lit.value { - ast::NameConstant::True => Arc::new(Type::bool_lit(true)), - ast::NameConstant::False => Arc::new(Type::bool_lit(false)), - ast::NameConstant::None | ast::NameConstant::Undefined => self.none_ty(), - } - } - - fn walk_joined_string(&mut self, joined_string: &'ctx ast::JoinedString) -> Self::Result { - self.ctx.l_value = false; - self.exprs(&joined_string.values); - self.str_ty() - } - - fn walk_formatted_value(&mut self, formatted_value: &'ctx ast::FormattedValue) -> Self::Result { - if let Some(spec) = &formatted_value.format_spec { - let spec_lower = spec.to_lowercase(); - if !VALID_FORMAT_SPEC_SET.contains(&spec_lower.as_str()) { - self.handler.add_compile_error( - &format!("{} is a invalid format spec", spec), - formatted_value.value.get_span_pos(), - ); - } - } - self.expr(&formatted_value.value) - } - - fn walk_comment(&mut self, _comment: &'ctx ast::Comment) -> Self::Result { - // Nothing to do. - self.any_ty() - } - - fn walk_missing_expr(&mut self, _missing_expr: &'ctx ast::MissingExpr) -> Self::Result { - // Nothing to do. - self.any_ty() - } -} - -impl<'ctx> Resolver<'_> { - pub fn stmts(&mut self, stmts: &'ctx [ast::NodeRef]) -> ResolvedResult { - let stmt_types: Vec = stmts.iter().map(|stmt| self.stmt(&stmt)).collect(); - match stmt_types.last() { - Some(ty) => ty.clone(), - _ => self.any_ty(), - } - } - - #[inline] - pub fn exprs(&mut self, exprs: &'ctx [ast::NodeRef]) -> Vec { - exprs.iter().map(|expr| self.expr(&expr)).collect() - } - - pub fn expr(&mut self, expr: &'ctx ast::NodeRef) -> ResolvedResult { - if let ast::Expr::Identifier(_) = &expr.node { - let (start, end) = expr.get_span_pos(); - self.ctx.start_pos = start; - self.ctx.end_pos = end; - } - - let expected_ty = match self.ctx.config_expr_context.last() { - Some(ty) => ty.clone().map(|o| o.ty), - None => None, - }; - - let ty = self.walk_expr(&expr.node); - - if let Some(expected_ty) = expected_ty { - let upgrade_ty = self.upgrade_dict_to_schema(ty.clone(), expected_ty); - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(expr.id.clone()), upgrade_ty); - } else { - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(expr.id.clone()), ty.clone()); - } - - ty - } - - pub fn stmt(&mut self, stmt: &'ctx ast::NodeRef) -> ResolvedResult { - let (start, end) = stmt.get_span_pos(); - self.ctx.start_pos = start; - self.ctx.end_pos = end; - let ty = self.walk_stmt(&stmt.node); - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(stmt.id.clone()), ty.clone()); - ty - } - - pub fn expr_or_any_type( - &mut self, - expr: &'ctx Option>, - ) -> ResolvedResult { - match expr { - Some(expr) => { - let ty = self.walk_expr(&expr.node); - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(expr.id.clone()), ty.clone()); - ty - } - None => self.any_ty(), - } - } - - pub fn walk_identifier_expr( - &mut self, - identifier: &'ctx ast::NodeRef, - ) -> ResolvedResult { - let tys = self.resolve_var( - &identifier.node.get_names(), - &identifier.node.pkgpath, - identifier.get_span_pos(), - ); - for (index, name) in identifier.node.names.iter().enumerate() { - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(name.id.clone()), tys[index].clone()); - } - let ident_ty = tys.last().unwrap().clone(); - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(identifier.id.clone()), ident_ty.clone()); - - ident_ty - } - - pub fn walk_target_expr(&mut self, target: &'ctx ast::NodeRef) -> ResolvedResult { - let tys = self.resolve_target(&target.node, target.get_span_pos()); - if let Some(ty) = tys.first() { - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(target.node.name.id.clone()), ty.clone()); - } - for (index, name) in target.node.paths.iter().enumerate() { - self.node_ty_map.borrow_mut().insert( - self.get_node_key(name.id()), - tys.get(index + 1).unwrap_or(&self.any_ty()).clone(), - ); - } - let target_ty = tys.last().unwrap_or(&self.any_ty()).clone(); - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(target.id.clone()), target_ty.clone()); - target_ty - } -} diff --git a/kclvm/sema/src/resolver/schema.rs b/kclvm/sema/src/resolver/schema.rs deleted file mode 100644 index 571410cfe..000000000 --- a/kclvm/sema/src/resolver/schema.rs +++ /dev/null @@ -1,332 +0,0 @@ -use std::cell::RefCell; -use std::collections::HashMap; -use std::rc::Rc; - -use crate::builtin::BUILTIN_DECORATORS; -use crate::resolver::Resolver; -use crate::ty::{Decorator, DecoratorTarget, TypeKind, TypeRef}; -use kclvm_ast::ast; -use kclvm_ast::pos::GetPos; -use kclvm_ast::walker::MutSelfTypedResultWalker; -use kclvm_ast_pretty::{print_ast_node, ASTNode}; -use kclvm_error::diagnostic::Range; -use kclvm_error::{ErrorKind, Message, Position, Style}; - -use super::node::ResolvedResult; -use super::scope::{ScopeKind, ScopeObject, ScopeObjectKind}; - -impl<'ctx> Resolver<'_> { - pub(crate) fn resolve_schema_stmt( - &mut self, - schema_stmt: &'ctx ast::SchemaStmt, - ) -> ResolvedResult { - let (start, end) = (self.ctx.start_pos.clone(), self.ctx.end_pos.clone()); - self.resolve_unique_key(&schema_stmt.name.node, &schema_stmt.name.get_span_pos()); - let ty = - self.lookup_type_from_scope(&schema_stmt.name.node, schema_stmt.name.get_span_pos()); - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(schema_stmt.name.id.clone()), ty.clone()); - let scope_ty = if ty.is_schema() { - ty.into_schema_type() - } else { - self.handler.add_error( - ErrorKind::TypeError, - &[Message { - range: schema_stmt.get_span_pos(), - style: Style::LineAndColumn, - message: format!("expected schema type, got {}", ty.ty_str()), - note: None, - suggested_replacement: None, - }], - ); - return ty; - }; - self.ctx.schema = Some(Rc::new(RefCell::new(scope_ty.clone()))); - if let Some(args) = &schema_stmt.args { - for (i, arg) in args.node.args.iter().enumerate() { - let ty = args.node.get_arg_type_node(i); - let ty = self.parse_ty_with_scope(ty, arg.get_span_pos()); - if let Some(name) = arg.node.names.last() { - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(name.id.clone()), ty.clone()); - } - } - } - self.do_parameters_check(&schema_stmt.args); - self.enter_scope( - start.clone(), - end.clone(), - ScopeKind::Schema(schema_stmt.name.node.to_string()), - ); - for param in &scope_ty.func.params { - self.insert_object( - ¶m.name, - ScopeObject { - name: param.name.clone(), - start: start.clone(), - end: end.clone(), - ty: param.ty.clone(), - kind: ScopeObjectKind::Parameter, - doc: None, - }, - ) - } - // Schema index signature - if let (Some(index_signature), Some(index_signature_node)) = - (scope_ty.index_signature, &schema_stmt.index_signature) - { - // Insert the schema index signature key name into the scope. - if let Some(key_name) = index_signature.key_name { - let (start, end) = index_signature_node.get_span_pos(); - self.insert_object( - &key_name, - ScopeObject { - name: key_name.clone(), - start, - end, - ty: index_signature.key_ty.clone(), - kind: ScopeObjectKind::Variable, - doc: None, - }, - ) - } - // Check index signature default value type. - if let Some(value) = &index_signature_node.node.value { - let expected_ty = index_signature.val_ty; - let value_ty = if let TypeKind::Schema(ty) = &expected_ty.kind { - let (start, end) = value.get_span_pos(); - let obj = self.new_config_expr_context_item( - &ty.name, - expected_ty.clone(), - start, - end, - ); - let init_stack_depth = self.switch_config_expr_context(Some(obj)); - let value_ty = self.expr(value); - self.clear_config_expr_context(init_stack_depth as usize, false); - value_ty - } else { - self.expr(value) - }; - self.must_assignable_to( - value_ty, - expected_ty, - index_signature_node.get_span_pos(), - None, - ); - } - } - let schema_attr_names = schema_stmt.get_left_identifier_list(); - for (line, column, name) in schema_attr_names { - if !self.contains_object(&name) { - self.insert_object( - &name, - ScopeObject { - name: name.clone(), - start: Position { - filename: self.ctx.filename.clone(), - line, - column: Some(column), - }, - end: Position::dummy_pos(), - ty: self.any_ty(), - kind: ScopeObjectKind::Variable, - doc: None, - }, - ); - } - } - // Schema body. - self.stmts(&schema_stmt.body); - // Schema check blocks. - for check_expr in &schema_stmt.checks { - self.walk_check_expr(&check_expr.node); - } - self.leave_scope(); - self.ctx.schema = None; - ty - } - - pub(crate) fn resolve_rule_stmt(&mut self, rule_stmt: &'ctx ast::RuleStmt) -> ResolvedResult { - self.resolve_unique_key(&rule_stmt.name.node, &rule_stmt.name.get_span_pos()); - let ty = self.lookup_type_from_scope(&rule_stmt.name.node, rule_stmt.name.get_span_pos()); - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(rule_stmt.name.id.clone()), ty.clone()); - let scope_ty = if ty.is_schema() { - ty.into_schema_type() - } else { - self.handler.add_error( - ErrorKind::TypeError, - &[Message { - range: rule_stmt.get_span_pos(), - style: Style::LineAndColumn, - message: format!("expected rule type, got {}", ty.ty_str()), - note: None, - suggested_replacement: None, - }], - ); - return ty; - }; - self.ctx.schema = Some(Rc::new(RefCell::new(scope_ty.clone()))); - let (start, end) = rule_stmt.get_span_pos(); - self.do_parameters_check(&rule_stmt.args); - self.enter_scope( - start.clone(), - end.clone(), - ScopeKind::Schema(rule_stmt.name.node.to_string()), - ); - for param in &scope_ty.func.params { - self.insert_object( - ¶m.name, - ScopeObject { - name: param.name.clone(), - start: start.clone(), - end: end.clone(), - ty: param.ty.clone(), - kind: ScopeObjectKind::Parameter, - doc: None, - }, - ) - } - // Rule check blocks. - for check_expr in &rule_stmt.checks { - self.walk_check_expr(&check_expr.node); - } - self.leave_scope(); - self.ctx.schema = None; - ty - } - - pub(crate) fn resolve_decorators( - &mut self, - decorators: &'ctx [ast::NodeRef], - target: DecoratorTarget, - key: &str, - ) -> Vec { - let mut decorator_objs = vec![]; - for decorator in decorators { - let name = if let ast::Expr::Identifier(identifier) = &decorator.node.func.node { - if identifier.names.len() == 1 { - Some(identifier.names[0].node.clone()) - } else { - None - } - } else { - None - }; - match name { - Some(name) => match BUILTIN_DECORATORS.get(&name) { - Some(ty) => match &ty.kind { - TypeKind::Function(func_ty) => { - self.do_arguments_type_check( - &decorator.node.func, - &decorator.node.args, - &decorator.node.keywords, - &func_ty, - ); - let (arguments, keywords) = self.arguments_to_string( - &decorator.node.args, - &decorator.node.keywords, - ); - decorator_objs.push(Decorator { - target: target.clone(), - name, - key: key.to_string(), - arguments, - keywords, - }) - } - _ => bug!("invalid builtin decorator function type"), - }, - None => { - self.handler.add_compile_error_with_suggestions( - &format!("UnKnown decorator {}", name), - decorator.get_span_pos(), - Some(vec![]), - ); - } - }, - None => { - self.handler.add_type_error( - "decorator name must be a single identifier", - decorator.get_span_pos(), - ); - } - } - } - decorator_objs - } - - /// Walk expr and check the type and return the value type. - pub(crate) fn upgrade_type_for_expr( - &mut self, - expected_ty: TypeRef, - expr: &'ctx ast::NodeRef, - target_range: Range, - def_range: Option, - ) -> TypeRef { - let (start, end) = expr.get_span_pos(); - let value_ty = match &expected_ty.kind { - TypeKind::Schema(ty) => { - let obj = - self.new_config_expr_context_item(&ty.name, expected_ty.clone(), start, end); - let init_stack_depth = self.switch_config_expr_context(Some(obj)); - let value_ty = self.expr(expr); - self.clear_config_expr_context(init_stack_depth as usize, false); - value_ty - } - TypeKind::List(_) | TypeKind::Dict(_) | TypeKind::Union(_) => { - let obj = self.new_config_expr_context_item("[]", expected_ty.clone(), start, end); - let init_stack_depth = self.switch_config_expr_context(Some(obj)); - let value_ty = self.expr(expr); - self.clear_config_expr_context(init_stack_depth as usize, false); - value_ty - } - _ => { - self.ctx.config_expr_context.push(None); - let value_ty = self.expr(expr); - self.ctx.config_expr_context.pop(); - value_ty - } - }; - self.must_assignable_to( - value_ty.clone(), - expected_ty.clone(), - target_range, - def_range, - ); - value_ty - } - - fn arguments_to_string( - &mut self, - args: &'ctx [ast::NodeRef], - kwargs: &'ctx [ast::NodeRef], - ) -> (Vec, HashMap) { - if self.options.resolve_val { - ( - args.iter() - .map(|a| print_ast_node(ASTNode::Expr(a))) - .collect(), - kwargs - .iter() - .map(|a| { - ( - a.node.arg.node.get_name(), - a.node - .value - .as_ref() - .map(|v| print_ast_node(ASTNode::Expr(v))) - .unwrap_or_default(), - ) - }) - .collect(), - ) - } else { - (vec![], HashMap::new()) - } - } -} diff --git a/kclvm/sema/src/resolver/scope.rs b/kclvm/sema/src/resolver/scope.rs deleted file mode 100644 index 030208232..000000000 --- a/kclvm/sema/src/resolver/scope.rs +++ /dev/null @@ -1,773 +0,0 @@ -use anyhow::bail; -use compiler_base_session::Session; -use kclvm_ast::ast::NodeRef; -use kclvm_ast::ast::Stmt; -use kclvm_ast::ast::Stmt::Import; -use kclvm_ast::{ast, MAIN_PKG}; -use kclvm_error::diagnostic::Range; -use kclvm_error::{Handler, Level}; -use kclvm_primitives::DefaultHashBuilder; -use kclvm_primitives::{IndexMap, IndexSet}; -use std::collections::HashMap; -use std::collections::HashSet; -use std::collections::VecDeque; -use std::sync::Arc; -use std::{ - cell::RefCell, - rc::{Rc, Weak}, -}; - -use crate::resolver::Resolver; -use crate::ty::SchemaType; -use crate::ty::TypeRef; -use crate::{builtin::BUILTIN_FUNCTIONS, ty::TypeInferMethods}; -use kclvm_ast::ast::AstIndex; -use kclvm_ast::pos::ContainsPos; -use kclvm_ast::pos::GetPos; -use kclvm_error::Position; -use parking_lot::RwLock; -use serde::Serialize; - -/// The object stored in the scope. -#[derive(PartialEq, Clone, Debug)] -pub struct ScopeObject { - /// The scope object name. - pub name: String, - /// The scope object start position. - pub start: Position, - /// The scope object end position. - pub end: Position, - /// The type of the scope object. - pub ty: TypeRef, - /// The scope object kind. - pub kind: ScopeObjectKind, - /// The doc of the scope object, will be None unless the scope object represents a schema or schema attribute. - pub doc: Option, -} - -impl ScopeObject { - /// Positions of the scope object are valid. - #[inline] - pub fn pos_is_valid(&self) -> bool { - self.start.is_valid() && self.end.is_valid() - } -} - -impl ContainsPos for ScopeObject { - fn contains_pos(&self, pos: &Position) -> bool { - self.start.less_equal(pos) && pos.less_equal(&self.end) - } -} - -impl GetPos for ScopeObject { - fn get_span_pos(&self) -> Range { - (self.start.clone(), self.end.clone()) - } - fn get_pos(&self) -> Position { - self.start.clone() - } - - fn get_end_pos(&self) -> Position { - self.end.clone() - } -} - -#[derive(PartialEq, Clone, Debug)] -pub enum ScopeObjectKind { - Variable, - Attribute, - Definition, - Parameter, - TypeAlias, - FunctionCall, - Module(Module), -} - -/// A scope object of module type represents an import stmt on an AST and -/// is used to record information on the AST -#[derive(PartialEq, Clone, Debug)] -pub struct Module { - /// Record stmts which import this module and whether has been used, for check unused imported module and var definition - pub import_stmts: Vec<(NodeRef, bool)>, -} - -/// A Scope maintains a set of objects and links to its containing -/// (parent) and contained (children) scopes. Objects may be inserted -/// and looked up by name. The zero value for Scope is a ready-to-use -/// empty scope. -#[derive(Clone, Debug)] -pub struct Scope { - /// The parent scope. - pub parent: Option>>, - /// The child scope list. - pub children: Vec>>, - /// The scope object mapping with its name. - pub elems: IndexMap>>, - /// The scope start position. - pub start: Position, - /// The scope end position. - pub end: Position, - /// The scope kind. - pub kind: ScopeKind, -} - -impl Scope { - /// Lookup the scope object recursively with the name. - pub fn lookup(&self, name: &str) -> Option>> { - match self.elems.get(name) { - Some(obj) => Some(obj.clone()), - None => match &self.parent { - Some(parent) => match parent.upgrade() { - Some(parent) => { - let parent = parent.borrow(); - parent.lookup(name) - } - None => None, - }, - None => None, - }, - } - } - - /// Get all usable scope objects in current and parent scope. - pub fn all_usable_objects(&self) -> IndexMap>> { - let mut res = match &self.parent { - Some(parent) => match parent.upgrade() { - Some(parent) => parent.borrow().all_usable_objects(), - None => IndexMap::with_hasher(DefaultHashBuilder::default()), - }, - None => IndexMap::with_hasher(DefaultHashBuilder::default()), - }; - - for (name, obj) in &self.elems { - match &obj.borrow().kind { - ScopeObjectKind::Module(module) => { - for stmt in &module.import_stmts { - if let Import(import_stmt) = &stmt.0.node { - res.insert(import_stmt.name.clone(), obj.clone()); - } - } - } - _ => { - res.insert(name.clone(), obj.clone()); - } - } - } - res - } - - /// Set a type by name to existed object, return true if found. - pub fn set_ty(&mut self, name: &str, ty: TypeRef) -> bool { - match self.elems.get_mut(name) { - Some(obj) => { - let mut obj = obj.borrow_mut(); - obj.ty = ty; - true - } - None => false, - } - } -} - -impl ContainsPos for Scope { - /// Check if current scope contains a position - fn contains_pos(&self, pos: &Position) -> bool { - match &self.kind { - ScopeKind::Package(files) => files.contains(&pos.filename), - _ => self.start.less_equal(pos) && pos.less_equal(&self.end), - } - } -} - -#[derive(Clone, Debug)] -pub enum ScopeKind { - /// Package scope. - Package(IndexSet), - /// Builtin scope. - Builtin, - /// Schema name string. - Schema(String), - /// Loop scope. - Loop, - /// Condition statement. - CondStmt, - /// Lambda expression. - Lambda, - /// Config expression - Config, -} - -impl Scope { - /// Check if current scope contains a position on the AST statement. - pub fn contains_pos_on_stmt(&self, pos: &Position, stmt: &ast::Node) -> bool { - match &stmt.node { - ast::Stmt::Schema(schema) => { - schema.body.iter().any(|n| n.contains_pos(pos)) - || schema.checks.iter().any(|n| n.contains_pos(pos)) - || schema - .index_signature - .as_ref() - .map(|n| n.contains_pos(pos)) - .is_some() - } - ast::Stmt::Rule(rule) => rule.checks.iter().any(|n| n.contains_pos(pos)), - _ => self.contains_pos(pos), - } - } - /// Returns the inner most scope on the position. - pub fn inner_most(&self, pos: &Position) -> Option { - // Builtin scope - if self.parent.is_none() { - for child in self.children.iter() { - let child = child.borrow(); - if child.contains_pos(pos) { - return child.inner_most(pos); - } - } - return None; - } - // self is not BUILTIN_SCOPE - if self.contains_pos(pos) { - for child in self.children.iter() { - let child = child.borrow(); - if child.contains_pos(pos) { - return child.inner_most(pos); - } - } - return Some(self.clone()); - } - None - } - - /// Get the enclosing scope - #[inline] - pub fn get_enclosing_scope(&self) -> Option>> { - self.parent.as_ref().map(|scope| scope.upgrade().unwrap()) - } - - /// Search child scope by the scope name. - pub fn search_child_scope_by_name(&self, name: &str) -> Option>> { - match self.elems.get(name) { - Some(_) => { - for child in self.children.iter() { - let child_ref = child.borrow(); - if let ScopeKind::Schema(schema_name) = &child_ref.kind { - if name == schema_name { - return Some(Rc::clone(child)); - } - } - } - None - } - None => None, - } - } - - /// Search scope obj by the object name. - pub fn search_obj_by_name(&self, name: &str) -> Vec { - let mut res = vec![]; - for (obj_name, obj) in &self.elems { - if obj_name == name { - res.push(obj.borrow().clone()) - } - } - for c in &self.children { - let c = c.borrow(); - let mut objs = c.search_obj_by_name(name); - res.append(&mut objs); - } - res - } -} - -/// Program scope is scope contains a multiple scopes related to the -/// package path. -#[derive(Clone, Debug, Default)] -pub struct ProgramScope { - pub scope_map: IndexMap>>, - pub import_names: IndexMap>, - pub schema_mapping: IndexMap>>, - pub node_ty_map: Rc>, - pub handler: Handler, -} - -unsafe impl Send for ProgramScope {} - -unsafe impl Send for Scope {} -unsafe impl Sync for Scope {} - -impl ProgramScope { - /// Get all package paths. - #[inline] - pub fn pkgpaths(&self) -> Vec { - self.scope_map.keys().cloned().collect::>() - } - - /// Get the scope in the main package. - #[inline] - pub fn main_scope(&self) -> Option<&Rc>> { - self.scope_map.get(MAIN_PKG) - } - - /// Return diagnostic pretty string but do not abort if the session exists any diagnostic. - pub fn emit_diagnostics_to_string( - &self, - sess: Arc, - include_warning: bool, - ) -> Result<(), String> { - let emit_error = || -> anyhow::Result<()> { - // Add resolve errors into the session - for diag in &self.handler.diagnostics { - if matches!(diag.level, Level::Error) || matches!(diag.level, Level::Suggestions) { - sess.add_err(diag.clone())?; - } - if include_warning && matches!(diag.level, Level::Warning) { - sess.add_err(diag.clone())?; - } - } - // If has syntax and resolve errors, return its string format. - if sess.diag_handler.has_errors()? { - let errors = sess.emit_all_diags_into_string()?; - let mut error_strings = vec![]; - for error in errors { - error_strings.push(error?); - } - bail!(error_strings.join("\n")) - } else { - Ok(()) - } - }; - emit_error().map_err(|e| e.to_string()) - } - - /// Returns the inner most scope on the position. - pub fn inner_most_scope(&self, pos: &Position) -> Option { - for (_, scope) in &self.scope_map { - match scope.borrow().inner_most(&pos) { - Some(scope) => return Some(scope), - None => continue, - } - } - None - } -} - -/// Construct a builtin scope -pub fn builtin_scope() -> Scope { - let mut elems = IndexMap::default(); - for (name, builtin_func) in BUILTIN_FUNCTIONS.iter() { - elems.insert( - name.to_string(), - Rc::new(RefCell::new(ScopeObject { - name: name.to_string(), - start: Position::dummy_pos(), - end: Position::dummy_pos(), - ty: Arc::new(builtin_func.clone()), - kind: ScopeObjectKind::Definition, - doc: None, - })), - ); - } - Scope { - parent: None, - children: vec![], - elems, - start: Position::dummy_pos(), - end: Position::dummy_pos(), - kind: ScopeKind::Builtin, - } -} - -impl<'ctx> Resolver<'ctx> { - /// Enter scope such as schema statement, for loop expressions. - pub fn enter_scope(&mut self, start: Position, end: Position, kind: ScopeKind) { - let scope = Scope { - parent: Some(Rc::downgrade(&self.scope)), - children: vec![], - elems: IndexMap::default(), - start, - end, - kind, - }; - let scope = Rc::new(RefCell::new(scope)); - { - // Borrow self.scope - let mut scope_ref = self.scope.borrow_mut(); - let children = &mut scope_ref.children; - children.push(Rc::clone(&scope)); - // Deref self.scope - } - self.scope_level += 1; - self.scope = Rc::clone(&scope); - } - - /// Leave scope. - pub fn leave_scope(&mut self) { - self.ctx.local_vars.clear(); - let parent = match &self.scope.borrow().parent { - Some(parent) => parent.upgrade().unwrap(), - None => bug!("the scope parent is empty, can't leave the scope"), - }; - self.scope_level -= 1; - self.scope = Rc::clone(&parent); - } - - /// Find scope object type by name. - #[inline] - pub fn find_type_in_scope(&mut self, name: &str) -> Option { - self.scope - .borrow() - .lookup(name) - .map(|obj| obj.borrow().ty.clone()) - } - - /// Lookup type from the scope by name, if not found, emit a compile error and - /// return the any type. - pub fn lookup_type_from_scope(&mut self, name: &str, range: Range) -> TypeRef { - match self.find_type_in_scope(name) { - Some(ty) => ty, - None => { - let mut suggestion = String::new(); - let names = self - .scope - .borrow() - .all_usable_objects() - .keys() - .cloned() - .collect::>(); - let suggs = suggestions::provide_suggestions(name, &names); - if suggs.len() > 0 { - suggestion = format!(", did you mean '{:?}'?", suggs); - } - self.handler.add_compile_error_with_suggestions( - &format!( - "name '{}' is not defined{}", - name.replace('@', ""), - suggestion - ), - range, - Some(suggs.clone()), - ); - self.any_ty() - } - } - } - - /// Set type to the scope exited object, if not found, emit a compile error. - pub fn set_infer_type_to_scope(&mut self, name: &str, ty: TypeRef, node: &ast::Node) { - let mut scope = self.scope.borrow_mut(); - match scope.elems.get_mut(name) { - Some(obj) => { - let mut obj = obj.borrow_mut(); - let infer_ty = self.ctx.ty_ctx.infer_to_variable_type(ty); - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(node.id.clone()), infer_ty.clone()); - obj.ty = infer_ty; - } - None => { - self.handler.add_compile_error( - &format!("name '{}' is not defined", name.replace('@', "")), - node.get_span_pos(), - ); - } - } - } - - /// Set type to the scope exited object, if not found, emit a compile error. - pub fn set_type_to_scope(&mut self, name: &str, ty: TypeRef, node: &ast::Node) { - let mut scope = self.scope.borrow_mut(); - match scope.elems.get_mut(name) { - Some(obj) => { - let mut obj = obj.borrow_mut(); - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(node.id.clone()), ty.clone()); - obj.ty = ty; - } - None => { - self.handler.add_compile_error( - &format!("name '{}' is not defined", name.replace('@', "")), - node.get_span_pos(), - ); - } - } - } - - /// Insert object into the current scope. - #[inline] - pub fn insert_object(&mut self, name: &str, obj: ScopeObject) { - let mut scope = self.scope.borrow_mut(); - scope - .elems - .insert(name.to_string(), Rc::new(RefCell::new(obj))); - } - - /// Contains object into the current scope. - #[inline] - pub fn contains_object(&mut self, name: &str) -> bool { - self.scope.borrow().elems.contains_key(name) - } - - pub fn get_node_key(&self, id: AstIndex) -> NodeKey { - NodeKey { - pkgpath: self.ctx.pkgpath.clone(), - id, - } - } -} - -#[derive(Clone, Debug, Hash, PartialEq, Eq, Serialize)] -pub struct NodeKey { - pub pkgpath: String, - pub id: AstIndex, -} - -pub type NodeTyMap = IndexMap; -pub type KCLScopeCache = Arc>; - -/// For CachedScope, we assume that all changed files must be located in kclvm_ast::MAIN_PKG , -/// if this is not the case, please clear the cache directly -#[derive(Debug, Clone, Default)] -pub struct CachedScope { - pub program_root: String, - pub scope_map: IndexMap>>, - pub schema_mapping: IndexMap>>, - pub node_ty_map: NodeTyMap, - pub invalidate_pkgs: HashSet, - /// Specify the invalid module in the program packages, used for invalidate_module(). - /// If it is None, all modules in the main package will be invalidated - pub invalidate_pkg_modules: Option>, - dependency_graph: DependencyGraph, -} - -unsafe impl Send for CachedScope {} -unsafe impl Sync for CachedScope {} - -#[derive(Debug, Clone, Default)] -struct DependencyGraph { - /// map filename to pkgpath - pub module_map: HashMap>, - /// map pkgpath to node - pub node_map: HashMap, -} - -impl DependencyGraph { - pub fn clear(&mut self) { - self.module_map.clear(); - self.node_map.clear(); - } - - pub fn update( - &mut self, - program: &ast::Program, - invalidate_pkg_modules: &Option>, - ) -> Result, String> { - let mut new_modules = HashMap::new(); - for (pkgpath, modules) in program.pkgs.iter() { - if pkgpath == kclvm_ast::MAIN_PKG { - continue; - } - if !self.node_map.contains_key(pkgpath) { - self.node_map.insert( - pkgpath.to_string(), - DependencyNode { - pkgpath: pkgpath.to_string(), - parents: HashSet::new(), - children: HashSet::new(), - }, - ); - } - for module in modules { - let module = program - .get_module(module) - .expect("Failed to acquire module lock") - .expect(&format!("module {:?} not found in program", module)); - let filename = module.filename.clone(); - if !self.module_map.contains_key(&filename) { - new_modules.insert(filename.clone(), module); - self.module_map.insert(filename.clone(), HashSet::new()); - } - self.module_map - .get_mut(&filename) - .unwrap() - .insert(pkgpath.to_string()); - } - } - - for new_module in new_modules.values() { - self.add_new_module(new_module); - } - - let mut invalidated_set = HashSet::new(); - - match invalidate_pkg_modules { - Some(modules) => { - for module_name in modules { - let result = self.invalidate_module(module_name)?; - for pkg in result { - invalidated_set.insert(pkg); - } - self.remove_dependency_from_pkg(&module_name); - if let Ok(m) = program.get_module(module_name) { - if let Some(module) = m { - self.add_new_module(&module); - } - } - } - } - None => { - if let Some(main_modules) = program.pkgs.get(kclvm_ast::MAIN_PKG) { - for module in main_modules { - let module = program - .get_module(module) - .expect("Failed to acquire module lock") - .expect(&format!("module {:?} not found in program", module)); - let result = self.invalidate_module(&module.filename)?; - for pkg in result { - invalidated_set.insert(pkg); - } - self.remove_dependency_from_pkg(&module.filename); - self.add_new_module(&module); - } - } - } - } - Ok(invalidated_set) - } - - fn add_new_module(&mut self, new_module: &ast::Module) { - let module_file = new_module.filename.clone(); - if let Some(pkgpaths) = self.module_map.get(&module_file) { - for stmt in &new_module.body { - if let ast::Stmt::Import(import_stmt) = &stmt.node { - let parent_pkg = &import_stmt.path.node; - if let Some(parent_node) = self.node_map.get_mut(parent_pkg) { - parent_node.children.insert(new_module.filename.clone()); - } - for pkgpath in pkgpaths { - let cur_node = self.node_map.get_mut(pkgpath).unwrap(); - cur_node.parents.insert(parent_pkg.clone()); - } - } - } - } - } - - fn invalidate_module(&mut self, changed_module: &str) -> Result, String> { - let mut invalidated_set = HashSet::new(); - if let Some(pkgpaths) = self.module_map.get(changed_module).cloned() { - let mut pkg_queue = VecDeque::new(); - for pkgpath in pkgpaths.iter() { - pkg_queue.push_back(self.node_map.get(pkgpath)); - } - - let mut old_size: i64 = -1; - while old_size < invalidated_set.len() as i64 { - old_size = invalidated_set.len() as i64; - let cur_node = loop { - match pkg_queue.pop_front() { - Some(cur_node) => match cur_node { - None => continue, - Some(cur_node) => { - if invalidated_set.contains(&cur_node.pkgpath) { - continue; - } - invalidated_set.insert(cur_node.pkgpath.clone()); - break Some(cur_node); - } - }, - None => break None, - } - }; - if let Some(cur_node) = cur_node { - for child in cur_node.children.iter() { - if let Some(child_pkgs) = self.module_map.get(child) { - for child_pkg in child_pkgs { - if invalidated_set.contains(child_pkg) { - continue; - } - pkg_queue.push_back(self.node_map.get(child_pkg)); - } - } - } - } - } - }; - Ok(invalidated_set) - } - - fn remove_dependency_from_pkg(&mut self, filename: &str) { - if let Some(pkgpaths) = self.module_map.get(filename).cloned() { - for pkgpath in pkgpaths { - if let Some(node) = self.node_map.get(&pkgpath).cloned() { - for parent in node.parents { - if let Some(parent_node) = self.node_map.get_mut(&parent) { - parent_node.children.remove(filename); - } - } - } - } - } - } -} - -#[derive(Debug, Clone, Default)] -struct DependencyNode { - // The package path of the current node. - pkgpath: String, - // The pkgpath which is imported by this package. - parents: HashSet, - // Files which import this package. - children: HashSet, -} - -impl CachedScope { - pub fn new(scope: &ProgramScope, program: &ast::Program) -> Self { - let mut cached_scope = Self { - program_root: program.root.to_string(), - scope_map: scope.scope_map.clone(), - node_ty_map: scope.node_ty_map.borrow().clone(), - invalidate_pkgs: HashSet::default(), - dependency_graph: DependencyGraph::default(), - schema_mapping: scope.schema_mapping.clone(), - invalidate_pkg_modules: None, - }; - let invalidated_pkgs = cached_scope - .dependency_graph - .update(program, &cached_scope.invalidate_pkg_modules); - cached_scope.invalidate_cache(invalidated_pkgs.as_ref()); - cached_scope - } - - pub fn clear(&mut self) { - self.scope_map.clear(); - self.node_ty_map.clear(); - self.dependency_graph.clear(); - self.invalidate_pkgs.clear(); - self.invalidate_pkg_modules = None; - } - - pub fn invalidate_cache(&mut self, invalidated_pkgs: Result<&HashSet, &String>) { - match invalidated_pkgs { - Ok(invalidated_pkgs) => { - for invalidated_pkg in invalidated_pkgs.iter() { - self.scope_map.swap_remove(invalidated_pkg); - } - self.invalidate_pkgs = invalidated_pkgs.clone(); - } - Err(_) => self.clear(), - } - } - - pub fn update(&mut self, program: &ast::Program) { - if self.program_root != program.root { - self.clear(); - self.program_root = program.root.clone(); - } - let invalidated_pkgs = self - .dependency_graph - .update(program, &self.invalidate_pkg_modules); - self.invalidate_cache(invalidated_pkgs.as_ref()); - } -} diff --git a/kclvm/sema/src/resolver/tests.rs b/kclvm/sema/src/resolver/tests.rs deleted file mode 100644 index 2c566e8aa..000000000 --- a/kclvm/sema/src/resolver/tests.rs +++ /dev/null @@ -1,1166 +0,0 @@ -use super::Options; -use super::Resolver; -use crate::builtin::BUILTIN_FUNCTION_NAMES; -use crate::pre_process::pre_process_program; -use crate::resolver::resolve_program; -use crate::resolver::resolve_program_with_opts; -use crate::resolver::scope::*; -use crate::ty::{Type, TypeKind}; -use anyhow::Result; -use kclvm_ast::ast; -use kclvm_ast::pos::ContainsPos; -use kclvm_ast::MAIN_PKG; -use kclvm_error::*; -use kclvm_parser::load_program; -use kclvm_parser::parse_file_force_errors; -use kclvm_parser::LoadProgramOptions; -use kclvm_parser::ParseSession; -use kclvm_utils::path::PathPrefix; -use parking_lot::lock_api::RwLock; -use std::collections::HashMap; -use std::collections::HashSet; -use std::path::Path; -use std::sync::Arc; -use std::sync::RwLock as Lock; - -pub fn parse_program(filename: &str) -> Result { - let abspath = std::fs::canonicalize(std::path::PathBuf::from(filename)).expect(filename); - - let mut prog = ast::Program { - root: abspath.parent().unwrap().adjust_canonicalization(), - pkgs: HashMap::new(), - modules: HashMap::new(), - pkgs_not_imported: HashMap::new(), - modules_not_imported: HashMap::new(), - }; - - let mut module = parse_file_force_errors(abspath.to_str().unwrap(), None)?; - module.filename = filename.to_string(); - - prog.pkgs - .insert(kclvm_ast::MAIN_PKG.to_string(), vec![filename.to_string()]); - - prog.modules - .insert(filename.to_string(), Arc::new(Lock::new(module))); - - Ok(prog) -} - -#[test] -fn test_scope() { - let mut scope = builtin_scope(); - for name in BUILTIN_FUNCTION_NAMES { - let obj = scope.lookup(name).unwrap(); - let obj_ref = obj.borrow_mut(); - assert!(obj_ref.ty.is_func()); - } - for name in BUILTIN_FUNCTION_NAMES { - scope.set_ty(name, Arc::new(Type::ANY)); - } - for name in BUILTIN_FUNCTION_NAMES { - let obj = scope.lookup(name).unwrap(); - let obj_ref = obj.borrow_mut(); - assert!(obj_ref.ty.is_any()); - } -} - -#[test] -fn test_resolve_program() { - let mut program = parse_program("./src/resolver/test_data/assign.k").unwrap(); - let scope = resolve_program(&mut program); - assert_eq!(scope.pkgpaths(), vec!["__main__".to_string()]); - let main_scope = scope.main_scope().unwrap(); - let main_scope = main_scope.borrow_mut(); - assert!(main_scope.lookup("a").is_some()); - assert!(main_scope.lookup("b").is_some()); - assert!(main_scope.lookup("print").is_none()); -} - -#[test] -fn test_resolve_program_with_cache() { - let mut program = parse_program("./src/resolver/test_data/assign.k").unwrap(); - - let scope = resolve_program_with_opts( - &mut program, - Options { - merge_program: false, - type_erasure: false, - ..Default::default() - }, - None, - ); - let cached_scope = Arc::new(RwLock::new(CachedScope::new(&scope, &program))); - let scope = resolve_program_with_opts( - &mut program, - Options { - merge_program: false, - type_erasure: false, - ..Default::default() - }, - Some(cached_scope), - ); - assert_eq!(scope.pkgpaths(), vec!["__main__".to_string()]); - let main_scope = scope.main_scope().unwrap(); - let main_scope = main_scope.borrow_mut(); - assert!(main_scope.lookup("a").is_some()); - assert!(main_scope.lookup("b").is_some()); - assert!(main_scope.lookup("print").is_none()); -} - -#[test] -fn test_pkg_init_in_schema_resolve() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/pkg_init_in_schema.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - assert_eq!( - scope.pkgpaths(), - vec!["__main__".to_string(), "pkg".to_string()] - ); - let module = &program.pkgs["pkg"][0]; - let module = program - .get_module(&module) - .expect("Failed to acquire module lock") - .expect(&format!("module {:?} not found in program", module)); - if let ast::Stmt::Schema(schema) = &module.body[1].node { - if let ast::Stmt::SchemaAttr(attr) = &schema.body[0].node { - let value = attr.value.as_ref().unwrap(); - if let ast::Expr::Schema(schema_expr) = &value.node { - assert_eq!(schema_expr.name.node.get_names(), vec!["Name".to_string()]); - } else { - panic!("test failed, expect schema expr, got {:?}", value) - } - } else { - panic!( - "test failed, expect schema attribute, got {:?}", - schema.body[0] - ) - } - } else { - panic!( - "test failed, expect schema statement, got {:?}", - module.body[1] - ) - } -} - -#[test] -fn test_resolve_program_fail() { - let work_dir = "./src/resolver/test_fail_data/"; - let cases = &[ - "attr.k", - "cannot_find_member_0.k", - "cannot_find_member_1.k", - "cannot_find_module.k", - "comp_clause_error_0.k", - "comp_clause_error_1.k", - "comp_clause_error_2.k", - "comp_clause_error_3.k", - "comp_clause_error_4.k", - "config_expr.k", - "invalid_mixin_0.k", - "lambda_schema_ty_0.k", - "lambda_schema_ty_1.k", - "lambda_schema_ty_2.k", - "lambda_schema_ty_3.k", - "module_optional_select.k", - "mutable_error_0.k", - "mutable_error_1.k", - "unique_key_error_0.k", - "unique_key_error_1.k", - "unmatched_index_sign_default_value.k", - "unmatched_args.k", - "unmatched_nest_schema_attr_0.k", - "unmatched_nest_schema_attr_1.k", - "unmatched_nest_schema_attr_2.k", - "unmatched_nest_schema_attr_3.k", - "unmatched_schema_attr_0.k", - "unmatched_schema_attr_1.k", - "unmatched_schema_attr_2.k", - "unmatched_schema_attr_3.k", - ]; - for case in cases { - let path = Path::new(work_dir).join(case); - let mut program = parse_program(&path.to_string_lossy()).unwrap(); - let scope = resolve_program(&mut program); - assert!(scope.handler.diagnostics.len() > 0, "{}", case); - } -} - -#[test] -fn test_resolve_program_redefine() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_fail_data/redefine_import/main.k"], - None, - None, - ) - .unwrap() - .program; - - let scope = resolve_program(&mut program); - assert_eq!(scope.handler.diagnostics.len(), 2); - let diag = &scope.handler.diagnostics[0]; - assert_eq!( - diag.code, - Some(DiagnosticId::Error(ErrorKind::CompileError)) - ); - assert_eq!(diag.messages.len(), 1); - assert_eq!( - diag.messages[0].message, - "the name 's' is defined multiple times, 's' must be defined only once" - ); -} - -#[test] -fn test_resolve_program_mismatch_type_fail() { - let mut program = parse_program("./src/resolver/test_fail_data/config_expr.k").unwrap(); - let scope = resolve_program(&mut program); - assert_eq!(scope.handler.diagnostics.len(), 1); - let diag = &scope.handler.diagnostics[0]; - assert_eq!(diag.code, Some(DiagnosticId::Error(ErrorKind::TypeError))); - assert_eq!(diag.messages.len(), 1); - assert_eq!( - diag.messages[0].message, - "expected int, got {str(key):int(1)}" - ); -} - -#[test] -fn test_resolve_program_cycle_reference_fail() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_fail_data/cycle_reference/file2.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - let err_messages = [ - "There is a circular reference between modules file1, file2", - "There is a circular reference between modules file1, file2", - "There is a circular reference between schemas file1.SchemaBase, file1.SchemaSub", - "There is a circular reference between schemas file1.SchemaBase, file1.SchemaSub", - "There is a circular reference between rules file1.RuleBase, file1.RuleSub", - "There is a circular reference between rules file1.RuleBase, file1.RuleSub", - "There is a circular reference between schemas file1.A, file1.B, file1.C", - "There is a circular reference between schemas file1.A, file1.B, file1.C", - "There is a circular reference between schemas file1.A, file1.B, file1.C", - "Module 'file1' imported but unused", - "Module 'file2' imported but unused", - ]; - assert_eq!(scope.handler.diagnostics.len(), err_messages.len()); - for (diag, msg) in scope.handler.diagnostics.iter().zip(err_messages.iter()) { - assert_eq!(diag.messages[0].message, msg.to_string(),); - } -} - -#[test] -fn test_record_used_module() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/record_used_module.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - let main_scope = scope - .scope_map - .get(kclvm_runtime::MAIN_PKG_PATH) - .unwrap() - .borrow_mut() - .clone(); - for (_, obj) in main_scope.elems { - let obj = obj.borrow_mut().clone(); - if let ScopeObjectKind::Module(m) = obj.kind { - for (_, used) in m.import_stmts { - if obj.name == "math" { - assert!(!used); - } else { - assert!(used); - } - } - } - } -} - -#[test] -fn test_resolve_program_illegal_attr_fail() { - let mut program = parse_program("./src/resolver/test_fail_data/attr.k").unwrap(); - let scope = resolve_program(&mut program); - assert_eq!(scope.handler.diagnostics.len(), 2); - let expect_err_msg = "A attribute must be string type, got 'Data'"; - let diag = &scope.handler.diagnostics[0]; - assert_eq!( - diag.code, - Some(DiagnosticId::Error(ErrorKind::IllegalAttributeError)) - ); - assert_eq!(diag.messages.len(), 1); - assert_eq!(diag.messages[0].range.0.line, 4); - assert_eq!(diag.messages[0].message, expect_err_msg,); - let diag = &scope.handler.diagnostics[1]; - assert_eq!( - diag.code, - Some(DiagnosticId::Error(ErrorKind::IllegalAttributeError)) - ); - assert_eq!(diag.messages.len(), 1); - assert_eq!(diag.messages[0].message, expect_err_msg,); - assert_eq!(diag.messages[0].range.0.line, 5); -} - -#[test] -fn test_resolve_program_unmatched_args_fail() { - let mut program = parse_program("./src/resolver/test_fail_data/unmatched_args.k").unwrap(); - let scope = resolve_program(&mut program); - assert_eq!(scope.handler.diagnostics.len(), 3); - let expect_err_msg = "\"Foo\" takes 1 positional argument but 3 were given"; - let diag = &scope.handler.diagnostics[0]; - assert_eq!( - diag.code, - Some(DiagnosticId::Error(ErrorKind::CompileError)) - ); - assert_eq!(diag.messages.len(), 1); - assert_eq!(diag.messages[0].range.0.line, 6); - assert_eq!(diag.messages[0].message, expect_err_msg); - - let expect_err_msg = "\"f\" takes 1 positional argument but 2 were given"; - let diag = &scope.handler.diagnostics[1]; - assert_eq!( - diag.code, - Some(DiagnosticId::Error(ErrorKind::CompileError)) - ); - assert_eq!(diag.messages.len(), 1); - assert_eq!(diag.messages[0].range.0.line, 7); - assert_eq!(diag.messages[0].message, expect_err_msg); - - let expect_err_msg = "\"Foo2\" takes 2 positional arguments but 3 were given"; - let diag = &scope.handler.diagnostics[2]; - assert_eq!( - diag.code, - Some(DiagnosticId::Error(ErrorKind::CompileError)) - ); - assert_eq!(diag.messages.len(), 1); - assert_eq!(diag.messages[0].range.0.line, 12); - assert_eq!(diag.messages[0].message, expect_err_msg); -} - -#[test] -fn test_resolve_program_module_optional_select_fail() { - let mut program = - parse_program("./src/resolver/test_fail_data/module_optional_select.k").unwrap(); - let scope = resolve_program(&mut program); - assert_eq!(scope.handler.diagnostics.len(), 2); - let expect_err_msg = - "For the module type, the use of '?.log' is unnecessary and it can be modified as '.log'"; - let diag = &scope.handler.diagnostics[0]; - assert_eq!( - diag.code, - Some(DiagnosticId::Error(ErrorKind::CompileError)) - ); - assert_eq!(diag.messages.len(), 1); - assert_eq!(diag.messages[0].range.0.line, 3); - assert_eq!(diag.messages[0].message, expect_err_msg); - - let expect_err_msg = "Module 'math' imported but unused"; - let diag = &scope.handler.diagnostics[1]; - assert_eq!( - diag.code, - Some(DiagnosticId::Warning(WarningKind::UnusedImportWarning)) - ); - assert_eq!(diag.messages.len(), 1); - assert_eq!(diag.messages[0].range.0.line, 1); - assert_eq!(diag.messages[0].message, expect_err_msg); -} - -#[test] -fn test_lint() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/lint.k"], - None, - None, - ) - .unwrap() - .program; - let opts = Options::default(); - pre_process_program(&mut program, &opts); - let mut resolver = Resolver::new(&program, opts); - resolver.resolve_import(); - resolver.check_and_lint_all_pkgs(); - - let root = &program.root.clone(); - let filename = Path::new(&root.clone()) - .join("lint.k") - .display() - .to_string(); - let mut handler = Handler::default(); - handler.add_warning( - WarningKind::ImportPositionWarning, - &[Message { - range: ( - Position { - filename: filename.clone(), - line: 11, - column: Some(0), - }, - Position { - filename: filename.clone(), - line: 11, - column: Some(20), - }, - ), - style: Style::Line, - message: format!("The import stmt should be placed at the top of the module"), - note: Some("Consider moving tihs statement to the top of the file".to_string()), - suggested_replacement: None, - }], - ); - handler.add_warning( - WarningKind::ReimportWarning, - &[Message { - range: ( - Position { - filename: filename.clone(), - line: 2, - column: Some(0), - }, - Position { - filename: filename.clone(), - line: 2, - column: Some(20), - }, - ), - style: Style::Line, - message: format!("Module 'a' is reimported multiple times"), - note: Some("Consider removing this statement".to_string()), - suggested_replacement: None, - }], - ); - handler.add_warning( - WarningKind::UnusedImportWarning, - &[Message { - range: ( - Position { - filename: filename.clone(), - line: 1, - column: Some(0), - }, - Position { - filename: filename.clone(), - line: 1, - column: Some(20), - }, - ), - style: Style::Line, - message: format!("Module 'a' imported but unused"), - note: Some("Consider removing this statement".to_string()), - suggested_replacement: None, - }], - ); - for (d1, d2) in resolver - .linter - .handler - .diagnostics - .iter() - .zip(handler.diagnostics.iter()) - { - assert_eq!(d1, d2); - } -} - -#[test] -fn test_resolve_schema_doc() { - let mut program = parse_program("./src/resolver/test_data/doc.k").unwrap(); - let scope = resolve_program(&mut program); - let main_scope = scope - .scope_map - .get(kclvm_runtime::MAIN_PKG_PATH) - .unwrap() - .borrow_mut() - .clone(); - - let schema_scope_obj = &main_scope.elems[0].borrow().clone(); - let schema_summary = match &schema_scope_obj.ty.kind { - TypeKind::Schema(schema_ty) => schema_ty.doc.clone(), - _ => "".to_string(), - }; - - let schema_scope = &main_scope.children[0]; - let attrs_scope = &schema_scope.borrow().elems; - assert_eq!("Server is the common user interface for long-running services adopting the best practice of Kubernetes.".to_string(), schema_summary); - assert_eq!( - Some( - "Use this attribute to specify which kind of long-running service you want. -Valid values: Deployment, CafeDeployment. -See also: kusion_models/core/v1/workload_metadata.k." - .to_string() - ), - attrs_scope.get("workloadType").unwrap().borrow().doc - ); - assert_eq!( - Some( - "A Server-level attribute. -The name of the long-running service. -See also: kusion_models/core/v1/metadata.k." - .to_string() - ), - attrs_scope.get("name").unwrap().borrow().doc - ); - assert_eq!( - Some( - "A Server-level attribute. -The labels of the long-running service. -See also: kusion_models/core/v1/metadata.k." - .to_string() - ), - attrs_scope.get("labels").unwrap().borrow().doc - ); -} - -#[test] -fn test_pkg_scope() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/pkg_scope.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - - assert_eq!(scope.scope_map.len(), 2); - let main_scope = scope - .scope_map - .get(kclvm_runtime::MAIN_PKG_PATH) - .unwrap() - .borrow_mut() - .clone(); - let pkg_scope = scope.scope_map.get("pkg").unwrap().borrow_mut().clone(); - - let root = &program.root.clone(); - let filename = Path::new(&root.clone()) - .join("pkg_scope.k") - .display() - .to_string(); - - let pos = Position { - filename: filename.clone(), - line: 2, - column: Some(0), - }; - - assert!(main_scope.contains_pos(&pos)); - - let filename = Path::new(&root.clone()) - .join("pkg") - .join("pkg.k") - .display() - .to_string(); - - let pos = Position { - filename: filename.clone(), - line: 4, - column: Some(0), - }; - - assert!(pkg_scope.contains_pos(&pos)); -} - -#[test] -fn test_system_package() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/system_package.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - let main_scope = scope - .scope_map - .get(kclvm_runtime::MAIN_PKG_PATH) - .unwrap() - .borrow_mut() - .clone(); - - assert!(main_scope.lookup("base64").unwrap().borrow().ty.is_module()); - assert!(main_scope - .lookup("base64_encode") - .unwrap() - .borrow() - .ty - .is_func()); - assert!(main_scope - .lookup("base64_decode") - .unwrap() - .borrow() - .ty - .is_func()); - - // Add assertions for base32 module - assert!(main_scope.lookup("base32").unwrap().borrow().ty.is_module()); - assert!(main_scope - .lookup("base32_encode") - .unwrap() - .borrow() - .ty - .is_func()); - assert!(main_scope - .lookup("base32_decode") - .unwrap() - .borrow() - .ty - .is_func()); -} - -#[test] -fn test_resolve_program_import_suggest() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_fail_data/not_found_suggest/main.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - assert_eq!(scope.handler.diagnostics.len(), 2); - let diag = &scope.handler.diagnostics[0]; - assert_eq!( - diag.code, - Some(DiagnosticId::Error(ErrorKind::CompileError)) - ); - assert_eq!(diag.messages.len(), 1); - assert_eq!( - diag.messages[0].message, - "name 's' is not defined, did you mean '[\"s1\"]'?" - ); -} - -#[test] -fn test_resolve_assignment_in_lambda() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/assign_in_lambda.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - let main_scope = scope.scope_map.get("__main__").unwrap().clone(); - assert_eq!(main_scope.borrow().children.len(), 1); - let lambda_scope = main_scope.borrow().children[0].clone(); - assert_eq!(lambda_scope.borrow().elems.len(), 2); - let images_scope_obj = lambda_scope.borrow().elems.get("images").unwrap().clone(); - assert_eq!(images_scope_obj.borrow().ty.ty_str(), "[str]"); -} - -#[test] -fn test_resolve_function_with_default_values() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/function_with_default_values.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - assert!(!scope.handler.has_errors()); - let main_scope = scope.main_scope().unwrap(); - let func = main_scope.borrow().lookup("is_alpha").unwrap(); - assert!(func.borrow().ty.is_func()); - let func_ty = func.borrow().ty.into_func_type(); - assert_eq!(func_ty.params.len(), 3); - assert_eq!(func_ty.params[0].has_default, false); - assert_eq!(func_ty.params[1].has_default, true); - assert_eq!(func_ty.params[2].has_default, true); -} - -#[test] -fn test_assignment_type_annotation_check_in_lambda() { - let sess = Arc::new(ParseSession::default()); - let opts = LoadProgramOptions::default(); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/annotation_check_assignment.k"], - Some(opts), - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - assert_eq!(scope.handler.diagnostics.len(), 0); -} - -#[test] -fn test_resolve_lambda_assignment_diagnostic() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_fail_data/lambda_ty_error.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - assert_eq!(scope.handler.diagnostics.len(), 1); - let diag = &scope.handler.diagnostics[0]; - assert_eq!(diag.code, Some(DiagnosticId::Error(ErrorKind::TypeError))); - assert_eq!(diag.messages.len(), 1); - assert_eq!( - diag.messages[0].message, - "expected (int, int) -> int, got (int, int) -> str" - ); -} - -#[test] -fn test_ty_check_in_dict_assign_to_schema() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/attr_ty_check.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - assert_eq!(scope.handler.diagnostics.len(), 2); - let diag = &scope.handler.diagnostics[0]; - assert_eq!(diag.code, Some(DiagnosticId::Error(ErrorKind::TypeError))); - assert_eq!(diag.messages.len(), 2); - assert_eq!(diag.messages[0].message, "expected int, got str(1)"); - assert_eq!( - diag.messages[1].message, - "variable is defined here, its type is int, but got str(1)" - ); -} - -#[test] -fn test_pkg_not_found_suggestion() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/pkg_not_found_suggestion.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - assert_eq!(scope.handler.diagnostics.len(), 4); - let diag = &scope.handler.diagnostics[1]; - assert_eq!(diag.code, Some(DiagnosticId::Suggestions)); - assert_eq!(diag.messages.len(), 1); - assert_eq!( - diag.messages[0].message, - "try 'kcl mod add k9s' to download the missing package" - ); - let diag = &scope.handler.diagnostics[2]; - assert_eq!(diag.code, Some(DiagnosticId::Suggestions)); - assert_eq!(diag.messages.len(), 1); - assert_eq!( - diag.messages[0].message, - "browse more packages at 'https://artifacthub.io'" - ); -} - -#[test] -fn undef_lambda_param() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/undef_lambda_param.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - assert_eq!(scope.handler.diagnostics.len(), 1); - - let root = &program.root.clone(); - let filename = Path::new(&root.clone()) - .join("undef_lambda_param.k") - .display() - .to_string(); - - let range = scope.handler.diagnostics[0].messages[0].range.clone(); - - assert_eq!( - range, - ( - Position { - filename: filename.clone(), - line: 1, - column: Some(10), - }, - Position { - filename: filename.clone(), - line: 1, - column: Some(15), - } - ) - ); -} - -#[test] -fn test_schema_params_count() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/schema_params_miss.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - assert_eq!(scope.handler.diagnostics.len(), 1); - let diag = &scope.handler.diagnostics[0]; - assert_eq!( - diag.code, - Some(DiagnosticId::Error(ErrorKind::CompileError)) - ); - assert_eq!(diag.messages.len(), 1); - assert_eq!( - diag.messages[0].message, - "expected 1 positional argument, found 0" - ); -} - -#[test] -fn test_set_ty_in_lambda() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/ty_in_lambda.k"], - None, - None, - ) - .unwrap() - .program; - assert_eq!( - resolve_program(&mut program) - .main_scope() - .unwrap() - .borrow() - .lookup("result") - .unwrap() - .borrow() - .ty - .clone() - .ty_str(), - "{str:str}" - ); -} - -#[test] -fn test_pkg_asname() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/pkg_asname/pkg_asname.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - let diags = scope.handler.diagnostics; - assert_eq!(diags.len(), 4); - assert_eq!(diags[0].messages[0].message, "name 'pkg' is not defined"); - assert_eq!(diags[1].messages[0].message, "name 'subpkg' is not defined"); -} - -#[test] -fn test_builtin_file_invalid() { - let test_cases = [ - ( - "./src/resolver/test_data/test_builtin/read.k", - "expected 1 positional argument, found 0", - ), - ( - "./src/resolver/test_data/test_builtin/glob.k", - "expected 1 positional argument, found 0", - ), - ]; - - for (file, expected_message) in &test_cases { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program(sess.clone(), &[file], None, None) - .unwrap() - .program; - let scope = resolve_program(&mut program); - let diags = scope.handler.diagnostics; - assert_eq!(diags.len(), 1); - assert_eq!(diags[0].messages[0].message, *expected_message); - } -} - -#[test] -fn test_schema_index_signature_check() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/index_signature_check.k"], - None, - None, - ) - .unwrap() - .program; - let scope = resolve_program(&mut program); - let diags = scope.handler.diagnostics; - assert!(diags.is_empty()) -} - -#[test] -fn test_clear_cache_by_module() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/cache/main.k"], - None, - None, - ) - .unwrap() - .program; - - let scope = resolve_program_with_opts( - &mut program, - Options { - merge_program: false, - type_erasure: false, - ..Default::default() - }, - None, - ); - let cached_scope = Arc::new(RwLock::new(CachedScope::new(&scope, &program))); - // first compile - let _ = resolve_program_with_opts( - &mut program, - Options { - merge_program: false, - type_erasure: false, - ..Default::default() - }, - Some(cached_scope.clone()), - ); - - // recompile and clear cache - let invalidate_module = std::fs::canonicalize(std::path::PathBuf::from( - "./src/resolver/test_data/cache/main.k", - )) - .unwrap() - .to_str() - .unwrap() - .to_string() - .adjust_canonicalization(); - - if let Some(mut cached_scope) = cached_scope.try_write() { - let mut invalidate_pkg_modules = HashSet::new(); - invalidate_pkg_modules.insert(invalidate_module); - cached_scope.invalidate_pkg_modules = Some(invalidate_pkg_modules); - }; - - let _ = resolve_program_with_opts( - &mut program, - Options { - merge_program: false, - type_erasure: false, - ..Default::default() - }, - Some(cached_scope.clone()), - ); - if let Some(cached_scope) = cached_scope.try_write() { - // main - a - // - b - c - // invalidate main, invalidate_pkgs main - let mut expect = HashSet::new(); - expect.insert(MAIN_PKG.to_string()); - assert_eq!(cached_scope.invalidate_pkgs, expect); - }; - - // recompile and clear cache - let invalidate_module = std::fs::canonicalize(std::path::PathBuf::from( - "./src/resolver/test_data/cache/a/a.k", - )) - .unwrap() - .to_str() - .unwrap() - .to_string() - .adjust_canonicalization(); - - if let Some(mut cached_scope) = cached_scope.try_write() { - let mut invalidate_pkg_modules = HashSet::new(); - invalidate_pkg_modules.insert(invalidate_module); - cached_scope.invalidate_pkg_modules = Some(invalidate_pkg_modules); - }; - - let _ = resolve_program_with_opts( - &mut program, - Options { - merge_program: false, - type_erasure: false, - ..Default::default() - }, - Some(cached_scope.clone()), - ); - - if let Some(cached_scope) = cached_scope.try_write() { - // main - a - // - b - c - // invalidate a, invalidate_pkgs a, main - let mut expect = HashSet::new(); - expect.insert(MAIN_PKG.to_string()); - expect.insert("cache.a".to_string()); - assert_eq!(cached_scope.invalidate_pkgs, expect); - }; - - // recompile and clear cache - let invalidate_module = std::fs::canonicalize(std::path::PathBuf::from( - "./src/resolver/test_data/cache/b/b.k", - )) - .unwrap() - .to_str() - .unwrap() - .to_string() - .adjust_canonicalization(); - - if let Some(mut cached_scope) = cached_scope.try_write() { - let mut invalidate_pkg_modules = HashSet::new(); - invalidate_pkg_modules.insert(invalidate_module); - cached_scope.invalidate_pkg_modules = Some(invalidate_pkg_modules); - }; - - let _ = resolve_program_with_opts( - &mut program, - Options { - merge_program: false, - type_erasure: false, - ..Default::default() - }, - Some(cached_scope.clone()), - ); - - if let Some(cached_scope) = cached_scope.try_write() { - // main - a - // - b - c - // invalidate b, invalidate_pkgs b, main - let mut expect = HashSet::new(); - expect.insert(MAIN_PKG.to_string()); - expect.insert("cache.b".to_string()); - assert_eq!(cached_scope.invalidate_pkgs, expect); - }; - - // recompile and clear cache - let invalidate_module = std::fs::canonicalize(std::path::PathBuf::from( - "./src/resolver/test_data/cache/c/c.k", - )) - .unwrap() - .to_str() - .unwrap() - .to_string() - .adjust_canonicalization(); - - if let Some(mut cached_scope) = cached_scope.try_write() { - let mut invalidate_pkg_modules = HashSet::new(); - invalidate_pkg_modules.insert(invalidate_module); - cached_scope.invalidate_pkg_modules = Some(invalidate_pkg_modules); - }; - - let _ = resolve_program_with_opts( - &mut program, - Options { - merge_program: false, - type_erasure: false, - ..Default::default() - }, - Some(cached_scope.clone()), - ); - - if let Some(cached_scope) = cached_scope.try_write() { - // main - a - // - b - c - // invalidate c, invalidate_pkgs c, b, main - let mut expect = HashSet::new(); - expect.insert(MAIN_PKG.to_string()); - expect.insert("cache.b".to_string()); - expect.insert("cache.c".to_string()); - assert_eq!(cached_scope.invalidate_pkgs, expect); - }; -} - -#[test] -fn clear_cache_test() { - let sess = Arc::new(ParseSession::default()); - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/cache/main.k"], - None, - None, - ) - .unwrap() - .program; - - let scope_cache = Arc::new(RwLock::new(CachedScope::default())); - let first_scope = resolve_program_with_opts( - &mut program, - Options { - merge_program: false, - type_erasure: false, - ..Default::default() - }, - Some(scope_cache.clone()), - ); - - let mut program = load_program( - sess.clone(), - &["./src/resolver/test_data/cache/main.k"], - None, - None, - ) - .unwrap() - .program; - - let second_scope = resolve_program_with_opts( - &mut program, - Options { - merge_program: false, - type_erasure: false, - ..Default::default() - }, - Some(scope_cache.clone()), - ); - let first_node_ty_map_len = first_scope.node_ty_map.borrow().len(); - let second_node_ty_map_len = second_scope.node_ty_map.borrow().len(); - assert_eq!(first_node_ty_map_len, second_node_ty_map_len); - assert_eq!(first_scope.scope_map.len(), second_scope.scope_map.len()); - assert_eq!( - first_scope.schema_mapping.len(), - second_scope.schema_mapping.len() - ); -} diff --git a/kclvm/sema/src/resolver/ty.rs b/kclvm/sema/src/resolver/ty.rs deleted file mode 100644 index 0a73e2f2e..000000000 --- a/kclvm/sema/src/resolver/ty.rs +++ /dev/null @@ -1,636 +0,0 @@ -use std::sync::Arc; - -use super::node::ResolvedResult; -use crate::resolver::Resolver; -use crate::ty::parser::parse_type_str; -use crate::ty::{ - assignable_to, is_upper_bound, Attr, DictType, Parameter, SchemaType, Type, TypeKind, TypeRef, -}; -use kclvm_ast::ast; -use kclvm_ast::pos::GetPos; -use kclvm_error::diagnostic::Range; -use kclvm_error::*; -use kclvm_primitives::IndexMap; - -fn ty_str_to_pkgpath(ty_str: &str) -> &str { - let splits: Vec<&str> = ty_str.rsplitn(2, '.').collect(); - let len = splits.len(); - splits[len - 1] -} - -pub fn ty_str_replace_pkgpath(ty_str: &str, pkgpath: &str) -> String { - let pkgpath = format!("@{}", pkgpath); - if ty_str.contains('.') && ty_str_to_pkgpath(ty_str) == pkgpath { - ty_str.replacen(&format!("{}.", pkgpath), "", 1) - } else { - ty_str.to_string() - } -} - -impl<'ctx> Resolver<'_> { - #[inline] - pub fn any_ty(&self) -> TypeRef { - self.ctx.ty_ctx.builtin_types.any.clone() - } - #[inline] - pub fn int_ty(&self) -> TypeRef { - self.ctx.ty_ctx.builtin_types.int.clone() - } - #[inline] - pub fn float_ty(&self) -> TypeRef { - self.ctx.ty_ctx.builtin_types.float.clone() - } - #[inline] - pub fn bool_ty(&self) -> TypeRef { - self.ctx.ty_ctx.builtin_types.bool.clone() - } - #[inline] - pub fn str_ty(&self) -> TypeRef { - self.ctx.ty_ctx.builtin_types.str.clone() - } - #[inline] - pub fn none_ty(&self) -> TypeRef { - self.ctx.ty_ctx.builtin_types.none.clone() - } - #[inline] - pub fn void_ty(&self) -> TypeRef { - self.ctx.ty_ctx.builtin_types.void.clone() - } - /// Parse the type string with the scope, if parse_ty returns a Named type(schema type or type alias), - /// found it from the scope. - pub fn parse_ty_with_scope( - &mut self, - ty_node: Option<&ast::Node>, - range: Range, - ) -> ResolvedResult { - let ty: TypeRef = if let Some(ty) = ty_node { - Arc::new(ty.node.clone().into()) - } else { - Arc::new(Type::ANY) - }; - // If a named type, find it from scope to get the specific type - let ret_ty = self.upgrade_named_ty_with_scope(ty.clone(), &range, ty_node); - self.add_type_alias( - &ty.into_type_annotation_str(), - &ret_ty.into_type_annotation_str(), - ); - if let Some(ty) = ty_node { - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(ty.id.clone()), ret_ty.clone()); - }; - ret_ty - } - - pub fn parse_ty_str_with_scope(&mut self, ty_str: &str, range: Range) -> ResolvedResult { - let ty: TypeRef = parse_type_str(ty_str); - // If a named type, find it from scope to get the specific type - let ret_ty = self.upgrade_named_ty_with_scope(ty, &range, None); - self.add_type_alias(ty_str, &ret_ty.into_type_annotation_str()); - ret_ty - } - - /// The given expression must be the expected type. - #[inline] - pub fn must_be_type(&mut self, expr: &'ctx ast::NodeRef, expected_ty: TypeRef) { - let ty = self.expr(expr); - self.must_assignable_to(ty, expected_ty, expr.get_span_pos(), None); - } - - /// Must assignable to the expected type. - #[inline] - pub fn must_assignable_to( - &mut self, - ty: TypeRef, - expected_ty: TypeRef, - range: Range, - def_range: Option, - ) { - self.attr_must_assignable_to(ty, expected_ty, range, def_range, None); - } - - /// Attribute must assignable to the expected type. - pub fn attr_must_assignable_to( - &mut self, - ty: TypeRef, - expected_ty: TypeRef, - range: Range, - def_range: Option, - attr_range: Option, - ) { - if !self.check_type(ty.clone(), expected_ty.clone(), &range) { - let mut msgs = vec![Message { - range, - style: Style::LineAndColumn, - message: format!("expected {}, got {}", expected_ty.ty_str(), ty.ty_str(),), - note: None, - suggested_replacement: None, - }]; - - if let Some(def_range) = def_range { - // If the range is not a dummy range, append the definition error message - // in the diagnostic. - if !def_range.0.filename.is_empty() && !def_range.1.filename.is_empty() { - msgs.push(Message { - range: def_range, - style: Style::LineAndColumn, - message: format!( - "variable is defined here, its type is {}, but got {}", - expected_ty.ty_str(), - ty.ty_str(), - ), - note: None, - suggested_replacement: None, - }); - } - } - if let Some(attr_range) = attr_range { - msgs.push(Message { - range: attr_range.clone(), - style: Style::LineAndColumn, - message: "config attribute is defined here".to_string(), - note: None, - suggested_replacement: None, - }); - } - self.handler.add_error(ErrorKind::TypeError, &msgs); - } - } - - // Upgrade the dict type into schema type if it is expected to schema - pub(crate) fn upgrade_dict_to_schema(&mut self, ty: TypeRef, expected_ty: TypeRef) -> TypeRef { - match (&ty.kind, &expected_ty.kind) { - (TypeKind::Dict(dict_ty), TypeKind::Schema(schema_ty)) => { - if self.upgrade_dict_to_schema_attr_check(dict_ty, schema_ty) { - expected_ty - } else { - ty - } - } - (TypeKind::List(item_ty), TypeKind::List(expected_item_ty)) => { - Type::list(self.upgrade_dict_to_schema(item_ty.clone(), expected_item_ty.clone())) - .into() - } - ( - TypeKind::Dict(DictType { key_ty, val_ty, .. }), - TypeKind::Dict(DictType { - key_ty: expected_key_ty, - val_ty: expected_val_ty, - .. - }), - ) => Type::dict( - self.upgrade_dict_to_schema(key_ty.clone(), expected_key_ty.clone()), - self.upgrade_dict_to_schema(val_ty.clone(), expected_val_ty.clone()), - ) - .into(), - (TypeKind::Dict(dict_ty), TypeKind::Union(expected_union_type)) => { - let types: Vec> = expected_union_type - .iter() - .filter(|ty| match ty.kind { - TypeKind::Schema(_) => true, - _ => false, - }) - .filter(|ty| { - self.upgrade_dict_to_schema_attr_check(dict_ty, &ty.into_schema_type()) - }) - .map(|ty| ty.clone()) - .collect(); - crate::ty::sup(&types).into() - } - _ => ty, - } - } - - /// Check the type assignment statement between type annotation and target. - pub fn check_assignment_type_annotation( - &mut self, - assign_stmt: &kclvm_ast::ast::AssignStmt, - value_ty: TypeRef, - ) { - if assign_stmt.ty.is_none() { - return; - } - for target in &assign_stmt.targets { - let name = &target.node.name.node; - // If the assignment statement has type annotation, check the type of value and the type annotation of target - - if let Some(ty_annotation) = &assign_stmt.ty { - let annotation_ty = - self.parse_ty_with_scope(Some(&ty_annotation), ty_annotation.get_span_pos()); - // If the target defined in the scope, check the type of value and the type annotation of target - let target_ty = if let Some(obj) = self.scope.borrow().elems.get(name) { - let obj = obj.borrow(); - if obj.ty.is_any() { - annotation_ty - } else { - if !is_upper_bound(annotation_ty.clone(), obj.ty.clone()) { - self.handler.add_error( - ErrorKind::TypeError, - &[ - Message { - range: target.get_span_pos(), - style: Style::LineAndColumn, - message: format!( - "can not change the type of '{}' to {}", - name, - annotation_ty.ty_str() - ), - note: None, - suggested_replacement: None, - }, - Message { - range: obj.get_span_pos(), - style: Style::LineAndColumn, - message: format!("expected {}", obj.ty.ty_str()), - note: None, - suggested_replacement: None, - }, - ], - ); - } - obj.ty.clone() - } - } else { - annotation_ty - }; - - self.set_type_to_scope(name, target_ty.clone(), &target.node.name); - - // Check if this is a list assignment with schema type annotation - let is_list_with_schema_elements = match (&target_ty.kind, &value_ty.kind) { - (TypeKind::List(expected_item_ty), TypeKind::List(_)) => { - // Check if the expected type is a Schema - match &expected_item_ty.kind { - TypeKind::Schema(_) => true, - _ => false, - } - } - _ => false, - }; - - // For list with schema elements, we need stricter checking - if is_list_with_schema_elements { - // Type checking for lists with schema elements should be stricter to - // ensure all elements are of the expected schema type - self.must_assignable_to( - value_ty.clone(), - target_ty.clone(), - target.get_span_pos(), - None, - ); - } else { - // Regular type checking for other types - self.must_assignable_to( - value_ty.clone(), - target_ty, - target.get_span_pos(), - None, - ) - } - } - } - } - - /// The check type main function, returns a boolean result. - #[inline] - pub fn check_type(&mut self, ty: TypeRef, expected_ty: TypeRef, range: &Range) -> bool { - // Check assignable between types. - match (&ty.kind, &expected_ty.kind) { - (TypeKind::List(item_ty), TypeKind::List(expected_item_ty)) => { - // Check that the item type of the list is assignable to the expected item type - self.check_type(item_ty.clone(), expected_item_ty.clone(), range) - } - ( - TypeKind::Dict(DictType { key_ty, val_ty, .. }), - TypeKind::Dict(DictType { - key_ty: expected_key_ty, - val_ty: expected_val_ty, - .. - }), - ) => { - self.check_type(key_ty.clone(), expected_key_ty.clone(), range) - && self.check_type(val_ty.clone(), expected_val_ty.clone(), range) - } - (TypeKind::Dict(dict_ty), TypeKind::Schema(schema_ty)) => { - self.dict_assignable_to_schema(dict_ty, schema_ty, range) - } - (TypeKind::Union(types), _) => types - .iter() - .all(|ty| self.check_type(ty.clone(), expected_ty.clone(), range)), - (_, TypeKind::Union(types)) => types - .iter() - .any(|expected_ty| self.check_type(ty.clone(), expected_ty.clone(), range)), - _ => assignable_to(ty, expected_ty), - } - } - - /// Judge a dict can be converted to schema in compile time - /// Do relaxed schema check key and value type check. - pub(crate) fn dict_assignable_to_schema( - &mut self, - dict_ty: &DictType, - schema_ty: &SchemaType, - range: &Range, - ) -> bool { - let (key_ty, val_ty) = (dict_ty.key_ty.clone(), dict_ty.val_ty.clone()); - if let Some(index_signature) = &schema_ty.index_signature { - let val_ty = match (&key_ty.kind, &val_ty.kind) { - (TypeKind::Union(key_tys), TypeKind::Union(val_tys)) => { - let mut index_signature_val_tys: Vec = vec![]; - for (i, key_ty) in key_tys.iter().enumerate() { - if let TypeKind::StrLit(s) = &key_ty.kind { - if schema_ty.attrs.get(s).is_none() && val_tys.get(i).is_some() { - index_signature_val_tys.push(val_tys.get(i).unwrap().clone()); - } - } - } - crate::ty::sup(&index_signature_val_tys).into() - } - _ => val_ty, - }; - if dict_ty.attrs.is_empty() { - if !self.check_type(val_ty.clone(), index_signature.val_ty.clone(), range) { - self.handler.add_type_error( - &format!( - "expected schema index signature value type {}, got {}", - index_signature.val_ty.ty_str(), - val_ty.ty_str() - ), - range.clone(), - ); - } - } else { - for (name, attr) in &dict_ty.attrs { - if index_signature.any_other { - if let Some(attr_obj) = schema_ty.attrs.get(name) { - self.must_assignable_to( - attr.ty.clone(), - attr_obj.ty.clone(), - range.clone(), - Some(attr_obj.range.clone()), - ); - } else { - self.must_assignable_to( - attr.ty.clone(), - index_signature.val_ty.clone(), - attr.range.clone(), - None, - ); - } - } else { - self.must_assignable_to( - attr.ty.clone(), - index_signature.val_ty.clone(), - attr.range.clone(), - None, - ); - } - } - } - true - } else { - // When assigning a dict type to an instance of a schema type, - // check whether the type of key value pair in dict matches the attribute type in the schema. - if let TypeKind::StrLit(key_name) = &key_ty.kind { - if let Some(attr_obj) = schema_ty.attrs.get(key_name) { - if let Some(attr) = dict_ty.attrs.get(key_name) { - self.must_assignable_to( - attr.ty.clone(), - attr_obj.ty.clone(), - range.clone(), - Some(attr_obj.range.clone()), - ); - } - return true; - } - } - true - } - } - - /// Judge a dict can be upgrade to schema. - /// More strict than `dict_assign_to_schema()`: schema attr contains all attributes in key - pub fn upgrade_dict_to_schema_attr_check( - &mut self, - dict_ty: &DictType, - schema_ty: &SchemaType, - ) -> bool { - if schema_ty.index_signature.is_some() { - return true; - } - match &dict_ty.key_ty.kind { - // empty dict {} - TypeKind::Any => true, - // single key: {key1: value1} - TypeKind::StrLit(s) => schema_ty.attrs.len() >= 1 && schema_ty.attrs.contains_key(s), - // multi key: { - // key1: value1 - // key2: value2 - // ... - // } - TypeKind::Union(types) => { - let (attrs, has_index_signature) = Self::get_schema_attrs(schema_ty); - match (attrs.len() >= types.len(), has_index_signature) { - (true, _) => types.iter().all(|ty| match &ty.kind { - TypeKind::StrLit(s) => attrs.contains(s), - _ => false, - }), - // TODO: do more index_signature check with dict type attrs - (false, true) => true, - (false, false) => false, - } - } - _ => false, - } - } - - fn get_schema_attrs(schema_ty: &SchemaType) -> (Vec, bool) { - let mut attrs: Vec = schema_ty.attrs.keys().map(|attr| attr.clone()).collect(); - let mut has_index_signature = schema_ty.index_signature.is_some(); - if let Some(base) = &schema_ty.base { - let (base_attrs, index_signature) = Self::get_schema_attrs(base); - attrs.extend(base_attrs); - has_index_signature &= index_signature; - } - (attrs, has_index_signature) - } - - fn upgrade_named_ty_with_scope( - &mut self, - ty: TypeRef, - range: &Range, - ty_node: Option<&ast::Node>, - ) -> ResolvedResult { - match &ty.kind { - TypeKind::List(item_ty) => { - let mut inner_node = None; - if let Some(ty_node) = ty_node { - if let ast::Type::List(list_type) = &ty_node.node { - inner_node = list_type.inner_type.as_ref().map(|ty| ty.as_ref()) - } - }; - Type::list_ref(self.upgrade_named_ty_with_scope(item_ty.clone(), range, inner_node)) - } - TypeKind::Dict(DictType { - key_ty, - val_ty, - attrs, - }) => { - let mut key_node = None; - let mut value_node = None; - if let Some(ty_node) = ty_node { - if let ast::Type::Dict(dict_type) = &ty_node.node { - key_node = dict_type.key_type.as_ref().map(|ty| ty.as_ref()); - value_node = dict_type.value_type.as_ref().map(|ty| ty.as_ref()); - } - }; - Type::dict_ref_with_attrs( - self.upgrade_named_ty_with_scope(key_ty.clone(), range, key_node), - self.upgrade_named_ty_with_scope(val_ty.clone(), range, value_node), - attrs - .into_iter() - .map(|(key, attr)| { - ( - key.to_string(), - Attr { - ty: self.upgrade_named_ty_with_scope( - val_ty.clone(), - range, - None, - ), - range: attr.range.clone(), - }, - ) - }) - .collect(), - ) - } - TypeKind::Union(types) => Type::union_ref( - &types - .iter() - .enumerate() - .map(|(index, ty)| { - let mut elem_node = None; - if let Some(ty_node) = ty_node { - if let ast::Type::Union(union_type) = &ty_node.node { - elem_node = - union_type.type_elements.get(index).map(|ty| ty.as_ref()) - } - }; - self.upgrade_named_ty_with_scope(ty.clone(), range, elem_node) - }) - .collect::>(), - ), - TypeKind::Named(ty_str) => { - let ty_str = ty_str_replace_pkgpath(ty_str, &self.ctx.pkgpath); - let names: Vec<&str> = if ty_str.starts_with('@') { - let names: Vec<&str> = ty_str.rsplitn(2, '.').collect(); - names.iter().rev().cloned().collect() - } else { - ty_str.split('.').collect() - }; - if names.is_empty() { - self.handler - .add_compile_error("missing type annotation", range.clone()); - return self.any_ty(); - } - let mut pkgpath = "".to_string(); - let name = names[0]; - if names.len() > 1 && !self.ctx.local_vars.contains(&name.to_string()) { - if let Some(mapping) = self.ctx.import_names.get(&self.ctx.filename) { - pkgpath = mapping - .get(name) - .map_or("".to_string(), |pkgpath| pkgpath.to_string()); - } - } - self.ctx.l_value = false; - let tys = self.resolve_var( - &names.iter().map(|n| n.to_string()).collect::>(), - &pkgpath, - range.clone(), - ); - - if let Some(ty_node) = ty_node { - if let ast::Type::Named(identifier) = &ty_node.node { - for (index, name) in identifier.names.iter().enumerate() { - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(name.id.clone()), tys[index].clone()); - } - let ident_ty = tys.last().unwrap().clone(); - self.node_ty_map - .borrow_mut() - .insert(self.get_node_key(ty_node.id.clone()), ident_ty.clone()); - } - }; - tys.last().unwrap().clone() - } - TypeKind::Function(fn_ty) => { - // Replace the type 'Named' to the real type in function params and return type - let mut params_ty = vec![]; - let mut ret_ty = Type::any_ref(); - if let Some(ty_node) = ty_node { - if let ast::Type::Function(fn_ast_type) = &ty_node.node { - if let Some(params_ast_ty) = fn_ast_type.params_ty.as_ref() { - for (ast_ty, ty) in params_ast_ty.iter().zip(fn_ty.params.iter()) { - params_ty.push(Parameter { - name: ty.name.clone(), - ty: self.upgrade_named_ty_with_scope( - ty.ty.clone(), - range, - Some(ast_ty.as_ref()), - ), - has_default: ty.has_default, - default_value: ty.default_value.clone(), - range: ty_node.get_span_pos(), - }); - } - } - - ret_ty = if let Some(ret_ast_ty) = fn_ast_type.ret_ty.as_ref() { - self.upgrade_named_ty_with_scope( - fn_ty.return_ty.clone(), - range, - Some(ret_ast_ty.as_ref()), - ) - } else { - Type::any_ref() - }; - } - }; - - Arc::new(Type::function( - fn_ty.self_ty.clone(), - ret_ty, - params_ty.as_slice(), - &fn_ty.doc, - fn_ty.is_variadic, - fn_ty.kw_only_index, - )) - } - _ => ty.clone(), - } - } - - pub fn add_type_alias(&mut self, name: &str, alias: &str) { - if alias.starts_with('@') { - if name == &alias[1..] { - return; - } - } else if name == alias { - return; - } - match self.ctx.type_alias_mapping.get_mut(&self.ctx.pkgpath) { - Some(mapping) => { - mapping.insert(name.to_string(), alias.to_string()); - } - None => { - let mut mapping = IndexMap::default(); - mapping.insert(name.to_string(), alias.to_string()); - self.ctx - .type_alias_mapping - .insert(self.ctx.pkgpath.clone(), mapping); - } - } - } -} diff --git a/kclvm/sema/src/ty/context.rs b/kclvm/sema/src/ty/context.rs deleted file mode 100644 index 145c2849d..000000000 --- a/kclvm/sema/src/ty/context.rs +++ /dev/null @@ -1,223 +0,0 @@ -use std::collections::HashMap; -use std::sync::Arc; - -use super::{sup, DictType, Type, TypeFlags, TypeKind, TypeRef}; -use kclvm_error::diagnostic::Range; -use petgraph::algo::kosaraju_scc; -use petgraph::graph::{DiGraph, NodeIndex}; -use petgraph::visit::{depth_first_search, DfsEvent}; - -/// TypeContext responsible for type generation, calculation, -/// and equality and subtype judgment between types. -#[derive(Debug)] -pub struct TypeContext { - pub dep_graph: DiGraph, - pub builtin_types: BuiltinTypes, - node_index_map: HashMap, - node_range_map: HashMap, -} - -#[derive(Debug)] -pub struct BuiltinTypes { - pub any: TypeRef, - pub bool: TypeRef, - pub int: TypeRef, - pub float: TypeRef, - pub str: TypeRef, - pub void: TypeRef, - pub none: TypeRef, -} - -impl Default for TypeContext { - fn default() -> Self { - Self::new() - } -} - -impl TypeContext { - /// New a type context. - pub fn new() -> Self { - TypeContext { - dep_graph: DiGraph::new(), - builtin_types: BuiltinTypes { - any: Arc::new(Type::ANY), - bool: Arc::new(Type::BOOL), - int: Arc::new(Type::INT), - float: Arc::new(Type::FLOAT), - str: Arc::new(Type::STR), - void: Arc::new(Type::VOID), - none: Arc::new(Type::NONE), - }, - node_index_map: HashMap::new(), - node_range_map: HashMap::new(), - } - } - - /// Return true if the dep graph contains a cycle from node. - #[inline] - pub fn is_cyclic_from_node(&self, node: &String) -> bool { - let idx = match self.node_index_map.get(node) { - Some(idx) => idx, - None => return false, - }; - depth_first_search(&self.dep_graph, vec![idx.clone()], |event| match event { - DfsEvent::BackEdge(_, _) => Err(()), - _ => Ok(()), - }) - .is_err() - } - - pub fn find_cycle_nodes(&self, node: &String) -> Vec> { - let idx = match self.node_index_map.get(node) { - Some(idx) => idx, - None => return vec![], - }; - let mut res = vec![]; - let strongly_connected_components: Vec> = kosaraju_scc(&self.dep_graph); - for comp in strongly_connected_components { - if comp.len() > 1 && comp.contains(idx) { - res.push(comp) - } - } - res - } - - #[inline] - pub fn get_node_range(&self, idx: &NodeIndex) -> Option { - self.node_range_map.get(idx).cloned() - } - - /// Add dependencies between "from" and "to". - pub fn add_dependencies(&mut self, from: &str, to: &str, from_node_range: Range) { - let from_idx = self.get_or_insert_node_index(from); - let to_idx = self.get_or_insert_node_index(to); - self.dep_graph.add_edge(from_idx, to_idx, ()); - self.node_range_map.insert(from_idx, from_node_range); - } - - /// Get the node index from the node index map or insert it into the dependency graph. - #[inline] - fn get_or_insert_node_index(&mut self, name: &str) -> NodeIndex { - match self.node_index_map.get(name) { - Some(idx) => *idx, - None => { - let idx = self.dep_graph.add_node(name.to_string()); - self.node_index_map.insert(name.to_string(), idx); - idx - } - } - } - - /// Convert the literal union type to its variable type - /// e.g., 1|2 -> int, 's'|'ss' -> str. - pub fn literal_union_type_to_variable_type(&self, ty: TypeRef) -> TypeRef { - if ty.is_union() { - self.infer_to_variable_type(ty) - } else { - ty - } - } - - /// Judge a type kind in the type kind list or the union - /// type kinds are all in the type kind. - pub fn is_kind_type_or_kind_union_type(&self, ty: TypeRef, flags: &[TypeFlags]) -> bool { - match &ty.kind { - TypeKind::Union(types) => types - .iter() - .all(|ty| flags.iter().any(|flag| ty.contains_flags(*flag))), - _ => flags.iter().any(|flag| ty.contains_flags(*flag)), - } - } - - #[inline] - pub fn is_number_type_or_number_union_type(&self, ty: TypeRef) -> bool { - self.is_kind_type_or_kind_union_type(ty, &[TypeFlags::INT, TypeFlags::FLOAT]) - } - - #[inline] - pub fn is_number_bool_type_or_number_bool_union_type(&self, ty: TypeRef) -> bool { - self.is_kind_type_or_kind_union_type( - ty, - &[TypeFlags::INT, TypeFlags::FLOAT, TypeFlags::BOOL], - ) - } - - #[inline] - pub fn is_config_type_or_config_union_type(&self, ty: TypeRef) -> bool { - self.is_kind_type_or_kind_union_type(ty, &[TypeFlags::DICT, TypeFlags::SCHEMA]) - } - - #[inline] - pub fn is_str_type_or_str_union_type(&self, ty: TypeRef) -> bool { - self.is_kind_type_or_kind_union_type(ty, &[TypeFlags::STR]) - } - - #[inline] - pub fn is_primitive_type_or_primitive_union_type(&self, ty: TypeRef) -> bool { - self.is_kind_type_or_kind_union_type( - ty, - &[ - TypeFlags::INT, - TypeFlags::FLOAT, - TypeFlags::BOOL, - TypeFlags::STR, - ], - ) - } - - #[inline] - pub fn is_mul_val_type_or_mul_val_union_type(&self, ty: TypeRef) -> bool { - self.is_kind_type_or_kind_union_type( - ty, - &[ - TypeFlags::INT, - TypeFlags::FLOAT, - TypeFlags::STR, - TypeFlags::LIST, - ], - ) - } - - /// Convert type to the real type annotation - #[inline] - pub fn into_type_annotation_str(&self, ty: TypeRef) -> String { - ty.into_type_annotation_str() - } -} - -pub trait TypeInferMethods { - /// Infer the value type to the variable type" - fn infer_to_variable_type(&self, ty: TypeRef) -> TypeRef; -} - -impl TypeInferMethods for TypeContext { - /// Infer the value type to the variable type" - fn infer_to_variable_type(&self, ty: TypeRef) -> TypeRef { - match &ty.kind { - // None/Undefined type to any type e.g., None -> any - TypeKind::None => self.builtin_types.any.clone(), - // Literal type to its named type e.g., 1 -> int, "s" -> str - TypeKind::BoolLit(_) => self.builtin_types.bool.clone(), - TypeKind::IntLit(_) => self.builtin_types.int.clone(), - TypeKind::FloatLit(_) => self.builtin_types.float.clone(), - TypeKind::StrLit(_) => self.builtin_types.str.clone(), - TypeKind::List(item_ty) => Type::list_ref(self.infer_to_variable_type(item_ty.clone())), - // Dict type e.g., {str:1|2} -> {str:int} - TypeKind::Dict(DictType { - key_ty, - val_ty, - attrs, - }) => Type::dict_ref_with_attrs( - self.infer_to_variable_type(key_ty.clone()), - self.infer_to_variable_type(val_ty.clone()), - attrs.clone(), - ), - // Union type e.g., 1|2|"s" -> int|str - TypeKind::Union(types) => sup(&types - .iter() - .map(|ty| self.infer_to_variable_type(ty.clone())) - .collect::>()), - _ => ty.clone(), - } - } -} diff --git a/kclvm/sema/src/ty/into.rs b/kclvm/sema/src/ty/into.rs deleted file mode 100644 index 21ded369e..000000000 --- a/kclvm/sema/src/ty/into.rs +++ /dev/null @@ -1,201 +0,0 @@ -use super::*; -use kclvm_ast::pos::GetPos; - -impl Type { - /// Downcast ty into the list type. - #[inline] - pub fn list_item_ty(&self) -> TypeRef { - match &self.kind { - TypeKind::List(item_ty) => item_ty.clone(), - _ => bug!("invalid list type {}", self.ty_str()), - } - } - /// Downcast ty into the dict entry type. - #[inline] - pub fn dict_entry_ty(&self) -> (TypeRef, TypeRef) { - match &self.kind { - TypeKind::Dict(DictType { key_ty, val_ty, .. }) => (key_ty.clone(), val_ty.clone()), - _ => bug!("invalid dict type {}", self.ty_str()), - } - } - /// Downcast ty into the config key type. - #[inline] - pub fn config_key_ty(&self) -> TypeRef { - match &self.kind { - TypeKind::Dict(DictType { key_ty, .. }) => key_ty.clone(), - TypeKind::Schema(schema_ty) => schema_ty.key_ty(), - _ => bug!("invalid config type {}", self.ty_str()), - } - } - /// Downcast ty into the config value type. - #[inline] - pub fn config_val_ty(&self) -> TypeRef { - match &self.kind { - TypeKind::Dict(DictType { - key_ty: _, val_ty, .. - }) => val_ty.clone(), - TypeKind::Schema(schema_ty) => schema_ty.val_ty(), - _ => bug!("invalid config type {}", self.ty_str()), - } - } - /// Get types from the union type. - #[inline] - pub fn union_types(&self) -> Vec { - match &self.kind { - TypeKind::Union(types) => types.clone(), - _ => bug!("invalid {} into union type", self.ty_str()), - } - } - /// Into schema type. - #[inline] - pub fn into_schema_type(&self) -> SchemaType { - match &self.kind { - TypeKind::Schema(schema_ty) => schema_ty.clone(), - _ => bug!("invalid type {} into schema type", self.ty_str()), - } - } - /// Into function type. - #[inline] - pub fn into_func_type(&self) -> FunctionType { - match &self.kind { - TypeKind::Function(func_ty) => func_ty.clone(), - _ => bug!("invalid type {} into function type", self.ty_str()), - } - } - /// Into number multiplier type. - #[inline] - pub fn into_number_multiplier(&self) -> NumberMultiplierType { - match &self.kind { - TypeKind::NumberMultiplier(number_multiplier) => number_multiplier.clone(), - _ => bug!("invalid type {} into number multiplier type", self.ty_str()), - } - } - /// Get the type string. - pub fn into_type_annotation_str(&self) -> String { - match &self.kind { - TypeKind::None => NAME_CONSTANT_NONE.to_string(), - TypeKind::BoolLit(v) => (if *v { - NAME_CONSTANT_TRUE - } else { - NAME_CONSTANT_FALSE - }) - .to_string(), - TypeKind::IntLit(v) => v.to_string(), - TypeKind::FloatLit(v) => { - let mut float_str = v.to_string(); - if !float_str.contains('.') { - float_str.push_str(".0"); - } - float_str - } - TypeKind::StrLit(v) => format!("\"{}\"", v.replace('"', "\\\"")), - TypeKind::List(item_ty) => format!("[{}]", item_ty.into_type_annotation_str()), - TypeKind::Dict(DictType { key_ty, val_ty, .. }) => { - format!( - "{{{}:{}}}", - key_ty.into_type_annotation_str(), - val_ty.into_type_annotation_str() - ) - } - TypeKind::Union(types) => types - .iter() - .map(|ty| ty.into_type_annotation_str()) - .collect::>() - .join(" | "), - TypeKind::Schema(schema_ty) => schema_ty.ty_str_with_at_pkgpath_prefix(), - TypeKind::NumberMultiplier(number_multiplier) => { - if number_multiplier.is_literal { - format!( - "{}({}{})", - NUMBER_MULTIPLIER_TYPE_STR, - number_multiplier.raw_value, - number_multiplier.binary_suffix - ) - } else { - NUMBER_MULTIPLIER_PKG_TYPE_STR.to_string() - } - } - TypeKind::Function(fn_ty) => fn_ty.ty_str(), - _ => self.ty_str(), - } - } -} - -impl From for Type { - fn from(ty: ast::Type) -> Type { - match ty { - ast::Type::Any => Type::ANY, - ast::Type::Basic(basic_ty) => match basic_ty { - ast::BasicType::Bool => Type::BOOL, - ast::BasicType::Int => Type::INT, - ast::BasicType::Float => Type::FLOAT, - ast::BasicType::Str => Type::STR, - }, - ast::Type::Named(identifier) => Type::named(&identifier.get_name()), - ast::Type::List(list_ty) => Type::list( - list_ty - .inner_type - .as_ref() - .map_or(Arc::new(Type::ANY), |ty| Arc::new(ty.node.clone().into())), - ), - ast::Type::Dict(dict_ty) => Type::dict( - dict_ty - .key_type - .as_ref() - .map_or(Arc::new(Type::ANY), |ty| Arc::new(ty.node.clone().into())), - dict_ty - .value_type - .as_ref() - .map_or(Arc::new(Type::ANY), |ty| Arc::new(ty.node.clone().into())), - ), - ast::Type::Union(union_ty) => Type::union( - &union_ty - .type_elements - .iter() - .map(|ty| Arc::new(ty.node.clone().into())) - .collect::>(), - ), - ast::Type::Literal(literal_ty) => match literal_ty { - ast::LiteralType::Bool(v) => Type::bool_lit(v), - ast::LiteralType::Int(ast::IntLiteralType { - value: v, - suffix: suffix_option, - }) => match suffix_option { - Some(suffix) => Type::number_multiplier( - kclvm_runtime::cal_num(v, &suffix.value()), - v, - &suffix.value(), - ), - None => Type::int_lit(v), - }, - ast::LiteralType::Float(v) => Type::float_lit(v), - ast::LiteralType::Str(v) => Type::str_lit(&v), - }, - // Ast::function => Sema::function, - ast::Type::Function(func_ty) => Type::function( - None, - func_ty - .ret_ty - .as_ref() - .map_or(Arc::new(Type::ANY), |ty| Arc::new(ty.node.clone().into())), - func_ty - .params_ty - .map_or(vec![], |tys| { - tys.iter() - .map(|ty| Parameter { - name: "".to_string(), - ty: Arc::new(ty.node.clone().into()), - has_default: false, - range: ty.get_span_pos(), - default_value: None, - }) - .collect::>() - }) - .as_slice(), - "", - false, - None, - ), - } - } -} diff --git a/kclvm/sema/src/ty/mod.rs b/kclvm/sema/src/ty/mod.rs deleted file mode 100644 index 6ac46184d..000000000 --- a/kclvm/sema/src/ty/mod.rs +++ /dev/null @@ -1,555 +0,0 @@ -mod constants; -mod constructor; -mod context; -mod into; -pub mod parser; -mod unify; -mod walker; - -use std::collections::HashMap; -use std::sync::Arc; - -pub use constants::*; -pub use context::{TypeContext, TypeInferMethods}; -use kclvm_ast::ast; -use kclvm_ast::MAIN_PKG; -use kclvm_error::diagnostic::Range; -use kclvm_error::Position; -use kclvm_primitives::IndexMap; -pub use unify::*; -pub use walker::walk_type; - -use super::resolver::doc::Example; - -#[cfg(test)] -mod tests; - -/// TypeRef represents a reference to a type that exists to avoid copying types everywhere affecting -/// performance. For example, for two instances that are both integer types, there is actually no -/// difference between them. -pub type TypeRef = Arc; - -#[derive(Debug, Clone, PartialEq)] -pub struct Type { - // The type kind. - pub kind: TypeKind, - // Is a type alias. - pub is_type_alias: bool, - /// This field provides fast access to information that is - /// also contained in `kind`. - flags: TypeFlags, -} - -unsafe impl Send for Type {} - -impl Type { - /// Whether the type contains the flag. - #[inline] - pub fn contains_flags(&self, flag: TypeFlags) -> bool { - self.flags.contains(flag) - } - /// Returns the type string used for the error handler. - pub fn ty_str(&self) -> String { - match &self.kind { - TypeKind::None => NONE_TYPE_STR.to_string(), - TypeKind::Any => ANY_TYPE_STR.to_string(), - TypeKind::Bool => BOOL_TYPE_STR.to_string(), - TypeKind::BoolLit(v) => { - format!( - "{}({})", - BOOL_TYPE_STR, - if *v { - NAME_CONSTANT_TRUE - } else { - NAME_CONSTANT_FALSE - } - ) - } - TypeKind::Int => INT_TYPE_STR.to_string(), - TypeKind::IntLit(v) => format!("{}({})", INT_TYPE_STR, v), - TypeKind::Float => FLOAT_TYPE_STR.to_string(), - TypeKind::FloatLit(v) => format!("{}({})", FLOAT_TYPE_STR, v), - TypeKind::Str => STR_TYPE_STR.to_string(), - TypeKind::StrLit(v) => format!("{}({})", STR_TYPE_STR, v), - TypeKind::List(item_ty) => format!("[{}]", item_ty.ty_str()), - TypeKind::Dict(DictType { key_ty, val_ty, .. }) => { - format!("{{{}:{}}}", key_ty.ty_str(), val_ty.ty_str()) - } - TypeKind::Union(types) => types - .iter() - .map(|ty| ty.ty_str()) - .collect::>() - .join(" | "), - TypeKind::Schema(schema_ty) => schema_ty.name.to_string(), - TypeKind::NumberMultiplier(number_multiplier) => number_multiplier.ty_str(), - TypeKind::Function(func_ty) => func_ty.ty_str(), - TypeKind::Void => VOID_TYPE_STR.to_string(), - TypeKind::Module(module_ty) => format!("{} '{}'", MODULE_TYPE_STR, module_ty.pkgpath), - TypeKind::Named(name) => name.to_string(), - } - } - - pub fn ty_hint(&self) -> String { - match &self.kind { - TypeKind::StrLit(s) => format!("\"{}\"", s), - TypeKind::IntLit(v) => v.to_string(), - TypeKind::FloatLit(v) => v.to_string(), - TypeKind::List(item_ty) => format!("[{}]", item_ty.ty_hint()), - TypeKind::Dict(DictType { key_ty, val_ty, .. }) => { - format!("{{{}:{}}}", key_ty.ty_hint(), val_ty.ty_hint()) - } - TypeKind::Union(types) => types - .iter() - .map(|ty| ty.ty_hint()) - .collect::>() - .join(" | "), - _ => self.ty_str(), - } - } - - /// Returns the full type string with the package path used for the error handler. - pub fn full_ty_str(&self) -> String { - match &self.kind { - TypeKind::List(item_ty) => format!("[{}]", item_ty.full_ty_str()), - TypeKind::Dict(DictType { key_ty, val_ty, .. }) => { - format!("{{{}:{}}}", key_ty.full_ty_str(), val_ty.full_ty_str()) - } - TypeKind::Union(types) => types - .iter() - .map(|ty| ty.full_ty_str()) - .collect::>() - .join(" | "), - TypeKind::Schema(schema_ty) => schema_ty.full_ty_str(), - _ => self.ty_str(), - } - } - - pub fn ty_doc(&self) -> Option { - match &self.kind { - TypeKind::Schema(schema) => Some(schema.doc.clone()), - TypeKind::Function(func) => Some(func.doc.clone()), - _ => None, - } - } -} - -unsafe impl Send for TypeKind {} -unsafe impl Sync for TypeKind {} - -#[derive(Debug, Clone, PartialEq)] -pub enum TypeKind { - /// A primitive None name constant. - None, - /// The any type. - Any, - /// The primitive boolean type. Written as `bool`. - Bool, - BoolLit(bool), - /// A primitive integer type. Written as `int`. - Int, - /// A primitive integer literal type. - IntLit(i64), - /// A primitive float type. Written as `float`. - Float, - /// A primitive float literal type. - FloatLit(f64), - /// The primitive string type; holds a Unicode scalar value - /// (a non-surrogate code point). Written as `str`. - Str, - /// A primitive string literal type. - StrLit(String), - /// The pointer of an array slice. Written as `[T]`. - List(TypeRef), - /// A map type. Written as `{kT, vT}`. - Dict(DictType), - /// A union type. Written as ty1 | ty2 | ... | tyn - Union(Vec), - /// A schema type. - Schema(SchemaType), - /// A number multiplier type. - NumberMultiplier(NumberMultiplierType), - /// The function type. - Function(FunctionType), - /// The bottom never type. - Void, - /// The module type. - Module(ModuleType), - /// A named type alias. - Named(String), -} - -bitflags::bitflags! { - /// TypeFlags provides fast access to information that is also contained - /// in `kind`. - pub struct TypeFlags: u16 { - const VOID = 1 << 0; - const INT = 1 << 1; - const FLOAT = 1 << 2; - const STR = 1 << 3; - const BOOL = 1 << 4; - const ANY = 1 << 5; - const NONE = 1 << 6; - const LIST = 1 << 7; - const DICT = 1 << 8; - const SCHEMA = 1 << 9; - const UNION = 1 << 10; - const LITERAL = 1 << 11; - const NUMBER_MULTIPLIER = 1 << 12; - const FUNCTION = 1 << 13; - const MODULE = 1 << 14; - const NAMED = 1 << 15; - } -} - -#[derive(Debug, Clone, PartialEq)] -pub struct DictType { - pub key_ty: TypeRef, - pub val_ty: TypeRef, - pub attrs: IndexMap, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Attr { - pub ty: TypeRef, - pub range: Range, -} - -/// The schema type. -#[derive(Debug, Clone, PartialEq)] -pub struct SchemaType { - /// The schema name. - pub name: String, - /// The schema definition package path - pub pkgpath: String, - /// The schema definition file path. - pub filename: String, - /// The schema definition document string. - pub doc: String, - /// The code snippets of the schema usage examples - pub examples: HashMap, - /// Indicates whether the schema is a type of a instance or - /// a type (value). Besides, it is necessary to distinguish - /// between a type instance and a type value, such as the following code: - /// ```no_check - /// # `Person` in `schema Person` is a type and it is not a schema instance. - /// schema Person: - /// name: str - /// - /// # `person` is a schema instance. - /// person = Person {name = "Alice"} - /// # `person` is a schema instance used in the value expression. - /// name = person.name - /// # `Person` in `persons: [Person]` is a type, `Person` in `Person.instances()` - /// # is a type value, and they are not schema instances. - /// persons: [Person] = Person.instances() - /// ``` - pub is_instance: bool, - /// Indicates whether it is a schema mixin. - pub is_mixin: bool, - /// Indicates whether it is a schema protocol. - pub is_protocol: bool, - /// Indicates whether it is a rule. - pub is_rule: bool, - /// Base schema. - pub base: Option>, - /// Protocol schema. - pub protocol: Option>, - /// Schema Mixins. - pub mixins: Vec, - /// Schema attributes. - pub attrs: IndexMap, - /// Schema function type. - pub func: Box, - /// Schema index signature. - pub index_signature: Option>, - /// Schema decorators including self and attribute decorators. - pub decorators: Vec, -} - -impl SchemaType { - /// Get the object type string with @pkgpath prefix. - pub fn ty_str_with_at_pkgpath_prefix(&self) -> String { - if self.pkgpath.is_empty() || self.pkgpath == MAIN_PKG { - self.name.clone() - } else { - format!("@{}.{}", self.pkgpath, self.name) - } - } - /// Get the object type string. - pub fn full_ty_str(&self) -> String { - full_ty_str(&self.pkgpath, &self.name) - } - /// Is `name` a schema member function - pub fn is_member_functions(&self, name: &str) -> bool { - !self.is_instance && SCHEMA_MEMBER_FUNCTIONS.contains(&name) - } - - pub fn set_type_of_attr(&mut self, attr: &str, ty: TypeRef) { - match self.attrs.get_mut(attr) { - Some(attr) => attr.ty = ty, - None => { - let schema_attr = SchemaAttr { - is_optional: true, - has_default: false, - default: None, - ty, - range: (Position::dummy_pos(), Position::dummy_pos()), - doc: None, - decorators: vec![], - }; - self.attrs.insert(attr.to_string(), schema_attr); - } - } - } - - #[inline] - pub fn get_type_of_attr(&self, attr: &str) -> Option { - self.get_obj_of_attr(attr).map(|attr| attr.ty.clone()) - } - - #[inline] - pub fn get_obj_of_attr(&self, attr: &str) -> Option<&SchemaAttr> { - match self.attrs.get(attr) { - Some(attr) => Some(attr), - None => self.base.as_ref().map_or( - self.protocol - .as_ref() - .and_then(|protocol| protocol.get_obj_of_attr(attr)), - |base| base.get_obj_of_attr(attr), - ), - } - } - - pub fn key_ty(&self) -> TypeRef { - Arc::new(Type::STR) - } - - pub fn val_ty(&self) -> TypeRef { - if let Some(index_signature) = &self.index_signature { - index_signature.val_ty.clone() - } else { - Arc::new(Type::ANY) - } - } - - pub fn schema_ty_signature_str(&self) -> (String, String) { - let base: String = if let Some(base) = &self.base { - format!("({})", base.name) - } else { - "".to_string() - }; - let params: String = if self.func.params.is_empty() { - "".to_string() - } else { - format!( - "[{}]", - self.func - .params - .iter() - .map(|p| format!("{}: {}", p.name.clone(), p.ty.ty_str())) - .collect::>() - .join(", ") - ) - }; - - let rest_sign = format!("schema {}{}{}:", self.name, params, base); - - (self.pkgpath.clone(), rest_sign) - } - - pub fn schema_ty_signature_no_pkg(&self) -> String { - let base: String = if let Some(base) = &self.base { - format!("({})", base.name) - } else { - "".to_string() - }; - let params: String = if self.func.params.is_empty() { - "".to_string() - } else { - format!( - "[{}]", - self.func - .params - .iter() - .map(|p| format!("{}: {}", p.name.clone(), p.ty.ty_str())) - .collect::>() - .join(", ") - ) - }; - let params_str = if !params.is_empty() && !base.is_empty() { - format!("\\{}{}", params, base) - } else if !params.is_empty() { - format!("{}", params) - } else if !base.is_empty() { - format!("{}", base) - } else { - "".to_string() - }; - format!("schema {}{}", self.name, params_str) - } -} - -pub fn full_ty_str(pkgpath: &str, name: &str) -> String { - if pkgpath.is_empty() || pkgpath == MAIN_PKG { - name.to_string() - } else { - format!("{}.{}", pkgpath, name) - } -} - -#[derive(Debug, Clone, PartialEq)] -pub struct SchemaAttr { - pub is_optional: bool, - pub has_default: bool, - /// `default` denotes the schema attribute optional value string. For example, - /// for the schema attribute definition `name?: str = "Alice"`, the value of - /// `default` is [Some("Alice")]. - /// For the schema attribute definition `name?: str`, the value of `default` - /// is [None]. - pub default: Option, - pub ty: TypeRef, - pub range: Range, - pub doc: Option, - pub decorators: Vec, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct SchemaIndexSignature { - pub key_name: Option, - pub key_ty: TypeRef, - pub val_ty: TypeRef, - pub any_other: bool, -} - -impl SchemaIndexSignature { - pub fn ty_str(&self) -> String { - let key_name_str = match &self.key_name { - Some(name) => format!("[{}: ", name), - None => "[".to_string(), - }; - let any_other_str = if self.any_other { "..." } else { "" }; - key_name_str - + any_other_str - + &format!("{}]: {}", self.key_ty.ty_str(), self.val_ty.ty_str()) - } -} - -/// The module type. -#[derive(Debug, Clone, PartialEq)] -pub struct ModuleType { - pub pkgpath: String, - pub imported: Vec, - pub kind: ModuleKind, -} - -/// The module kind. -#[derive(Debug, Clone, PartialEq)] -pub enum ModuleKind { - User, - System, - Plugin, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct Decorator { - /// The decorator target e.g., the schema statement or schema attribute. - pub target: DecoratorTarget, - /// The decorator name. - pub name: String, - /// The schema or attribute name of decorator dimension. - pub key: String, - /// The decorator argument list values. - pub arguments: Vec, - /// The decorator keyword mapping values. - pub keywords: HashMap, -} - -#[derive(Debug, Clone, PartialEq)] -pub enum DecoratorTarget { - Schema, - Attribute, -} - -/// The number multiplier type. -#[derive(Debug, Clone, PartialEq)] -pub struct NumberMultiplierType { - pub value: f64, - pub raw_value: i64, - pub binary_suffix: String, - pub is_literal: bool, -} - -impl NumberMultiplierType { - pub fn ty_str(&self) -> String { - if self.is_literal { - format!( - "{}({}{})", - NUMBER_MULTIPLIER_TYPE_STR, self.raw_value, self.binary_suffix - ) - } else { - NUMBER_MULTIPLIER_TYPE_STR.to_string() - } - } -} - -/// The function type. -#[derive(Debug, Clone, PartialEq)] -pub struct FunctionType { - pub doc: String, - pub params: Vec, - pub self_ty: Option, - pub return_ty: TypeRef, - pub is_variadic: bool, - pub kw_only_index: Option, -} - -impl FunctionType { - pub fn ty_str(&self) -> String { - format!( - "({}) -> {}", - self.params - .iter() - .map(|param| param.ty.ty_str()) - .collect::>() - .join(", "), - self.return_ty.ty_str() - ) - } - - pub fn func_signature_str(&self, name: &String) -> String { - format!( - "function {}({}) -> {}", - name, - self.params - .iter() - .map(|param| format!("{}: {}", param.name, param.ty.ty_str())) - .collect::>() - .join(", "), - self.return_ty.ty_str() - ) - } -} - -impl FunctionType { - #[inline] - pub fn variadic_func() -> Self { - Self { - doc: "".to_string(), - params: vec![], - self_ty: None, - return_ty: Type::any_ref(), - is_variadic: true, - kw_only_index: None, - } - } -} - -/// The function parameter type and position information. -#[derive(Debug, Clone, PartialEq)] -pub struct Parameter { - pub name: String, - pub ty: TypeRef, - pub has_default: bool, - pub default_value: Option, - pub range: Range, -} diff --git a/kclvm/span/Cargo.lock b/kclvm/span/Cargo.lock deleted file mode 100644 index 910a9ab65..000000000 --- a/kclvm/span/Cargo.lock +++ /dev/null @@ -1,634 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "arrayvec" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "block-buffer" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324" -dependencies = [ - "generic-array", -] - -[[package]] -name = "cc" -version = "1.0.73" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "cpufeatures" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b" -dependencies = [ - "libc", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" -dependencies = [ - "cfg-if 1.0.0", - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1145cf131a2c6ba0615079ab6a638f7e1973ac9c2634fcbeaaad6114246efe8c" -dependencies = [ - "autocfg", - "cfg-if 1.0.0", - "crossbeam-utils", - "lazy_static", - "memoffset", - "scopeguard", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf124c720b7686e3c2663cf54062ab0f68a88af2fb6a030e87e30bf721fcb38" -dependencies = [ - "cfg-if 1.0.0", - "lazy_static", -] - -[[package]] -name = "crypto-common" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "digest" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506" -dependencies = [ - "block-buffer", - "crypto-common", -] - -[[package]] -name = "either" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" - -[[package]] -name = "ena" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7402b94a93c24e742487327a7cd839dc9d36fec9de9fb25b09f2dae459f36c3" -dependencies = [ - "log", -] - -[[package]] -name = "fastrand" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf" -dependencies = [ - "instant", -] - -[[package]] -name = "generic-array" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "hashbrown" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" - -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - -[[package]] -name = "indexmap" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" -dependencies = [ - "autocfg", - "hashbrown", - "rustc-rayon", -] - -[[package]] -name = "instant" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "jobserver" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af25a77299a7f711a01975c35a6a424eb6862092cc2d6c72c4ed6cbc56dfc1fa" -dependencies = [ - "libc", -] - -[[package]] -name = "kclvm-macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "kclvm-span" -version = "0.1.0" -dependencies = [ - "kclvm-macros", - "rustc_span", - "scoped-tls", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.123" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb691a747a7ab48abc15c5b42066eaafde10dc427e3b6ee2a1cf43db04c763bd" - -[[package]] -name = "lock_api" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" -dependencies = [ - "autocfg", - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6389c490849ff5bc16be905ae24bc913a9c8892e19b2341dbc175e14c341c2b8" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "md-5" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "658646b21e0b72f7866c7038ab086d3d5e1cd6271f060fd37defb241949d0582" -dependencies = [ - "digest", -] - -[[package]] -name = "memmap2" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "723e3ebdcdc5c023db1df315364573789f8857c11b631a2fdfad7c00f5c046b4" -dependencies = [ - "libc", -] - -[[package]] -name = "memoffset" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_cpus" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "parking_lot" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f5ec2493a61ac0506c0f4199f99070cbe83857b0337006a30f3e6719b8ef58" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "995f667a6c822200b0433ac218e05582f0e2efa1b922a3fd2fbaadc5f87bab37" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "redox_syscall", - "smallvec", - "windows-sys", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e280fbe77cc62c91527259e9442153f4688736748d24660126286329742b4c6c" - -[[package]] -name = "proc-macro2" -version = "1.0.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "psm" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "871372391786ccec00d3c5d3d6608905b3d4db263639cfe075d3b60a736d115a" -dependencies = [ - "cc", -] - -[[package]] -name = "quote" -version = "1.0.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "632d02bff7f874a36f33ea8bb416cd484b90cc66c1194b1a1110d067a7013f58" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "redox_syscall" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" -dependencies = [ - "bitflags", -] - -[[package]] -name = "remove_dir_all" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" -dependencies = [ - "winapi", -] - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - -[[package]] -name = "rustc-rayon" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9974ab223660e61c1b4e7b43b827379df286736ca988308ce7e16f59f2d89246" -dependencies = [ - "crossbeam-deque", - "either", - "rustc-rayon-core", -] - -[[package]] -name = "rustc-rayon-core" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "564bfd27be8db888d0fa76aa4335e7851aaed0c2c11ad1e93aeb9349f6b88500" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", - "lazy_static", - "num_cpus", -] - -[[package]] -name = "rustc_data_structures" -version = "0.0.0" -dependencies = [ - "arrayvec", - "bitflags", - "cfg-if 0.1.10", - "ena", - "indexmap", - "jobserver", - "libc", - "memmap2", - "parking_lot", - "rustc-hash", - "rustc-rayon", - "rustc-rayon-core", - "stable_deref_trait", - "stacker", - "tempfile", - "tracing", - "winapi", -] - -[[package]] -name = "rustc_span" -version = "0.0.0" -dependencies = [ - "cfg-if 0.1.10", - "md-5", - "rustc_data_structures", - "scoped-tls", - "sha-1", - "sha2", - "tracing", - "unicode-width", -] - -[[package]] -name = "scoped-tls" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" - -[[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - -[[package]] -name = "sha-1" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest", -] - -[[package]] -name = "sha2" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest", -] - -[[package]] -name = "smallvec" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83" - -[[package]] -name = "stable_deref_trait" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" - -[[package]] -name = "stacker" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90939d5171a4420b3ff5fbc8954d641e7377335454c259dcb80786f3f21dc9b4" -dependencies = [ - "cc", - "cfg-if 1.0.0", - "libc", - "psm", - "winapi", -] - -[[package]] -name = "syn" -version = "1.0.90" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "704df27628939572cd88d33f171cd6f896f4eaca85252c6e0a72d8d8287ee86f" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "synstructure" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "unicode-xid", -] - -[[package]] -name = "tempfile" -version = "3.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" -dependencies = [ - "cfg-if 1.0.0", - "fastrand", - "libc", - "redox_syscall", - "remove_dir_all", - "winapi", -] - -[[package]] -name = "tracing" -version = "0.1.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0ecdcb44a79f0fe9844f0c4f33a342cbcbb5117de8001e6ba0dc2351327d09" -dependencies = [ - "cfg-if 1.0.0", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e65ce065b4b5c53e73bb28912318cb8c9e9ad3921f1d669eb0e68b4c8143a2b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tracing-core" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f54c8ca710e81886d498c2fd3331b56c93aa248d49de2222ad2742247c60072f" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "typenum" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" - -[[package]] -name = "unicode-width" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" - -[[package]] -name = "unicode-xid" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-sys" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5acdd78cb4ba54c0045ac14f62d8f94a03d10047904ae2a40afa1e99d8f70825" -dependencies = [ - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17cffbe740121affb56fad0fc0e421804adf0ae00891205213b5cecd30db881d" - -[[package]] -name = "windows_i686_gnu" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2564fde759adb79129d9b4f54be42b32c89970c18ebf93124ca8870a498688ed" - -[[package]] -name = "windows_i686_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cd9d32ba70453522332c14d38814bceeb747d80b3958676007acadd7e166956" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfce6deae227ee8d356d19effc141a509cc503dfd1f850622ec4b0f84428e1f4" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d19538ccc21819d01deaf88d6a17eae6596a12e9aafdbb97916fb49896d89de9" diff --git a/kclvm/span/Cargo.toml b/kclvm/span/Cargo.toml deleted file mode 100644 index 0b278f0b2..000000000 --- a/kclvm/span/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "kclvm-span" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -compiler_base_span = "0.1.2" - -kclvm-macros = { path = "../macros" } -scoped-tls = "1.0" -parking_lot = "0.11" diff --git a/kclvm/span/src/lib.rs b/kclvm/span/src/lib.rs deleted file mode 100644 index 7f50765e6..000000000 --- a/kclvm/span/src/lib.rs +++ /dev/null @@ -1,22 +0,0 @@ -//! Source positions and related helper functions. -//! -//! Important concepts in this module include: -//! -//! - the *span*, represented by [`Span`] and related types; -//! - interned strings, represented by [`Symbol`]s, with some common symbols available statically in the [`sym`] module. -//! -//! Reference: https://github.com/rust-lang/rust/blob/master/compiler/rustc_span/src/lib.rs - -mod session_globals; -pub mod symbol; - -#[cfg(test)] -mod tests; - -pub use compiler_base_span::{BytePos, FilePathMapping, Loc, SourceFile, SourceMap, Span}; -pub use session_globals::create_session_globals_then; -use session_globals::with_session_globals; -pub use symbol::{Ident, Symbol}; - -#[macro_use] -extern crate kclvm_macros; diff --git a/kclvm/span/src/symbol.rs b/kclvm/span/src/symbol.rs deleted file mode 100644 index d57abd990..000000000 --- a/kclvm/span/src/symbol.rs +++ /dev/null @@ -1,246 +0,0 @@ -use compiler_base_span::{Span, DUMMY_SP}; -use std::{ - fmt, - hash::{Hash, Hasher}, -}; - -use crate::session_globals::Interner; -use crate::with_session_globals; - -// The proc macro code for this is in `kclvm_macros/src/symbols.rs`. -symbols! { - // After modifying this list adjust `is_special`, `is_used_keyword`/`is_unused_keyword`, - // this should be rarely necessary though if the keywords are kept in alphabetic order. - Keywords { - // Special reserved identifiers used internally for elided lifetimes, - // unnamed method parameters, crate root module, error recovery etc. - Empty: "", - As: "as", - Import: "import", - Rule: "rule", - Schema: "schema", - Mixin: "mixin", - Protocol: "protocol", - Check: "check", - For: "for", - Assert: "assert", - If: "if", - Elif: "elif", - Else: "else", - Or: "or", - And: "and", - Not: "not", - In: "in", - Is: "is", - Lambda: "lambda", - All: "all", - Any: "any", - Filter: "filter", - Map: "map", - Type: "type", - True: "True", - False: "False", - None: "None", - Undefined: "Undefined", - } - // Pre-interned symbols that can be referred to with `kclvm_span::sym::*`. - Symbols { - bool, - float, - int, - str, - } -} - -/// Ident denotes a identifier with a symbol name and span -/// -/// ``` -/// use kclvm_span::*; -/// use compiler_base_span::span::new_byte_pos; -/// -/// create_session_globals_then(||{ -/// let ident = Ident::new( -/// Symbol::intern("identifier"), -/// Span::new(new_byte_pos(0), new_byte_pos(10)), -/// ); -/// }) -/// ``` -#[derive(Debug, Copy, Clone, Eq)] -pub struct Ident { - pub name: Symbol, - pub span: Span, -} - -impl std::str::FromStr for Ident { - type Err = String; - /// Maps a string to an identifier with a dummy span. - fn from_str(s: &str) -> Result { - Ok(Ident::with_dummy_span(Symbol::intern(s))) - } -} - -impl Ident { - #[inline] - /// Constructs a new identifier from a symbol and a span. - pub const fn new(name: Symbol, span: Span) -> Ident { - Ident { name, span } - } - - /// Constructs a new identifier with a dummy span. - #[inline] - pub const fn with_dummy_span(name: Symbol) -> Ident { - Ident::new(name, DUMMY_SP) - } - - /// Maps a string and a span to an identifier. - pub fn from_str_and_span(string: &str, span: Span) -> Ident { - Ident::new(Symbol::intern(string), span) - } - - pub fn without_first_quote(self) -> Ident { - Ident::new( - Symbol::intern(self.as_str().trim_start_matches('\'')), - self.span, - ) - } - - /// Access the underlying string. This is a slowish operation because it - /// requires locking the symbol interner. - /// - /// Note that the lifetime of the return value is a lie. See - /// `Symbol::as_str()` for details. - pub fn as_str(&self) -> String { - self.name.as_str() - } -} - -impl PartialEq for Ident { - fn eq(&self, rhs: &Self) -> bool { - self.name == rhs.name - } -} - -impl Hash for Ident { - fn hash(&self, state: &mut H) { - self.name.hash(state); - self.span.hash(state); - } -} - -/// An interned string. -/// -/// Internally, a `Symbol` is implemented as an index, and all operations -/// (including hashing, equality, and ordering) operate on that index. -/// -/// ``` -/// use kclvm_span::*; -/// create_session_globals_then(||{ -/// let sym = Symbol::intern("name"); -/// }); -/// ``` -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -pub struct Symbol(pub(crate) SymbolIndex); - -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -pub struct SymbolIndex { - pub(crate) idx: u32, -} - -impl Symbol { - pub(crate) const fn new(n: u32) -> Self { - Symbol(SymbolIndex { idx: n }) - } - - /// Maps a string to its interned representation. - pub fn intern(string: &str) -> Self { - with_session_globals(|session_globals| session_globals.symbol_interner.intern(string)) - } - - /// Access the underlying string. This is a slowish operation because it - /// requires locking the symbol interner. - /// - /// Note that the lifetime of the return value is a lie. It's not the same - /// as `&self`, but actually tied to the lifetime of the underlying - /// interner. Interners are long-lived, and there are very few of them, and - /// this function is typically used for short-lived things, so in practice - /// it works out ok. - pub fn as_str(&self) -> String { - with_session_globals(|session_globals| session_globals.symbol_interner.get(*self)) - } - - pub fn as_u32(self) -> u32 { - self.0.idx - } - - /// This method is supposed to be used in error messages, so it's expected to be - /// identical to printing the original identifier token written in source code - /// (`token_to_string`, `Ident::to_string`), except that symbols don't keep the rawness flag - /// or edition, so we have to guess the rawness using the global edition. - pub fn to_ident_string(self) -> String { - format!("{:?}", Ident::with_dummy_span(self)) - } -} - -impl fmt::Display for Symbol { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt(&self.as_str(), f) - } -} - -impl From for String { - fn from(val: Symbol) -> Self { - val.as_str() - } -} - -// This module has a very short name because it's used a lot. -/// This module contains all the defined keyword `Symbol`s. -/// -/// Given that `kw` is imported, use them like `kw::keyword_name`. -/// For example `kw::Loop` or `kw::Break`. -pub mod kw { - pub use super::kw_generated::*; -} - -// This module has a very short name because it's used a lot. -/// This module contains all the defined non-keyword `Symbol`s. -/// -/// Given that `sym` is imported, use them like `sym::symbol_name`. -/// For example `sym::rustfmt` or `sym::u8`. -pub mod sym { - use super::Symbol; - use std::convert::TryInto; - - #[doc(inline)] - pub use super::sym_generated::*; - - /// Get the symbol for an integer. - /// - /// The first few non-negative integers each have a static symbol and therefore - /// are fast. - pub fn integer + Copy + ToString>(n: N) -> Symbol { - if let Result::Ok(idx) = n.try_into() { - if idx < 10 { - return Symbol::new(super::SYMBOL_DIGITS_BASE + idx as u32); - } - } - Symbol::intern(&n.to_string()) - } -} - -pub mod reserved { - - pub use super::reserved_word; - - pub fn is_reserved_word(word: &str) -> bool { - reserved_word::reserved_words.contains(&word) - } -} - -/// Special symbols related to KCL keywords. -impl Symbol { - /// Returns `true` if the symbol is `true` or `false`. - pub fn is_bool_lit(self) -> bool { - self == kw::True || self == kw::False - } -} diff --git a/kclvm/spec/gpyrpc/gpyrpc.proto b/kclvm/spec/gpyrpc/gpyrpc.proto deleted file mode 100644 index 440e508d0..000000000 --- a/kclvm/spec/gpyrpc/gpyrpc.proto +++ /dev/null @@ -1,1479 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. -// -// This file defines the request parameters and return structure of the KCL RPC server. - -syntax = "proto3"; - -package gpyrpc; - -// Message representing an external package for KCL. -// kcl main.k -E pkg_name=pkg_path -message ExternalPkg { - // Name of the package. - string pkg_name = 1; - // Path of the package. - string pkg_path = 2; -} - -// Message representing a key-value argument for KCL. -// kcl main.k -D name=value -message Argument { - // Name of the argument. - string name = 1; - // Value of the argument. - string value = 2; -} - -// ---------------------------------------------------------------------------- -// Error types -// ---------------------------------------------------------------------------- - -// Message representing an error. -message Error { - // Level of the error (e.g., "Error", "Warning"). - string level = 1; - // Error code. (e.g., "E1001") - string code = 2; - // List of error messages. - repeated Message messages = 3; -} - -// Message representing a detailed error message with a position. -message Message { - // The error message text. - string msg = 1; - // The position in the source code where the error occurred. - Position pos = 2; -} - -// ---------------------------------------------------------------------------- -// service request/response -// ---------------------------------------------------------------------------- - -// Service for built-in functionality. -service BuiltinService { - // Sends a ping request. - rpc Ping(Ping_Args) returns (Ping_Result); - // Lists available methods. - rpc ListMethod(ListMethod_Args) returns (ListMethod_Result); -} - -// Service for KCL VM interactions. -service KclvmService { - /// Ping KclvmService, return the same value as the parameter - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "Ping", - /// "params": { - /// "value": "hello" - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "value": "hello" - /// }, - /// "id": 1 - /// } - /// ``` - rpc Ping(Ping_Args) returns (Ping_Result); - - /// GetVersion KclvmService, return the kclvm service version information - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "GetVersion", - /// "params": {}, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "version": "0.9.1", - /// "checksum": "c020ab3eb4b9179219d6837a57f5d323", - /// "git_sha": "1a9a72942fffc9f62cb8f1ae4e1d5ca32aa1f399", - /// "version_info": "Version: 0.9.1-c020ab3eb4b9179219d6837a57f5d323\nPlatform: aarch64-apple-darwin\nGitCommit: 1a9a72942fffc9f62cb8f1ae4e1d5ca32aa1f399" - /// }, - /// "id": 1 - /// } - /// ``` - rpc GetVersion(GetVersion_Args) returns (GetVersion_Result); - - /// Parse KCL program with entry files. - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "ParseProgram", - /// "params": { - /// "paths": ["./src/testdata/test.k"] - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "ast_json": "{...}", - /// "paths": ["./src/testdata/test.k"], - /// "errors": [] - /// }, - /// "id": 1 - /// } - /// ``` - rpc ParseProgram(ParseProgram_Args) returns (ParseProgram_Result); - - /// Parse KCL single file to Module AST JSON string with import dependencies - /// and parse errors. - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "ParseFile", - /// "params": { - /// "path": "./src/testdata/parse/main.k" - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "ast_json": "{...}", - /// "deps": ["./dep1", "./dep2"], - /// "errors": [] - /// }, - /// "id": 1 - /// } - /// ``` - rpc ParseFile(ParseFile_Args) returns (ParseFile_Result); - - /// load_package provides users with the ability to parse kcl program and semantic model - /// information including symbols, types, definitions, etc. - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "LoadPackage", - /// "params": { - /// "parse_args": { - /// "paths": ["./src/testdata/parse/main.k"] - /// }, - /// "resolve_ast": true - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "program": "{...}", - /// "paths": ["./src/testdata/parse/main.k"], - /// "parse_errors": [], - /// "type_errors": [], - /// "symbols": { ... }, - /// "scopes": { ... }, - /// "node_symbol_map": { ... }, - /// "symbol_node_map": { ... }, - /// "fully_qualified_name_map": { ... }, - /// "pkg_scope_map": { ... } - /// }, - /// "id": 1 - /// } - /// ``` - rpc LoadPackage(LoadPackage_Args) returns (LoadPackage_Result); - - /// list_options provides users with the ability to parse kcl program and get all option information. - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "ListOptions", - /// "params": { - /// "paths": ["./src/testdata/option/main.k"] - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "options": [ - /// { "name": "option1", "type": "str", "required": true, "default_value": "", "help": "option 1 help" }, - /// { "name": "option2", "type": "int", "required": false, "default_value": "0", "help": "option 2 help" }, - /// { "name": "option3", "type": "bool", "required": false, "default_value": "false", "help": "option 3 help" } - /// ] - /// }, - /// "id": 1 - /// } - /// ``` - rpc ListOptions(ParseProgram_Args) returns (ListOptions_Result); - - /// list_variables provides users with the ability to parse kcl program and get all variables by specs. - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "ListVariables", - /// "params": { - /// "files": ["./src/testdata/variables/main.k"], - /// "specs": ["a"] - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "variables": { - /// "a": { - /// "variables": [ - /// { "value": "1", "type_name": "int", "op_sym": "", "list_items": [], "dict_entries": [] } - /// ] - /// } - /// }, - /// "unsupported_codes": [], - /// "parse_errors": [] - /// }, - /// "id": 1 - /// } - /// ``` - rpc ListVariables(ListVariables_Args) returns (ListVariables_Result); - - /// Execute KCL file with args. **Note that it is not thread safe.** - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "ExecProgram", - /// "params": { - /// "work_dir": "./src/testdata", - /// "k_filename_list": ["test.k"] - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "json_result": "{\"alice\": {\"age\": 18}}", - /// "yaml_result": "alice:\n age: 18", - /// "log_message": "", - /// "err_message": "" - /// }, - /// "id": 1 - /// } - /// - /// // Request with code - /// { - /// "jsonrpc": "2.0", - /// "method": "ExecProgram", - /// "params": { - /// "k_filename_list": ["file.k"], - /// "k_code_list": ["alice = {age = 18}"] - /// }, - /// "id": 2 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "json_result": "{\"alice\": {\"age\": 18}}", - /// "yaml_result": "alice:\n age: 18", - /// "log_message": "", - /// "err_message": "" - /// }, - /// "id": 2 - /// } - /// - /// // Error case - cannot find file - /// { - /// "jsonrpc": "2.0", - /// "method": "ExecProgram", - /// "params": { - /// "k_filename_list": ["invalid_file.k"] - /// }, - /// "id": 3 - /// } - /// - /// // Error Response - /// { - /// "jsonrpc": "2.0", - /// "error": { - /// "code": -32602, - /// "message": "Cannot find the kcl file" - /// }, - /// "id": 3 - /// } - /// - /// // Error case - no input files - /// { - /// "jsonrpc": "2.0", - /// "method": "ExecProgram", - /// "params": { - /// "k_filename_list": [] - /// }, - /// "id": 4 - /// } - /// - /// // Error Response - /// { - /// "jsonrpc": "2.0", - /// "error": { - /// "code": -32602, - /// "message": "No input KCL files or paths" - /// }, - /// "id": 4 - /// } - /// ``` - rpc ExecProgram(ExecProgram_Args) returns (ExecProgram_Result); - - /// Build the KCL program to an artifact. - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "BuildProgram", - /// "params": { - /// "exec_args": { - /// "work_dir": "./src/testdata", - /// "k_filename_list": ["test.k"] - /// }, - /// "output": "./build" - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "path": "./build/test.k" - /// }, - /// "id": 1 - /// } - /// ``` - rpc BuildProgram(BuildProgram_Args) returns (BuildProgram_Result); - - /// Execute the KCL artifact with args. **Note that it is not thread safe.** - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "ExecArtifact", - /// "params": { - /// "path": "./artifact_path", - /// "exec_args": { - /// "work_dir": "./src/testdata", - /// "k_filename_list": ["test.k"] - /// } - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "json_result": "{\"alice\": {\"age\": 18}}", - /// "yaml_result": "alice:\n age: 18", - /// "log_message": "", - /// "err_message": "" - /// }, - /// "id": 1 - /// } - /// ``` - rpc ExecArtifact(ExecArtifact_Args) returns (ExecProgram_Result); - - /// Override KCL file with args. - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "OverrideFile", - /// "params": { - /// "file": "./src/testdata/test.k", - /// "specs": ["alice.age=18"] - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "result": true, - /// "parse_errors": [] - /// }, - /// "id": 1 - /// } - /// ``` - rpc OverrideFile(OverrideFile_Args) returns (OverrideFile_Result); - - /// Get schema type mapping. - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "GetSchemaTypeMapping", - /// "params": { - /// "exec_args": { - /// "work_dir": "./src/testdata", - /// "k_filename_list": ["main.k"], - /// "external_pkgs": [ - /// { - /// "pkg_name":"pkg", - /// "pkg_path": "./src/testdata/pkg" - /// } - /// ] - /// }, - /// "schema_name": "Person" - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "schema_type_mapping": { - /// "Person": { - /// "type": "schema", - /// "schema_name": "Person", - /// "properties": { - /// "name": { "type": "str" }, - /// "age": { "type": "int" } - /// }, - /// "required": ["name", "age"], - /// "decorators": [] - /// } - /// } - /// }, - /// "id": 1 - /// } - /// ``` - rpc GetSchemaTypeMapping(GetSchemaTypeMapping_Args) returns (GetSchemaTypeMapping_Result); - - /// Format code source. - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "FormatCode", - /// "params": { - /// "source": "schema Person {\n name: str\n age: int\n}\nperson = Person {\n name = \"Alice\"\n age = 18\n}\n" - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "formatted": "schema Person {\n name: str\n age: int\n}\nperson = Person {\n name = \"Alice\"\n age = 18\n}\n" - /// }, - /// "id": 1 - /// } - /// ``` - rpc FormatCode(FormatCode_Args) returns (FormatCode_Result); - - /// Format KCL file or directory path contains KCL files and returns the changed file paths. - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "FormatPath", - /// "params": { - /// "path": "./src/testdata/test.k" - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "changed_paths": [] - /// }, - /// "id": 1 - /// } - /// ``` - rpc FormatPath(FormatPath_Args) returns (FormatPath_Result); - - /// Lint files and return error messages including errors and warnings. - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "LintPath", - /// "params": { - /// "paths": ["./src/testdata/test-lint.k"] - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "results": ["Module 'math' imported but unused"] - /// }, - /// "id": 1 - /// } - /// ``` - rpc LintPath(LintPath_Args) returns (LintPath_Result); - - /// Validate code using schema and data strings. - /// - /// **Note that it is not thread safe.** - /// - /// # Examples - /// - /// ```jsonrpc - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "ValidateCode", - /// "params": { - /// "code": "schema Person {\n name: str\n age: int\n check: 0 < age < 120\n}", - /// "data": "{\"name\": \"Alice\", \"age\": 10}" - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "success": true, - /// "err_message": "" - /// }, - /// "id": 1 - /// } - /// ``` - rpc ValidateCode(ValidateCode_Args) returns (ValidateCode_Result); - - rpc ListDepFiles(ListDepFiles_Args) returns (ListDepFiles_Result); - /// Build setting file config from args. - /// - /// # Examples - /// - /// - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "LoadSettingsFiles", - /// "params": { - /// "work_dir": "./src/testdata/settings", - /// "files": ["./src/testdata/settings/kcl.yaml"] - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "kcl_cli_configs": { - /// "files": ["./src/testdata/settings/kcl.yaml"], - /// "output": "", - /// "overrides": [], - /// "path_selector": [], - /// "strict_range_check": false, - /// "disable_none": false, - /// "verbose": 0, - /// "debug": false, - /// "sort_keys": false, - /// "show_hidden": false, - /// "include_schema_type_path": false, - /// "fast_eval": false - /// }, - /// "kcl_options": [] - /// }, - /// "id": 1 - /// } - /// ``` - rpc LoadSettingsFiles(LoadSettingsFiles_Args) returns (LoadSettingsFiles_Result); - - /// Rename all the occurrences of the target symbol in the files. This API will rewrite files if they contain symbols to be renamed. - /// Return the file paths that got changed. - /// - /// # Examples - /// - /// - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "Rename", - /// "params": { - /// "package_root": "./src/testdata/rename_doc", - /// "symbol_path": "a", - /// "file_paths": ["./src/testdata/rename_doc/main.k"], - /// "new_name": "a2" - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "changed_files": ["./src/testdata/rename_doc/main.k"] - /// }, - /// "id": 1 - /// } - /// ``` - rpc Rename(Rename_Args) returns (Rename_Result); - - /// Rename all the occurrences of the target symbol and return the modified code if any code has been changed. This API won't rewrite files but return the changed code. - /// - /// # Examples - /// - /// - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "RenameCode", - /// "params": { - /// "package_root": "/mock/path", - /// "symbol_path": "a", - /// "source_codes": { - /// "/mock/path/main.k": "a = 1\nb = a" - /// }, - /// "new_name": "a2" - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "changed_codes": { - /// "/mock/path/main.k": "a2 = 1\nb = a2" - /// } - /// }, - /// "id": 1 - /// } - /// ``` - rpc RenameCode(RenameCode_Args) returns (RenameCode_Result); - - /// Test KCL packages with test arguments. - /// - /// # Examples - /// - /// - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "Test", - /// "params": { - /// "exec_args": { - /// "work_dir": "./src/testdata/testing/module", - /// "k_filename_list": ["main.k"] - /// }, - /// "pkg_list": ["./src/testdata/testing/module/..."] - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "info": [ - /// {"name": "test_case_1", "error": "", "duration": 1000, "log_message": ""}, - /// {"name": "test_case_2", "error": "some error", "duration": 2000, "log_message": ""} - /// ] - /// }, - /// "id": 1 - /// } - /// ``` - rpc Test(Test_Args) returns (Test_Result); - - /// Download and update dependencies defined in the kcl.mod file. - /// - /// # Examples - /// - /// - /// // Request - /// { - /// "jsonrpc": "2.0", - /// "method": "UpdateDependencies", - /// "params": { - /// "manifest_path": "./src/testdata/update_dependencies" - /// }, - /// "id": 1 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "external_pkgs": [ - /// {"pkg_name": "pkg1", "pkg_path": "./src/testdata/update_dependencies/pkg1"} - /// ] - /// }, - /// "id": 1 - /// } - /// - /// // Request with vendor flag - /// { - /// "jsonrpc": "2.0", - /// "method": "UpdateDependencies", - /// "params": { - /// "manifest_path": "./src/testdata/update_dependencies", - /// "vendor": true - /// }, - /// "id": 2 - /// } - /// - /// // Response - /// { - /// "jsonrpc": "2.0", - /// "result": { - /// "external_pkgs": [ - /// {"pkg_name": "pkg1", "pkg_path": "./src/testdata/update_dependencies/pkg1"} - /// ] - /// }, - /// "id": 2 - /// } - /// ``` - rpc UpdateDependencies(UpdateDependencies_Args) returns (UpdateDependencies_Result); -} - -// Message for ping request arguments. -message Ping_Args { - // Value to be sent in the ping request. - string value = 1; -} - -// Message for ping response. -message Ping_Result { - // Value received in the ping response. - string value = 1; -} - -// Message for version request arguments. Empty message. -message GetVersion_Args { - // empty -} - -// Message for version response. -message GetVersion_Result { - // KCL version. - string version = 1; - // Checksum of the KCL version. - string checksum = 2; - // Git Git SHA of the KCL code repo. - string git_sha = 3; - // Detailed version information as a string. - string version_info = 4; -} - -// Message for list method request arguments. Empty message. -message ListMethod_Args { - // empty -} - -// Message for list method response. -message ListMethod_Result { - // List of available method names. - repeated string method_name_list = 1; -} - -// Message for parse file request arguments. -message ParseFile_Args { - // Path of the file to be parsed. - string path = 1; - // Source code to be parsed. - string source = 2; - // External packages path. - repeated ExternalPkg external_pkgs = 3; -} - -// Message for parse file response. -message ParseFile_Result { - // Abstract Syntax Tree (AST) in JSON format. - string ast_json = 1; - // File dependency paths. - repeated string deps = 2; - // List of parse errors. - repeated Error errors = 3; -} - -// Message for parse program request arguments. -message ParseProgram_Args { - // Paths of the program files to be parsed. - repeated string paths = 1; - // Source codes to be parsed. - repeated string sources = 2; - // External packages path. - repeated ExternalPkg external_pkgs = 3; -} - -// Message for parse program response. -message ParseProgram_Result { - // Abstract Syntax Tree (AST) in JSON format. - string ast_json = 1; - // Returns the files in the order they should be compiled. - repeated string paths = 2; - // List of parse errors. - repeated Error errors = 3; -} - -// Message for load package request arguments. -message LoadPackage_Args { - // Arguments for parsing the program. - ParseProgram_Args parse_args = 1; - // Flag indicating whether to resolve AST. - bool resolve_ast = 2; - // Flag indicating whether to load built-in modules. - bool load_builtin = 3; - // Flag indicating whether to include AST index. - bool with_ast_index = 4; -} - -// Message for load package response. -message LoadPackage_Result { - // Program Abstract Syntax Tree (AST) in JSON format. - string program = 1; - // Returns the files in the order they should be compiled. - repeated string paths = 2; - // List of parse errors. - repeated Error parse_errors = 3; - // List of type errors. - repeated Error type_errors = 4; - // Map of scopes with scope index as key. - map scopes = 5; - // Map of symbols with symbol index as key. - map symbols = 6; - // Map of node-symbol associations with AST index UUID as key. - map node_symbol_map = 7; - // Map of symbol-node associations with symbol index as key. - map symbol_node_map = 8; - // Map of fully qualified names with symbol index as key. - map fully_qualified_name_map = 9; - // Map of package scope with package path as key. - map pkg_scope_map = 10; -} - -// Message for list options response. -message ListOptions_Result { - // List of available options. - repeated OptionHelp options = 2; -} - -// Message representing a help option. -message OptionHelp { - // Name of the option. - string name = 1; - // Type of the option. - string type = 2; - // Flag indicating if the option is required. - bool required = 3; - // Default value of the option. - string default_value = 4; - // Help text for the option. - string help = 5; -} - -// Message representing a symbol in KCL. -message Symbol { - // Type of the symbol. - KclType ty = 1; - // Name of the symbol. - string name = 2; - // Owner of the symbol. - SymbolIndex owner = 3; - // Definition of the symbol. - SymbolIndex def = 4; - // Attributes of the symbol. - repeated SymbolIndex attrs = 5; - // Flag indicating if the symbol is global. - bool is_global = 6; -} - -// Message representing a scope in KCL. -message Scope { - // Type of the scope. - string kind = 1; - // Parent scope. - ScopeIndex parent = 2; - // Owner of the scope. - SymbolIndex owner = 3; - // Children of the scope. - repeated ScopeIndex children = 4; - // Definitions in the scope. - repeated SymbolIndex defs = 5; -} - -// Message representing a symbol index. -message SymbolIndex { - // Index identifier. - uint64 i = 1; - // Global identifier. - uint64 g = 2; - // Type of the symbol or scope. - string kind = 3; -} - -// Message representing a scope index. -message ScopeIndex { - // Index identifier. - uint64 i = 1; - // Global identifier. - uint64 g = 2; - // Type of the scope. - string kind = 3; -} - -// Message for execute program request arguments. -message ExecProgram_Args { - // Working directory. - string work_dir = 1; - // List of KCL filenames. - repeated string k_filename_list = 2; - // List of KCL codes. - repeated string k_code_list = 3; - // Arguments for the program. - repeated Argument args = 4; - // Override configurations. - repeated string overrides = 5; - // Flag to disable YAML result. - bool disable_yaml_result = 6; - // Flag to print override AST. - bool print_override_ast = 7; - // Flag for strict range check. - bool strict_range_check = 8; - // Flag to disable none values. - bool disable_none = 9; - // Verbose level. - int32 verbose = 10; - // Debug level. - int32 debug = 11; - // Flag to sort keys in YAML/JSON results. - bool sort_keys = 12; - // External packages path. - repeated ExternalPkg external_pkgs = 13; - // Flag to include schema type path in results. - bool include_schema_type_path = 14; - // Flag to compile only without execution. - bool compile_only = 15; - // Flag to show hidden attributes. - bool show_hidden = 16; - // Path selectors for results. - repeated string path_selector = 17; - // Flag for fast evaluation. - bool fast_eval = 18; -} - -// Message for execute program response. -message ExecProgram_Result { - // Result in JSON format. - string json_result = 1; - // Result in YAML format. - string yaml_result = 2; - // Log message from execution. - string log_message = 3; - // Error message from execution. - string err_message = 4; -} - -// Message for build program request arguments. -message BuildProgram_Args { - // Arguments for executing the program. - ExecProgram_Args exec_args = 1; - // Output path. - string output = 2; -} - -// Message for build program response. -message BuildProgram_Result { - // Path of the built program. - string path = 1; -} - -// Message for execute artifact request arguments. -message ExecArtifact_Args { - // Path of the artifact. - string path = 1; - // Arguments for executing the program. - ExecProgram_Args exec_args = 2; -} - -// Message for format code request arguments. -message FormatCode_Args { - // Source code to be formatted. - string source = 1; -} - -// Message for format code response. -message FormatCode_Result { - // Formatted code as bytes. - bytes formatted = 1; -} - -// Message for format file path request arguments. -message FormatPath_Args { - // Path of the file to format. - string path = 1; -} - -// Message for format file path response. -message FormatPath_Result { - // List of changed file paths. - repeated string changed_paths = 1; -} - -// Message for lint file path request arguments. -message LintPath_Args { - // Paths of the files to lint. - repeated string paths = 1; -} - -// Message for lint file path response. -message LintPath_Result { - // List of lint results. - repeated string results = 1; -} - -// Message for override file request arguments. -message OverrideFile_Args { - // Path of the file to override. - string file = 1; - // List of override specifications. - repeated string specs = 2; - // List of import paths. - repeated string import_paths = 3; -} - -// Message for override file response. -message OverrideFile_Result { - // Result of the override operation. - bool result = 1; - // List of parse errors encountered. - repeated Error parse_errors = 2; -} - -// Message for list variables options. -message ListVariables_Options { - // Flag to merge program configuration. - bool merge_program = 1; -} - -// Message representing a list of variables. -message VariableList { - // List of variables. - repeated Variable variables = 1; -} - -// Message for list variables request arguments. -message ListVariables_Args { - // Files to be processed. - repeated string files = 1; - // Specifications for variables. - repeated string specs = 2; - // Options for listing variables. - ListVariables_Options options = 3; -} - -// Message for list variables response. -message ListVariables_Result { - // Map of variable lists by file. - map variables = 1; - // List of unsupported codes. - repeated string unsupported_codes = 2; - // List of parse errors encountered. - repeated Error parse_errors = 3; -} - -// Message representing a variable. -message Variable { - // Value of the variable. - string value = 1; - // Type name of the variable. - string type_name = 2; - // Operation symbol associated with the variable. - string op_sym = 3; - // List items if the variable is a list. - repeated Variable list_items = 4; - // Dictionary entries if the variable is a dictionary. - repeated MapEntry dict_entries = 5; -} - -// Message representing a map entry. -message MapEntry { - // Key of the map entry. - string key = 1; - // Value of the map entry. - Variable value = 2; -} - -// Message for get schema type mapping request arguments. -message GetSchemaTypeMapping_Args { - // Arguments for executing the program. - ExecProgram_Args exec_args = 1; - // Name of the schema. - string schema_name = 2; -} - -// Message for get schema type mapping response. -message GetSchemaTypeMapping_Result { - // Map of schema type mappings. - map schema_type_mapping = 1; -} - -// Message for get schema type mapping response. -message GetSchemaTypeMappingUnderPath_Result { - // Map of pkg and schema types mappings. - map schema_type_mapping = 1; -} - -message SchemaTypes { - // List of schema type mappings. - repeated KclType schema_type = 1; -} - -// Message for validate code request arguments. -message ValidateCode_Args { - // Path to the data file. - string datafile = 1; - // Data content. - string data = 2; - // Path to the code file. - string file = 3; - // Source code content. - string code = 4; - // Name of the schema. - string schema = 5; - // Name of the attribute. - string attribute_name = 6; - // Format of the validation (e.g., "json", "yaml"). - string format = 7; - // List of external packages updated. - repeated ExternalPkg external_pkgs = 8; -} - -// Message for validate code response. -message ValidateCode_Result { - // Flag indicating if validation was successful. - bool success = 1; - // Error message from validation. - string err_message = 2; -} - -// Message representing a position in the source code. -message Position { - // Line number. - int64 line = 1; - // Column number. - int64 column = 2; - // Filename the position refers to. - string filename = 3; -} - -// Message for list dependency files request arguments. -message ListDepFiles_Args { - // Working directory. - string work_dir = 1; - // Flag to use absolute paths. - bool use_abs_path = 2; - // Flag to include all files. - bool include_all = 3; - // Flag to use fast parser. - bool use_fast_parser = 4; -} - -// Message for list dependency files response. -message ListDepFiles_Result { - // Root package path. - string pkgroot = 1; - // Package path. - string pkgpath = 2; - // List of file paths in the package. - repeated string files = 3; -} - -// --------------------------------------------------------------------------------- -// LoadSettingsFiles API -// Input work dir and setting files and return the merged kcl singleton config. -// --------------------------------------------------------------------------------- - -// Message for load settings files request arguments. -message LoadSettingsFiles_Args { - // Working directory. - string work_dir = 1; - // Setting files to load. - repeated string files = 2; -} - -// Message for load settings files response. -message LoadSettingsFiles_Result { - // KCL CLI configuration. - CliConfig kcl_cli_configs = 1; - // List of KCL options as key-value pairs. - repeated KeyValuePair kcl_options = 2; -} - -// Message representing KCL CLI configuration. -message CliConfig { - // List of files. - repeated string files = 1; - // Output path. - string output = 2; - // List of overrides. - repeated string overrides = 3; - // Path selectors. - repeated string path_selector = 4; - // Flag for strict range check. - bool strict_range_check = 5; - // Flag to disable none values. - bool disable_none = 6; - // Verbose level. - int64 verbose = 7; - // Debug flag. - bool debug = 8; - // Flag to sort keys in YAML/JSON results. - bool sort_keys = 9; - // Flag to show hidden attributes. - bool show_hidden = 10; - // Flag to include schema type path in results. - bool include_schema_type_path = 11; - // Flag for fast evaluation. - bool fast_eval = 12; -} - -// Message representing a key-value pair. -message KeyValuePair { - // Key of the pair. - string key = 1; - // Value of the pair. - string value = 2; -} - -// --------------------------------------------------------------------------------- -// Rename API -// Find all the occurrences of the target symbol and rename them. -// This API will rewrite files if they contain symbols to be renamed. -// --------------------------------------------------------------------------------- - -// Message for rename request arguments. -message Rename_Args { - // File path to the package root. - string package_root = 1; - // Path to the target symbol to be renamed. - string symbol_path = 2; - // Paths to the source code files. - repeated string file_paths = 3; - // New name of the symbol. - string new_name = 4; -} - -// Message for rename response. -message Rename_Result { - // List of file paths that got changed. - repeated string changed_files = 1; -} - -// --------------------------------------------------------------------------------- -// RenameCode API -// Find all the occurrences of the target symbol and rename them. -// This API won't rewrite files but return the modified code if any code has been changed. -// --------------------------------------------------------------------------------- - -// Message for rename code request arguments. -message RenameCode_Args { - // File path to the package root. - string package_root = 1; - // Path to the target symbol to be renamed. - string symbol_path = 2; - // Map of source code with filename as key and code as value. - map source_codes = 3; - // New name of the symbol. - string new_name = 4; -} - -// Message for rename code response. -message RenameCode_Result { - // Map of changed code with filename as key and modified code as value. - map changed_codes = 1; -} - -// --------------------------------------------------------------------------------- -// Test API -// Test KCL packages with test arguments. -// --------------------------------------------------------------------------------- - -// Message for test request arguments. -message Test_Args { - // Execution program arguments. - ExecProgram_Args exec_args = 1; - // List of KCL package paths to be tested. - repeated string pkg_list = 2; - // Regular expression for filtering tests to run. - string run_regexp = 3; - // Flag to stop the test run on the first failure. - bool fail_fast = 4; -} - -// Message for test response. -message Test_Result { - // List of test case information. - repeated TestCaseInfo info = 2; -} - -// Message representing information about a single test case. -message TestCaseInfo { - // Name of the test case. - string name = 1; - // Error message if any. - string error = 2; - // Duration of the test case in microseconds. - uint64 duration = 3; - // Log message from the test case. - string log_message = 4; -} - -// --------------------------------------------------------------------------------- -// UpdateDependencies API -// Download and update dependencies defined in the kcl.mod file. -// --------------------------------------------------------------------------------- - -// Message for update dependencies request arguments. -message UpdateDependencies_Args { - // Path to the manifest file. - string manifest_path = 1; - // Flag to vendor dependencies locally. - bool vendor = 2; -} - -// Message for update dependencies response. -message UpdateDependencies_Result { - // List of external packages updated. - repeated ExternalPkg external_pkgs = 3; -} - -// ---------------------------------------------------------------------------- -// KCL Type Structure -// ---------------------------------------------------------------------------- - -// Message representing a KCL type. -message KclType { - // Type name (e.g., schema, dict, list, str, int, float, bool, any, union, number_multiplier). - string type = 1; - // Union types if applicable. - repeated KclType union_types = 2; - // Default value of the type. - string default = 3; - // Name of the schema if applicable. - string schema_name = 4; - // Documentation for the schema. - string schema_doc = 5; - // Properties of the schema as a map with property name as key. - map properties = 6; - // List of required schema properties. - repeated string required = 7; - // Key type if the KclType is a dictionary. - KclType key = 8; - // Item type if the KclType is a list or dictionary. - KclType item = 9; - // Line number where the type is defined. - int32 line = 10; - // List of decorators for the schema. - repeated Decorator decorators = 11; - // Absolute path of the file where the attribute is located. - string filename = 12; - // Path of the package where the attribute is located. - string pkg_path = 13; - // Documentation for the attribute. - string description = 14; - // Map of examples with example name as key. - map examples = 15; - // Base schema if applicable. - KclType base_schema = 16; -} - -// Message representing a decorator in KCL. -message Decorator { - // Name of the decorator. - string name = 1; - // Arguments for the decorator. - repeated string arguments = 2; - // Keyword arguments for the decorator as a map with keyword name as key. - map keywords = 3; -} - -// Message representing an example in KCL. -message Example { - // Short description for the example. - string summary = 1; - // Long description for the example. - string description = 2; - // Embedded literal example. - string value = 3; -} - -// ---------------------------------------------------------------------------- -// END -// ---------------------------------------------------------------------------- diff --git a/kclvm/src/capi.rs b/kclvm/src/capi.rs deleted file mode 100644 index 31cf412bb..000000000 --- a/kclvm/src/capi.rs +++ /dev/null @@ -1,261 +0,0 @@ -#![allow(clippy::missing_safety_doc)] - -use kclvm_runner::runner::KCL_RUNTIME_PANIC_RECORD; -use std::alloc::{alloc, dealloc, Layout}; -use std::ffi::c_char; -use std::ffi::{CStr, CString}; -use std::{mem, ptr}; - -use crate::{intern_fmt, intern_run}; - -/// Exposes an allocation function to the WASM host. -/// -/// _This implementation is copied from wasm-bindgen_ -#[no_mangle] -pub unsafe extern "C-unwind" fn kcl_malloc(size: usize) -> *mut u8 { - let align = mem::align_of::(); - let layout = Layout::from_size_align(size, align).expect("Invalid layout"); - if layout.size() > 0 { - let ptr = alloc(layout); - if !ptr.is_null() { - ptr::write_bytes(ptr, 0, size); - ptr - } else { - std::alloc::handle_alloc_error(layout); - } - } else { - align as *mut u8 - } -} - -/// Expose a deallocation function to the WASM host. -/// -/// _This implementation is copied from wasm-bindgen_ -#[no_mangle] -pub unsafe extern "C-unwind" fn kcl_free(ptr: *mut u8, size: usize) { - // This happens for zero-length slices, and in that case `ptr` is - // likely bogus so don't actually send this to the system allocator - if size == 0 { - return; - } - let align = mem::align_of::(); - let layout = Layout::from_size_align_unchecked(size, align); - dealloc(ptr, layout); -} - -#[repr(C)] -pub struct ExecProgramResult { - json_result: *const c_char, - yaml_result: *const c_char, - log_message: *const c_char, - err_message: *const c_char, -} - -/// Execute KCL file with arguments and return the JSON/YAML result. -#[no_mangle] -pub unsafe extern "C-unwind" fn kcl_exec_program( - filename_ptr: *const c_char, - src_ptr: *const c_char, -) -> *const ExecProgramResult { - if filename_ptr.is_null() || src_ptr.is_null() { - return std::ptr::null(); - } - let filename = unsafe { CStr::from_ptr(filename_ptr).to_str().unwrap() }; - let src = unsafe { CStr::from_ptr(src_ptr).to_str().unwrap() }; - - match intern_run(filename, src) { - Ok(result) => { - let json = CString::new(result.json_result).unwrap().into_raw(); - let yaml = CString::new(result.yaml_result).unwrap().into_raw(); - let log = CString::new(result.log_message).unwrap().into_raw(); - let err = CString::new(result.err_message).unwrap().into_raw(); - - let exec_result = ExecProgramResult { - json_result: json, - yaml_result: yaml, - log_message: log, - err_message: err, - }; - - Box::into_raw(Box::new(exec_result)) as *const ExecProgramResult - } - Err(err) => { - let result = ExecProgramResult { - err_message: CString::new(err).unwrap().into_raw(), - json_result: std::ptr::null(), - yaml_result: std::ptr::null(), - log_message: std::ptr::null(), - }; - Box::into_raw(Box::new(result)) as *const ExecProgramResult - } - } -} - -/// Free memory allocated for the ExecProgramResult. -#[no_mangle] -pub unsafe extern "C-unwind" fn kcl_free_exec_program_result(result: *const ExecProgramResult) { - if result.is_null() { - return; - } - - let result = Box::from_raw(result as *mut ExecProgramResult); - - if !result.json_result.is_null() { - let _ = CString::from_raw(result.json_result as *mut c_char); // Free the C string - } - if !result.yaml_result.is_null() { - let _ = CString::from_raw(result.yaml_result as *mut c_char); // Free the C string - } - if !result.log_message.is_null() { - let _ = CString::from_raw(result.log_message as *mut c_char); // Free the C string - } - if !result.err_message.is_null() { - let _ = CString::from_raw(result.err_message as *mut c_char); // Free the C string - } - - // Result itself will be freed when going out of scope -} - -/// Get the YAML result from ExecProgramResult. -#[no_mangle] -pub unsafe extern "C-unwind" fn kcl_result_get_yaml_result( - result: *const ExecProgramResult, -) -> *const c_char { - if result.is_null() { - return std::ptr::null(); - } - - let result = &*result; - if result.yaml_result.is_null() { - return std::ptr::null(); - } - - result.yaml_result -} - -/// Get the JSON result from ExecProgramResult. -#[no_mangle] -pub unsafe extern "C-unwind" fn kcl_result_get_json_result( - result: *const ExecProgramResult, -) -> *const c_char { - if result.is_null() { - return std::ptr::null(); - } - - let result = &*result; - if result.json_result.is_null() { - return std::ptr::null(); - } - - result.json_result -} - -/// Get the error message from ExecProgramResult. -#[no_mangle] -pub unsafe extern "C-unwind" fn kcl_result_get_err_message( - result: *const ExecProgramResult, -) -> *const c_char { - if result.is_null() { - return std::ptr::null(); - } - - let result = &*result; - if result.err_message.is_null() { - return std::ptr::null(); - } - - result.err_message -} - -/// Get the log message from ExecProgramResult. -#[no_mangle] -pub unsafe extern "C-unwind" fn kcl_result_get_log_message( - result: *const ExecProgramResult, -) -> *const c_char { - if result.is_null() { - return std::ptr::null(); - } - - let result = &*result; - if result.log_message.is_null() { - return std::ptr::null(); - } - - result.log_message -} - -/// Exposes a normal kcl run function to the WASM host. -#[no_mangle] -pub unsafe extern "C-unwind" fn kcl_run( - filename_ptr: *const c_char, - src_ptr: *const c_char, -) -> *const c_char { - if filename_ptr.is_null() || src_ptr.is_null() { - return std::ptr::null(); - } - let filename = unsafe { CStr::from_ptr(filename_ptr).to_str().unwrap() }; - let src = unsafe { CStr::from_ptr(src_ptr).to_str().unwrap() }; - - match intern_run(filename, src) { - Ok(result) => CString::new(result.yaml_result).unwrap().into_raw(), - Err(err) => CString::new(format!("ERROR:{err}")).unwrap().into_raw(), - } -} - -/// Exposes a normal kcl run function with the log message to the WASM host. -#[no_mangle] -pub unsafe extern "C-unwind" fn kcl_run_with_log_message( - filename_ptr: *const c_char, - src_ptr: *const c_char, -) -> *const c_char { - if filename_ptr.is_null() || src_ptr.is_null() { - return std::ptr::null(); - } - let filename = unsafe { CStr::from_ptr(filename_ptr).to_str().unwrap() }; - let src = unsafe { CStr::from_ptr(src_ptr).to_str().unwrap() }; - - match intern_run(filename, src) { - Ok(result) => CString::new(result.log_message + &result.yaml_result) - .unwrap() - .into_raw(), - Err(err) => CString::new(format!("ERROR:{err}")).unwrap().into_raw(), - } -} - -/// Exposes a normal kcl fmt function to the WASM host. -#[no_mangle] -pub unsafe extern "C-unwind" fn kcl_fmt(src_ptr: *const c_char) -> *const c_char { - if src_ptr.is_null() { - return std::ptr::null(); - } - let src = unsafe { CStr::from_ptr(src_ptr).to_str().unwrap() }; - - match intern_fmt(src) { - Ok(result) => CString::new(result).unwrap().into_raw(), - Err(err) => CString::new(format!("ERROR:{err}")).unwrap().into_raw(), - } -} - -/// Exposes a normal kcl version function to the WASM host. -#[no_mangle] -pub unsafe extern "C-unwind" fn kcl_version() -> *const c_char { - CString::new(kclvm_version::VERSION).unwrap().into_raw() -} - -/// Exposes a normal kcl runtime error function to the WASM host. -#[no_mangle] -pub unsafe extern "C-unwind" fn kcl_runtime_err(buffer: *mut u8, length: usize) -> isize { - KCL_RUNTIME_PANIC_RECORD.with(|e| { - let message = &e.borrow().message; - if !message.is_empty() { - let bytes = message.as_bytes(); - let copy_len = std::cmp::min(bytes.len(), length); - unsafe { - std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, copy_len); - } - copy_len as isize - } else { - 0 - } - }) -} diff --git a/kclvm/src/lib.rs b/kclvm/src/lib.rs deleted file mode 100644 index e8f5b2374..000000000 --- a/kclvm/src/lib.rs +++ /dev/null @@ -1,134 +0,0 @@ -#![allow(clippy::missing_safety_doc)] - -use std::ffi::{c_char, c_int, CStr}; -use std::process::ExitCode; - -use kclvm_api::FormatCodeArgs; -use kclvm_api::{ExecProgramArgs, API}; - -mod capi; -pub use capi::*; -use kclvm_parser::ParseSessionRef; -use kclvm_runner::exec_program; -use kclvm_runtime::PanicInfo; - -/// KCL CLI run function CAPI. -/// -/// args is a ExecProgramArgs JSON string. -#[no_mangle] -pub unsafe extern "C-unwind" fn kclvm_cli_run( - args: *const c_char, - plugin_agent: *const c_char, -) -> *const c_char { - let prev_hook = std::panic::take_hook(); - - // disable print panic info - std::panic::set_hook(Box::new(|_info| {})); - let kclvm_cli_run_unsafe_result = - std::panic::catch_unwind(|| kclvm_cli_run_unsafe(args, plugin_agent)); - std::panic::set_hook(prev_hook); - - match kclvm_cli_run_unsafe_result { - Ok(result) => match result { - Ok(result) => { - let c_string = - std::ffi::CString::new(result.as_str()).expect("CString::new failed"); - let ptr = c_string.into_raw(); - ptr as *const c_char - } - Err(result) => { - let result = format!("ERROR:{result}"); - let c_string = - std::ffi::CString::new(result.as_str()).expect("CString::new failed"); - let ptr = c_string.into_raw(); - ptr as *const c_char - } - }, - Err(err) => { - let err_message = kclvm_error::err_to_str(err); - let result = format!("ERROR:{err_message:}"); - let c_string = std::ffi::CString::new(result.as_str()).expect("CString::new failed"); - let ptr = c_string.into_raw(); - ptr as *const c_char - } - } -} - -/// KCL CLI run function CAPI. -fn kclvm_cli_run_unsafe( - args: *const c_char, - plugin_agent: *const c_char, -) -> Result { - let mut args = kclvm_runner::ExecProgramArgs::from_str( - unsafe { std::ffi::CStr::from_ptr(args) }.to_str().unwrap(), - ); - args.plugin_agent = plugin_agent as u64; - exec_program(ParseSessionRef::default(), &args) - .map_err(|e| PanicInfo::from(e.to_string()).to_json_string()) - .map(|r| r.json_result) -} - -/// KCL CLI main function CAPI. -#[no_mangle] -pub unsafe extern "C-unwind" fn kclvm_cli_main( - argc: c_int, - argv: *const *const c_char, -) -> *mut ExitCode { - let prev_hook = std::panic::take_hook(); - - // disable print panic info - std::panic::set_hook(Box::new(|_info| {})); - let kclvm_cli_main_result = std::panic::catch_unwind(|| { - let args: Vec<&str> = unsafe { - std::slice::from_raw_parts(argv, argc as usize) - .iter() - .map(|ptr| CStr::from_ptr(*ptr).to_str().unwrap()) - .collect() - }; - kclvm_cmd::main(args.as_slice()) - }); - std::panic::set_hook(prev_hook); - - match kclvm_cli_main_result { - Ok(result) => match result { - Ok(()) => Box::into_raw(Box::new(ExitCode::SUCCESS)), - Err(err) => { - let backtrace = format!("{}", err.backtrace()); - if backtrace.is_empty() || backtrace.contains("disabled backtrace") { - eprintln!("{err}"); - } else { - eprintln!("{err}\nStack backtrace:\n{backtrace}"); - } - Box::into_raw(Box::new(ExitCode::FAILURE)) - } - }, - Err(err) => { - let err_str = kclvm_error::err_to_str(err); - if !err_str.is_empty() { - eprintln!("{err_str}"); - } - Box::into_raw(Box::new(ExitCode::FAILURE)) - } - } -} - -fn intern_run(filename: &str, src: &str) -> Result { - let api = API::default(); - let args = &ExecProgramArgs { - k_filename_list: vec![filename.to_string()], - k_code_list: vec![src.to_string()], - ..Default::default() - }; - api.exec_program(args).map_err(|err| err.to_string()) -} - -fn intern_fmt(src: &str) -> Result { - let api = API::default(); - let args = &FormatCodeArgs { - source: src.to_string(), - }; - match api.format_code(args) { - Ok(result) => String::from_utf8(result.formatted).map_err(|err| err.to_string()), - Err(err) => Err(err.to_string()), - } -} diff --git a/kclvm/tests/Cargo.lock b/kclvm/tests/Cargo.lock deleted file mode 100644 index 7f9e7f10f..000000000 --- a/kclvm/tests/Cargo.lock +++ /dev/null @@ -1,7 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "tests" -version = "0.1.0" diff --git a/kclvm/tests/Cargo.toml b/kclvm/tests/Cargo.toml deleted file mode 100644 index ec8ef80a9..000000000 --- a/kclvm/tests/Cargo.toml +++ /dev/null @@ -1,8 +0,0 @@ -[package] -name = "tests" -version = "0.5.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] diff --git a/kclvm/tests/fuzz/.gitignore b/kclvm/tests/fuzz/.gitignore deleted file mode 100644 index a0925114d..000000000 --- a/kclvm/tests/fuzz/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -target -corpus -artifacts diff --git a/kclvm/tests/fuzz/Cargo.lock b/kclvm/tests/fuzz/Cargo.lock deleted file mode 100644 index 414b2c723..000000000 --- a/kclvm/tests/fuzz/Cargo.lock +++ /dev/null @@ -1,4654 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "addr2line" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4fa78e18c64fce05e902adecd7a5eed15a5e0a3439f7b0e169f0252214865e3" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" - -[[package]] -name = "ahash" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" -dependencies = [ - "getrandom", - "once_cell", - "version_check", -] - -[[package]] -name = "aho-corasick" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43f6cb1bf222025340178f382c426f13757b2960e89779dfcb319c32542a5a41" -dependencies = [ - "memchr", -] - -[[package]] -name = "always-assert" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4436e0292ab1bb631b42973c61205e704475fe8126af845c8d923c0996328127" -dependencies = [ - "log", -] - -[[package]] -name = "android-tzdata" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" - -[[package]] -name = "android_system_properties" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" -dependencies = [ - "libc", -] - -[[package]] -name = "annotate-snippets" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccaf7e9dfbb6ab22c82e473cd1a8a7bd313c19a5b7e40970f3d89ef5a5c9e81e" -dependencies = [ - "unicode-width", - "yansi-term", -] - -[[package]] -name = "anstream" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ca84f3628370c59db74ee214b3263d58f9aadd9b4fe7e711fd87dc452b7f163" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon 1.0.1", - "colorchoice", - "is-terminal", - "utf8parse", -] - -[[package]] -name = "anstream" -version = "0.6.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "418c75fa768af9c03be99d17643f93f79bbba589895012a80e3452a19ddda15b" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon 3.0.3", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "038dfcf04a5feb68e9c60b21c9625a54c2c0616e79b72b0fd87075a056ae1d1b" - -[[package]] -name = "anstyle-parse" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "938874ff5980b03a87c5524b3ae5b59cf99b1d6bc836848df7bc5ada9643c333" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b" -dependencies = [ - "windows-sys 0.48.0", -] - -[[package]] -name = "anstyle-wincon" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "180abfa45703aebe0093f79badacc01b8fd4ea2e35118747e5811127f926e188" -dependencies = [ - "anstyle", - "windows-sys 0.48.0", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61a38449feb7068f52bb06c12759005cf459ee52bb4adc1d5a7c4322d716fb19" -dependencies = [ - "anstyle", - "windows-sys 0.52.0", -] - -[[package]] -name = "anyhow" -version = "1.0.72" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b13c32d80ecc7ab747b80c3784bce54ee8a7a0cc4fbda9bf4cda2cf6fe90854" -dependencies = [ - "backtrace", -] - -[[package]] -name = "arbitrary" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c38b6b6b79f671c25e1a3e785b7b82d7562ffc9cd3efdc98627e5668a2472490" -dependencies = [ - "derive_arbitrary", -] - -[[package]] -name = "arrayvec" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" - -[[package]] -name = "async-stream" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd56dd203fef61ac097dd65721a419ddccb106b2d2b70ba60a6b529f03961a51" -dependencies = [ - "async-stream-impl", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream-impl" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.67", -] - -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi 0.1.19", - "libc", - "winapi", -] - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "backtrace" -version = "0.3.68" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4319208da049c43661739c5fade2ba182f09d1dc2299b32298d3a31692b17e12" -dependencies = [ - "addr2line", - "cc", - "cfg-if 1.0.0", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", -] - -[[package]] -name = "base-x" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cbbc9d0964165b47557570cce6c952866c2678457aca742aafc9fb771d30270" - -[[package]] -name = "base64" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "bit-set" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e11e16035ea35e4e5997b393eacbf6f63983188f7a2ad25bfb13465f5ad59de" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" - -[[package]] -name = "bitmaps" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "031043d04099746d8db04daf1fa424b2bc8bd69d92b25962dcde24da39ab64a2" -dependencies = [ - "typenum", -] - -[[package]] -name = "block-buffer" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" -dependencies = [ - "block-padding", - "byte-tools", - "byteorder", - "generic-array 0.12.4", -] - -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "generic-array 0.14.5", -] - -[[package]] -name = "block-buffer" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324" -dependencies = [ - "generic-array 0.14.5", -] - -[[package]] -name = "block-padding" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" -dependencies = [ - "byte-tools", -] - -[[package]] -name = "bstr" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" -dependencies = [ - "lazy_static", - "memchr", - "regex-automata 0.1.10", -] - -[[package]] -name = "bumpalo" -version = "3.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1" - -[[package]] -name = "byte-tools" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "bytes" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" - -[[package]] -name = "cc" -version = "1.0.99" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96c51067fd44124faa7f870b4b1c969379ad32b2ba805aa959430ceaa384f695" - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "chrono" -version = "0.4.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" -dependencies = [ - "android-tzdata", - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-targets 0.52.0", -] - -[[package]] -name = "clap" -version = "4.3.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd304a20bff958a57f04c4e96a2e7594cc4490a0e809cbd48bb6437edaa452d" -dependencies = [ - "clap_builder", -] - -[[package]] -name = "clap_builder" -version = "4.3.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01c6a3f08f1fe5662a35cfe393aec09c4df95f60ee93b7556505260f75eee9e1" -dependencies = [ - "anstream 0.3.2", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_lex" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b" - -[[package]] -name = "colorchoice" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" - -[[package]] -name = "compiler_base_error" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32e6a143200e9657a565b093fde64a590af93884d1f820829db6461de1ff0086" -dependencies = [ - "anyhow", - "compiler_base_macros", - "compiler_base_span", - "fluent", - "pretty_assertions", - "rustc_errors", - "rustc_span", - "termcolor", - "unic-langid", - "walkdir", -] - -[[package]] -name = "compiler_base_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21900034f34b69f860a5ff66e0577b8e66d310090b04bf0334afea9a041e0cee" - -[[package]] -name = "compiler_base_session" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67411f0b5421d9c9f045ec08c4d01fe3861197d11215d1e2e448be663aff9ad9" -dependencies = [ - "anyhow", - "compiler_base_error", - "compiler_base_span", -] - -[[package]] -name = "compiler_base_span" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a42aae2adfa4b418441ede52835f3c96e9ca63d595f0ac861d94935757e9cb2e" -dependencies = [ - "rustc_span", -] - -[[package]] -name = "const_fn" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbdcdcb6d86f71c5e97409ad45898af11cbc995b4ee8112d59095a28d376c935" - -[[package]] -name = "core-foundation-sys" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" - -[[package]] -name = "cpufeatures" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b" -dependencies = [ - "libc", -] - -[[package]] -name = "crc32fast" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "crossbeam-channel" -version = "0.5.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82a9b73a36529d9c47029b9fb3a6f0ea3cc916a261195352ba19e770fc1748b2" -dependencies = [ - "cfg-if 1.0.0", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" -dependencies = [ - "cfg-if 1.0.0", - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1145cf131a2c6ba0615079ab6a638f7e1973ac9c2634fcbeaaad6114246efe8c" -dependencies = [ - "autocfg", - "cfg-if 1.0.0", - "crossbeam-utils", - "lazy_static", - "memoffset", - "scopeguard", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3a430a770ebd84726f584a90ee7f020d28db52c6d02138900f22341f866d39c" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "crypto-common" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8" -dependencies = [ - "generic-array 0.14.5", - "typenum", -] - -[[package]] -name = "dashmap" -version = "5.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3495912c9c1ccf2e18976439f4443f3fee0fd61f424ff99fde6a66b15ecb448f" -dependencies = [ - "cfg-if 1.0.0", - "hashbrown 0.12.3", - "lock_api", - "parking_lot_core 0.9.3", -] - -[[package]] -name = "deranged" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7684a49fb1af197853ef7b2ee694bc1f5b4179556f1e5710e1760c5db6f5e929" - -[[package]] -name = "derive_arbitrary" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "98e23c06c035dac87bd802d98f368df73a7f2cb05a66ffbd1f377e821fac4af9" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.95", -] - -[[package]] -name = "diff" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" - -[[package]] -name = "digest" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" -dependencies = [ - "generic-array 0.12.4", -] - -[[package]] -name = "digest" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" -dependencies = [ - "generic-array 0.14.5", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer 0.10.2", - "crypto-common", - "subtle", -] - -[[package]] -name = "dirs" -version = "5.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" -dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys 0.48.0", -] - -[[package]] -name = "discard" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "212d0f5754cb6769937f4501cc0e67f4f4483c8d2c3e1e922ee9edbe4ab4c7c0" - -[[package]] -name = "displaydoc" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.67", -] - -[[package]] -name = "either" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" - -[[package]] -name = "ena" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7402b94a93c24e742487327a7cd839dc9d36fec9de9fb25b09f2dae459f36c3" -dependencies = [ - "log", -] - -[[package]] -name = "enquote" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06c36cb11dbde389f4096111698d8b567c0720e3452fd5ac3e6b4e47e1939932" -dependencies = [ - "thiserror", -] - -[[package]] -name = "env_filter" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a009aa4810eb158359dda09d0c87378e4bbb89b5a801f016885a4707ba24f7ea" -dependencies = [ - "log", - "regex", -] - -[[package]] -name = "env_logger" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38b35839ba51819680ba087cd351788c9a3c476841207e0b8cee0b04722343b9" -dependencies = [ - "anstream 0.6.14", - "anstyle", - "env_filter", - "humantime", - "log", -] - -[[package]] -name = "equivalent" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" - -[[package]] -name = "erased-serde" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da96524cc884f6558f1769b6c46686af2fe8e8b4cd253bd5a3cdba8181b8e070" -dependencies = [ - "serde", -] - -[[package]] -name = "errno" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "fancy-regex" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d6b8560a05112eb52f04b00e5d3790c0dd75d9d980eb8a122fb23b92a623ccf" -dependencies = [ - "bit-set", - "regex", -] - -[[package]] -name = "fastrand" -version = "2.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6999dc1837253364c2ebb0704ba97994bd874e8f195d665c50b7548f6ea92764" - -[[package]] -name = "filetime" -version = "0.2.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ee447700ac8aa0b2f2bd7bc4462ad686ba06baa6727ac149a2d6277f0d240fd" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "redox_syscall 0.4.1", - "windows-sys 0.52.0", -] - -[[package]] -name = "fixedbitset" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "279fb028e20b3c4c320317955b77c5e0c9701f05a1d309905d6fc702cdc5053e" - -[[package]] -name = "flate2" -version = "1.0.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f54427cfd1c7829e2a139fcefea601bf088ebca651d2bf53ebc600eac295dae" -dependencies = [ - "crc32fast", - "miniz_oxide", -] - -[[package]] -name = "fluent" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61f69378194459db76abd2ce3952b790db103ceb003008d3d50d97c41ff847a7" -dependencies = [ - "fluent-bundle", - "unic-langid", -] - -[[package]] -name = "fluent-bundle" -version = "0.15.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e242c601dec9711505f6d5bbff5bedd4b61b2469f2e8bb8e57ee7c9747a87ffd" -dependencies = [ - "fluent-langneg", - "fluent-syntax", - "intl-memoizer", - "intl_pluralrules", - "rustc-hash", - "self_cell 0.10.3", - "smallvec", - "unic-langid", -] - -[[package]] -name = "fluent-langneg" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c4ad0989667548f06ccd0e306ed56b61bd4d35458d54df5ec7587c0e8ed5e94" -dependencies = [ - "unic-langid", -] - -[[package]] -name = "fluent-syntax" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0abed97648395c902868fee9026de96483933faa54ea3b40d652f7dfe61ca78" -dependencies = [ - "thiserror", -] - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "form_urlencoded" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "fsevent-sys" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" -dependencies = [ - "libc", -] - -[[package]] -name = "fslock" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04412b8935272e3a9bae6f48c7bfff74c2911f60525404edfdd28e49884c3bfb" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "fst" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ab85b9b05e3978cc9a9cf8fea7f01b494e1a09ed3037e16ba39edc7a29eb61a" - -[[package]] -name = "futures" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23342abe12aba583913b2e62f22225ff9c950774065e4bfb61a19cd9770fec40" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "955518d47e09b25bbebc7a18df10b81f0c766eaf4c4f1cccef2fca5f2a4fb5f2" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bca583b7e26f571124fe5b7561d49cb2868d79116cfa0eefce955557c6fee8c" - -[[package]] -name = "futures-executor" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccecee823288125bd88b4d7f565c9e58e41858e47ab72e8ea2d64e93624386e0" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964" - -[[package]] -name = "futures-macro" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.67", -] - -[[package]] -name = "futures-sink" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f43be4fe21a13b9781a69afa4985b0f6ee0e1afab2c6f454a8cf30e2b2237b6e" - -[[package]] -name = "futures-task" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76d3d132be6c0e6aa1534069c705a74a5997a356c0dc2f86a47765e5617c5b65" - -[[package]] -name = "futures-util" -version = "0.3.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26b01e40b772d54cf6c6d721c1d1abd0647a0106a12ecaa1c186273392a69533" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "pin-utils", - "slab", -] - -[[package]] -name = "generational-arena" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877e94aff08e743b651baaea359664321055749b398adff8740a7399af7796e7" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "generic-array" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" -dependencies = [ - "typenum", -] - -[[package]] -name = "generic-array" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "wasi", -] - -[[package]] -name = "gimli" -version = "0.27.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c80984affa11d98d1b88b66ac8853f143217b399d3c74116778ff8fdb4ed2e" - -[[package]] -name = "glob" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" - -[[package]] -name = "handlebars" -version = "5.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d08485b96a0e6393e9e4d1b8d48cf74ad6c063cd905eb33f42c1ce3f0377539b" -dependencies = [ - "log", - "pest", - "pest_derive", - "serde", - "serde_json", - "thiserror", -] - -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" - -[[package]] -name = "hashbrown" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "290f1a1d9242c78d09ce40a5e87e7554ee637af1351968159f4952f028f75604" - -[[package]] -name = "heck" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" -dependencies = [ - "unicode-segmentation", -] - -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - -[[package]] -name = "hermit-abi" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b" - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest 0.10.7", -] - -[[package]] -name = "http" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - -[[package]] -name = "http-auth" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "643c9bbf6a4ea8a656d6b4cd53d34f79e3f841ad5203c1a55fb7d761923bc255" -dependencies = [ - "memchr", -] - -[[package]] -name = "http-body" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643" -dependencies = [ - "bytes", - "http", -] - -[[package]] -name = "http-body-util" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" -dependencies = [ - "bytes", - "futures-util", - "http", - "http-body", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fcc0b4a115bf80b728eb8ea024ad5bd707b615bfed49e0665b6e0f86fd082d9" - -[[package]] -name = "humantime" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" - -[[package]] -name = "hyper" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe575dd17d0862a9a33781c8c4696a55c320909004a67a00fb286ba8b1bc496d" -dependencies = [ - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "httparse", - "itoa", - "pin-project-lite", - "smallvec", - "tokio", - "want", -] - -[[package]] -name = "hyper-rustls" -version = "0.27.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ee4be2c948921a1a5320b629c4193916ed787a7f7f293fd3f7f5a6c9de74155" -dependencies = [ - "futures-util", - "http", - "hyper", - "hyper-util", - "rustls", - "rustls-pki-types", - "tokio", - "tokio-rustls", - "tower-service", - "webpki-roots", -] - -[[package]] -name = "hyper-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b875924a60b96e5d7b9ae7b066540b1dd1cbd90d1828f54c92e02a283351c56" -dependencies = [ - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "hyper", - "pin-project-lite", - "socket2", - "tokio", - "tower", - "tower-service", - "tracing", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "idna" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" -dependencies = [ - "unicode-bidi", - "unicode-normalization", -] - -[[package]] -name = "im-rc" -version = "15.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af1955a75fa080c677d3972822ec4bad316169ab1cfc6c257a942c2265dbe5fe" -dependencies = [ - "bitmaps", - "rand_core", - "rand_xoshiro", - "sized-chunks", - "typenum", - "version_check", -] - -[[package]] -name = "indexmap" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", - "rustc-rayon 0.5.0", -] - -[[package]] -name = "indexmap" -version = "2.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" -dependencies = [ - "equivalent", - "hashbrown 0.14.3", -] - -[[package]] -name = "inotify" -version = "0.9.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8069d3ec154eb856955c1c0fbffefbf5f3c40a104ec912d4797314c1801abff" -dependencies = [ - "bitflags 1.3.2", - "inotify-sys", - "libc", -] - -[[package]] -name = "inotify-sys" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb" -dependencies = [ - "libc", -] - -[[package]] -name = "instant" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "intl-memoizer" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c310433e4a310918d6ed9243542a6b83ec1183df95dff8f23f87bb88a264a66f" -dependencies = [ - "type-map", - "unic-langid", -] - -[[package]] -name = "intl_pluralrules" -version = "7.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "078ea7b7c29a2b4df841a7f6ac8775ff6074020c6776d48491ce2268e068f972" -dependencies = [ - "unic-langid", -] - -[[package]] -name = "inventory" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a53088c87cf71c9d4f3372a2cb9eea1e7b8a0b1bf8b7f7d23fe5b76dbb07e63b" - -[[package]] -name = "ipnet" -version = "2.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" - -[[package]] -name = "is-terminal" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb0889898416213fab133e1d33a0e5858a48177452750691bde3666d0fdbaf8b" -dependencies = [ - "hermit-abi 0.3.2", - "rustix", - "windows-sys 0.48.0", -] - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8478577c03552c21db0e2724ffb8986a5ce7af88107e6be5d2ee6e158c12800" - -[[package]] -name = "itertools" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112c678d4050afce233f4f2852bb2eb519230b3cf12f33585275537d7e41578d" - -[[package]] -name = "jobserver" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af25a77299a7f711a01975c35a6a424eb6862092cc2d6c72c4ed6cbc56dfc1fa" -dependencies = [ - "libc", -] - -[[package]] -name = "jod-thread" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b23360e99b8717f20aaa4598f5a6541efbe30630039fbc7706cf954a87947ae" - -[[package]] -name = "js-sys" -version = "0.3.64" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" -dependencies = [ - "wasm-bindgen", -] - -[[package]] -name = "json-spanned-value" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb343fa4e3b1b22b344937deedac88da995abf139c2232cbeaa436c38380a210" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "jsonrpc-core" -version = "18.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14f7f76aef2d054868398427f6c54943cf3d1caa9a7ec7d0c38d69df97a965eb" -dependencies = [ - "futures", - "futures-executor", - "futures-util", - "log", - "serde", - "serde_derive", - "serde_json", -] - -[[package]] -name = "jsonrpc-stdio-server" -version = "18.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6878586767497326eb3d011bd6dbb583e9f008b11528f82fd47798ec46bb6c26" -dependencies = [ - "futures", - "jsonrpc-core", - "log", - "tokio", - "tokio-util 0.6.10", -] - -[[package]] -name = "jwt" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6204285f77fe7d9784db3fdc449ecce1a0114927a51d5a41c4c7a292011c015f" -dependencies = [ - "base64 0.13.0", - "crypto-common", - "digest 0.10.7", - "hmac", - "serde", - "serde_json", - "sha2 0.10.2", -] - -[[package]] -name = "kcl-language-server" -version = "0.9.0" -dependencies = [ - "anyhow", - "chrono", - "clap", - "compiler_base_session", - "crossbeam-channel", - "dashmap", - "env_logger", - "im-rc", - "indexmap 1.9.3", - "kclvm-ast", - "kclvm-config", - "kclvm-driver", - "kclvm-error", - "kclvm-parser", - "kclvm-query", - "kclvm-sema", - "kclvm-span", - "kclvm-tools", - "kclvm-utils", - "kclvm-version", - "log", - "lsp-server", - "lsp-types", - "maplit", - "parking_lot 0.12.3", - "proc_macro_crate", - "ra_ap_vfs", - "ra_ap_vfs-notify", - "ropey", - "rustc-hash", - "rustc_lexer", - "salsa", - "serde", - "serde_json", - "threadpool", - "tokio", - "tokio-test", -] - -[[package]] -name = "kclvm" -version = "0.9.0" -dependencies = [ - "kclvm-api", - "kclvm-ast", - "kclvm-cmd", - "kclvm-compiler", - "kclvm-config", - "kclvm-driver", - "kclvm-error", - "kclvm-evaluator", - "kclvm-loader", - "kclvm-parser", - "kclvm-query", - "kclvm-runner", - "kclvm-runtime", - "kclvm-sema", - "kclvm-tools", - "kclvm-version", -] - -[[package]] -name = "kclvm-api" -version = "0.9.0" -dependencies = [ - "anyhow", - "futures", - "indexmap 1.9.3", - "jsonrpc-stdio-server", - "kcl-language-server", - "kclvm-ast", - "kclvm-ast-pretty", - "kclvm-config", - "kclvm-driver", - "kclvm-error", - "kclvm-loader", - "kclvm-parser", - "kclvm-query", - "kclvm-runner", - "kclvm-runtime", - "kclvm-sema", - "kclvm-tools", - "kclvm-utils", - "maplit", - "once_cell", - "prost", - "prost-build", - "prost-types", - "prost-wkt", - "prost-wkt-build", - "prost-wkt-types", - "protoc-bin-vendored", - "serde", - "serde_json", - "serde_yaml", - "tempfile", - "tokio", -] - -[[package]] -name = "kclvm-ast" -version = "0.9.0" -dependencies = [ - "compiler_base_span", - "kclvm-error", - "kclvm-span", - "kclvm-utils", - "serde", - "serde_json", - "thread_local", - "uuid", -] - -[[package]] -name = "kclvm-ast-pretty" -version = "0.9.0" -dependencies = [ - "compiler_base_macros", - "compiler_base_session", - "fancy-regex", - "indexmap 1.9.3", - "kclvm-ast", - "kclvm-error", - "pretty_assertions", -] - -[[package]] -name = "kclvm-cmd" -version = "0.9.0" -dependencies = [ - "anyhow", - "clap", - "compiler_base_session", - "kclvm-api", - "kclvm-config", - "kclvm-driver", - "kclvm-error", - "kclvm-parser", - "kclvm-runner", - "kclvm-runtime", - "kclvm-tools", - "kclvm-version", -] - -[[package]] -name = "kclvm-compiler" -version = "0.9.0" -dependencies = [ - "ahash", - "bit-set", - "bitflags 1.3.2", - "fancy-regex", - "indexmap 1.9.3", - "kclvm-ast", - "kclvm-error", - "kclvm-runtime", - "kclvm-sema", - "once_cell", - "phf", - "time 0.2.27", - "unicode_names2", -] - -[[package]] -name = "kclvm-config" -version = "0.9.0" -dependencies = [ - "ahash", - "anyhow", - "chrono", - "dirs", - "glob", - "indexmap 1.9.3", - "kclvm-ast", - "kclvm-utils", - "kclvm-version", - "md-5 0.8.0", - "pathdiff", - "regex", - "ron", - "serde", - "serde_json", - "serde_yaml", - "toml", -] - -[[package]] -name = "kclvm-driver" -version = "0.9.0" -dependencies = [ - "anyhow", - "flate2", - "glob", - "indexmap 2.2.6", - "kclvm-ast", - "kclvm-config", - "kclvm-parser", - "kclvm-runtime", - "kclvm-utils", - "notify 6.1.1", - "oci-distribution", - "once_cell", - "parking_lot 0.12.3", - "serde", - "serde_json", - "tar", - "tokio", - "walkdir", -] - -[[package]] -name = "kclvm-error" -version = "0.9.0" -dependencies = [ - "annotate-snippets", - "anyhow", - "atty", - "compiler_base_error", - "compiler_base_macros", - "compiler_base_session", - "compiler_base_span", - "indexmap 1.9.3", - "kclvm-runtime", - "kclvm-span", - "kclvm-utils", - "serde", - "serde_json", - "termize", - "thiserror", - "tracing", -] - -[[package]] -name = "kclvm-evaluator" -version = "0.9.0" -dependencies = [ - "anyhow", - "generational-arena", - "indexmap 1.9.3", - "kclvm-ast", - "kclvm-error", - "kclvm-runtime", - "kclvm-sema", -] - -[[package]] -name = "kclvm-lexer" -version = "0.9.0" -dependencies = [ - "kclvm-error", - "rustc_lexer", - "unic-emoji-char", -] - -[[package]] -name = "kclvm-loader" -version = "0.9.0" -dependencies = [ - "anyhow", - "indexmap 1.9.3", - "kclvm-ast", - "kclvm-ast-pretty", - "kclvm-error", - "kclvm-parser", - "kclvm-query", - "kclvm-sema", - "maplit", -] - -[[package]] -name = "kclvm-macros" -version = "0.9.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.95", - "synstructure", -] - -[[package]] -name = "kclvm-parser" -version = "0.9.0" -dependencies = [ - "anyhow", - "bstr", - "compiler_base_error", - "compiler_base_macros", - "compiler_base_session", - "compiler_base_span", - "either", - "enquote", - "indexmap 1.9.3", - "kclvm-ast", - "kclvm-config", - "kclvm-error", - "kclvm-lexer", - "kclvm-sema", - "kclvm-span", - "kclvm-utils", - "num-bigint", - "petgraph", - "regex", - "rustc_lexer", - "serde", - "serde_json", - "tracing", - "unicode_names2", -] - -[[package]] -name = "kclvm-query" -version = "0.9.0" -dependencies = [ - "anyhow", - "compiler_base_macros", - "compiler_base_session", - "fancy-regex", - "indexmap 1.9.3", - "kclvm-ast", - "kclvm-ast-pretty", - "kclvm-error", - "kclvm-parser", - "kclvm-sema", - "maplit", - "serde", - "serde_json", -] - -[[package]] -name = "kclvm-runner" -version = "0.9.0" -dependencies = [ - "anyhow", - "cc", - "chrono", - "compiler_base_macros", - "compiler_base_session", - "glob", - "indexmap 1.9.3", - "kclvm-ast", - "kclvm-compiler", - "kclvm-config", - "kclvm-driver", - "kclvm-error", - "kclvm-evaluator", - "kclvm-parser", - "kclvm-query", - "kclvm-runtime", - "kclvm-sema", - "kclvm-utils", - "kclvm-version", - "libc", - "libloading", - "once_cell", - "serde", - "serde_json", - "tempfile", - "threadpool", - "uuid", - "walkdir", -] - -[[package]] -name = "kclvm-runtime" -version = "0.9.0" -dependencies = [ - "ahash", - "base64 0.13.0", - "bstr", - "chrono", - "fancy-regex", - "generational-arena", - "glob", - "handlebars", - "indexmap 1.9.3", - "itertools", - "kclvm_runtime_internal_macros", - "lazy_static", - "libc", - "md5", - "num-integer", - "phf", - "regex", - "serde", - "serde_json", - "serde_yaml", - "sha1", - "sha2 0.9.9", - "unic-ucd-bidi", - "unic-ucd-category", - "unicode-casing", - "uuid", -] - -[[package]] -name = "kclvm-sema" -version = "0.9.0" -dependencies = [ - "ahash", - "anyhow", - "bit-set", - "bitflags 1.3.2", - "compiler_base_error", - "compiler_base_macros", - "compiler_base_session", - "compiler_base_span", - "fancy-regex", - "generational-arena", - "indexmap 1.9.3", - "kclvm-ast", - "kclvm-ast-pretty", - "kclvm-error", - "kclvm-runtime", - "kclvm-span", - "kclvm-utils", - "lazy_static", - "once_cell", - "petgraph", - "phf", - "regex", - "serde", - "serde_json", - "suggestions", - "unicode_names2", -] - -[[package]] -name = "kclvm-span" -version = "0.9.0" -dependencies = [ - "compiler_base_span", - "kclvm-macros", - "parking_lot 0.11.2", - "scoped-tls", -] - -[[package]] -name = "kclvm-tools" -version = "0.9.0" -dependencies = [ - "anyhow", - "compiler_base_session", - "compiler_base_span", - "fancy-regex", - "indexmap 1.9.3", - "json-spanned-value", - "kclvm-ast", - "kclvm-ast-pretty", - "kclvm-config", - "kclvm-driver", - "kclvm-error", - "kclvm-parser", - "kclvm-query", - "kclvm-runner", - "kclvm-runtime", - "kclvm-sema", - "kclvm-utils", - "located_yaml", - "once_cell", - "regex", - "rustc_lexer", - "serde_json", - "serde_yaml", - "walkdir", -] - -[[package]] -name = "kclvm-utils" -version = "0.9.0" -dependencies = [ - "anyhow", - "fslock", - "regex", -] - -[[package]] -name = "kclvm-version" -version = "0.9.0" -dependencies = [ - "vergen", -] - -[[package]] -name = "kclvm_runtime_internal_macros" -version = "0.5.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.95", -] - -[[package]] -name = "kqueue" -version = "1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7447f1ca1b7b563588a205fe93dea8df60fd981423a768bc1c0ded35ed147d0c" -dependencies = [ - "kqueue-sys", - "libc", -] - -[[package]] -name = "kqueue-sys" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed9625ffda8729b85e45cf04090035ac368927b8cebc34898e7c120f52e4838b" -dependencies = [ - "bitflags 1.3.2", - "libc", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.155" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" - -[[package]] -name = "libfuzzer-sys" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "336244aaeab6a12df46480dc585802aa743a72d66b11937844c61bbca84c991d" -dependencies = [ - "arbitrary", - "cc", - "once_cell", -] - -[[package]] -name = "libloading" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efbc0f03f9a775e9f6aed295c6a1ba2253c5757a9e03d55c6caa46a681abcddd" -dependencies = [ - "cfg-if 1.0.0", - "winapi", -] - -[[package]] -name = "linked-hash-map" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" -dependencies = [ - "serde", -] - -[[package]] -name = "linux-raw-sys" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" - -[[package]] -name = "located_yaml" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bc68ee6f87a1be7fdba1dcfd854528371aa84a8390279b5d7a99d5da82add76" -dependencies = [ - "linked-hash-map", - "serde", - "yaml-rust", -] - -[[package]] -name = "lock_api" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" -dependencies = [ - "autocfg", - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" - -[[package]] -name = "lsp-server" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "248f65b78f6db5d8e1b1604b4098a28b43d21a8eb1deeca22b1c421b276c7095" -dependencies = [ - "crossbeam-channel", - "log", - "serde", - "serde_json", -] - -[[package]] -name = "lsp-types" -version = "0.93.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9be6e9c7e2d18f651974370d7aff703f9513e0df6e464fd795660edc77e6ca51" -dependencies = [ - "bitflags 1.3.2", - "serde", - "serde_json", - "serde_repr", - "url", -] - -[[package]] -name = "maplit" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" - -[[package]] -name = "matches" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" - -[[package]] -name = "md-5" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a18af3dcaf2b0219366cdb4e2af65a6101457b415c3d1a5c71dd9c2b7c77b9c8" -dependencies = [ - "block-buffer 0.7.3", - "digest 0.8.1", - "opaque-debug 0.2.3", -] - -[[package]] -name = "md-5" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "658646b21e0b72f7866c7038ab086d3d5e1cd6271f060fd37defb241949d0582" -dependencies = [ - "digest 0.10.7", -] - -[[package]] -name = "md5" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" - -[[package]] -name = "memchr" -version = "2.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" - -[[package]] -name = "memmap2" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "723e3ebdcdc5c023db1df315364573789f8857c11b631a2fdfad7c00f5c046b4" -dependencies = [ - "libc", -] - -[[package]] -name = "memoffset" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" -dependencies = [ - "autocfg", -] - -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[package]] -name = "miniz_oxide" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" -dependencies = [ - "adler", -] - -[[package]] -name = "mio" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" -dependencies = [ - "libc", - "log", - "wasi", - "windows-sys 0.48.0", -] - -[[package]] -name = "miow" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ffbca2f655e33c08be35d87278e5b18b89550a37dbd598c20db92f6a471123" -dependencies = [ - "windows-sys 0.42.0", -] - -[[package]] -name = "multimap" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a" - -[[package]] -name = "notify" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "729f63e1ca555a43fe3efa4f3efdf4801c479da85b432242a7b726f353c88486" -dependencies = [ - "bitflags 1.3.2", - "crossbeam-channel", - "filetime", - "fsevent-sys", - "inotify", - "kqueue", - "libc", - "mio", - "walkdir", - "windows-sys 0.45.0", -] - -[[package]] -name = "notify" -version = "6.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6205bd8bb1e454ad2e27422015fb5e4f2bcc7e08fa8f27058670d208324a4d2d" -dependencies = [ - "bitflags 2.5.0", - "crossbeam-channel", - "filetime", - "fsevent-sys", - "inotify", - "kqueue", - "libc", - "log", - "mio", - "walkdir", - "windows-sys 0.48.0", -] - -[[package]] -name = "num-bigint" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f" -dependencies = [ - "autocfg", - "num-integer", - "num-traits", -] - -[[package]] -name = "num-integer" -version = "0.1.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" -dependencies = [ - "autocfg", - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_cpus" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" -dependencies = [ - "hermit-abi 0.1.19", - "libc", -] - -[[package]] -name = "num_threads" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44" -dependencies = [ - "libc", -] - -[[package]] -name = "object" -version = "0.31.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bda667d9f2b5051b8833f59f3bf748b28ef54f850f4fcb389a252aa383866d1" -dependencies = [ - "memchr", -] - -[[package]] -name = "oci-distribution" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b95a2c51531af0cb93761f66094044ca6ea879320bccd35ab747ff3fcab3f422" -dependencies = [ - "bytes", - "chrono", - "futures-util", - "http", - "http-auth", - "jwt", - "lazy_static", - "olpc-cjson", - "regex", - "reqwest", - "serde", - "serde_json", - "sha2 0.10.2", - "thiserror", - "tokio", - "tracing", - "unicase", -] - -[[package]] -name = "olpc-cjson" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d637c9c15b639ccff597da8f4fa968300651ad2f1e968aefc3b4927a6fb2027a" -dependencies = [ - "serde", - "serde_json", - "unicode-normalization", -] - -[[package]] -name = "once_cell" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" - -[[package]] -name = "oorandom" -version = "11.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" - -[[package]] -name = "opaque-debug" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" - -[[package]] -name = "opaque-debug" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" - -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - -[[package]] -name = "parking_lot" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" -dependencies = [ - "instant", - "lock_api", - "parking_lot_core 0.8.6", -] - -[[package]] -name = "parking_lot" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" -dependencies = [ - "lock_api", - "parking_lot_core 0.9.3", -] - -[[package]] -name = "parking_lot_core" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc" -dependencies = [ - "cfg-if 1.0.0", - "instant", - "libc", - "redox_syscall 0.2.13", - "smallvec", - "winapi", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09a279cbf25cb0757810394fbc1e359949b59e348145c643a939a525692e6929" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "redox_syscall 0.2.13", - "smallvec", - "windows-sys 0.36.1", -] - -[[package]] -name = "pathdiff" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" - -[[package]] -name = "percent-encoding" -version = "2.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" - -[[package]] -name = "pest" -version = "2.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "560131c633294438da9f7c4b08189194b20946c8274c6b9e38881a7874dc8ee8" -dependencies = [ - "memchr", - "thiserror", - "ucd-trie", -] - -[[package]] -name = "pest_derive" -version = "2.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26293c9193fbca7b1a3bf9b79dc1e388e927e6cacaa78b4a3ab705a1d3d41459" -dependencies = [ - "pest", - "pest_generator", -] - -[[package]] -name = "pest_generator" -version = "2.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ec22af7d3fb470a85dd2ca96b7c577a1eb4ef6f1683a9fe9a8c16e136c04687" -dependencies = [ - "pest", - "pest_meta", - "proc-macro2", - "quote", - "syn 2.0.67", -] - -[[package]] -name = "pest_meta" -version = "2.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7a240022f37c361ec1878d646fc5b7d7c4d28d5946e1a80ad5a7a4f4ca0bdcd" -dependencies = [ - "once_cell", - "pest", - "sha2 0.10.2", -] - -[[package]] -name = "petgraph" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a13a2fa9d0b63e5f22328828741e523766fff0ee9e779316902290dff3f824f" -dependencies = [ - "fixedbitset", - "indexmap 1.9.3", -] - -[[package]] -name = "phf" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2ac8b67553a7ca9457ce0e526948cad581819238f4a9d1ea74545851fa24f37" -dependencies = [ - "phf_macros", - "phf_shared", - "proc-macro-hack", -] - -[[package]] -name = "phf_generator" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43f3220d96e0080cc9ea234978ccd80d904eafb17be31bb0f76daaea6493082" -dependencies = [ - "phf_shared", - "rand", -] - -[[package]] -name = "phf_macros" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b706f5936eb50ed880ae3009395b43ed19db5bff2ebd459c95e7bf013a89ab86" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro-hack", - "proc-macro2", - "quote", - "syn 1.0.95", -] - -[[package]] -name = "phf_shared" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a68318426de33640f02be62b4ae8eb1261be2efbc337b60c54d845bf4484e0d9" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pin-project" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6bf43b791c5b9e34c3d182969b4abb522f9343702850a2e57f460d00d09b4b3" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.67", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" - -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - -[[package]] -name = "ppv-lite86" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" - -[[package]] -name = "pretty_assertions" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af7cee1a6c8a5b9208b3cb1061f10c0cb689087b3d8ce85fb9d2dd7a29b6ba66" -dependencies = [ - "diff", - "yansi", -] - -[[package]] -name = "prettyplease" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c8646e95016a7a6c4adea95bafa8a16baab64b583356217f2c85db4a39d9a86" -dependencies = [ - "proc-macro2", - "syn 1.0.95", -] - -[[package]] -name = "proc-macro-hack" -version = "0.5.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" - -[[package]] -name = "proc-macro2" -version = "1.0.86" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "proc_macro_crate" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.67", -] - -[[package]] -name = "prost" -version = "0.11.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b82eaa1d779e9a4bc1c3217db8ffbeabaae1dca241bf70183242128d48681cd" -dependencies = [ - "bytes", - "prost-derive", -] - -[[package]] -name = "prost-build" -version = "0.11.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "119533552c9a7ffacc21e099c24a0ac8bb19c2a2a3f363de84cd9b844feab270" -dependencies = [ - "bytes", - "heck 0.4.1", - "itertools", - "lazy_static", - "log", - "multimap", - "petgraph", - "prettyplease", - "prost", - "prost-types", - "regex", - "syn 1.0.95", - "tempfile", - "which", -] - -[[package]] -name = "prost-derive" -version = "0.11.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5d2d8d10f3c6ded6da8b05b5fb3b8a5082514344d56c9f871412d29b4e075b4" -dependencies = [ - "anyhow", - "itertools", - "proc-macro2", - "quote", - "syn 1.0.95", -] - -[[package]] -name = "prost-types" -version = "0.11.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "213622a1460818959ac1181aaeb2dc9c7f63df720db7d788b3e24eacd1983e13" -dependencies = [ - "prost", -] - -[[package]] -name = "prost-wkt" -version = "0.4.1" -dependencies = [ - "chrono", - "inventory", - "prost", - "serde", - "serde_derive", - "serde_json", - "typetag", -] - -[[package]] -name = "prost-wkt-build" -version = "0.4.1" -dependencies = [ - "heck 0.4.1", - "prost", - "prost-build", - "prost-types", - "quote", -] - -[[package]] -name = "prost-wkt-types" -version = "0.4.1" -dependencies = [ - "chrono", - "prost", - "prost-build", - "prost-types", - "prost-wkt", - "prost-wkt-build", - "protoc-bin-vendored", - "regex", - "serde", - "serde_derive", - "serde_json", -] - -[[package]] -name = "protoc-bin-vendored" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "005ca8623e5633e298ad1f917d8be0a44bcf406bf3cde3b80e63003e49a3f27d" -dependencies = [ - "protoc-bin-vendored-linux-aarch_64", - "protoc-bin-vendored-linux-ppcle_64", - "protoc-bin-vendored-linux-x86_32", - "protoc-bin-vendored-linux-x86_64", - "protoc-bin-vendored-macos-x86_64", - "protoc-bin-vendored-win32", -] - -[[package]] -name = "protoc-bin-vendored-linux-aarch_64" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fb9fc9cce84c8694b6ea01cc6296617b288b703719b725b8c9c65f7c5874435" - -[[package]] -name = "protoc-bin-vendored-linux-ppcle_64" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02d2a07dcf7173a04d49974930ccbfb7fd4d74df30ecfc8762cf2f895a094516" - -[[package]] -name = "protoc-bin-vendored-linux-x86_32" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d54fef0b04fcacba64d1d80eed74a20356d96847da8497a59b0a0a436c9165b0" - -[[package]] -name = "protoc-bin-vendored-linux-x86_64" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8782f2ce7d43a9a5c74ea4936f001e9e8442205c244f7a3d4286bd4c37bc924" - -[[package]] -name = "protoc-bin-vendored-macos-x86_64" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5de656c7ee83f08e0ae5b81792ccfdc1d04e7876b1d9a38e6876a9e09e02537" - -[[package]] -name = "protoc-bin-vendored-win32" -version = "3.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9653c3ed92974e34c5a6e0a510864dab979760481714c172e0a34e437cb98804" - -[[package]] -name = "quinn" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4ceeeeabace7857413798eb1ffa1e9c905a9946a57d81fb69b4b71c4d8eb3ad" -dependencies = [ - "bytes", - "pin-project-lite", - "quinn-proto", - "quinn-udp", - "rustc-hash", - "rustls", - "thiserror", - "tokio", - "tracing", -] - -[[package]] -name = "quinn-proto" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddf517c03a109db8100448a4be38d498df8a210a99fe0e1b9eaf39e78c640efe" -dependencies = [ - "bytes", - "rand", - "ring", - "rustc-hash", - "rustls", - "slab", - "thiserror", - "tinyvec", - "tracing", -] - -[[package]] -name = "quinn-udp" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9096629c45860fc7fb143e125eb826b5e721e10be3263160c7d60ca832cf8c46" -dependencies = [ - "libc", - "once_cell", - "socket2", - "tracing", - "windows-sys 0.52.0", -] - -[[package]] -name = "quote" -version = "1.0.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "ra_ap_paths" -version = "0.0.149" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d780b450680460bd7ea3e2483dcf15a3ac0ce0ec028696caa342c577d65e5506" - -[[package]] -name = "ra_ap_stdx" -version = "0.0.149" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d776542bf771f4fdf40c21ced864bf213924d8a60d580c970715818471ebd74c" -dependencies = [ - "always-assert", - "libc", - "miow", - "winapi", -] - -[[package]] -name = "ra_ap_vfs" -version = "0.0.149" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8cd60adecd0947e1dd41a3077713381aa0cdcba6dc8777300d7d5b83b9fbe84" -dependencies = [ - "fst", - "indexmap 1.9.3", - "ra_ap_paths", - "ra_ap_stdx", - "rustc-hash", -] - -[[package]] -name = "ra_ap_vfs-notify" -version = "0.0.149" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a680f2dbd796844ebeaa2a4d01ae209f412ddc2981f6512ab8bc9b471156e6cd" -dependencies = [ - "crossbeam-channel", - "jod-thread", - "notify 5.2.0", - "ra_ap_paths", - "ra_ap_vfs", - "tracing", - "walkdir", -] - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha", - "rand_core", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" -dependencies = [ - "getrandom", -] - -[[package]] -name = "rand_xoshiro" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f97cdb2a36ed4183de61b2f824cc45c9f1037f28afe0a322e9fff4c108b5aaa" -dependencies = [ - "rand_core", -] - -[[package]] -name = "redox_syscall" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" -dependencies = [ - "bitflags 1.3.2", -] - -[[package]] -name = "redox_syscall" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" -dependencies = [ - "bitflags 1.3.2", -] - -[[package]] -name = "redox_syscall" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" -dependencies = [ - "bitflags 1.3.2", -] - -[[package]] -name = "redox_users" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b" -dependencies = [ - "getrandom", - "redox_syscall 0.2.13", - "thiserror", -] - -[[package]] -name = "regex" -version = "1.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata 0.4.7", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" - -[[package]] -name = "regex-automata" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" - -[[package]] -name = "reqwest" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7d6d2a27d57148378eb5e111173f4276ad26340ecc5c49a4a2152167a2d6a37" -dependencies = [ - "base64 0.22.1", - "bytes", - "futures-core", - "futures-util", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-util", - "ipnet", - "js-sys", - "log", - "mime", - "once_cell", - "percent-encoding", - "pin-project-lite", - "quinn", - "rustls", - "rustls-pemfile", - "rustls-pki-types", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tokio-rustls", - "tokio-util 0.7.11", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "wasm-streams", - "web-sys", - "webpki-roots", - "winreg", -] - -[[package]] -name = "ring" -version = "0.17.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" -dependencies = [ - "cc", - "cfg-if 1.0.0", - "getrandom", - "libc", - "spin", - "untrusted", - "windows-sys 0.52.0", -] - -[[package]] -name = "ron" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b861ecaade43ac97886a512b360d01d66be9f41f3c61088b42cedf92e03d678" -dependencies = [ - "base64 0.13.0", - "bitflags 1.3.2", - "serde", -] - -[[package]] -name = "ropey" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93411e420bcd1a75ddd1dc3caf18c23155eda2c090631a85af21ba19e97093b5" -dependencies = [ - "smallvec", - "str_indices", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - -[[package]] -name = "rustc-rayon" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9974ab223660e61c1b4e7b43b827379df286736ca988308ce7e16f59f2d89246" -dependencies = [ - "crossbeam-deque", - "either", - "rustc-rayon-core 0.3.2", -] - -[[package]] -name = "rustc-rayon" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb81aadc8837ca6ecebe0fe1353f15df83b3b3cc2cf7a8afd571bc22aa121710" -dependencies = [ - "either", - "rustc-rayon-core 0.5.0", -] - -[[package]] -name = "rustc-rayon-core" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "564bfd27be8db888d0fa76aa4335e7851aaed0c2c11ad1e93aeb9349f6b88500" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", - "lazy_static", - "num_cpus", -] - -[[package]] -name = "rustc-rayon-core" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67668daaf00e359c126f6dcb40d652d89b458a008c8afa727a42a2d20fca0b7f" -dependencies = [ - "crossbeam-channel", - "crossbeam-deque", - "crossbeam-utils", - "num_cpus", -] - -[[package]] -name = "rustc_data_structures" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a38bae9c6afa27015bcaa2869e03bb111ecf0d0e0edc2da559a91d4057174c9a" -dependencies = [ - "arrayvec", - "bitflags 1.3.2", - "cfg-if 0.1.10", - "ena", - "indexmap 1.9.3", - "jobserver", - "libc", - "memmap2", - "parking_lot 0.12.3", - "rustc-hash", - "rustc-rayon 0.3.2", - "rustc-rayon-core 0.3.2", - "stable_deref_trait", - "tempfile", - "tracing", - "winapi", -] - -[[package]] -name = "rustc_errors" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00299b1841816d2c41129e6d4f86b0b446ee387e8203871c2551e1c405b1243c" -dependencies = [ - "termcolor", - "winapi", -] - -[[package]] -name = "rustc_lexer" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c86aae0c77166108c01305ee1a36a1e77289d7dc6ca0a3cd91ff4992de2d16a5" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "rustc_span" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "043e9cc06c53de1f6a125e41e4b915d23a130241610a114ad4fe4f654617eae4" -dependencies = [ - "cfg-if 0.1.10", - "md-5 0.10.1", - "rustc_data_structures", - "scoped-tls", - "sha-1", - "sha2 0.10.2", - "tracing", - "unicode-width", -] - -[[package]] -name = "rustc_version" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -dependencies = [ - "semver 0.9.0", -] - -[[package]] -name = "rustc_version" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" -dependencies = [ - "semver 1.0.18", -] - -[[package]] -name = "rustix" -version = "0.38.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" -dependencies = [ - "bitflags 2.5.0", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.52.0", -] - -[[package]] -name = "rustls" -version = "0.23.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05cff451f60db80f490f3c182b77c35260baace73209e9cdbbe526bfe3a4d402" -dependencies = [ - "once_cell", - "ring", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-pemfile" -version = "2.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d" -dependencies = [ - "base64 0.22.1", - "rustls-pki-types", -] - -[[package]] -name = "rustls-pki-types" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d" - -[[package]] -name = "rustls-webpki" -version = "0.102.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff448f7e92e913c4b7d4c6d8e4540a1724b319b4152b8aef6d4cf8339712b33e" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", -] - -[[package]] -name = "rustversion" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" - -[[package]] -name = "ryu" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3f6f92acf49d1b98f7a81226834412ada05458b7364277387724a237f062695" - -[[package]] -name = "salsa" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b84d9f96071f3f3be0dc818eae3327625d8ebc95b58da37d6850724f31d3403" -dependencies = [ - "crossbeam-utils", - "indexmap 1.9.3", - "lock_api", - "log", - "oorandom", - "parking_lot 0.11.2", - "rustc-hash", - "salsa-macros", - "smallvec", -] - -[[package]] -name = "salsa-macros" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd3904a4ba0a9d0211816177fd34b04c7095443f8cdacd11175064fe541c8fe2" -dependencies = [ - "heck 0.3.3", - "proc-macro2", - "quote", - "syn 1.0.95", -] - -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "scoped-tls" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" - -[[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - -[[package]] -name = "self_cell" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e14e4d63b804dc0c7ec4a1e52bcb63f02c7ac94476755aa579edac21e01f915d" -dependencies = [ - "self_cell 1.0.2", -] - -[[package]] -name = "self_cell" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e388332cd64eb80cd595a00941baf513caffae8dce9cfd0467fc9c66397dade6" - -[[package]] -name = "semver" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -dependencies = [ - "semver-parser", -] - -[[package]] -name = "semver" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" - -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" - -[[package]] -name = "serde" -version = "1.0.203" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7253ab4de971e72fb7be983802300c30b5a7f0c2e56fab8abfc6a214307c0094" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.203" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "500cbc0ebeb6f46627f50f3f5811ccf6bf00643be300b4c3eabc0ef55dc5b5ba" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.67", -] - -[[package]] -name = "serde_json" -version = "1.0.115" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12dc5c46daa8e9fdf4f5e71b6cf9a53f2487da0e86e55808e2d35539666497dd" -dependencies = [ - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_repr" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3081f5ffbb02284dda55132aa26daecedd7372a42417bbbab6f14ab7d6bb9145" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.67", -] - -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_yaml" -version = "0.9.34+deprecated" -dependencies = [ - "indexmap 2.2.6", - "itoa", - "ryu", - "serde", - "unsafe-libyaml", -] - -[[package]] -name = "sha-1" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.7", -] - -[[package]] -name = "sha1" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" -dependencies = [ - "sha1_smol", -] - -[[package]] -name = "sha1_smol" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" - -[[package]] -name = "sha2" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.9.0", - "opaque-debug 0.3.0", -] - -[[package]] -name = "sha2" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.7", -] - -[[package]] -name = "signal-hook-registry" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" -dependencies = [ - "libc", -] - -[[package]] -name = "siphasher" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bd3e3206899af3f8b12af284fafc038cc1dc2b41d1b89dd17297221c5d225de" - -[[package]] -name = "sized-chunks" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16d69225bde7a69b235da73377861095455d298f2b970996eec25ddbb42b3d1e" -dependencies = [ - "bitmaps", - "typenum", -] - -[[package]] -name = "slab" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6528351c9bc8ab22353f9d776db39a20288e8d6c37ef8cfe3317cf875eecfc2d" -dependencies = [ - "autocfg", -] - -[[package]] -name = "smallvec" -version = "1.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" - -[[package]] -name = "socket2" -version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "spin" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" - -[[package]] -name = "stable_deref_trait" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" - -[[package]] -name = "standback" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e113fb6f3de07a243d434a56ec6f186dfd51cb08448239fe7bcae73f87ff28ff" -dependencies = [ - "version_check", -] - -[[package]] -name = "stdweb" -version = "0.4.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d022496b16281348b52d0e30ae99e01a73d737b2f45d38fed4edf79f9325a1d5" -dependencies = [ - "discard", - "rustc_version 0.2.3", - "stdweb-derive", - "stdweb-internal-macros", - "stdweb-internal-runtime", - "wasm-bindgen", -] - -[[package]] -name = "stdweb-derive" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c87a60a40fccc84bef0652345bbbbbe20a605bf5d0ce81719fc476f5c03b50ef" -dependencies = [ - "proc-macro2", - "quote", - "serde", - "serde_derive", - "syn 1.0.95", -] - -[[package]] -name = "stdweb-internal-macros" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58fa5ff6ad0d98d1ffa8cb115892b6e69d67799f6763e162a1c9db421dc22e11" -dependencies = [ - "base-x", - "proc-macro2", - "quote", - "serde", - "serde_derive", - "serde_json", - "sha1", - "syn 1.0.95", -] - -[[package]] -name = "stdweb-internal-runtime" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0" - -[[package]] -name = "str_indices" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9557cb6521e8d009c51a8666f09356f4b817ba9ba0981a305bd86aee47bd35c" - -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - -[[package]] -name = "subtle" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d0208408ba0c3df17ed26eb06992cb1a1268d41b2c0e12e65203fbe3972cee5" - -[[package]] -name = "suggestions" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5441c382482e49aaac2c3ea9cbcd24290531246e879ee94af5dfc4b144f11e80" -dependencies = [ - "strsim", -] - -[[package]] -name = "syn" -version = "1.0.95" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbaf6116ab8924f39d52792136fb74fd60a80194cf1b1c6ffa6453eef1c3f942" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "2.0.67" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff8655ed1d86f3af4ee3fd3263786bc14245ad17c4c7e85ba7187fb3ae028c90" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "sync_wrapper" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" - -[[package]] -name = "synstructure" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.95", - "unicode-xid", -] - -[[package]] -name = "tar" -version = "0.4.41" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb797dad5fb5b76fcf519e702f4a589483b5ef06567f160c392832c1f5e44909" -dependencies = [ - "filetime", - "libc", - "xattr", -] - -[[package]] -name = "tempfile" -version = "3.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc02fddf48964c42031a0b3fe0428320ecf3a73c401040fc0096f97794310651" -dependencies = [ - "cfg-if 1.0.0", - "fastrand", - "redox_syscall 0.3.5", - "rustix", - "windows-sys 0.48.0", -] - -[[package]] -name = "termcolor" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "termize" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1706be6b564323ce7092f5f7e6b118a14c8ef7ed0e69c8c5329c914a9f101295" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "tests-fuzz" -version = "0.0.0" -dependencies = [ - "arbitrary", - "kclvm", - "kclvm-parser", - "kclvm-runtime", - "libfuzzer-sys", - "serde_json", -] - -[[package]] -name = "thiserror" -version = "1.0.61" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.61" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.67", -] - -[[package]] -name = "thread_local" -version = "1.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdd6f064ccff2d6567adcb3873ca630700f00b5ad3f060c25b5dcfd9a4ce152" -dependencies = [ - "cfg-if 1.0.0", - "once_cell", -] - -[[package]] -name = "threadpool" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" -dependencies = [ - "num_cpus", -] - -[[package]] -name = "time" -version = "0.2.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4752a97f8eebd6854ff91f1c1824cd6160626ac4bd44287f7f4ea2035a02a242" -dependencies = [ - "const_fn", - "libc", - "standback", - "stdweb", - "time-macros 0.1.1", - "version_check", - "winapi", -] - -[[package]] -name = "time" -version = "0.3.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fdd63d58b18d663fbdf70e049f00a22c8e42be082203be7f26589213cd75ea" -dependencies = [ - "deranged", - "itoa", - "libc", - "num_threads", - "serde", - "time-core", - "time-macros 0.2.11", -] - -[[package]] -name = "time-core" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb" - -[[package]] -name = "time-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "957e9c6e26f12cb6d0dd7fc776bb67a706312e7299aed74c8dd5b17ebb27e2f1" -dependencies = [ - "proc-macro-hack", - "time-macros-impl", -] - -[[package]] -name = "time-macros" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb71511c991639bb078fd5bf97757e03914361c48100d52878b8e52b46fb92cd" -dependencies = [ - "time-core", -] - -[[package]] -name = "time-macros-impl" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3c141a1b43194f3f56a1411225df8646c55781d5f26db825b3d98507eb482f" -dependencies = [ - "proc-macro-hack", - "proc-macro2", - "quote", - "standback", - "syn 1.0.95", -] - -[[package]] -name = "tinystr" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ac3f5b6856e931e15e07b478e98c8045239829a65f9156d4fa7e7788197a5ef" -dependencies = [ - "displaydoc", -] - -[[package]] -name = "tinyvec" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - -[[package]] -name = "tokio" -version = "1.38.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba4f4a02a7a80d6f274636f0aa95c7e383b912d41fe721a31f29e29698585a4a" -dependencies = [ - "backtrace", - "bytes", - "libc", - "mio", - "num_cpus", - "parking_lot 0.12.3", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys 0.48.0", -] - -[[package]] -name = "tokio-macros" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.67", -] - -[[package]] -name = "tokio-rustls" -version = "0.26.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" -dependencies = [ - "rustls", - "rustls-pki-types", - "tokio", -] - -[[package]] -name = "tokio-stream" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "397c988d37662c7dda6d2208364a706264bf3d6138b11d436cbac0ad38832842" -dependencies = [ - "futures-core", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "tokio-test" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e89b3cbabd3ae862100094ae433e1def582cf86451b4e9bf83aa7ac1d8a7d719" -dependencies = [ - "async-stream", - "bytes", - "futures-core", - "tokio", - "tokio-stream", -] - -[[package]] -name = "tokio-util" -version = "0.6.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36943ee01a6d67977dd3f84a5a1d2efeb4ada3a1ae771cadfaa535d9d9fc6507" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "log", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "tokio-util" -version = "0.7.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cf6b47b3771c49ac75ad09a6162f53ad4b8088b76ac60e8ec1455b31a189fe1" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "toml" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" -dependencies = [ - "serde", -] - -[[package]] -name = "tower" -version = "0.4.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" -dependencies = [ - "futures-core", - "futures-util", - "pin-project", - "pin-project-lite", - "tokio", - "tower-layer", - "tower-service", -] - -[[package]] -name = "tower-layer" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0" - -[[package]] -name = "tower-service" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" - -[[package]] -name = "tracing" -version = "0.1.40" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" -dependencies = [ - "log", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.67", -] - -[[package]] -name = "tracing-core" -version = "0.1.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c06d3da6113f116aaee68e4d601191614c9053067f9ab7f6edbcb161237daa54" -dependencies = [ - "once_cell", -] - -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - -[[package]] -name = "type-map" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6d3364c5e96cb2ad1603037ab253ddd34d7fb72a58bdddf4b7350760fc69a46" -dependencies = [ - "rustc-hash", -] - -[[package]] -name = "typenum" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" - -[[package]] -name = "typetag" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aec6850cc671cd0cfb3ab285465e48a3b927d9de155051c35797446b32f9169f" -dependencies = [ - "erased-serde", - "inventory", - "once_cell", - "serde", - "typetag-impl", -] - -[[package]] -name = "typetag-impl" -version = "0.2.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30c49a6815b4f8379c36f06618bc1b80ca77aaf8a3fd4d8549dca6fdb016000f" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.67", -] - -[[package]] -name = "ucd-trie" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" - -[[package]] -name = "unic-char-property" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" -dependencies = [ - "unic-char-range", -] - -[[package]] -name = "unic-char-range" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" - -[[package]] -name = "unic-common" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" - -[[package]] -name = "unic-emoji-char" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b07221e68897210270a38bde4babb655869637af0f69407f96053a34f76494d" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-langid" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "398f9ad7239db44fd0f80fe068d12ff22d78354080332a5077dc6f52f14dcf2f" -dependencies = [ - "unic-langid-impl", - "unic-langid-macros", -] - -[[package]] -name = "unic-langid-impl" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e35bfd2f2b8796545b55d7d3fd3e89a0613f68a0d1c8bc28cb7ff96b411a35ff" -dependencies = [ - "tinystr", -] - -[[package]] -name = "unic-langid-macros" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "055e618bf694161ffff0466d95cef3e1a5edc59f6ba1888e97801f2b4ebdc4fe" -dependencies = [ - "proc-macro-hack", - "tinystr", - "unic-langid-impl", - "unic-langid-macros-impl", -] - -[[package]] -name = "unic-langid-macros-impl" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f5cdec05b907f4e2f6843f4354f4ce6a5bebe1a56df320a49134944477ce4d8" -dependencies = [ - "proc-macro-hack", - "quote", - "syn 1.0.95", - "unic-langid-impl", -] - -[[package]] -name = "unic-ucd-bidi" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1d568b51222484e1f8209ce48caa6b430bf352962b877d592c29ab31fb53d8c" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-category" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b8d4591f5fcfe1bd4453baaf803c40e1b1e69ff8455c47620440b46efef91c0" -dependencies = [ - "matches", - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-version" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" -dependencies = [ - "unic-common", -] - -[[package]] -name = "unicase" -version = "2.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7d2d4dafb69621809a81864c9c1b864479e1235c0dd4e199924b9742439ed89" -dependencies = [ - "version_check", -] - -[[package]] -name = "unicode-bidi" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f2528f27a9eb2b21e69c95319b30bd0efd85d09c379741b0f78ea1d86be2416" - -[[package]] -name = "unicode-casing" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "623f59e6af2a98bdafeb93fa277ac8e1e40440973001ca15cf4ae1541cd16d56" - -[[package]] -name = "unicode-ident" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d22af068fba1eb5edcb4aea19d382b2a3deb4c8f9d475c589b6ada9e0fd493ee" - -[[package]] -name = "unicode-normalization" -version = "0.1.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-segmentation" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36" - -[[package]] -name = "unicode-width" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" - -[[package]] -name = "unicode-xid" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04" - -[[package]] -name = "unicode_names2" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87d6678d7916394abad0d4b19df4d3802e1fd84abd7d701f39b75ee71b9e8cf1" - -[[package]] -name = "unsafe-libyaml" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" - -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "url" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31e6302e3bb753d46e83516cae55ae196fc0c309407cf11ab35cc51a4c2a4633" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "utf8parse" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" - -[[package]] -name = "uuid" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a183cf7feeba97b4dd1c0d46788634f6221d87fa961b305bed08c851829efcc0" -dependencies = [ - "getrandom", - "serde", -] - -[[package]] -name = "vergen" -version = "8.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbc5ad0d9d26b2c49a5ab7da76c3e79d3ee37e7821799f8223fcb8f2f391a2e7" -dependencies = [ - "anyhow", - "rustc_version 0.4.0", - "rustversion", - "time 0.3.25", -] - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "walkdir" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "808cf2735cd4b6866113f648b791c6adc5714537bc222d9347bb203386ffda56" -dependencies = [ - "same-file", - "winapi", - "winapi-util", -] - -[[package]] -name = "want" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" -dependencies = [ - "try-lock", -] - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" - -[[package]] -name = "wasm-bindgen" -version = "0.2.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" -dependencies = [ - "cfg-if 1.0.0", - "wasm-bindgen-macro", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" -dependencies = [ - "bumpalo", - "log", - "once_cell", - "proc-macro2", - "quote", - "syn 2.0.67", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" -dependencies = [ - "cfg-if 1.0.0", - "js-sys", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.67", - "wasm-bindgen-backend", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" - -[[package]] -name = "wasm-streams" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b65dc4c90b63b118468cf747d8bf3566c1913ef60be765b5730ead9e0a3ba129" -dependencies = [ - "futures-util", - "js-sys", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - -[[package]] -name = "web-sys" -version = "0.3.64" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "webpki-roots" -version = "0.26.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd7c23921eeb1713a4e851530e9b9756e4fb0e89978582942612524cf09f01cd" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "which" -version = "4.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2441c784c52b289a054b7201fc93253e288f094e2f4be9058343127c4226a269" -dependencies = [ - "either", - "libc", - "once_cell", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" -dependencies = [ - "winapi", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-core" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" -dependencies = [ - "windows-targets 0.52.0", -] - -[[package]] -name = "windows-sys" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2" -dependencies = [ - "windows_aarch64_msvc 0.36.1", - "windows_i686_gnu 0.36.1", - "windows_i686_msvc 0.36.1", - "windows_x86_64_gnu 0.36.1", - "windows_x86_64_msvc 0.36.1", -] - -[[package]] -name = "windows-sys" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - -[[package]] -name = "windows-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" -dependencies = [ - "windows-targets 0.42.2", -] - -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.1", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets 0.52.0", -] - -[[package]] -name = "windows-targets" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - -[[package]] -name = "windows-targets" -version = "0.48.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05d4b17490f70499f20b9e791dcf6a299785ce8af4d709018206dc5b4953e95f" -dependencies = [ - "windows_aarch64_gnullvm 0.48.0", - "windows_aarch64_msvc 0.48.0", - "windows_i686_gnu 0.48.0", - "windows_i686_msvc 0.48.0", - "windows_x86_64_gnu 0.48.0", - "windows_x86_64_gnullvm 0.48.0", - "windows_x86_64_msvc 0.48.0", -] - -[[package]] -name = "windows-targets" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd" -dependencies = [ - "windows_aarch64_gnullvm 0.52.0", - "windows_aarch64_msvc 0.52.0", - "windows_i686_gnu 0.52.0", - "windows_i686_msvc 0.52.0", - "windows_x86_64_gnu 0.52.0", - "windows_x86_64_gnullvm 0.52.0", - "windows_x86_64_msvc 0.52.0", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" - -[[package]] -name = "windows_i686_gnu" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6" - -[[package]] -name = "windows_i686_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" - -[[package]] -name = "windows_i686_gnu" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" - -[[package]] -name = "windows_i686_msvc" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024" - -[[package]] -name = "windows_i686_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" - -[[package]] -name = "windows_i686_msvc" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" - -[[package]] -name = "winreg" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5" -dependencies = [ - "cfg-if 1.0.0", - "windows-sys 0.48.0", -] - -[[package]] -name = "xattr" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da84f1a25939b27f6820d92aed108f83ff920fdf11a7b19366c27c4cda81d4f" -dependencies = [ - "libc", - "linux-raw-sys", - "rustix", -] - -[[package]] -name = "yaml-rust" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" -dependencies = [ - "linked-hash-map", -] - -[[package]] -name = "yansi" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" - -[[package]] -name = "yansi-term" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5c30ade05e61656247b2e334a031dfd0cc466fadef865bdcdea8d537951bf1" -dependencies = [ - "winapi", -] - -[[package]] -name = "zeroize" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" diff --git a/kclvm/tests/fuzz/Cargo.toml b/kclvm/tests/fuzz/Cargo.toml deleted file mode 100644 index 75867f156..000000000 --- a/kclvm/tests/fuzz/Cargo.toml +++ /dev/null @@ -1,29 +0,0 @@ -[package] -name = "tests-fuzz" -version = "0.0.0" -authors = ["Automatically generated"] -publish = false -edition = "2018" - -[package.metadata] -cargo-fuzz = true - -[dependencies] -kclvm-runtime = {path = "../../runtime"} -kclvm-parser = {path = "../../parser"} -libfuzzer-sys = { version = "0.4.0", features = ["arbitrary-derive"] } -arbitrary = { version = "1", features = ["derive"] } -serde_json = "1.0" - -[dependencies.kclvm] -path = "../.." - -# Prevent this from interfering with workspaces -[workspace] -members = ["."] - -[[bin]] -name = "fuzz_parser" -path = "fuzz_targets/fuzz_parser.rs" -test = false -doc = false diff --git a/kclvm/tests/fuzz/fuzz_targets/fuzz_parser.rs b/kclvm/tests/fuzz/fuzz_targets/fuzz_parser.rs deleted file mode 100644 index 3c22d3444..000000000 --- a/kclvm/tests/fuzz/fuzz_targets/fuzz_parser.rs +++ /dev/null @@ -1,35 +0,0 @@ -#![no_main] -use kclvm_parser::parse_expr; -use kclvm_runtime::PanicInfo; -use libfuzzer_sys::arbitrary::Arbitrary; -use libfuzzer_sys::fuzz_target; -use serde_json; -use std::panic::catch_unwind; -use std::panic::set_hook; - -#[derive(Arbitrary, Debug)] -enum ParserMethod<'a> { - ParseExpr { src: &'a str }, -} - -fuzz_target!(|method: ParserMethod| { - // fuzzed code goes here - match method { - ParserMethod::ParseExpr { src } => { - set_hook(Box::new(|_info| {})); - let result = catch_unwind(|| { - parse_expr(src); - }); - match result { - Err(e) => match e.downcast::() { - Ok(_v) => { - let got = _v.to_string(); - let _u: PanicInfo = serde_json::from_str(&got).unwrap(); - } - _ => unreachable!(), - }, - _ => {} - }; - } - } -}); diff --git a/kclvm/tests/integration/konfig/test_konfig_kcl.py b/kclvm/tests/integration/konfig/test_konfig_kcl.py deleted file mode 100644 index 0461deda6..000000000 --- a/kclvm/tests/integration/konfig/test_konfig_kcl.py +++ /dev/null @@ -1,127 +0,0 @@ -""" -this testing framework is developed based on pytest. -see quick start of pytest: https://docs.pytest.org/en/latest/example/simple.html - -""" -import os -import subprocess -from pathlib import Path - -import pytest -from ruamel.yaml import YAML -from collections.abc import Mapping, Sequence - -TEST_FILE = "kcl.yaml" -CI_TEST_DIR = "ci-test" -STDOUT_GOLDEN = "stdout.golden.yaml" -SETTINGS_FILE = "settings.yaml" -SKIP_TESTS = ["kcl-vault-csi"] - -ROOT_STR = "test/integration/konfig" -ROOT = str(Path(__file__).parent.parent.parent.parent.parent.joinpath(ROOT_STR)) - -yaml = YAML(typ="unsafe", pure=True) - - -def find_test_dirs(): - result = [] - root_dirs = [ROOT] - for root_dir in root_dirs: - for root, _, files in os.walk(root_dir): - for name in files: - if name == TEST_FILE: - if any([p in SKIP_TESTS for p in Path(root).parts]): - print(f"Skip {root}") - else: - result.append(root) - return result - - -def compare_results(result, golden_result): - """Convert result and golden_result string to string lines with line ending stripped, then compare.""" - result = [ - r - for r in list(yaml.load_all(result)) - if r and r.get("kind") != "SecretProviderClass" - ] - # Convert kusion compile spec to kcl result - expected = [ - r - for r in list(yaml.load_all(golden_result))[0] - if r["attributes"] - # Remove CRDs - and not r["id"].startswith("apiextensions.k8s.io/v1:CustomResourceDefinition") - ] - print(len(result), len(expected)) - assert compare_unordered_yaml_objects(result, expected) - - -def compare_unordered_yaml_objects(result, golden_result): - """Comparing the contents of two YAML objects for equality in an unordered manner""" - if isinstance(result, Mapping) and isinstance(golden_result, Mapping): - if result.keys() != golden_result.keys(): - return False - for key in result.keys(): - if not compare_unordered_yaml_objects(result[key], golden_result[key]): - return False - - return True - elif isinstance(result, Sequence) and isinstance(golden_result, Sequence): - if len(result) != len(golden_result): - return False - for item in result: - if item not in golden_result: - return False - for item in golden_result: - if item not in result: - return False - return True - else: - return result == golden_result - - -def has_settings_file(directory): - settings_file = directory / SETTINGS_FILE - return settings_file.is_file() - - -print("##### K Language Grammar Test Suite #####") -test_dirs = find_test_dirs() -pwd = str(Path(__file__).parent.parent.parent.parent) -os.environ["PYTHONPATH"] = pwd - - -@pytest.mark.parametrize("test_dir", test_dirs) -def test_konfigs(test_dir): - print(f"Testing {test_dir}") - test_dir = Path(test_dir) - kcl_file_name = test_dir / TEST_FILE - ci_test_dir = test_dir / CI_TEST_DIR - if not ci_test_dir.is_dir(): - # Skip invalid test cases - return - golden_file = ci_test_dir / STDOUT_GOLDEN - if not golden_file.is_file(): - # Skip invalid test cases - return - kcl_command = ["kcl"] - if has_settings_file(ci_test_dir): - kcl_command.append("-Y") - kcl_command.append(f"{CI_TEST_DIR}/{SETTINGS_FILE}") - kcl_command.append(f"kcl.yaml") - else: - kcl_command.append(f"{TEST_FILE}") - process = subprocess.run( - kcl_command, capture_output=True, cwd=test_dir, env=dict(os.environ) - ) - stdout, stderr = process.stdout, process.stderr - print(f"STDOUT:\n{stdout.decode()}") - assert ( - process.returncode == 0 and len(stderr) == 0 - ), f"Error executing file {kcl_file_name}.\nexit code = {process.returncode}\nstderr = {stderr}" - if process.returncode == 0 and len(stderr) == 0: - try: - with open(golden_file, "r") as golden: - compare_results(stdout.decode(), golden) - except FileNotFoundError: - raise Exception(f"Error reading expected result from file {golden_file}") diff --git a/kclvm/tests/src/lib.rs b/kclvm/tests/src/lib.rs deleted file mode 100644 index 8b1378917..000000000 --- a/kclvm/tests/src/lib.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/kclvm/tests/test_units/runtime/kclvm_runtime.py b/kclvm/tests/test_units/runtime/kclvm_runtime.py deleted file mode 100644 index 255f85226..000000000 --- a/kclvm/tests/test_units/runtime/kclvm_runtime.py +++ /dev/null @@ -1,100 +0,0 @@ -# Copyright The KCL Authors. All rights reserved. - -import ctypes -import json -import os -import sys - - -def _find_default_dylib_path() -> str: - _executable_root = os.path.dirname(os.environ.get("KCLVM_CLI_BIN_PATH") or sys.executable) - - pathList = [ - f"{_executable_root}/lib/libkclvm_cli_cdylib.dylib", - f"{_executable_root}/lib/libkclvm_cli_cdylib.so", - f"{_executable_root}/bin/libkclvm_cli_cdylib.dylib", - f"{_executable_root}/bin/libkclvm_cli_cdylib.so", - f"{_executable_root}\\bin\\kclvm_cli_cdylib.dll", - f"{os.path.dirname(__file__)}/../../../target/release/libkclvm_cli_cdylib.dylib", - f"{os.path.dirname(__file__)}/../../../target/release/libkclvm_cli_cdylib.so", - f"{os.path.dirname(__file__)}\\..\\..\\..\\target\\release\\kclvm_cli_cdylib.dll", - f"{os.path.dirname(__file__)}/../../../target/debug/libkclvm_cli_cdylib.dylib", - f"{os.path.dirname(__file__)}/../../../target/debug/libkclvm_cli_cdylib.so", - f"{os.path.dirname(__file__)}\\..\\..\\..\\target\\debug\\kclvm_cli_cdylib.dll", - ] - - for s in pathList: - if os.path.exists(s): - return s - return "" - - -class KclvmRuntimeDylib: - def __init__(self, dllpath: str = None): - if dllpath is None: - dllpath = _find_default_dylib_path() - if not dllpath: - raise f"kclvm runtime lib not found" - - self.dllpath = dllpath - self._app_dll = ctypes.cdll.LoadLibrary(dllpath) - self._app_lib = ctypes.CDLL(dllpath) - self.ctx = None - - # kclvm_context_t* kclvm_context_new(); - self._app_lib.kclvm_context_new.restype = ctypes.c_void_p - - # void kclvm_context_delete(kclvm_context_t* p); - self._app_lib.kclvm_context_delete.argtypes = [ - ctypes.c_void_p, - ] - - # const char* kclvm_context_invoke(kclvm_context_t* p, const char* method, const char* args, const char* kwargs); - self._app_lib.kclvm_context_invoke.restype = ctypes.c_char_p - self._app_lib.kclvm_context_invoke.argtypes = [ - ctypes.c_void_p, - ctypes.c_char_p, - ctypes.c_char_p, - ctypes.c_char_p, - ] - - def _kclvm_context_new(self) -> ctypes.c_void_p: - return self._app_lib.kclvm_context_new() - - def kclvm_context_delete(self, ctx: ctypes.c_void_p): - self._app_lib.kclvm_context_delete(ctx) - - def _kclvm_context_invoke( - self, ctx: ctypes.c_void_p, method: str, args: str, kwargs: str - ) -> any: - jsonValue = self._app_lib.kclvm_context_invoke( - ctx, method.encode(), args.encode(), kwargs.encode() - ) - return json.loads(jsonValue) - - def Path(self) -> str: - return self.dllpath - - def Invoke(self, method: str, *args, **kwargs) -> any: - if self.ctx is None: - self.ctx = self._kclvm_context_new() - - if not method.startswith("kclvm_"): - if method.startswith("str."): - # str.startswith => kclvm_builtin_str_startswith - method = f'kclvm_builtin_{method.replace(".", "_")}' - elif "." in method: - # regex.match => kclvm_regex_match - method = f'kclvm_{method.replace(".", "_")}' # json.encode => kclvm_json_encode - else: - method = f"kclvm_builtin_{method}" # print => kclvm_builtin_print - - return self._kclvm_context_invoke( - self.ctx, method, json.dumps(args), json.dumps(kwargs) - ) - - -if __name__ == "__main__": - dylib = KclvmRuntimeDylib() - dylib.Invoke(f"print", "hello kclvm") - diff --git a/kclvm/tests/test_units/runtime/str/Makefile b/kclvm/tests/test_units/runtime/str/Makefile deleted file mode 100644 index 7668a7923..000000000 --- a/kclvm/tests/test_units/runtime/str/Makefile +++ /dev/null @@ -1,7 +0,0 @@ -# Copyright The KCL Authors. All rights reserved. - -default: - python3 -m black . - python3 -m pytest - -clean: diff --git a/kclvm/tools/Cargo.lock b/kclvm/tools/Cargo.lock deleted file mode 100644 index f73510d48..000000000 --- a/kclvm/tools/Cargo.lock +++ /dev/null @@ -1,4577 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "addr2line" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e4503c46a5c0c7844e948c9a4d6acd9f50cccb4de1c48eb9e291ea17470c678" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" - -[[package]] -name = "aho-corasick" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" -dependencies = [ - "memchr", -] - -[[package]] -name = "android-tzdata" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" - -[[package]] -name = "android_system_properties" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" -dependencies = [ - "libc", -] - -[[package]] -name = "anes" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" - -[[package]] -name = "annotate-snippets" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccaf7e9dfbb6ab22c82e473cd1a8a7bd313c19a5b7e40970f3d89ef5a5c9e81e" -dependencies = [ - "unicode-width", - "yansi-term", -] - -[[package]] -name = "anstyle" -version = "1.0.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" - -[[package]] -name = "anyhow" -version = "1.0.100" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" -dependencies = [ - "backtrace", -] - -[[package]] -name = "arrayref" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" - -[[package]] -name = "arrayvec" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "backtrace" -version = "0.3.73" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cc23269a4f8976d0a4d2e7109211a419fe30e8d88d677cd60b6bc79c5732e0a" -dependencies = [ - "addr2line", - "cc", - "cfg-if 1.0.0", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", -] - -[[package]] -name = "base-x" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cbbc9d0964165b47557570cce6c952866c2678457aca742aafc9fb771d30270" - -[[package]] -name = "base32" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23ce669cd6c8588f79e15cf450314f9638f967fc5770ff1c7c1deb0925ea7cfa" - -[[package]] -name = "base64" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "bit-set" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e11e16035ea35e4e5997b393eacbf6f63983188f7a2ad25bfb13465f5ad59de" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" - -[[package]] -name = "blake3" -version = "1.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3888aaa89e4b2a40fca9848e400f6a658a5a3978de7be858e209cafa8be9a4a0" -dependencies = [ - "arrayref", - "arrayvec", - "cc", - "cfg-if 1.0.0", - "constant_time_eq", -] - -[[package]] -name = "block-buffer" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" -dependencies = [ - "block-padding", - "byte-tools", - "byteorder", - "generic-array 0.12.4", -] - -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "generic-array 0.14.5", -] - -[[package]] -name = "block-buffer" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324" -dependencies = [ - "generic-array 0.14.5", -] - -[[package]] -name = "block-padding" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" -dependencies = [ - "byte-tools", -] - -[[package]] -name = "bstr" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" -dependencies = [ - "lazy_static", - "memchr", - "regex-automata 0.1.10", -] - -[[package]] -name = "bumpalo" -version = "3.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535" - -[[package]] -name = "byte-tools" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "bytes" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9" - -[[package]] -name = "cast" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" - -[[package]] -name = "cc" -version = "1.2.47" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd405d82c84ff7f35739f175f67d8b9fb7687a0e84ccdc78bd3568839827cf07" -dependencies = [ - "find-msvc-tools", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "chrono" -version = "0.4.38" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" -dependencies = [ - "android-tzdata", - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-targets 0.52.5", -] - -[[package]] -name = "ciborium" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" -dependencies = [ - "ciborium-io", - "ciborium-ll", - "serde", -] - -[[package]] -name = "ciborium-io" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" - -[[package]] -name = "ciborium-ll" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" -dependencies = [ - "ciborium-io", - "half", -] - -[[package]] -name = "cidr" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd1b64030216239a2e7c364b13cd96a2097ebf0dfe5025f2dedee14a23f2ab60" - -[[package]] -name = "clap" -version = "4.5.53" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9e340e012a1bf4935f5282ed1436d1489548e8f72308207ea5df0e23d2d03f8" -dependencies = [ - "clap_builder", -] - -[[package]] -name = "clap_builder" -version = "4.5.53" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d76b5d13eaa18c901fd2f7fca939fefe3a0727a953561fefdf3b2922b8569d00" -dependencies = [ - "anstyle", - "clap_lex", -] - -[[package]] -name = "clap_lex" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d" - -[[package]] -name = "compiler_base_error" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32e6a143200e9657a565b093fde64a590af93884d1f820829db6461de1ff0086" -dependencies = [ - "anyhow", - "compiler_base_macros", - "compiler_base_span", - "fluent", - "pretty_assertions", - "rustc_errors", - "rustc_span", - "termcolor", - "unic-langid", - "walkdir", -] - -[[package]] -name = "compiler_base_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21900034f34b69f860a5ff66e0577b8e66d310090b04bf0334afea9a041e0cee" - -[[package]] -name = "compiler_base_session" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67411f0b5421d9c9f045ec08c4d01fe3861197d11215d1e2e448be663aff9ad9" -dependencies = [ - "anyhow", - "compiler_base_error", - "compiler_base_span", -] - -[[package]] -name = "compiler_base_span" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a42aae2adfa4b418441ede52835f3c96e9ca63d595f0ac861d94935757e9cb2e" -dependencies = [ - "rustc_span", -] - -[[package]] -name = "console" -version = "0.15.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e1f83fc076bd6dd27517eacdf25fef6c4dfe5f1d7448bafaaf3a26f13b5e4eb" -dependencies = [ - "encode_unicode", - "lazy_static", - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "const_fn" -version = "0.4.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "373e9fafaa20882876db20562275ff58d50e0caa2590077fe7ce7bef90211d0d" - -[[package]] -name = "constant_time_eq" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" - -[[package]] -name = "core-foundation-sys" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" - -[[package]] -name = "cpufeatures" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b" -dependencies = [ - "libc", -] - -[[package]] -name = "crc32fast" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a97769d94ddab943e4510d138150169a2758b5ef3eb191a9ee688de3e23ef7b3" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "criterion" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" -dependencies = [ - "anes", - "cast", - "ciborium", - "clap", - "criterion-plot", - "is-terminal", - "itertools", - "num-traits", - "once_cell", - "oorandom", - "plotters", - "rayon", - "regex", - "serde", - "serde_derive", - "serde_json", - "tinytemplate", - "walkdir", -] - -[[package]] -name = "criterion-plot" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" -dependencies = [ - "cast", - "itertools", -] - -[[package]] -name = "crossbeam-channel" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aaa7bd5fb665c6864b5f963dd9097905c54125909c7aa94c9e18507cdbe6c53" -dependencies = [ - "cfg-if 1.0.0", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" -dependencies = [ - "cfg-if 1.0.0", - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1145cf131a2c6ba0615079ab6a638f7e1973ac9c2634fcbeaaad6114246efe8c" -dependencies = [ - "autocfg", - "cfg-if 1.0.0", - "crossbeam-utils", - "lazy_static", - "memoffset", - "scopeguard", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf124c720b7686e3c2663cf54062ab0f68a88af2fb6a030e87e30bf721fcb38" -dependencies = [ - "cfg-if 1.0.0", - "lazy_static", -] - -[[package]] -name = "crunchy" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" - -[[package]] -name = "crypto-common" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8" -dependencies = [ - "generic-array 0.14.5", - "typenum", -] - -[[package]] -name = "ctor" -version = "0.1.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f877be4f7c9f246b183111634f75baa039715e3f46ce860677d3b19a69fb229c" -dependencies = [ - "quote", - "syn 1.0.107", -] - -[[package]] -name = "darling" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" -dependencies = [ - "darling_core", - "darling_macro", -] - -[[package]] -name = "darling_core" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim 0.11.1", - "syn 2.0.87", -] - -[[package]] -name = "darling_macro" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" -dependencies = [ - "darling_core", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "deranged" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ececcb659e7ba858fb4f10388c250a7252eb0a27373f1a72b8748afdd248e587" -dependencies = [ - "powerfmt", -] - -[[package]] -name = "derive_builder" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" -dependencies = [ - "derive_builder_macro", -] - -[[package]] -name = "derive_builder_core" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" -dependencies = [ - "darling", - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "derive_builder_macro" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" -dependencies = [ - "derive_builder_core", - "syn 2.0.87", -] - -[[package]] -name = "diff" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e25ea47919b1560c4e3b7fe0aaab9becf5b84a10325ddf7db0f0ba5e1026499" - -[[package]] -name = "digest" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" -dependencies = [ - "generic-array 0.12.4", -] - -[[package]] -name = "digest" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" -dependencies = [ - "generic-array 0.14.5", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer 0.10.2", - "crypto-common", - "subtle", -] - -[[package]] -name = "dirs" -version = "5.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" -dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys 0.48.0", -] - -[[package]] -name = "discard" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "212d0f5754cb6769937f4501cc0e67f4f4483c8d2c3e1e922ee9edbe4ab4c7c0" - -[[package]] -name = "displaydoc" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "dns-lookup" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf5597a4b7fe5275fc9dcf88ce26326bc8e4cb87d0130f33752d4c5f717793cf" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "socket2 0.6.1", - "windows-sys 0.60.2", -] - -[[package]] -name = "either" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" - -[[package]] -name = "ena" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7402b94a93c24e742487327a7cd839dc9d36fec9de9fb25b09f2dae459f36c3" -dependencies = [ - "log", -] - -[[package]] -name = "encode_unicode" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" - -[[package]] -name = "encoding_rs" -version = "0.8.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "enquote" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06c36cb11dbde389f4096111698d8b567c0720e3452fd5ac3e6b4e47e1939932" -dependencies = [ - "thiserror 1.0.61", -] - -[[package]] -name = "equivalent" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" - -[[package]] -name = "errno" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "534c5cf6194dfab3db3242765c03bbe257cf92f22b38f6bc0c58d59108a820ba" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "fancy-regex" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d6b8560a05112eb52f04b00e5d3790c0dd75d9d980eb8a122fb23b92a623ccf" -dependencies = [ - "bit-set", - "regex", -] - -[[package]] -name = "fastrand" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" - -[[package]] -name = "filetime" -version = "0.2.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ee447700ac8aa0b2f2bd7bc4462ad686ba06baa6727ac149a2d6277f0d240fd" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "redox_syscall 0.4.1", - "windows-sys 0.52.0", -] - -[[package]] -name = "find-msvc-tools" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a3076410a55c90011c298b04d0cfa770b00fa04e1e3c97d3f6c9de105a03844" - -[[package]] -name = "fixedbitset" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "279fb028e20b3c4c320317955b77c5e0c9701f05a1d309905d6fc702cdc5053e" - -[[package]] -name = "flate2" -version = "1.0.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f54427cfd1c7829e2a139fcefea601bf088ebca651d2bf53ebc600eac295dae" -dependencies = [ - "crc32fast", - "miniz_oxide", -] - -[[package]] -name = "fluent" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb74634707bebd0ce645a981148e8fb8c7bccd4c33c652aeffd28bf2f96d555a" -dependencies = [ - "fluent-bundle", - "unic-langid", -] - -[[package]] -name = "fluent-bundle" -version = "0.15.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fe0a21ee80050c678013f82edf4b705fe2f26f1f9877593d13198612503f493" -dependencies = [ - "fluent-langneg", - "fluent-syntax", - "intl-memoizer", - "intl_pluralrules", - "rustc-hash 1.1.0", - "self_cell 0.10.3", - "smallvec", - "unic-langid", -] - -[[package]] -name = "fluent-langneg" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c4ad0989667548f06ccd0e306ed56b61bd4d35458d54df5ec7587c0e8ed5e94" -dependencies = [ - "unic-langid", -] - -[[package]] -name = "fluent-syntax" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a530c4694a6a8d528794ee9bbd8ba0122e779629ac908d15ad5a7ae7763a33d" -dependencies = [ - "thiserror 1.0.61", -] - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "form_urlencoded" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "fslock" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04412b8935272e3a9bae6f48c7bfff74c2911f60525404edfdd28e49884c3bfb" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "futures-channel" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" -dependencies = [ - "futures-core", -] - -[[package]] -name = "futures-core" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" - -[[package]] -name = "futures-io" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" - -[[package]] -name = "futures-macro" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "futures-sink" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fb8e00e87438d937621c1c6269e53f536c14d3fbd6a042bb24879e57d474fb5" - -[[package]] -name = "futures-task" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" - -[[package]] -name = "futures-util" -version = "0.3.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" -dependencies = [ - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "pin-utils", - "slab", -] - -[[package]] -name = "generational-arena" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877e94aff08e743b651baaea359664321055749b398adff8740a7399af7796e7" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "generic-array" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" -dependencies = [ - "typenum", -] - -[[package]] -name = "generic-array" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" -dependencies = [ - "cfg-if 1.0.0", - "js-sys", - "libc", - "wasi", - "wasm-bindgen", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if 1.0.0", - "js-sys", - "libc", - "r-efi", - "wasip2", - "wasm-bindgen", -] - -[[package]] -name = "gimli" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" - -[[package]] -name = "glob" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" - -[[package]] -name = "half" -version = "2.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" -dependencies = [ - "cfg-if 1.0.0", - "crunchy", - "zerocopy", -] - -[[package]] -name = "handlebars" -version = "5.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d08485b96a0e6393e9e4d1b8d48cf74ad6c063cd905eb33f42c1ce3f0377539b" -dependencies = [ - "log", - "pest", - "pest_derive", - "serde", - "serde_json", - "thiserror 1.0.61", -] - -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" - -[[package]] -name = "hashbrown" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" - -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - -[[package]] -name = "hermit-abi" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest 0.10.7", -] - -[[package]] -name = "hostname" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a56f203cd1c76362b69e3863fd987520ac36cf70a8c92627449b2f64a8cf7d65" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "windows-link 0.1.3", -] - -[[package]] -name = "http" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - -[[package]] -name = "http-auth" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "643c9bbf6a4ea8a656d6b4cd53d34f79e3f841ad5203c1a55fb7d761923bc255" -dependencies = [ - "memchr", -] - -[[package]] -name = "http-body" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643" -dependencies = [ - "bytes", - "http", -] - -[[package]] -name = "http-body-util" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" -dependencies = [ - "bytes", - "futures-util", - "http", - "http-body", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fcc0b4a115bf80b728eb8ea024ad5bd707b615bfed49e0665b6e0f86fd082d9" - -[[package]] -name = "hyper" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe575dd17d0862a9a33781c8c4696a55c320909004a67a00fb286ba8b1bc496d" -dependencies = [ - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "httparse", - "itoa", - "pin-project-lite", - "smallvec", - "tokio", - "want", -] - -[[package]] -name = "hyper-rustls" -version = "0.27.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ee4be2c948921a1a5320b629c4193916ed787a7f7f293fd3f7f5a6c9de74155" -dependencies = [ - "futures-util", - "http", - "hyper", - "hyper-util", - "rustls", - "rustls-pki-types", - "tokio", - "tokio-rustls", - "tower-service", - "webpki-roots", -] - -[[package]] -name = "hyper-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b875924a60b96e5d7b9ae7b066540b1dd1cbd90d1828f54c92e02a283351c56" -dependencies = [ - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "hyper", - "pin-project-lite", - "socket2 0.5.7", - "tokio", - "tower", - "tower-service", - "tracing", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "icu_collections" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" -dependencies = [ - "displaydoc", - "potential_utf", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" -dependencies = [ - "displaydoc", - "litemap", - "tinystr 0.8.2", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" - -[[package]] -name = "icu_properties" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e93fcd3157766c0c8da2f8cff6ce651a31f0810eaa1c51ec363ef790bbb5fb99" -dependencies = [ - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02845b3647bb045f1100ecd6480ff52f34c35f82d9880e029d329c21d1054899" - -[[package]] -name = "icu_provider" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "indexmap" -version = "1.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", - "rustc-rayon 0.4.0", -] - -[[package]] -name = "indexmap" -version = "2.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ad4bb2b565bca0645f4d68c5c9af97fba094e9791da685bf83cb5f3ce74acf2" -dependencies = [ - "equivalent", - "hashbrown 0.16.1", -] - -[[package]] -name = "inkwell" -version = "0.1.0" -source = "git+https://github.com/TheDan64/inkwell?branch=master#468320973ec40c237ad34e266a680a875605aa3a" -dependencies = [ - "either", - "inkwell_internals", - "libc", - "llvm-sys", - "once_cell", - "parking_lot 0.12.3", -] - -[[package]] -name = "inkwell_internals" -version = "0.7.0" -source = "git+https://github.com/TheDan64/inkwell?branch=master#468320973ec40c237ad34e266a680a875605aa3a" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.107", -] - -[[package]] -name = "insta" -version = "1.17.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6de657c6e99c9f665a595db63c6342de64cbd076a817f24c4a548847a81aee5" -dependencies = [ - "console", - "once_cell", - "serde", - "serde_json", - "serde_yaml", - "similar", -] - -[[package]] -name = "instant" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "intl-memoizer" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe22e020fce238ae18a6d5d8c502ee76a52a6e880d99477657e6acc30ec57bda" -dependencies = [ - "type-map", - "unic-langid", -] - -[[package]] -name = "intl_pluralrules" -version = "7.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "078ea7b7c29a2b4df841a7f6ac8775ff6074020c6776d48491ce2268e068f972" -dependencies = [ - "unic-langid", -] - -[[package]] -name = "ipnet" -version = "2.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f518f335dce6725a761382244631d86cf0ccb2863413590b31338feb467f9c3" - -[[package]] -name = "is-terminal" -version = "0.4.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" -dependencies = [ - "hermit-abi 0.5.2", - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "itertools" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" - -[[package]] -name = "jobserver" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af25a77299a7f711a01975c35a6a424eb6862092cc2d6c72c4ed6cbc56dfc1fa" -dependencies = [ - "libc", -] - -[[package]] -name = "js-sys" -version = "0.3.82" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b011eec8cc36da2aab2d5cff675ec18454fad408585853910a202391cf9f8e65" -dependencies = [ - "once_cell", - "wasm-bindgen", -] - -[[package]] -name = "json-spanned-value" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb343fa4e3b1b22b344937deedac88da995abf139c2232cbeaa436c38380a210" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "jwt" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6204285f77fe7d9784db3fdc449ecce1a0114927a51d5a41c4c7a292011c015f" -dependencies = [ - "base64 0.13.0", - "crypto-common", - "digest 0.10.7", - "hmac", - "serde", - "serde_json", - "sha2 0.10.2", -] - -[[package]] -name = "kclvm-ast" -version = "0.11.2" -dependencies = [ - "anyhow", - "compiler_base_span", - "kclvm-error", - "kclvm-span", - "kclvm-utils", - "serde", - "serde_json", - "thread_local", - "uuid", -] - -[[package]] -name = "kclvm-ast-pretty" -version = "0.11.2" -dependencies = [ - "compiler_base_macros", - "compiler_base_session", - "fancy-regex", - "kclvm-ast", - "kclvm-error", - "kclvm-primitives", - "pretty_assertions", -] - -[[package]] -name = "kclvm-compiler" -version = "0.11.2" -dependencies = [ - "bit-set", - "bitflags 1.3.2", - "fancy-regex", - "inkwell", - "kclvm-ast", - "kclvm-error", - "kclvm-primitives", - "kclvm-runtime", - "kclvm-sema", - "once_cell", - "phf", - "time 0.2.27", - "unicode_names2", -] - -[[package]] -name = "kclvm-config" -version = "0.11.2" -dependencies = [ - "anyhow", - "chrono", - "dirs", - "glob", - "kclvm-ast", - "kclvm-utils", - "kclvm-version", - "md-5 0.8.0", - "pathdiff", - "regex", - "ron", - "serde", - "serde_json", - "serde_yaml_ng", - "toml", - "url", -] - -[[package]] -name = "kclvm-driver" -version = "0.11.2" -dependencies = [ - "anyhow", - "flate2", - "kclvm-ast", - "kclvm-config", - "kclvm-parser", - "kclvm-primitives", - "kclvm-runtime", - "kclvm-utils", - "oci-client", - "once_cell", - "parking_lot 0.12.3", - "serde", - "serde_json", - "tar", - "tokio", - "walkdir", -] - -[[package]] -name = "kclvm-error" -version = "0.11.2" -dependencies = [ - "annotate-snippets", - "anyhow", - "compiler_base_error", - "compiler_base_macros", - "compiler_base_session", - "compiler_base_span", - "kclvm-primitives", - "kclvm-runtime", - "kclvm-span", - "kclvm-utils", - "serde", - "serde_json", - "termize", - "thiserror 2.0.17", - "tracing", -] - -[[package]] -name = "kclvm-evaluator" -version = "0.11.2" -dependencies = [ - "anyhow", - "generational-arena", - "kclvm-ast", - "kclvm-error", - "kclvm-primitives", - "kclvm-runtime", - "kclvm-sema", - "scopeguard", -] - -[[package]] -name = "kclvm-lexer" -version = "0.11.2" -dependencies = [ - "kclvm-error", - "rustc_lexer", - "unic-emoji-char", -] - -[[package]] -name = "kclvm-macros" -version = "0.11.2" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.107", - "synstructure 0.12.6", -] - -[[package]] -name = "kclvm-parser" -version = "0.11.2" -dependencies = [ - "anyhow", - "bstr", - "compiler_base_error", - "compiler_base_macros", - "compiler_base_session", - "compiler_base_span", - "either", - "enquote", - "glob", - "kclvm-ast", - "kclvm-config", - "kclvm-error", - "kclvm-lexer", - "kclvm-primitives", - "kclvm-sema", - "kclvm-span", - "kclvm-utils", - "num-bigint", - "parking_lot 0.12.3", - "petgraph", - "regex", - "rustc_lexer", - "serde", - "serde_json", - "tracing", - "unicode_names2", - "walkdir", -] - -[[package]] -name = "kclvm-primitives" -version = "0.11.2" -dependencies = [ - "indexmap 2.12.1", - "rustc-hash 2.1.1", -] - -[[package]] -name = "kclvm-query" -version = "0.11.2" -dependencies = [ - "anyhow", - "compiler_base_macros", - "compiler_base_session", - "fancy-regex", - "kclvm-ast", - "kclvm-ast-pretty", - "kclvm-error", - "kclvm-parser", - "kclvm-primitives", - "kclvm-sema", - "kclvm-utils", - "maplit", - "serde", - "serde_json", -] - -[[package]] -name = "kclvm-runner" -version = "0.11.2" -dependencies = [ - "anyhow", - "cc", - "chrono", - "compiler_base_macros", - "compiler_base_session", - "glob", - "kclvm-ast", - "kclvm-compiler", - "kclvm-config", - "kclvm-driver", - "kclvm-error", - "kclvm-evaluator", - "kclvm-parser", - "kclvm-primitives", - "kclvm-query", - "kclvm-runtime", - "kclvm-sema", - "kclvm-utils", - "kclvm-version", - "libc", - "libloading", - "once_cell", - "serde", - "serde_json", - "tempfile", - "threadpool", - "uuid", - "walkdir", -] - -[[package]] -name = "kclvm-runtime" -version = "0.11.2" -dependencies = [ - "anyhow", - "base32", - "base64 0.13.0", - "blake3", - "bstr", - "chrono", - "cidr", - "dns-lookup", - "encoding_rs", - "fancy-regex", - "generational-arena", - "glob", - "handlebars", - "hostname", - "itertools", - "kclvm-primitives", - "kclvm_runtime_internal_macros", - "lazy_static", - "libc", - "md5", - "num-integer", - "phf", - "regex", - "serde", - "serde_json", - "serde_yaml_ng", - "sha1", - "sha2 0.9.9", - "unic-ucd-bidi", - "unic-ucd-category", - "unicode-casing", - "uuid", - "walkdir", -] - -[[package]] -name = "kclvm-sema" -version = "0.11.2" -dependencies = [ - "anyhow", - "bit-set", - "bitflags 1.3.2", - "compiler_base_error", - "compiler_base_macros", - "compiler_base_session", - "compiler_base_span", - "fancy-regex", - "generational-arena", - "kclvm-ast", - "kclvm-ast-pretty", - "kclvm-error", - "kclvm-primitives", - "kclvm-runtime", - "kclvm-span", - "kclvm-utils", - "lazy_static", - "once_cell", - "parking_lot 0.12.3", - "petgraph", - "phf", - "regex", - "serde", - "serde_json", - "suggestions", - "unicode_names2", -] - -[[package]] -name = "kclvm-span" -version = "0.11.2" -dependencies = [ - "compiler_base_span", - "kclvm-macros", - "parking_lot 0.11.2", - "scoped-tls", -] - -[[package]] -name = "kclvm-tools" -version = "0.11.2" -dependencies = [ - "anyhow", - "compiler_base_session", - "compiler_base_span", - "criterion", - "fancy-regex", - "insta", - "json-spanned-value", - "kclvm-ast", - "kclvm-ast-pretty", - "kclvm-config", - "kclvm-driver", - "kclvm-error", - "kclvm-parser", - "kclvm-primitives", - "kclvm-query", - "kclvm-runner", - "kclvm-runtime", - "kclvm-sema", - "kclvm-utils", - "located_yaml", - "once_cell", - "pretty_assertions", - "regex", - "rustc_lexer", - "serde_json", - "serde_yaml_ng", - "walkdir", -] - -[[package]] -name = "kclvm-utils" -version = "0.11.2" -dependencies = [ - "anyhow", - "fslock", - "regex", -] - -[[package]] -name = "kclvm-version" -version = "0.11.2" -dependencies = [ - "vergen-gitcl", -] - -[[package]] -name = "kclvm_runtime_internal_macros" -version = "0.5.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.107", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.177" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" - -[[package]] -name = "libloading" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" -dependencies = [ - "cfg-if 1.0.0", - "winapi", -] - -[[package]] -name = "libredox" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" -dependencies = [ - "bitflags 2.5.0", - "libc", -] - -[[package]] -name = "linked-hash-map" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3" -dependencies = [ - "serde", - "serde_test", -] - -[[package]] -name = "linux-raw-sys" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78b3ae25bc7c8c38cec158d1f2757ee79e9b3740fbc7ccf0e59e4b08d793fa89" - -[[package]] -name = "litemap" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" - -[[package]] -name = "llvm-sys" -version = "120.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "909fd0ded1d3becfa3d52581b33602d87160d63da6a3844a86a51b0c93e8460c" -dependencies = [ - "cc", - "lazy_static", - "libc", - "regex", - "semver 0.11.0", -] - -[[package]] -name = "located_yaml" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bc68ee6f87a1be7fdba1dcfd854528371aa84a8390279b5d7a99d5da82add76" -dependencies = [ - "linked-hash-map", - "serde", - "yaml-rust", -] - -[[package]] -name = "lock_api" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" -dependencies = [ - "autocfg", - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "lru-slab" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" - -[[package]] -name = "maplit" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" - -[[package]] -name = "matches" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" - -[[package]] -name = "md-5" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a18af3dcaf2b0219366cdb4e2af65a6101457b415c3d1a5c71dd9c2b7c77b9c8" -dependencies = [ - "block-buffer 0.7.3", - "digest 0.8.1", - "opaque-debug 0.2.3", -] - -[[package]] -name = "md-5" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "658646b21e0b72f7866c7038ab086d3d5e1cd6271f060fd37defb241949d0582" -dependencies = [ - "digest 0.10.7", -] - -[[package]] -name = "md5" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" - -[[package]] -name = "memchr" -version = "2.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" - -[[package]] -name = "memmap2" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "723e3ebdcdc5c023db1df315364573789f8857c11b631a2fdfad7c00f5c046b4" -dependencies = [ - "libc", -] - -[[package]] -name = "memoffset" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" -dependencies = [ - "autocfg", -] - -[[package]] -name = "mime" -version = "0.3.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" - -[[package]] -name = "miniz_oxide" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8a240ddb74feaf34a79a7add65a741f3167852fba007066dcac1ca548d89c08" -dependencies = [ - "adler", -] - -[[package]] -name = "mio" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" -dependencies = [ - "libc", - "wasi", - "windows-sys 0.48.0", -] - -[[package]] -name = "num-bigint" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f" -dependencies = [ - "autocfg", - "num-integer", - "num-traits", -] - -[[package]] -name = "num-conv" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" - -[[package]] -name = "num-integer" -version = "0.1.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" -dependencies = [ - "autocfg", - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_cpus" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" -dependencies = [ - "hermit-abi 0.1.19", - "libc", -] - -[[package]] -name = "num_threads" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" -dependencies = [ - "libc", -] - -[[package]] -name = "object" -version = "0.36.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "576dfe1fc8f9df304abb159d767a29d0476f7750fbf8aa7ad07816004a207434" -dependencies = [ - "memchr", -] - -[[package]] -name = "oci-client" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "560faeb9396a5bae11b141bed3cec8bf9242e5bfec17d0f48feeeab0f879ca35" -dependencies = [ - "bytes", - "chrono", - "futures-util", - "http", - "http-auth", - "jwt", - "lazy_static", - "olpc-cjson", - "regex", - "reqwest", - "serde", - "serde_json", - "sha2 0.10.2", - "thiserror 1.0.61", - "tokio", - "tracing", - "unicase", -] - -[[package]] -name = "olpc-cjson" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d637c9c15b639ccff597da8f4fa968300651ad2f1e968aefc3b4927a6fb2027a" -dependencies = [ - "serde", - "serde_json", - "unicode-normalization", -] - -[[package]] -name = "once_cell" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" - -[[package]] -name = "oorandom" -version = "11.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575" - -[[package]] -name = "opaque-debug" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" - -[[package]] -name = "opaque-debug" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" - -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - -[[package]] -name = "output_vt100" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "628223faebab4e3e40667ee0b2336d34a5b960ff60ea743ddfdbcf7770bcfb66" -dependencies = [ - "winapi", -] - -[[package]] -name = "parking_lot" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" -dependencies = [ - "instant", - "lock_api", - "parking_lot_core 0.8.6", -] - -[[package]] -name = "parking_lot" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" -dependencies = [ - "lock_api", - "parking_lot_core 0.9.3", -] - -[[package]] -name = "parking_lot_core" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc" -dependencies = [ - "cfg-if 1.0.0", - "instant", - "libc", - "redox_syscall 0.2.13", - "smallvec", - "winapi", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09a279cbf25cb0757810394fbc1e359949b59e348145c643a939a525692e6929" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "redox_syscall 0.2.13", - "smallvec", - "windows-sys 0.36.1", -] - -[[package]] -name = "pathdiff" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "pest" -version = "2.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "560131c633294438da9f7c4b08189194b20946c8274c6b9e38881a7874dc8ee8" -dependencies = [ - "memchr", - "thiserror 1.0.61", - "ucd-trie", -] - -[[package]] -name = "pest_derive" -version = "2.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26293c9193fbca7b1a3bf9b79dc1e388e927e6cacaa78b4a3ab705a1d3d41459" -dependencies = [ - "pest", - "pest_generator", -] - -[[package]] -name = "pest_generator" -version = "2.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ec22af7d3fb470a85dd2ca96b7c577a1eb4ef6f1683a9fe9a8c16e136c04687" -dependencies = [ - "pest", - "pest_meta", - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "pest_meta" -version = "2.7.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7a240022f37c361ec1878d646fc5b7d7c4d28d5946e1a80ad5a7a4f4ca0bdcd" -dependencies = [ - "once_cell", - "pest", - "sha2 0.10.2", -] - -[[package]] -name = "petgraph" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a13a2fa9d0b63e5f22328828741e523766fff0ee9e779316902290dff3f824f" -dependencies = [ - "fixedbitset", - "indexmap 1.9.2", -] - -[[package]] -name = "phf" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2ac8b67553a7ca9457ce0e526948cad581819238f4a9d1ea74545851fa24f37" -dependencies = [ - "phf_macros", - "phf_shared", - "proc-macro-hack", -] - -[[package]] -name = "phf_generator" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43f3220d96e0080cc9ea234978ccd80d904eafb17be31bb0f76daaea6493082" -dependencies = [ - "phf_shared", - "rand 0.8.5", -] - -[[package]] -name = "phf_macros" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b706f5936eb50ed880ae3009395b43ed19db5bff2ebd459c95e7bf013a89ab86" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro-hack", - "proc-macro2", - "quote", - "syn 1.0.107", -] - -[[package]] -name = "phf_shared" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a68318426de33640f02be62b4ae8eb1261be2efbc337b60c54d845bf4484e0d9" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pin-project" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6bf43b791c5b9e34c3d182969b4abb522f9343702850a2e57f460d00d09b4b3" -dependencies = [ - "pin-project-internal", -] - -[[package]] -name = "pin-project-internal" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f38a4412a78282e09a2cf38d195ea5420d15ba0602cb375210efbc877243965" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" - -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - -[[package]] -name = "plotters" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a3fd9ec30b9749ce28cd91f255d569591cdf937fe280c312143e3c4bad6f2a" -dependencies = [ - "num-traits", - "plotters-backend", - "plotters-svg", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "plotters-backend" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d88417318da0eaf0fdcdb51a0ee6c3bed624333bff8f946733049380be67ac1c" - -[[package]] -name = "plotters-svg" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "521fa9638fa597e1dc53e9412a4f9cefb01187ee1f7413076f9e6749e2885ba9" -dependencies = [ - "plotters-backend", -] - -[[package]] -name = "potential_utf" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" -dependencies = [ - "zerovec", -] - -[[package]] -name = "powerfmt" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" - -[[package]] -name = "ppv-lite86" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" - -[[package]] -name = "pretty_assertions" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a25e9bcb20aa780fd0bb16b72403a9064d6b3f22f026946029acb941a50af755" -dependencies = [ - "ctor", - "diff", - "output_vt100", - "yansi", -] - -[[package]] -name = "proc-macro-hack" -version = "0.5.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" - -[[package]] -name = "proc-macro2" -version = "1.0.86" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quinn" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4ceeeeabace7857413798eb1ffa1e9c905a9946a57d81fb69b4b71c4d8eb3ad" -dependencies = [ - "bytes", - "pin-project-lite", - "quinn-proto", - "quinn-udp", - "rustc-hash 1.1.0", - "rustls", - "thiserror 1.0.61", - "tokio", - "tracing", -] - -[[package]] -name = "quinn-proto" -version = "0.11.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31" -dependencies = [ - "bytes", - "getrandom 0.3.4", - "lru-slab", - "rand 0.9.2", - "ring", - "rustc-hash 2.1.1", - "rustls", - "rustls-pki-types", - "slab", - "thiserror 2.0.17", - "tinyvec", - "tracing", - "web-time", -] - -[[package]] -name = "quinn-udp" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9096629c45860fc7fb143e125eb826b5e721e10be3263160c7d60ca832cf8c46" -dependencies = [ - "libc", - "once_cell", - "socket2 0.5.7", - "tracing", - "windows-sys 0.52.0", -] - -[[package]] -name = "quote" -version = "1.0.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.3", -] - -[[package]] -name = "rand" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" -dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.3", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.3", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.3", -] - -[[package]] -name = "rand_core" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" -dependencies = [ - "getrandom 0.2.15", -] - -[[package]] -name = "rand_core" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" -dependencies = [ - "getrandom 0.3.4", -] - -[[package]] -name = "rayon" -version = "1.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd99e5772ead8baa5215278c9b15bf92087709e9c1b2d1f97cdb5a183c933a7d" -dependencies = [ - "autocfg", - "crossbeam-deque", - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "258bcdb5ac6dad48491bb2992db6b7cf74878b0384908af124823d118c99683f" -dependencies = [ - "crossbeam-channel", - "crossbeam-deque", - "crossbeam-utils", - "num_cpus", -] - -[[package]] -name = "redox_syscall" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" -dependencies = [ - "bitflags 1.3.2", -] - -[[package]] -name = "redox_syscall" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" -dependencies = [ - "bitflags 1.3.2", -] - -[[package]] -name = "redox_users" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd283d9651eeda4b2a83a43c1c91b266c40fd76ecd39a50a8c630ae69dc72891" -dependencies = [ - "getrandom 0.2.15", - "libredox", - "thiserror 1.0.61", -] - -[[package]] -name = "regex" -version = "1.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b91213439dad192326a0d7c6ee3955910425f441d7038e0d6933b0aec5c4517f" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata 0.4.7", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" - -[[package]] -name = "regex-automata" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a66a03ae7c801facd77a29370b4faec201768915ac14a721ba36f20bc9c209b" - -[[package]] -name = "reqwest" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7d6d2a27d57148378eb5e111173f4276ad26340ecc5c49a4a2152167a2d6a37" -dependencies = [ - "base64 0.22.1", - "bytes", - "futures-core", - "futures-util", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-util", - "ipnet", - "js-sys", - "log", - "mime", - "once_cell", - "percent-encoding", - "pin-project-lite", - "quinn", - "rustls", - "rustls-pemfile", - "rustls-pki-types", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tokio-rustls", - "tokio-util", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "wasm-streams", - "web-sys", - "webpki-roots", - "winreg", -] - -[[package]] -name = "ring" -version = "0.17.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c17fa4cb658e3583423e915b9f3acc01cceaee1860e33d59ebae66adc3a2dc0d" -dependencies = [ - "cc", - "cfg-if 1.0.0", - "getrandom 0.2.15", - "libc", - "spin", - "untrusted", - "windows-sys 0.52.0", -] - -[[package]] -name = "ron" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b861ecaade43ac97886a512b360d01d66be9f41f3c61088b42cedf92e03d678" -dependencies = [ - "base64 0.13.0", - "bitflags 1.3.2", - "serde", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - -[[package]] -name = "rustc-hash" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" - -[[package]] -name = "rustc-rayon" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9974ab223660e61c1b4e7b43b827379df286736ca988308ce7e16f59f2d89246" -dependencies = [ - "crossbeam-deque", - "either", - "rustc-rayon-core 0.3.2", -] - -[[package]] -name = "rustc-rayon" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a79f0b0b2609e2eacf9758013f50e7176cb4b29fd6436a747b14a5362c8727a" -dependencies = [ - "autocfg", - "crossbeam-deque", - "either", - "rustc-rayon-core 0.4.1", -] - -[[package]] -name = "rustc-rayon-core" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "564bfd27be8db888d0fa76aa4335e7851aaed0c2c11ad1e93aeb9349f6b88500" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", - "lazy_static", - "num_cpus", -] - -[[package]] -name = "rustc-rayon-core" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02269144a0db9bb55cf5d4a41a5a0e95b334b0b78b08269018ca9b0250718c30" -dependencies = [ - "crossbeam-channel", - "crossbeam-deque", - "crossbeam-utils", - "num_cpus", -] - -[[package]] -name = "rustc_data_structures" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a38bae9c6afa27015bcaa2869e03bb111ecf0d0e0edc2da559a91d4057174c9a" -dependencies = [ - "arrayvec", - "bitflags 1.3.2", - "cfg-if 0.1.10", - "ena", - "indexmap 1.9.2", - "jobserver", - "libc", - "memmap2", - "parking_lot 0.12.3", - "rustc-hash 1.1.0", - "rustc-rayon 0.3.2", - "rustc-rayon-core 0.3.2", - "stable_deref_trait", - "tempfile", - "tracing", - "winapi", -] - -[[package]] -name = "rustc_errors" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00299b1841816d2c41129e6d4f86b0b446ee387e8203871c2551e1c405b1243c" -dependencies = [ - "termcolor", - "winapi", -] - -[[package]] -name = "rustc_lexer" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c86aae0c77166108c01305ee1a36a1e77289d7dc6ca0a3cd91ff4992de2d16a5" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "rustc_span" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "043e9cc06c53de1f6a125e41e4b915d23a130241610a114ad4fe4f654617eae4" -dependencies = [ - "cfg-if 0.1.10", - "md-5 0.10.1", - "rustc_data_structures", - "scoped-tls", - "sha-1", - "sha2 0.10.2", - "tracing", - "unicode-width", -] - -[[package]] -name = "rustc_version" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -dependencies = [ - "semver 0.9.0", -] - -[[package]] -name = "rustc_version" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" -dependencies = [ - "semver 1.0.10", -] - -[[package]] -name = "rustix" -version = "0.38.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" -dependencies = [ - "bitflags 2.5.0", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.52.0", -] - -[[package]] -name = "rustls" -version = "0.23.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05cff451f60db80f490f3c182b77c35260baace73209e9cdbbe526bfe3a4d402" -dependencies = [ - "once_cell", - "ring", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-pemfile" -version = "2.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29993a25686778eb88d4189742cd713c9bce943bc54251a33509dc63cbacf73d" -dependencies = [ - "base64 0.22.1", - "rustls-pki-types", -] - -[[package]] -name = "rustls-pki-types" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d" -dependencies = [ - "web-time", -] - -[[package]] -name = "rustls-webpki" -version = "0.102.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff448f7e92e913c4b7d4c6d8e4540a1724b319b4152b8aef6d4cf8339712b33e" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", -] - -[[package]] -name = "rustversion" -version = "1.0.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" - -[[package]] -name = "ryu" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" - -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "scoped-tls" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "self_cell" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e14e4d63b804dc0c7ec4a1e52bcb63f02c7ac94476755aa579edac21e01f915d" -dependencies = [ - "self_cell 1.0.4", -] - -[[package]] -name = "self_cell" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d369a96f978623eb3dc28807c4852d6cc617fed53da5d3c400feff1ef34a714a" - -[[package]] -name = "semver" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -dependencies = [ - "semver-parser 0.7.0", -] - -[[package]] -name = "semver" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" -dependencies = [ - "semver-parser 0.10.2", -] - -[[package]] -name = "semver" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a41d061efea015927ac527063765e73601444cdc344ba855bc7bd44578b25e1c" - -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" - -[[package]] -name = "semver-parser" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00b0bef5b7f9e0df16536d3961cfb6e84331c065b4066afb39768d0e319411f7" -dependencies = [ - "pest", -] - -[[package]] -name = "serde" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "serde_json" -version = "1.0.145" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" -dependencies = [ - "itoa", - "memchr", - "ryu", - "serde", - "serde_core", -] - -[[package]] -name = "serde_test" -version = "1.0.176" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a2f49ace1498612d14f7e0b8245519584db8299541dfe31a06374a828d620ab" -dependencies = [ - "serde", -] - -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_yaml" -version = "0.8.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578a7433b776b56a35785ed5ce9a7e777ac0598aac5a6dd1b4b18a307c7fc71b" -dependencies = [ - "indexmap 1.9.2", - "ryu", - "serde", - "yaml-rust", -] - -[[package]] -name = "serde_yaml_ng" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f" -dependencies = [ - "indexmap 2.12.1", - "itoa", - "ryu", - "serde", - "unsafe-libyaml", -] - -[[package]] -name = "sha-1" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.7", -] - -[[package]] -name = "sha1" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" -dependencies = [ - "sha1_smol", -] - -[[package]] -name = "sha1_smol" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" - -[[package]] -name = "sha2" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.9.0", - "opaque-debug 0.3.0", -] - -[[package]] -name = "sha2" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.7", -] - -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - -[[package]] -name = "signal-hook-registry" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" -dependencies = [ - "libc", -] - -[[package]] -name = "similar" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa42c91313f1d05da9b26f267f931cf178d4aba455b4c4622dd7355eb80c6640" - -[[package]] -name = "siphasher" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bd3e3206899af3f8b12af284fafc038cc1dc2b41d1b89dd17297221c5d225de" - -[[package]] -name = "slab" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" -dependencies = [ - "autocfg", -] - -[[package]] -name = "smallvec" -version = "1.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" - -[[package]] -name = "socket2" -version = "0.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] - -[[package]] -name = "socket2" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881" -dependencies = [ - "libc", - "windows-sys 0.60.2", -] - -[[package]] -name = "spin" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" - -[[package]] -name = "stable_deref_trait" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" - -[[package]] -name = "standback" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e113fb6f3de07a243d434a56ec6f186dfd51cb08448239fe7bcae73f87ff28ff" -dependencies = [ - "version_check", -] - -[[package]] -name = "stdweb" -version = "0.4.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d022496b16281348b52d0e30ae99e01a73d737b2f45d38fed4edf79f9325a1d5" -dependencies = [ - "discard", - "rustc_version 0.2.3", - "stdweb-derive", - "stdweb-internal-macros", - "stdweb-internal-runtime", - "wasm-bindgen", -] - -[[package]] -name = "stdweb-derive" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c87a60a40fccc84bef0652345bbbbbe20a605bf5d0ce81719fc476f5c03b50ef" -dependencies = [ - "proc-macro2", - "quote", - "serde", - "serde_derive", - "syn 1.0.107", -] - -[[package]] -name = "stdweb-internal-macros" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58fa5ff6ad0d98d1ffa8cb115892b6e69d67799f6763e162a1c9db421dc22e11" -dependencies = [ - "base-x", - "proc-macro2", - "quote", - "serde", - "serde_derive", - "serde_json", - "sha1", - "syn 1.0.107", -] - -[[package]] -name = "stdweb-internal-runtime" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0" - -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "subtle" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d0208408ba0c3df17ed26eb06992cb1a1268d41b2c0e12e65203fbe3972cee5" - -[[package]] -name = "suggestions" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5441c382482e49aaac2c3ea9cbcd24290531246e879ee94af5dfc4b144f11e80" -dependencies = [ - "strsim 0.10.0", -] - -[[package]] -name = "syn" -version = "1.0.107" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f4064b5b16e03ae50984a5a8ed5d4f8803e6bc1fd170a3cda91a1be4b18e3f5" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "2.0.87" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25aa4ce346d03a6dcd68dd8b4010bcb74e54e62c90c573f394c46eae99aba32d" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "sync_wrapper" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7065abeca94b6a8a577f9bd45aa0867a2238b74e8eb67cf10d492bc39351394" - -[[package]] -name = "synstructure" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.107", - "unicode-xid", -] - -[[package]] -name = "synstructure" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "tar" -version = "0.4.41" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb797dad5fb5b76fcf519e702f4a589483b5ef06567f160c392832c1f5e44909" -dependencies = [ - "filetime", - "libc", - "xattr", -] - -[[package]] -name = "tempfile" -version = "3.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" -dependencies = [ - "cfg-if 1.0.0", - "fastrand", - "rustix", - "windows-sys 0.52.0", -] - -[[package]] -name = "termcolor" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "termize" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1706be6b564323ce7092f5f7e6b118a14c8ef7ed0e69c8c5329c914a9f101295" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "thiserror" -version = "1.0.61" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c546c80d6be4bc6a00c0f01730c08df82eaa7a7a61f11d656526506112cc1709" -dependencies = [ - "thiserror-impl 1.0.61", -] - -[[package]] -name = "thiserror" -version = "2.0.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" -dependencies = [ - "thiserror-impl 2.0.17", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.61" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "thread_local" -version = "1.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c" -dependencies = [ - "cfg-if 1.0.0", - "once_cell", -] - -[[package]] -name = "threadpool" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" -dependencies = [ - "num_cpus", -] - -[[package]] -name = "time" -version = "0.2.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4752a97f8eebd6854ff91f1c1824cd6160626ac4bd44287f7f4ea2035a02a242" -dependencies = [ - "const_fn", - "libc", - "standback", - "stdweb", - "time-macros 0.1.1", - "version_check", - "winapi", -] - -[[package]] -name = "time" -version = "0.3.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e7d9e3bb61134e77bde20dd4825b97c010155709965fedf0f49bb138e52a9d" -dependencies = [ - "deranged", - "itoa", - "libc", - "num-conv", - "num_threads", - "powerfmt", - "serde", - "time-core", - "time-macros 0.2.24", -] - -[[package]] -name = "time-core" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40868e7c1d2f0b8d73e4a8c7f0ff63af4f6d19be117e90bd73eb1d62cf831c6b" - -[[package]] -name = "time-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "957e9c6e26f12cb6d0dd7fc776bb67a706312e7299aed74c8dd5b17ebb27e2f1" -dependencies = [ - "proc-macro-hack", - "time-macros-impl", -] - -[[package]] -name = "time-macros" -version = "0.2.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30cfb0125f12d9c277f35663a0a33f8c30190f4e4574868a330595412d34ebf3" -dependencies = [ - "num-conv", - "time-core", -] - -[[package]] -name = "time-macros-impl" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3c141a1b43194f3f56a1411225df8646c55781d5f26db825b3d98507eb482f" -dependencies = [ - "proc-macro-hack", - "proc-macro2", - "quote", - "standback", - "syn 1.0.107", -] - -[[package]] -name = "tinystr" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9117f5d4db391c1cf6927e7bea3db74b9a1c1add8f7eda9ffd5364f40f57b82f" -dependencies = [ - "displaydoc", -] - -[[package]] -name = "tinystr" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" -dependencies = [ - "displaydoc", - "zerovec", -] - -[[package]] -name = "tinytemplate" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "tinyvec" -version = "1.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - -[[package]] -name = "tokio" -version = "1.38.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba4f4a02a7a80d6f274636f0aa95c7e383b912d41fe721a31f29e29698585a4a" -dependencies = [ - "backtrace", - "bytes", - "libc", - "mio", - "num_cpus", - "parking_lot 0.12.3", - "pin-project-lite", - "signal-hook-registry", - "socket2 0.5.7", - "tokio-macros", - "windows-sys 0.48.0", -] - -[[package]] -name = "tokio-macros" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f5ae998a069d4b5aba8ee9dad856af7d520c3699e6159b185c2acd48155d39a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "tokio-rustls" -version = "0.26.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" -dependencies = [ - "rustls", - "rustls-pki-types", - "tokio", -] - -[[package]] -name = "tokio-util" -version = "0.7.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cf6b47b3771c49ac75ad09a6162f53ad4b8088b76ac60e8ec1455b31a189fe1" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "toml" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" -dependencies = [ - "serde", -] - -[[package]] -name = "tower" -version = "0.4.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8fa9be0de6cf49e536ce1851f987bd21a43b771b09473c3549a6c853db37c1c" -dependencies = [ - "futures-core", - "futures-util", - "pin-project", - "pin-project-lite", - "tokio", - "tower-layer", - "tower-service", -] - -[[package]] -name = "tower-layer" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0" - -[[package]] -name = "tower-service" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52" - -[[package]] -name = "tracing" -version = "0.1.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0ecdcb44a79f0fe9844f0c4f33a342cbcbb5117de8001e6ba0dc2351327d09" -dependencies = [ - "cfg-if 1.0.0", - "log", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc6b8ad3567499f98a1db7a752b07a7c8c7c7c34c332ec00effb2b0027974b7c" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.107", -] - -[[package]] -name = "tracing-core" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f54c8ca710e81886d498c2fd3331b56c93aa248d49de2222ad2742247c60072f" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - -[[package]] -name = "type-map" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "deb68604048ff8fa93347f02441e4487594adc20bb8a084f9e564d2b827a0a9f" -dependencies = [ - "rustc-hash 1.1.0", -] - -[[package]] -name = "typenum" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" - -[[package]] -name = "ucd-trie" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e79c4d996edb816c91e4308506774452e55e95c3c9de07b6729e17e15a5ef81" - -[[package]] -name = "unic-char-property" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" -dependencies = [ - "unic-char-range", -] - -[[package]] -name = "unic-char-range" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" - -[[package]] -name = "unic-common" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" - -[[package]] -name = "unic-emoji-char" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b07221e68897210270a38bde4babb655869637af0f69407f96053a34f76494d" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-langid" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23dd9d1e72a73b25e07123a80776aae3e7b0ec461ef94f9151eed6ec88005a44" -dependencies = [ - "unic-langid-impl", - "unic-langid-macros", -] - -[[package]] -name = "unic-langid-impl" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a5422c1f65949306c99240b81de9f3f15929f5a8bfe05bb44b034cc8bf593e5" -dependencies = [ - "tinystr 0.7.6", -] - -[[package]] -name = "unic-langid-macros" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0da1cd2c042d3c7569a1008806b02039e7a4a2bdf8f8e96bd3c792434a0e275e" -dependencies = [ - "proc-macro-hack", - "tinystr 0.7.6", - "unic-langid-impl", - "unic-langid-macros-impl", -] - -[[package]] -name = "unic-langid-macros-impl" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ed7f4237ba393424195053097c1516bd4590dc82b84f2f97c5c69e12704555b" -dependencies = [ - "proc-macro-hack", - "quote", - "syn 2.0.87", - "unic-langid-impl", -] - -[[package]] -name = "unic-ucd-bidi" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1d568b51222484e1f8209ce48caa6b430bf352962b877d592c29ab31fb53d8c" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-category" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b8d4591f5fcfe1bd4453baaf803c40e1b1e69ff8455c47620440b46efef91c0" -dependencies = [ - "matches", - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-version" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" -dependencies = [ - "unic-common", -] - -[[package]] -name = "unicase" -version = "2.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7d2d4dafb69621809a81864c9c1b864479e1235c0dd4e199924b9742439ed89" -dependencies = [ - "version_check", -] - -[[package]] -name = "unicode-casing" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "623f59e6af2a98bdafeb93fa277ac8e1e40440973001ca15cf4ae1541cd16d56" - -[[package]] -name = "unicode-ident" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc" - -[[package]] -name = "unicode-normalization" -version = "0.1.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a56d1686db2308d901306f92a263857ef59ea39678a5458e7cb17f01415101f5" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-width" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" - -[[package]] -name = "unicode-xid" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04" - -[[package]] -name = "unicode_names2" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87d6678d7916394abad0d4b19df4d3802e1fd84abd7d701f39b75ee71b9e8cf1" - -[[package]] -name = "unsafe-libyaml" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" - -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "url" -version = "2.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - -[[package]] -name = "uuid" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a183cf7feeba97b4dd1c0d46788634f6221d87fa961b305bed08c851829efcc0" -dependencies = [ - "getrandom 0.2.15", - "serde", -] - -[[package]] -name = "vergen" -version = "9.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b2bf58be11fc9414104c6d3a2e464163db5ef74b12296bda593cac37b6e4777" -dependencies = [ - "anyhow", - "derive_builder", - "rustc_version 0.4.1", - "rustversion", - "vergen-lib", -] - -[[package]] -name = "vergen-gitcl" -version = "1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9dfc1de6eb2e08a4ddf152f1b179529638bedc0ea95e6d667c014506377aefe" -dependencies = [ - "anyhow", - "derive_builder", - "rustversion", - "time 0.3.44", - "vergen", - "vergen-lib", -] - -[[package]] -name = "vergen-lib" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b07e6010c0f3e59fcb164e0163834597da68d1f864e2b8ca49f74de01e9c166" -dependencies = [ - "anyhow", - "derive_builder", - "rustversion", -] - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "walkdir" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" -dependencies = [ - "same-file", - "winapi-util", -] - -[[package]] -name = "want" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" -dependencies = [ - "try-lock", -] - -[[package]] -name = "wasi" -version = "0.11.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" - -[[package]] -name = "wasip2" -version = "1.0.1+wasi-0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" -dependencies = [ - "wit-bindgen", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da95793dfc411fbbd93f5be7715b0578ec61fe87cb1a42b12eb625caa5c5ea60" -dependencies = [ - "cfg-if 1.0.0", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.42" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76bc14366121efc8dbb487ab05bcc9d346b3b5ec0eaa76e46594cabbe51762c0" -dependencies = [ - "cfg-if 1.0.0", - "js-sys", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04264334509e04a7bf8690f2384ef5265f05143a4bff3889ab7a3269adab59c2" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "420bc339d9f322e562942d52e115d57e950d12d88983a14c79b86859ee6c7ebc" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 2.0.87", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76f218a38c84bcb33c25ec7059b07847d465ce0e0a76b995e134a45adcb6af76" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "wasm-streams" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b65dc4c90b63b118468cf747d8bf3566c1913ef60be765b5730ead9e0a3ba129" -dependencies = [ - "futures-util", - "js-sys", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - -[[package]] -name = "web-sys" -version = "0.3.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "webpki-roots" -version = "0.26.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd7c23921eeb1713a4e851530e9b9756e4fb0e89978582942612524cf09f01cd" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" -dependencies = [ - "winapi", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-core" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" -dependencies = [ - "windows-targets 0.52.5", -] - -[[package]] -name = "windows-link" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-sys" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2" -dependencies = [ - "windows_aarch64_msvc 0.36.1", - "windows_i686_gnu 0.36.1", - "windows_i686_msvc 0.36.1", - "windows_x86_64_gnu 0.36.1", - "windows_x86_64_msvc 0.36.1", -] - -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.5", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets 0.52.5", -] - -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", -] - -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", -] - -[[package]] -name = "windows-targets" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" -dependencies = [ - "windows_aarch64_gnullvm 0.52.5", - "windows_aarch64_msvc 0.52.5", - "windows_i686_gnu 0.52.5", - "windows_i686_gnullvm 0.52.5", - "windows_i686_msvc 0.52.5", - "windows_x86_64_gnu 0.52.5", - "windows_x86_64_gnullvm 0.52.5", - "windows_x86_64_msvc 0.52.5", -] - -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link 0.2.1", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - -[[package]] -name = "windows_i686_gnu" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6" - -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" - -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - -[[package]] -name = "windows_i686_msvc" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024" - -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" - -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.36.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - -[[package]] -name = "winreg" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a277a57398d4bfa075df44f501a17cfdf8542d224f0d36095a2adc7aee4ef0a5" -dependencies = [ - "cfg-if 1.0.0", - "windows-sys 0.48.0", -] - -[[package]] -name = "wit-bindgen" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" - -[[package]] -name = "writeable" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" - -[[package]] -name = "xattr" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da84f1a25939b27f6820d92aed108f83ff920fdf11a7b19366c27c4cda81d4f" -dependencies = [ - "libc", - "linux-raw-sys", - "rustix", -] - -[[package]] -name = "yaml-rust" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" -dependencies = [ - "linked-hash-map", -] - -[[package]] -name = "yansi" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09041cd90cf85f7f8b2df60c646f853b7f535ce68f85244eb6731cf89fa498ec" - -[[package]] -name = "yansi-term" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5c30ade05e61656247b2e334a031dfd0cc466fadef865bdcdea8d537951bf1" -dependencies = [ - "winapi", -] - -[[package]] -name = "yoke" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", - "synstructure 0.13.2", -] - -[[package]] -name = "zerocopy" -version = "0.8.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] - -[[package]] -name = "zerofrom" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", - "synstructure 0.13.2", -] - -[[package]] -name = "zeroize" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ced3678a2879b30306d323f4542626697a464a97c0a07c9aebf7ebca65cd4dde" - -[[package]] -name = "zerotrie" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", -] - -[[package]] -name = "zerovec" -version = "0.11.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.87", -] diff --git a/kclvm/tools/Cargo.toml b/kclvm/tools/Cargo.toml deleted file mode 100644 index 33c767723..000000000 --- a/kclvm/tools/Cargo.toml +++ /dev/null @@ -1,46 +0,0 @@ -[package] -name = "kclvm-tools" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -fancy-regex = "0.7.1" -walkdir = "2" -anyhow = "1.0" -compiler_base_session = "0.1.3" - -rustc_lexer = "0.1.0" -kclvm-ast = { path = "../ast" } -kclvm-error = { path = "../error" } -kclvm-parser = { path = "../parser" } -kclvm-sema = { path = "../sema" } -kclvm-config = { path = "../config" } -kclvm-ast-pretty = { path = "../ast_pretty" } -kclvm-query = { path = "../query" } -kclvm-runner = { path = "../runner" } -kclvm-runtime = { path = "../runtime" } -kclvm-driver = { path = "../driver" } -kclvm-utils = { path = "../utils" } -kclvm-primitives = { path = "../primitives" } - -serde_json = "1.0" -serde_yaml_ng = "0.10.0" -once_cell = "1.15.0" -regex = "1.3" -json-spanned-value = "0.2.2" -compiler_base_span = "0.1.2" -located_yaml = "0.2.1" - -[dev-dependencies] -pretty_assertions = "1.2.1" -criterion = "0.5" -insta = "1.8.0" - -[[bench]] -name = "benchmark" -harness = false - -[features] -llvm = ["kclvm-runner/llvm"] diff --git a/kclvm/tools/benches/proc_macro_crate/Cargo.toml b/kclvm/tools/benches/proc_macro_crate/Cargo.toml deleted file mode 100644 index a112f709b..000000000 --- a/kclvm/tools/benches/proc_macro_crate/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "proc_macro_crate" -version = "0.1.0" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[lib] -proc-macro = true - -[dependencies] -proc-macro2 = "1.0.7" -quote = "1" -syn = { version = "2.0.29", features = ["full","extra-traits"] } diff --git a/kclvm/tools/benches/proc_macro_crate/src/lib.rs b/kclvm/tools/benches/proc_macro_crate/src/lib.rs deleted file mode 100644 index b03050131..000000000 --- a/kclvm/tools/benches/proc_macro_crate/src/lib.rs +++ /dev/null @@ -1,32 +0,0 @@ -use proc_macro::TokenStream; -use quote::quote; -use syn::{parse_macro_input, ItemFn}; - -#[proc_macro_attribute] -pub fn bench_test(_attr: TokenStream, item: TokenStream) -> TokenStream { - let mut input_fn = parse_macro_input!(item as ItemFn); - - let fn_name = &input_fn.sig.ident; - let fn_body = &input_fn.block; - - let timing_code = quote! { - { - let start_time = std::time::Instant::now(); - let result = #fn_body; - let end_time = std::time::Instant::now(); - let time = (end_time - start_time).as_micros(); - println!("{} took {} μs", stringify!(#fn_name), (end_time - start_time).as_micros()); - // 400 ms - assert!(time < 400000, "Bench mark test failed"); - result - } - }; - - input_fn.block = Box::new(syn::parse2(timing_code).unwrap()); - - let output = quote! { - #input_fn - }; - - output.into() -} diff --git a/kclvm/tools/src/LSP/Cargo.toml b/kclvm/tools/src/LSP/Cargo.toml deleted file mode 100644 index 82a625764..000000000 --- a/kclvm/tools/src/LSP/Cargo.toml +++ /dev/null @@ -1,53 +0,0 @@ -[package] -name = "kcl-language-server" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -chrono = "0.4.19" -env_logger = "0.11.2" -ropey = "1.3.2" -tokio-test = "0.4.2" -serde = { version = "1.0", features = ["derive"] } -dashmap = "5.1.0" -log = "0.4.14" -im-rc = "15.0.0" -rustc_lexer = "0.1.0" -clap = { version = "4.3.0", features = ["string"] } -maplit = "1.0.2" -compiler_base_session = "0.1.3" - -kclvm-tools = { path = "../../../tools" } -kclvm-error = { path = "../../../error" } -kclvm-config = { path = "../../../config" } -kclvm-driver = { path = "../../../driver" } -kclvm-parser = { path = "../../../parser" } -kclvm-sema = { path = "../../../sema" } -kclvm-ast = { path = "../../../ast" } -kclvm-utils = { path = "../../../utils" } -kclvm-version = { path = "../../../version" } -kclvm-query = { path = "../../../query" } -kclvm-span = { path = "../../../span" } -kclvm-primitives = { path = "../../../primitives" } - -lsp-server = { version = "0.7.7", default-features = false } -anyhow = { version = "1.0", default-features = false, features = ["std"] } -crossbeam-channel = { version = "0.5.7", default-features = false } -ra_ap_vfs = "0.0.149" -ra_ap_vfs-notify = "0.0.149" -lsp-types = { version = "0.93.0", features = ["proposed"] } -threadpool = { version = "1.8.1", default-features = false } -salsa = { version = "0.16.1", default-features = false } -serde_json = { version = "1.0", default-features = false } -parking_lot = { version = "0.12.0", default-features = false } -rustc-hash = { version = "1.1.0", default-features = false } -proc_macro_crate = { path = "../../benches/proc_macro_crate" } -notify = "7.0.0" - -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] -tokio = { version = "1.37.0", features = ["full"] } - -[dev-dependencies] -insta = "1.8.0" diff --git a/kclvm/tools/src/LSP/src/main.rs b/kclvm/tools/src/LSP/src/main.rs deleted file mode 100644 index 7f26bff06..000000000 --- a/kclvm/tools/src/LSP/src/main.rs +++ /dev/null @@ -1,95 +0,0 @@ -mod analysis; -mod app; -mod capabilities; -mod compile; -mod completion; -mod dispatcher; -mod document_symbol; -mod error; -mod find_refs; -mod formatting; -mod from_lsp; -mod goto_def; -mod hover; -mod inlay_hints; -mod notification; -mod quick_fix; -mod request; -mod semantic_token; -mod signature_help; -mod state; -mod to_lsp; -mod util; -mod word_index; - -#[cfg(test)] -mod tests; - -use app::{app, main_loop}; - -/// Main entry point for the `kcl-language-server` executable. -fn main() -> Result<(), anyhow::Error> { - let args: Vec = std::env::args().collect(); - let matches = app() - .arg_required_else_help(false) - .try_get_matches_from(args); - match matches { - Ok(arg_matches) => match arg_matches.subcommand() { - Some(("version", _)) => { - println!("{}", kclvm_version::get_version_info()); - Ok(()) - } - Some((subcommand, _)) => Err(anyhow::anyhow!("unknown subcommand: {}", subcommand)), - None => { - let status: Result = { - run_server().map_err(|e| anyhow::anyhow!("{}", e))?; - Ok(ExitStatus::Success) - }; - match status.unwrap() { - ExitStatus::Success => {} - ExitStatus::Error => std::process::exit(1), - }; - Ok(()) - } - }, - Err(e) => e.exit(), - } -} - -#[allow(dead_code)] -/// Main entry point for the language server -fn run_server() -> anyhow::Result<()> { - // Setup IO connections - let (connection, io_threads) = lsp_server::Connection::stdio(); - // Wait for a client to connect - let (initialize_id, initialize_params) = connection.initialize_start()?; - - let initialize_params = - util::from_json::("InitializeParams", initialize_params)?; - - let server_capabilities = capabilities::server_capabilities(&initialize_params.capabilities); - - let initialize_result = lsp_types::InitializeResult { - capabilities: server_capabilities, - server_info: Some(lsp_types::ServerInfo { - name: String::from("kcl-language-server"), - version: None, - }), - offset_encoding: None, - }; - - let initialize_result = serde_json::to_value(initialize_result) - .map_err(|_| anyhow::anyhow!("Initialize result error"))?; - - connection.initialize_finish(initialize_id, initialize_result)?; - main_loop(connection, initialize_params)?; - io_threads.join()?; - Ok(()) -} - -#[allow(dead_code)] -#[derive(Copy, Debug, Clone, PartialEq, Eq)] -enum ExitStatus { - Success, - Error, -} diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_with_line_test/dep-with-line/kcl.mod.lock b/kclvm/tools/src/LSP/src/test_data/goto_def_with_line_test/dep-with-line/kcl.mod.lock deleted file mode 100644 index e69de29bb..000000000 diff --git a/kclvm/tools/src/LSP/src/test_data/goto_def_with_line_test/main_pkg/kcl.mod.lock b/kclvm/tools/src/LSP/src/test_data/goto_def_with_line_test/main_pkg/kcl.mod.lock deleted file mode 100644 index 8165e52f9..000000000 --- a/kclvm/tools/src/LSP/src/test_data/goto_def_with_line_test/main_pkg/kcl.mod.lock +++ /dev/null @@ -1,5 +0,0 @@ -[dependencies] - [dependencies.dep-with-line] - name = "dep-with-line" - full_name = "dep-with-line_0.0.1" - version = "0.0.1" diff --git a/kclvm/tools/src/LSP/src/test_data/goto_import_def_test/kcl.mod.lock b/kclvm/tools/src/LSP/src/test_data/goto_import_def_test/kcl.mod.lock deleted file mode 100644 index cb15ef06f..000000000 --- a/kclvm/tools/src/LSP/src/test_data/goto_import_def_test/kcl.mod.lock +++ /dev/null @@ -1,6 +0,0 @@ -[dependencies] - [dependencies.konfig] - name = "konfig" - full_name = "_" - url = "https://github.com/awesome-kusion/konfig.git" - git_tag = "v0.0.1" diff --git a/kclvm/tools/src/LSP/src/tests.rs b/kclvm/tools/src/LSP/src/tests.rs deleted file mode 100644 index 16992485e..000000000 --- a/kclvm/tools/src/LSP/src/tests.rs +++ /dev/null @@ -1,2692 +0,0 @@ -use crossbeam_channel::after; -use crossbeam_channel::select; -use kclvm_driver::lookup_compile_workspace; -use kclvm_driver::toolchain; -use kclvm_driver::toolchain::Metadata; -use kclvm_driver::WorkSpaceKind; -use kclvm_primitives::IndexMap; -use kclvm_primitives::IndexSet; -use kclvm_sema::core::global_state::GlobalState; -use kclvm_sema::ty::SchemaType; -use kclvm_utils::path::PathPrefix; - -use kclvm_sema::resolver::scope::KCLScopeCache; -use lsp_server::RequestId; -use lsp_server::Response; -use lsp_types::notification::Exit; -use lsp_types::request::GotoTypeDefinitionResponse; -use lsp_types::CompletionContext; -use lsp_types::CompletionItem; -use lsp_types::CompletionItemKind; -use lsp_types::CompletionParams; -use lsp_types::CompletionResponse; -use lsp_types::CompletionTriggerKind; -use lsp_types::DocumentFormattingParams; -use lsp_types::DocumentSymbolParams; -use lsp_types::GotoDefinitionParams; -use lsp_types::GotoDefinitionResponse; -use lsp_types::Hover; -use lsp_types::HoverContents; -use lsp_types::HoverParams; -use lsp_types::InitializeParams; -use lsp_types::MarkedString; -use lsp_types::PartialResultParams; -use lsp_types::PublishDiagnosticsParams; -use lsp_types::ReferenceContext; -use lsp_types::ReferenceParams; -use lsp_types::RenameParams; -use lsp_types::SemanticTokensParams; -use lsp_types::TextDocumentIdentifier; -use lsp_types::TextDocumentItem; -use lsp_types::TextDocumentPositionParams; -use lsp_types::TextEdit; -use lsp_types::Url; -use lsp_types::WorkDoneProgressParams; -use lsp_types::WorkspaceEdit; -use lsp_types::WorkspaceFolder; - -use parking_lot::lock_api::RwLock; -use serde::Serialize; -use std::cell::Cell; -use std::cell::RefCell; -use std::collections::HashMap; -use std::collections::HashSet; -use std::env; -use std::path::Path; -use std::path::PathBuf; -use std::process::Command; - -use std::sync::Arc; -use std::thread; -use std::time::Duration; - -use kclvm_ast::ast::Program; -use kclvm_error::Diagnostic as KCLDiagnostic; -use kclvm_error::Position as KCLPos; -use kclvm_parser::KCLModuleCache; - -use lsp_types::Diagnostic; -use lsp_types::DiagnosticRelatedInformation; -use lsp_types::DiagnosticSeverity; -use lsp_types::Location; -use lsp_types::NumberOrString; -use lsp_types::{Position, Range, TextDocumentContentChangeEvent}; - -use proc_macro_crate::bench_test; - -use lsp_server::{Connection, Message, Notification, Request}; - -use crate::compile::compile_with_params; -use crate::completion::completion; -use crate::from_lsp::file_path_from_url; - -use crate::app::main_loop; -use crate::compile::Params; -use crate::goto_def::goto_def; -use crate::hover::hover; -use crate::state::KCLGlobalStateCache; -use crate::state::KCLVfs; -use crate::to_lsp::kcl_diag_to_lsp_diags_by_file; -use crate::util::apply_document_changes; -use crate::util::to_json; - -macro_rules! wait_async { - () => { - thread::sleep(Duration::from_millis(100)); - }; - ($time_ms:expr) => { - thread::sleep(Duration::from_millis($time_ms)); - }; -} - -pub(crate) fn compare_goto_res( - res: Option, - pos: (&String, u32, u32, u32, u32), -) { - match res.unwrap() { - lsp_types::GotoDefinitionResponse::Scalar(loc) => { - let got_path = file_path_from_url(&loc.uri).unwrap(); - assert_eq!( - got_path.adjust_canonicalization(), - pos.0.to_string().adjust_canonicalization() - ); - - let (got_start, got_end) = (loc.range.start, loc.range.end); - - let expected_start = Position { - line: pos.1, // zero-based - character: pos.2, - }; - - let expected_end = Position { - line: pos.3, // zero-based - character: pos.4, - }; - assert_eq!(got_start, expected_start); - assert_eq!(got_end, expected_end); - } - _ => { - unreachable!("test error") - } - } -} - -pub(crate) fn compile_test_file( - testfile: &str, -) -> ( - String, - Program, - IndexSet, - GlobalState, - IndexMap>, -) { - let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let file = path - .join(testfile) - .canonicalize() - .unwrap() - .display() - .to_string() - .adjust_canonicalization(); - - let (diags, compile_res) = compile_with_params(Params { - file: Some(file.clone()), - module_cache: Some(KCLModuleCache::default()), - scope_cache: Some(KCLScopeCache::default()), - vfs: Some(KCLVfs::default()), - gs_cache: Some(KCLGlobalStateCache::default()), - }); - let (program, schema_map, gs) = compile_res.unwrap(); - (file, program, diags, gs, schema_map) -} - -pub(crate) fn compile_test_file_and_metadata( - testfile: &str, -) -> ( - String, - Program, - IndexSet, - GlobalState, - Option, - IndexMap>, -) { - let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - - let file = path - .join(testfile) - .canonicalize() - .unwrap() - .display() - .to_string() - .adjust_canonicalization(); - - let metadata = lookup_compile_workspace(&toolchain::default(), &file, true).2; - let (diags, compile_res) = compile_with_params(Params { - file: Some(file.clone()), - module_cache: Some(KCLModuleCache::default()), - scope_cache: Some(KCLScopeCache::default()), - vfs: Some(KCLVfs::default()), - gs_cache: Some(KCLGlobalStateCache::default()), - }); - let (program, schema_map, gs) = compile_res.unwrap(); - - (file, program, diags, gs, metadata, schema_map) -} - -type Info = (String, (u32, u32, u32, u32), String); - -fn build_lsp_diag( - pos: (u32, u32, u32, u32), - message: String, - severity: Option, - related_info: Vec, - code: Option, - data: Option, -) -> Diagnostic { - let related_information = if related_info.is_empty() { - None - } else { - Some( - related_info - .iter() - .map(|(file, pos, msg)| DiagnosticRelatedInformation { - location: Location { - uri: Url::from_file_path(file).unwrap(), - range: Range { - start: Position { - line: pos.0, - character: pos.1, - }, - end: Position { - line: pos.2, - character: pos.3, - }, - }, - }, - message: msg.clone(), - }) - .collect(), - ) - }; - Diagnostic { - range: lsp_types::Range { - start: Position { - line: pos.0, - character: pos.1, - }, - end: Position { - line: pos.2, - character: pos.3, - }, - }, - severity, - code, - code_description: None, - source: None, - message, - related_information, - tags: None, - data, - } -} - -fn build_expect_diags() -> Vec { - let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let mut test_file = path.clone(); - test_file.push("src/test_data/diagnostics/diagnostics.k"); - let file = test_file.to_str().unwrap(); - let expected_diags: Vec = vec![ - build_lsp_diag( - (1, 4, 2, 0), - "expected one of [\"identifier\", \"literal\", \"(\", \"[\", \"{\"] got newline" - .to_string(), - Some(DiagnosticSeverity::ERROR), - vec![], - Some(NumberOrString::String("InvalidSyntax".to_string())), - None, - ), - build_lsp_diag( - (0, 0, 0, 10), - "pkgpath abc not found in the program".to_string(), - Some(DiagnosticSeverity::ERROR), - vec![], - Some(NumberOrString::String("CannotFindModule".to_string())), - None, - ), - build_lsp_diag( - (0, 0, 0, 10), - format!( - "Cannot find the module abc from {}/src/test_data/diagnostics/abc", - path.to_str().unwrap() - ), - Some(DiagnosticSeverity::ERROR), - vec![], - Some(NumberOrString::String("CannotFindModule".to_string())), - None, - ), - build_lsp_diag( - (8, 0, 8, 1), - "Can not change the value of 'd', because it was declared immutable".to_string(), - Some(DiagnosticSeverity::ERROR), - vec![( - file.to_string(), - (7, 0, 7, 1), - "The variable 'd' is declared here".to_string(), - )], - Some(NumberOrString::String("ImmutableError".to_string())), - None, - ), - build_lsp_diag( - (7, 0, 7, 1), - "The variable 'd' is declared here".to_string(), - Some(DiagnosticSeverity::ERROR), - vec![( - file.to_string(), - (8, 0, 8, 1), - "Can not change the value of 'd', because it was declared immutable".to_string(), - )], - Some(NumberOrString::String("ImmutableError".to_string())), - None, - ), - build_lsp_diag( - (2, 0, 2, 1), - "expected str, got int(1)".to_string(), - Some(DiagnosticSeverity::ERROR), - vec![], - Some(NumberOrString::String("TypeError".to_string())), - None, - ), - build_lsp_diag( - (10, 8, 10, 10), - "name 'nu' is not defined, did you mean '[\"number\"]'?".to_string(), - Some(DiagnosticSeverity::ERROR), - vec![], - Some(NumberOrString::String("CompileError".to_string())), - Some(serde_json::json!({ "suggested_replacement": ["number"] })), - ), - build_lsp_diag( - (0, 0, 0, 10), - "Module 'abc' imported but unused".to_string(), - Some(DiagnosticSeverity::WARNING), - vec![], - Some(NumberOrString::String("UnusedImportWarning".to_string())), - None, - ), - ]; - expected_diags -} - -#[test] -#[bench_test] -fn diagnostics_test() { - let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let mut test_file = path.clone(); - test_file.push("src/test_data/diagnostics/diagnostics.k"); - let file = test_file.to_str().unwrap(); - - let diags = compile_with_params(Params { - file: Some(file.to_string()), - module_cache: None, - scope_cache: None, - vfs: Some(KCLVfs::default()), - gs_cache: Some(KCLGlobalStateCache::default()), - }) - .0; - - let diagnostics = diags - .iter() - .flat_map(|diag| kcl_diag_to_lsp_diags_by_file(diag, file)) - .collect::>(); - - let expected_diags: Vec = build_expect_diags(); - - for (get, expected) in diagnostics.iter().zip(expected_diags.iter()) { - assert_eq!(get, expected) - } -} - -#[test] -#[bench_test] -fn test_apply_document_changes() { - macro_rules! change { - [$($sl:expr, $sc:expr; $el:expr, $ec:expr => $text:expr),+] => { - vec![$(TextDocumentContentChangeEvent { - range: Some(Range { - start: Position { line: $sl, character: $sc }, - end: Position { line: $el, character: $ec }, - }), - range_length: None, - text: String::from($text), - }),+] - }; - } - - let mut text = String::new(); - apply_document_changes(&mut text, vec![]); - assert_eq!(text, ""); - - // Test if full updates work (without a range) - apply_document_changes( - &mut text, - vec![TextDocumentContentChangeEvent { - range: None, - range_length: None, - text: String::from("the"), - }], - ); - - assert_eq!(text, "the"); - apply_document_changes(&mut text, change![0, 3; 0, 3 => " quick"]); - assert_eq!(text, "the quick"); - - apply_document_changes(&mut text, change![0, 0; 0, 4 => "", 0, 5; 0, 5 => " foxes"]); - assert_eq!(text, "quick foxes"); - - apply_document_changes(&mut text, change![0, 11; 0, 11 => "\ndream"]); - assert_eq!(text, "quick foxes\ndream"); - - apply_document_changes(&mut text, change![1, 0; 1, 0 => "have "]); - assert_eq!(text, "quick foxes\nhave dream"); - - apply_document_changes( - &mut text, - change![0, 0; 0, 0 => "the ", 1, 4; 1, 4 => " quiet", 1, 16; 1, 16 => "s\n"], - ); - assert_eq!(text, "the quick foxes\nhave quiet dreams\n"); - - apply_document_changes( - &mut text, - change![0, 15; 0, 15 => "\n", 2, 17; 2, 17 => "\n"], - ); - assert_eq!(text, "the quick foxes\n\nhave quiet dreams\n\n"); - - apply_document_changes( - &mut text, - change![1, 0; 1, 0 => "DREAM", 2, 0; 2, 0 => "they ", 3, 0; 3, 0 => "DON'T THEY?"], - ); - assert_eq!( - text, - "the quick foxes\nDREAM\nthey have quiet dreams\nDON'T THEY?\n" - ); - - apply_document_changes(&mut text, change![0, 10; 1, 5 => "", 2, 0; 2, 12 => ""]); - assert_eq!(text, "the quick \nthey have quiet dreams\n"); - - text = String::from("❤️"); - apply_document_changes(&mut text, change![0, 0; 0, 0 => "a"]); - assert_eq!(text, "a❤️"); - - // todo: Non-ASCII char - // text = String::from("a\nb"); - // apply_document_changes(&mut text, change![0, 1; 1, 0 => "\nțc", 0, 1; 1, 1 => "d"]); - // assert_eq!(text, "adcb"); - - // text = String::from("a\nb"); - // apply_document_changes(&mut text, change![0, 1; 1, 0 => "ț\nc", 0, 2; 0, 2 => "c"]); - // assert_eq!(text, "ațc\ncb"); -} - -#[test] -#[bench_test] -fn file_path_from_url_test() { - if cfg!(windows) { - let url = - Url::parse("file:///c%3A/Users/abc/Desktop/%E4%B8%AD%E6%96%87/ab%20c/abc.k").unwrap(); - let path = file_path_from_url(&url).unwrap(); - assert_eq!(path, "C:\\Users\\abc\\Desktop\\中文\\ab c\\abc.k"); - } else { - let url = Url::parse("file:///Users/abc/Desktop/%E4%B8%AD%E6%96%87/ab%20c/abc.k").unwrap(); - let path = file_path_from_url(&url).unwrap(); - assert_eq!(path, "/Users/abc/Desktop/中文/ab c/abc.k"); - } -} - -#[test] -fn test_lsp_with_kcl_mod_in_order() { - goto_import_external_file_test(); - println!("goto_import_external_file_test PASS"); - goto_import_pkg_with_line_test(); - println!("goto_import_pkg_with_line_test PASS"); - complete_import_external_file_test(); - println!("complete_import_external_file_test PASS"); -} - -fn goto_import_pkg_with_line_test() { - let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let (file, _program, _, gs, _) = - compile_test_file("src/test_data/goto_def_with_line_test/main_pkg/main.k"); - let pos = KCLPos { - filename: file.adjust_canonicalization(), - line: 1, - column: Some(27), - }; - - let res = goto_def(&pos, &gs); - - match res.unwrap() { - lsp_types::GotoDefinitionResponse::Scalar(loc) => { - let got_path = file_path_from_url(&loc.uri).unwrap(); - let expected_path = path - .join("src/test_data/goto_def_with_line_test/dep-with-line/main.k") - .canonicalize() - .unwrap() - .display() - .to_string() - .adjust_canonicalization(); - assert_eq!(got_path, expected_path) - } - _ => { - unreachable!("test error") - } - } -} - -fn complete_import_external_file_test() { - let path = PathBuf::from(".") - .join("src") - .join("test_data") - .join("completion_test") - .join("import") - .join("external") - .join("external_0") - .join("main.k") - .canonicalize() - .unwrap() - .display() - .to_string(); - - let _ = Command::new("kcl") - .arg("mod") - .arg("metadata") - .arg("--update") - .current_dir( - PathBuf::from(".") - .join("src") - .join("test_data") - .join("completion_test") - .join("import") - .join("external") - .join("external_0") - .canonicalize() - .unwrap() - .display() - .to_string(), - ) - .output() - .unwrap(); - - let (program, schema_map, gs) = compile_with_params(Params { - file: Some(path.to_string()), - module_cache: None, - scope_cache: None, - vfs: Some(KCLVfs::default()), - gs_cache: Some(KCLGlobalStateCache::default()), - }) - .1 - .unwrap(); - - let pos = KCLPos { - filename: path.to_string().adjust_canonicalization(), - line: 1, - column: Some(11), - }; - let tool = toolchain::default(); - let res = completion(Some('.'), &program, &pos, &gs, &tool, None, &schema_map).unwrap(); - - let got_labels: Vec = match &res { - CompletionResponse::Array(arr) => arr.iter().map(|item| item.label.clone()).collect(), - CompletionResponse::List(_) => panic!("test failed"), - }; - let expected_labels: Vec<&str> = vec![ - "api", - "apiextensions_apiserver", - "apimachinery", - "kube_aggregator", - "vendor", - ]; - assert_eq!(got_labels, expected_labels); -} - -fn goto_import_external_file_test() { - let path = PathBuf::from(".") - .join("src") - .join("test_data") - .join("goto_import_def_test") - .join("main.k") - .canonicalize() - .unwrap() - .display() - .to_string(); - - let _ = Command::new("kcl") - .arg("mod") - .arg("metadata") - .arg("--update") - .current_dir( - PathBuf::from(".") - .join("src") - .join("test_data") - .join("goto_import_def_test") - .canonicalize() - .unwrap() - .display() - .to_string(), - ) - .output() - .unwrap(); - - let (diags, compile_res) = compile_with_params(Params { - file: Some(path.to_string()), - module_cache: None, - scope_cache: None, - vfs: Some(KCLVfs::default()), - gs_cache: Some(KCLGlobalStateCache::default()), - }); - let gs = compile_res.unwrap().2; - - assert_eq!(diags.len(), 0); - - // test goto import file: import .pkg.schema_def - let pos = KCLPos { - filename: path.to_string().adjust_canonicalization(), - line: 1, - column: Some(57), - }; - let res = goto_def(&pos, &gs); - assert!(res.is_some()); -} - -// LSP e2e test - -/// A `Project` represents a project that a language server can work with. Call the [`server`] -/// method to instantiate a language server that will serve information about the project. -pub struct Project {} - -impl Project { - /// Instantiates a language server for this project. - pub fn server(self, initialize_params: InitializeParams) -> Server { - Server::new(initialize_params) - } -} - -/// An object that runs the language server main loop and enables sending and receiving messages -/// to and from it. -pub struct Server { - next_request_id: Cell, - worker: Option>, - client: Connection, - messages: RefCell>, -} - -impl Server { - /// Constructs and initializes a new `Server` - pub fn new(initialize_params: InitializeParams) -> Self { - let (connection, client) = Connection::memory(); - - let worker = std::thread::spawn(move || { - main_loop(connection, initialize_params).unwrap(); - }); - - Self { - next_request_id: Cell::new(1), - worker: Some(worker), - client, - messages: RefCell::new(Vec::new()), - } - } - - /// Sends a request to the language server, returning the response - pub fn send_request(&self, params: R::Params) { - let id = self.next_request_id.get(); - self.next_request_id.set(id.wrapping_add(1)); - let r = Request::new(id.into(), R::METHOD.to_string(), params); - self.client.sender.send(r.into()).unwrap(); - } - - /// Sends an LSP notification to the main loop. - pub(crate) fn notification(&self, params: N::Params) - where - N::Params: Serialize, - { - let r = Notification::new(N::METHOD.to_string(), params); - self.send_notification(r); - } - - /// Sends a server notification to the main loop - fn send_notification(&self, not: Notification) { - self.client.sender.send(Message::Notification(not)).unwrap(); - wait_async!(); - } - - /// A function to wait for a specific message to arrive - fn wait_for_message_cond(&self, n: usize, cond: &dyn Fn(&Message) -> bool) { - let mut total = 0; - for msg in self.messages.borrow().iter() { - if cond(msg) { - total += 1 - } - } - while total < n { - let msg = self.recv().expect("no response"); - if cond(&msg) { - total += 1; - } - } - } - - /// Receives a message from the message or timeout. - pub(crate) fn recv(&self) -> Option { - let timeout = Duration::from_secs(5); - let msg = select! { - recv(self.client.receiver) -> msg => msg.ok(), - recv(after(timeout)) -> _ => panic!("timed out"), - }; - if let Some(ref msg) = msg { - self.messages.borrow_mut().push(msg.clone()); - } - msg - } - - /// Receives a message from the message, if timeout, return None. - pub(crate) fn recv_without_timeout(&self) -> Option { - let timeout = Duration::from_secs(5); - let msg = select! { - recv(self.client.receiver) -> msg => msg.ok(), - recv(after(timeout)) -> _ => return None, - }; - if let Some(ref msg) = msg { - self.messages.borrow_mut().push(msg.clone()); - } - msg - } - - /// Sends a request to the main loop and receives its response - fn send_and_receive(&self, r: Request) -> Response { - let id = r.id.clone(); - self.client.sender.send(r.into()).unwrap(); - while let Some(msg) = self.recv() { - match msg { - Message::Request(req) => { - panic!("did not expect a request as a response to a request: {req:?}") - } - Message::Notification(_) => (), - Message::Response(res) => { - assert_eq!(res.id, id); - return res; - } - } - } - panic!("did not receive a response to our request"); - } - - fn receive_response(&self, id: RequestId) -> Option { - while let Some(msg) = self.recv_without_timeout() { - match msg { - Message::Request(req) => { - panic!("did not expect a request as a response to a request: {req:?}") - } - Message::Notification(_) => (), - Message::Response(res) => { - if res.id == id { - return Some(res); - } - } - } - } - None - } -} - -impl Drop for Server { - fn drop(&mut self) { - // Send the proper shutdown sequence to ensure the main loop terminates properly - self.notification::(()); - - // Cancel the main_loop - if let Some(worker) = self.worker.take() { - worker.join().unwrap(); - } - } -} - -#[test] -fn notification_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let mut path = root.clone(); - - path.push("src/test_data/diagnostics/diagnostics.k"); - - let path = path.to_str().unwrap(); - let src = std::fs::read_to_string(path).unwrap(); - let server = Project {}.server(InitializeParams::default()); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: Url::from_file_path(path).unwrap(), - language_id: "KCL".to_string(), - version: 0, - text: src, - }, - }, - ); - - // Wait for first "textDocument/publishDiagnostics" notification - server.wait_for_message_cond(1, &|msg: &Message| match msg { - Message::Notification(not) => not.method == "textDocument/publishDiagnostics", - _ => false, - }); - - let msgs = server.messages.borrow(); - for msg in msgs.iter() { - match msg { - Message::Notification(not) => { - if let Some(uri) = not.params.get("uri") { - if uri.clone() == to_json(Url::from_file_path(path).unwrap()).unwrap() { - assert_eq!( - not.params, - to_json(PublishDiagnosticsParams { - uri: Url::from_file_path(path).unwrap(), - diagnostics: build_expect_diags(), - version: None, - }) - .unwrap() - ); - break; - } - } - } - _ => {} - } - } -} - -#[test] -fn close_file_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let mut path = root.clone(); - - path.push("src/test_data/diagnostics/diagnostics.k"); - - let path = path.to_str().unwrap(); - let src = std::fs::read_to_string(path).unwrap(); - let server = Project {}.server(InitializeParams::default()); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: Url::from_file_path(path).unwrap(), - language_id: "KCL".to_string(), - version: 0, - text: src.clone(), - }, - }, - ); - - // Mock close file - server.notification::( - lsp_types::DidCloseTextDocumentParams { - text_document: TextDocumentIdentifier { - uri: Url::from_file_path(path).unwrap(), - }, - }, - ); - - // Mock reopen file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: Url::from_file_path(path).unwrap(), - language_id: "KCL".to_string(), - version: 0, - text: src, - }, - }, - ); -} - -#[test] -fn non_kcl_file_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - - let server = Project {}.server(InitializeParams::default()); - let mut path = root.clone(); - path.push("src/test_data/diagnostics.kcl"); - - // Mock open a Non-KCL file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: Url::from_file_path(path.clone()).unwrap(), - language_id: "KCL".to_string(), - version: 0, - text: "".to_string(), - }, - }, - ); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - let r: Request = Request::new( - id.into(), - "textDocument/documentSymbol".to_string(), - DocumentSymbolParams { - text_document: TextDocumentIdentifier { - uri: Url::from_file_path(path).unwrap(), - }, - work_done_progress_params: Default::default(), - partial_result_params: Default::default(), - }, - ); - - // Send request and wait for it's response - let res = server.send_and_receive(r); - assert!(res.result.is_some()); -} - -#[test] -fn cancel_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let mut path = root.clone(); - - path.push("src/test_data/goto_def_test/goto_def.k"); - - let path = path.to_str().unwrap(); - let src = std::fs::read_to_string(path).unwrap(); - let server = Project {}.server(InitializeParams::default()); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: Url::from_file_path(path).unwrap(), - language_id: "KCL".to_string(), - version: 0, - text: src, - }, - }, - ); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - // send request - server.send_request::(GotoDefinitionParams { - text_document_position_params: TextDocumentPositionParams { - text_document: TextDocumentIdentifier { - uri: Url::from_file_path(path).unwrap(), - }, - position: Position::new(23, 9), - }, - work_done_progress_params: Default::default(), - partial_result_params: Default::default(), - }); - - // cancel request - server.notification::(lsp_types::CancelParams { - id: NumberOrString::Number(id), - }); - - assert!(server.receive_response(id.into()).is_none()); -} - -#[test] -fn goto_def_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.clone(); - let path = path - .join("src") - .join("test_data") - .join("goto_def_test") - .join("goto_def.k"); - - let path = path.to_str().unwrap(); - let src = std::fs::read_to_string(path).unwrap(); - let server = Project {}.server(InitializeParams::default()); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: Url::from_file_path(path).unwrap(), - language_id: "KCL".to_string(), - version: 0, - text: src, - }, - }, - ); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - let r: Request = Request::new( - id.into(), - "textDocument/definition".to_string(), - GotoDefinitionParams { - text_document_position_params: TextDocumentPositionParams { - text_document: TextDocumentIdentifier { - uri: Url::from_file_path(path).unwrap(), - }, - position: Position::new(23, 9), - }, - work_done_progress_params: Default::default(), - partial_result_params: Default::default(), - }, - ); - - // Send request and wait for it's response - let res = server.send_and_receive(r); - - assert_eq!( - res.result.unwrap(), - to_json(GotoDefinitionResponse::Scalar(Location { - uri: Url::from_file_path(path).unwrap(), - range: Range { - start: Position::new(20, 7), - end: Position::new(20, 13), - }, - })) - .unwrap() - ); -} - -#[test] -fn complete_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.clone(); - let path = path - .join("src") - .join("test_data") - .join("completion_test") - .join("dot") - .join("completion") - .join("completion.k"); - - let path = path.to_str().unwrap(); - let src = std::fs::read_to_string(path).unwrap(); - let server = Project {}.server(InitializeParams::default()); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: Url::from_file_path(path).unwrap(), - language_id: "KCL".to_string(), - version: 0, - text: src, - }, - }, - ); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - let r: Request = Request::new( - id.into(), - "textDocument/completion".to_string(), - CompletionParams { - text_document_position: TextDocumentPositionParams { - text_document: TextDocumentIdentifier { - uri: Url::from_file_path(path).unwrap(), - }, - position: Position::new(11, 7), - }, - work_done_progress_params: Default::default(), - partial_result_params: Default::default(), - context: Some(CompletionContext { - trigger_kind: CompletionTriggerKind::TRIGGER_CHARACTER, - trigger_character: Some(".".to_string()), - }), - }, - ); - - // Send request and wait for it's response - let res = server.send_and_receive(r); - - assert_eq!( - res.result.unwrap(), - to_json(CompletionResponse::Array(vec![ - CompletionItem { - label: "name".to_string(), - kind: Some(CompletionItemKind::FIELD), - detail: Some("name: str".to_string()), - ..Default::default() - }, - CompletionItem { - label: "age".to_string(), - kind: Some(CompletionItemKind::FIELD), - detail: Some("age: int".to_string()), - ..Default::default() - } - ])) - .unwrap() - ) -} - -#[test] -fn complete_with_version_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root.clone(); - let path = path - .join("src") - .join("test_data") - .join("completion_test") - .join("newline") - .join("newline_with_version") - .join("newline_with_version.k"); - let path = path.to_str().unwrap(); - let src = std::fs::read_to_string(path).unwrap(); - let server = Project {}.server(InitializeParams::default()); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: Url::from_file_path(path).unwrap(), - language_id: "KCL".to_string(), - version: 0, - text: src, - }, - }, - ); - - server.notification::( - lsp_types::DidChangeTextDocumentParams { - text_document: lsp_types::VersionedTextDocumentIdentifier { - uri: Url::from_file_path(path).unwrap(), - version: 1, - }, - content_changes: vec![TextDocumentContentChangeEvent { - range: None, - range_length: None, - text: "schema Name:\n name: str\n\nname1 = \"\"\n\nname: Name{\n \n}" - .to_string(), - }], - }, - ); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - let r: Request = Request::new( - id.into(), - "textDocument/completion".to_string(), - CompletionParams { - text_document_position: TextDocumentPositionParams { - text_document: TextDocumentIdentifier { - uri: Url::from_file_path(path).unwrap(), - }, - position: Position::new(6, 4), - }, - work_done_progress_params: Default::default(), - partial_result_params: Default::default(), - context: Some(CompletionContext { - trigger_kind: CompletionTriggerKind::TRIGGER_CHARACTER, - trigger_character: Some("\n".to_string()), - }), - }, - ); - - let id = r.id.clone(); - server.client.sender.send(r.into()).unwrap(); - - while let Some(msg) = server.recv() { - match msg { - Message::Request(req) => { - panic!("did not expect a request as a response to a request: {req:?}") - } - Message::Notification(_) => (), - Message::Response(res) => { - assert_eq!(res.id, id); - assert_eq!( - res.result.unwrap(), - to_json(CompletionResponse::Array(vec![CompletionItem { - label: "name".to_string(), - kind: Some(CompletionItemKind::FIELD), - detail: Some("name: str".to_string()), - ..Default::default() - },])) - .unwrap() - ); - break; - } - } - } -} - -#[test] -fn hover_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let path = root - .join("src") - .join("test_data") - .join("hover_test") - .join("hover.k"); - let path = path.to_str().unwrap(); - - let src = std::fs::read_to_string(path).unwrap(); - let server = Project {}.server(InitializeParams::default()); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: Url::from_file_path(path).unwrap(), - language_id: "KCL".to_string(), - version: 0, - text: src, - }, - }, - ); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - let r: Request = Request::new( - id.into(), - "textDocument/hover".to_string(), - HoverParams { - text_document_position_params: TextDocumentPositionParams { - text_document: TextDocumentIdentifier { - uri: Url::from_file_path(path).unwrap(), - }, - position: Position::new(15, 7), - }, - work_done_progress_params: Default::default(), - }, - ); - - // Send request and wait for it's response - let res = server.send_and_receive(r); - - assert_eq!( - res.result.unwrap(), - to_json(Hover { - contents: HoverContents::Array(vec![ - MarkedString::String("__main__".to_string()), - MarkedString::LanguageString(lsp_types::LanguageString { - language: "KCL".to_string(), - value: "schema Person:\n name: str\n age?: int".to_string() - }), - MarkedString::String("hover doc test".to_string()), - ]), - range: None - }) - .unwrap() - ) -} - -#[test] -fn hover_assign_in_lambda_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let mut path = root.clone(); - - path.push("src/test_data/hover_test/assign_in_lambda.k"); - - let path = path.to_str().unwrap(); - let src = std::fs::read_to_string(path).unwrap(); - let server = Project {}.server(InitializeParams::default()); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: Url::from_file_path(path).unwrap(), - language_id: "KCL".to_string(), - version: 0, - text: src, - }, - }, - ); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - let r: Request = Request::new( - id.into(), - "textDocument/hover".to_string(), - HoverParams { - text_document_position_params: TextDocumentPositionParams { - text_document: TextDocumentIdentifier { - uri: Url::from_file_path(path).unwrap(), - }, - position: Position::new(4, 7), - }, - work_done_progress_params: Default::default(), - }, - ); - - // Send request and wait for it's response - let res = server.send_and_receive(r); - - assert_eq!( - res.result.unwrap(), - to_json(Hover { - contents: HoverContents::Scalar(MarkedString::LanguageString( - lsp_types::LanguageString { - language: "KCL".to_string(), - value: "images: [str]".to_string() - } - )), - range: None - }) - .unwrap() - ) -} - -#[test] -fn formatting_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let mut path = root.clone(); - - path.push("src/test_data/format/format_range.k"); - - let path = path.to_str().unwrap(); - let src = std::fs::read_to_string(path).unwrap(); - let server = Project {}.server(InitializeParams::default()); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: Url::from_file_path(path).unwrap(), - language_id: "KCL".to_string(), - version: 0, - text: src, - }, - }, - ); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - let r: Request = Request::new( - id.into(), - "textDocument/formatting".to_string(), - DocumentFormattingParams { - text_document: TextDocumentIdentifier { - uri: Url::from_file_path(path).unwrap(), - }, - options: Default::default(), - work_done_progress_params: Default::default(), - }, - ); - - // Send request and wait for it's response - let res = server.send_and_receive(r); - - assert_eq!( - res.result.unwrap(), - to_json(Some(vec![TextEdit { - range: Range::new( - Position::new(0, 0), - Position::new(i32::MAX as u32, i32::MAX as u32), - ), - new_text: "a = 1\n\nb = 2\n\nc = 3\n\nd = 4\n".to_string() - }])) - .unwrap() - ) -} - -#[test] -fn formatting_unsaved_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - let mut path = root.clone(); - - path.push("src/test_data/format/format_range.k"); - - let path = path.to_str().unwrap(); - let src = std::fs::read_to_string(path).unwrap(); - let server = Project {}.server(InitializeParams::default()); - - let uri = Url::from_file_path(path).unwrap(); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: uri.clone(), - language_id: "KCL".to_string(), - version: 0, - text: src, - }, - }, - ); - - // Mock edit file - server.notification::( - lsp_types::DidChangeTextDocumentParams { - text_document: lsp_types::VersionedTextDocumentIdentifier { - uri: uri.clone(), - version: 1, - }, - content_changes: vec![lsp_types::TextDocumentContentChangeEvent { - range: Some(lsp_types::Range::new( - lsp_types::Position::new(0, 0), - lsp_types::Position::new(0, 0), - )), - range_length: Some(0), - text: String::from("unsaved = 0\n"), - }], - }, - ); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - let r: Request = Request::new( - id.into(), - "textDocument/formatting".to_string(), - DocumentFormattingParams { - text_document: TextDocumentIdentifier { - uri: Url::from_file_path(path).unwrap(), - }, - options: Default::default(), - work_done_progress_params: Default::default(), - }, - ); - - // Send request and wait for it's response - let res = server.send_and_receive(r); - - assert_eq!( - res.result.unwrap(), - to_json(Some(vec![TextEdit { - range: Range::new( - Position::new(0, 0), - Position::new(i32::MAX as u32, i32::MAX as u32), - ), - new_text: "unsaved = 0\n\na = 1\n\nb = 2\n\nc = 3\n\nd = 4\n".to_string() - }])) - .unwrap() - ) -} - -#[test] -fn complete_import_external_file_e2e_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("completion_test") - .join("import") - .join("external") - .join("external_1"); - let path = root - .join("main.k") - .canonicalize() - .unwrap() - .display() - .to_string(); - let _ = Command::new("kcl") - .arg("mod") - .arg("metadata") - .arg("--update") - .current_dir( - PathBuf::from(".") - .join("src") - .join("test_data") - .join("completion_test") - .join("import") - .join("external") - .join("external_1") - .canonicalize() - .unwrap() - .display() - .to_string(), - ) - .output() - .unwrap(); - - let src = std::fs::read_to_string(path.clone()).unwrap(); - - let initialize_params = InitializeParams { - workspace_folders: Some(vec![WorkspaceFolder { - uri: Url::from_file_path(root.clone()).unwrap(), - name: "test".to_string(), - }]), - ..Default::default() - }; - let server = Project {}.server(initialize_params); - - // FIXME: It takes longer to parse the k8s package on Windows - #[cfg(target_os = "windows")] - wait_async!(20000); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: Url::from_file_path(path.clone()).unwrap(), - language_id: "KCL".to_string(), - version: 0, - text: src, - }, - }, - ); - wait_async!(5000); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - let r: Request = Request::new( - id.into(), - "textDocument/completion".to_string(), - CompletionParams { - text_document_position: TextDocumentPositionParams { - text_document: TextDocumentIdentifier { - uri: Url::from_file_path(path).unwrap(), - }, - position: Position::new(0, 7), - }, - work_done_progress_params: Default::default(), - partial_result_params: Default::default(), - context: None, - }, - ); - - // Send request and wait for it's response - let res = server.send_and_receive(r); - match res.result.unwrap() { - serde_json::Value::Array(vec) => { - assert!( - (vec.iter() - .find(|v| match v { - serde_json::Value::Object(map) => { - map.get("label").unwrap() == "k8s" - } - _ => false, - }) - .is_some()), - "" - ); - } - _ => panic!("test failed"), - } -} - -// TODO: wait for fix `kcl mod metadata` to read only. Otherwise it will lead to an infinite loop -#[allow(dead_code)] -// #[test] -fn mod_file_watcher_test() { - let path = PathBuf::from(".") - .join("src") - .join("test_data") - .join("watcher") - .join("modify") - .canonicalize() - .unwrap(); - - let mod_file_path = path.join("kcl.mod"); - let main_path = path.join("main.k"); - - let mod_src_bac = std::fs::read_to_string(mod_file_path.clone()).unwrap(); - let main_src = std::fs::read_to_string(main_path.clone()).unwrap(); - - let initialize_params = InitializeParams { - workspace_folders: Some(vec![WorkspaceFolder { - uri: Url::from_file_path(path.clone()).unwrap(), - name: "test".to_string(), - }]), - ..Default::default() - }; - let server = Project {}.server(initialize_params); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: Url::from_file_path(main_path.clone()).unwrap(), - language_id: "KCL".to_string(), - version: 0, - text: main_src, - }, - }, - ); - - let _ = Command::new("kcl") - .arg("mod") - .arg("add") - .arg("helloworld") - .current_dir(path) - .output() - .unwrap(); - - // wait for download dependence - wait_async!(2000); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - let r: Request = Request::new( - id.into(), - "textDocument/hover".to_string(), - HoverParams { - text_document_position_params: TextDocumentPositionParams { - text_document: TextDocumentIdentifier { - uri: Url::from_file_path(main_path).unwrap(), - }, - position: Position::new(0, 8), - }, - work_done_progress_params: Default::default(), - }, - ); - - // Send request and wait for it's response - let res = server.send_and_receive(r); - - std::fs::write(mod_file_path, mod_src_bac).unwrap(); - assert_eq!( - res.result.unwrap(), - to_json(Hover { - contents: HoverContents::Scalar(MarkedString::LanguageString( - lsp_types::LanguageString { - language: "KCL".to_owned(), - value: "helloworld: ".to_string(), - } - )), - range: None - }) - .unwrap() - ) -} - -// Integration testing of lsp and konfig -fn konfig_path() -> PathBuf { - let konfig_path = Path::new(".") - .canonicalize() - .unwrap() - .parent() - .unwrap() - .parent() - .unwrap() - .parent() - .unwrap() - .parent() - .unwrap() - .join("test") - .join("integration") - .join("konfig"); - konfig_path -} - -#[test] -fn konfig_goto_def_test_base() { - let konfig_path = konfig_path(); - let base_path = konfig_path - .clone() - .join("appops") - .join("nginx-example") - .join("base") - .join("base.k"); - let base_path_str = base_path.to_str().unwrap().to_string(); - let (_program, _, gs) = compile_with_params(Params { - file: Some(base_path_str.clone()), - module_cache: None, - scope_cache: None, - vfs: Some(KCLVfs::default()), - gs_cache: Some(KCLGlobalStateCache::default()), - }) - .1 - .unwrap(); - - // schema def - let pos = KCLPos { - filename: base_path_str.clone().adjust_canonicalization(), - line: 7, - column: Some(30), - }; - let res = goto_def(&pos, &gs); - let expected_path = konfig_path - .clone() - .join("base") - .join("pkg") - .join("kusion_models") - .join("kube") - .join("frontend") - .join("server.k"); - - compare_goto_res( - res, - (&expected_path.to_str().unwrap().to_string(), 12, 7, 12, 13), - ); - - // schema def - let pos = KCLPos { - filename: base_path_str.clone().adjust_canonicalization(), - line: 9, - column: Some(32), - }; - let res = goto_def(&pos, &gs); - let expected_path = konfig_path - .clone() - .join("base") - .join("pkg") - .join("kusion_models") - .join("kube") - .join("frontend") - .join("container") - .join("container.k"); - compare_goto_res( - res, - (&expected_path.to_str().unwrap().to_string(), 5, 7, 5, 11), - ); - - // schema attr - let pos = KCLPos { - filename: base_path_str.clone().adjust_canonicalization(), - line: 9, - column: Some(9), - }; - let res = goto_def(&pos, &gs); - let expected_path = konfig_path - .clone() - .join("base") - .join("pkg") - .join("kusion_models") - .join("kube") - .join("frontend") - .join("server.k"); - compare_goto_res( - res, - ( - &expected_path.to_str().unwrap().to_string(), - 115, - 4, - 115, - 17, - ), - ); - - // schema attr - let pos = KCLPos { - filename: base_path_str.clone().adjust_canonicalization(), - line: 10, - column: Some(10), - }; - let res = goto_def(&pos, &gs); - let expected_path = konfig_path - .clone() - .join("base") - .join("pkg") - .join("kusion_models") - .join("kube") - .join("frontend") - .join("container") - .join("container.k"); - compare_goto_res( - res, - (&expected_path.to_str().unwrap().to_string(), 69, 4, 69, 9), - ); - - // import pkg - let pos = KCLPos { - filename: base_path_str.clone().adjust_canonicalization(), - line: 2, - column: Some(49), - }; - let res = goto_def(&pos, &gs); - - let expected_path = konfig_path - .clone() - .join("base") - .join("pkg") - .join("kusion_models") - .join("kube") - .join("frontend") - .join("service") - .join("service.k"); - compare_goto_res( - res, - (&expected_path.to_str().unwrap().to_string(), 0, 0, 0, 0), - ); -} - -#[test] -fn konfig_goto_def_test_main() { - let konfig_path = konfig_path(); - let main_path = konfig_path - .clone() - .join("appops") - .join("nginx-example") - .join("dev") - .join("main.k"); - let main_path_str = main_path.to_str().unwrap().to_string(); - let (_program, _, gs) = compile_with_params(Params { - file: Some(main_path_str.clone()), - module_cache: None, - scope_cache: None, - vfs: Some(KCLVfs::default()), - gs_cache: Some(KCLGlobalStateCache::default()), - }) - .1 - .unwrap(); - - // schema def - let pos = KCLPos { - filename: main_path_str.clone().adjust_canonicalization(), - line: 6, - column: Some(31), - }; - let res = goto_def(&pos, &gs); - let expected_path = konfig_path - .clone() - .join("base") - .join("pkg") - .join("kusion_models") - .join("kube") - .join("frontend") - .join("server.k"); - compare_goto_res( - res, - (&expected_path.to_str().unwrap().to_string(), 12, 7, 12, 13), - ); - - // schema attr - let pos = KCLPos { - filename: main_path_str.clone().adjust_canonicalization(), - line: 7, - column: Some(14), - }; - let res = goto_def(&pos, &gs); - let expected_path = konfig_path - .clone() - .join("base") - .join("pkg") - .join("kusion_models") - .join("kube") - .join("frontend") - .join("server.k"); - compare_goto_res( - res, - ( - &expected_path.to_str().unwrap().to_string(), - 112, - 4, - 112, - 22, - ), - ); - - // import pkg - let pos = KCLPos { - filename: main_path_str.clone().adjust_canonicalization(), - line: 2, - column: Some(61), - }; - let res = goto_def(&pos, &gs); - let expected_path = konfig_path - .clone() - .join("base") - .join("pkg") - .join("kusion_models") - .join("kube") - .join("templates") - .join("resource.k"); - compare_goto_res( - res, - (&expected_path.to_str().unwrap().to_string(), 0, 0, 0, 0), - ); -} - -#[test] -fn konfig_completion_test_main() { - let konfig_path = konfig_path(); - let main_path = konfig_path - .clone() - .join("appops") - .join("nginx-example") - .join("dev") - .join("main.k"); - let main_path_str = main_path.to_str().unwrap().to_string(); - let (program, schema_map, gs) = compile_with_params(Params { - file: Some(main_path_str.clone()), - module_cache: None, - scope_cache: None, - vfs: Some(KCLVfs::default()), - gs_cache: Some(KCLGlobalStateCache::default()), - }) - .1 - .unwrap(); - - // pkg's definition(schema) completion - let pos = KCLPos { - filename: main_path_str.clone().adjust_canonicalization(), - line: 6, - column: Some(27), - }; - let tool = toolchain::default(); - let got = completion(Some('.'), &program, &pos, &gs, &tool, None, &schema_map).unwrap(); - let got_labels: Vec = match got { - CompletionResponse::Array(arr) => arr.iter().map(|item| item.label.clone()).collect(), - CompletionResponse::List(_) => panic!("test failed"), - }; - - let expected_labels: Vec = ["Job", "Server"] - .iter() - .map(|attr| attr.to_string()) - .collect(); - assert_eq!(got_labels, expected_labels); - - // schema attr completion - let pos = KCLPos { - filename: main_path_str.clone().adjust_canonicalization(), - line: 7, - column: Some(4), - }; - let tool = toolchain::default(); - let got = completion(None, &program, &pos, &gs, &tool, None, &schema_map).unwrap(); - let mut got_labels: Vec = match got { - CompletionResponse::Array(arr) => arr.iter().map(|item| item.label.clone()).collect(), - CompletionResponse::List(_) => panic!("test failed"), - }; - let mut attr = [ - "annotations", - "configMaps", - "database", - "enableMonitoring", - "frontend", - "image", - "ingresses", - "initContainers", - "labels", - "mainContainer", - "name", - "needNamespace", - "podMetadata", - "renderType", - "replicas", - "res_tpl", - "schedulingStrategy", - "secrets", - "selector", - "serviceAccount", - "services", - "sidecarContainers", - "storage", - "useBuiltInLabels", - "useBuiltInSelector", - "volumes", - "workloadType", - ]; - got_labels.sort(); - attr.sort(); - assert_eq!(got_labels, attr); - - // import path completion - let pos = KCLPos { - filename: main_path_str.clone().adjust_canonicalization(), - line: 1, - column: Some(35), - }; - let tool = toolchain::default(); - let got = completion(Some('.'), &program, &pos, &gs, &tool, None, &schema_map).unwrap(); - let mut got_labels: Vec = match got { - CompletionResponse::Array(arr) => arr.iter().map(|item| item.label.clone()).collect(), - CompletionResponse::List(_) => panic!("test failed"), - }; - let mut pkgs = [ - "common", - "configmap", - "container", - "ingress", - "job", - "rbac", - "resource", - "secret", - "server", - "service", - "serviceaccount", - "sidecar", - "storage", - "strategy", - "volume", - ]; - got_labels.sort(); - pkgs.sort(); - assert_eq!(got_labels, pkgs); -} - -#[test] -fn konfig_hover_test_main() { - let konfig_path = konfig_path(); - let main_path = konfig_path - .clone() - .join("appops") - .join("nginx-example") - .join("dev") - .join("main.k"); - - let main_path_str = main_path.to_str().unwrap().to_string(); - let (_program, _, gs) = compile_with_params(Params { - file: Some(main_path_str.clone()), - module_cache: None, - scope_cache: None, - vfs: Some(KCLVfs::default()), - gs_cache: Some(KCLGlobalStateCache::default()), - }) - .1 - .unwrap(); - - // schema def hover - let pos = KCLPos { - filename: main_path_str.clone().adjust_canonicalization(), - line: 6, - column: Some(32), - }; - let got = hover(&pos, &gs).unwrap(); - match got.contents { - HoverContents::Array(arr) => { - let expect: Vec = vec![ - MarkedString::String("base.pkg.kusion_models.kube.frontend".to_string()), - MarkedString::LanguageString(lsp_types::LanguageString { - language: "KCL".to_string(), - value: "schema Server:\n name?: str\n workloadType: \"Deployment\" | \"StatefulSet\" = \"Deployment\"\n renderType?: \"Server\" | \"KubeVelaApplication\" = \"Server\"\n replicas: int = option(\"replicas\") or 1\n image: str = option(\"image\")\n schedulingStrategy: SchedulingStrategy = strategy.SchedulingStrategy {}\n mainContainer: Main\n sidecarContainers?: [Sidecar]\n initContainers?: [Sidecar]\n useBuiltInLabels?: bool = True\n labels?: {str:str}\n annotations?: {str:str}\n useBuiltInSelector?: bool = True\n selector?: {str:str}\n podMetadata?: ObjectMeta\n volumes?: [Volume]\n needNamespace?: bool = True\n enableMonitoring?: bool = False\n configMaps?: [ConfigMap]\n secrets?: [Secret]\n services?: [Service]\n ingresses?: [Ingress]\n serviceAccount?: ServiceAccount\n storage?: ObjectStorage\n database?: DataBase".to_string() - }), - MarkedString::String("Server is abstaction of Deployment and StatefulSet.".to_string()), - MarkedString::LanguageString(lsp_types::LanguageString { - language: "KCL".to_string(), - value: "import base.pkg.kusion_models.kube.frontend\nimport base.pkg.kusion_models.kube.frontend.container\nimport base.pkg.kusion_models.kube.templates.resource as res_tpl\n\nappConfiguration: frontend.Server {\n mainContainer = container.Main {\n name = \"php-redis\"\n env = [\n {\n name = \"GET_HOSTS_FROM\"\n value = \"dns\"\n }\n ]\n ports = [{containerPort = 80}]\n }\n selector = {\n tier = \"frontend\"\n }\n podMetadata.labels: {\n tier = \"frontend\"\n }\n schedulingStrategy.resource = res_tpl.tiny\n}\n".to_string() - }), - ]; - assert_eq!(expect, arr); - } - _ => unreachable!("test error"), - } - - // schema attr def hover - let pos = KCLPos { - filename: main_path_str.clone().adjust_canonicalization(), - line: 7, - column: Some(15), - }; - let got = hover(&pos, &gs).unwrap(); - match got.contents { - HoverContents::Array(arr) => { - let expect: Vec = vec![ - MarkedString::LanguageString(lsp_types::LanguageString { - language: "KCL".to_string(), - value: - "schedulingStrategy: SchedulingStrategy = strategy.SchedulingStrategy {}" - .to_string(), - }), - MarkedString::String( - "SchedulingStrategy represents scheduling strategy.".to_string(), - ), - ]; - assert_eq!(expect, arr); - } - _ => unreachable!("test error"), - } - - // variable hover - let pos = KCLPos { - filename: main_path_str.clone().adjust_canonicalization(), - line: 6, - column: Some(3), - }; - let got = hover(&pos, &gs).unwrap(); - match got.contents { - HoverContents::Scalar(s) => { - assert_eq!( - s, - MarkedString::LanguageString(lsp_types::LanguageString { - language: "KCL".to_string(), - value: "appConfiguration: Server".to_string() - }) - ); - } - _ => unreachable!("test error"), - } -} - -#[test] -fn lsp_version_test() { - let args = vec!["kcl-language-server".to_string(), "version".to_string()]; - let matches = crate::app::app() - .arg_required_else_help(false) - .try_get_matches_from(args); - match matches { - Ok(arg_match) => match arg_match.subcommand() { - Some(("version", _)) => {} - _ => panic!("test failed"), - }, - Err(_) => panic!("test failed"), - } -} - -#[test] -fn lsp_run_test() { - let args = vec!["kcl-language-server".to_string()]; - let matches = crate::app::app() - .arg_required_else_help(false) - .try_get_matches_from(args); - match matches { - Ok(arg_match) => match arg_match.subcommand() { - None => {} - _ => panic!("test failed"), - }, - Err(_) => panic!("test failed"), - } -} - -#[test] -fn lsp_invalid_subcommand_test() { - let args = vec!["kcl-language-server".to_string(), "invalid".to_string()]; - let matches = crate::app::app() - .arg_required_else_help(false) - .try_get_matches_from(args); - match matches { - Ok(_) => panic!("test failed"), - Err(e) => match e.kind() { - clap::error::ErrorKind::InvalidSubcommand => {} - _ => panic!("test failed"), - }, - } -} - -#[test] -fn find_refs_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("find_refs_test"); - let mut path = root.clone(); - path.push("main.k"); - - let path = path.to_str().unwrap(); - let src = std::fs::read_to_string(path).unwrap(); - let initialize_params = InitializeParams { - workspace_folders: Some(vec![WorkspaceFolder { - uri: Url::from_file_path(root.clone()).unwrap(), - name: "test".to_string(), - }]), - ..Default::default() - }; - let server = Project {}.server(initialize_params); - - // Wait for async build word_index_map - wait_async!(); - - let url = Url::from_file_path(path).unwrap(); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: url.clone(), - language_id: "KCL".to_string(), - version: 0, - text: src, - }, - }, - ); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - let r: Request = Request::new( - id.into(), - "textDocument/references".to_string(), - ReferenceParams { - text_document_position: TextDocumentPositionParams { - text_document: TextDocumentIdentifier { uri: url.clone() }, - position: Position::new(0, 1), - }, - work_done_progress_params: Default::default(), - partial_result_params: Default::default(), - context: ReferenceContext { - include_declaration: true, - }, - }, - ); - - // Send request and wait for it's response - let res = server.send_and_receive(r); - - assert_eq!( - res.result.unwrap(), - to_json(vec![ - Location { - uri: url.clone(), - range: Range { - start: Position::new(0, 0), - end: Position::new(0, 1), - }, - }, - Location { - uri: url.clone(), - range: Range { - start: Position::new(1, 4), - end: Position::new(1, 5), - }, - }, - Location { - uri: url.clone(), - range: Range { - start: Position::new(2, 4), - end: Position::new(2, 5), - }, - }, - Location { - uri: url.clone(), - range: Range { - start: Position::new(12, 14), - end: Position::new(12, 15), - }, - }, - ]) - .unwrap() - ); -} - -#[test] -fn find_refs_with_file_change_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("find_refs_test"); - let mut path = root.clone(); - path.push("main.k"); - - let path = path.to_str().unwrap(); - let src = std::fs::read_to_string(path).unwrap(); - let initialize_params = InitializeParams { - workspace_folders: Some(vec![WorkspaceFolder { - uri: Url::from_file_path(root.clone()).unwrap(), - name: "test".to_string(), - }]), - ..Default::default() - }; - let server = Project {}.server(initialize_params); - - // Wait for async build word_index_map - wait_async!(); - - let url = Url::from_file_path(path).unwrap(); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: url.clone(), - language_id: "KCL".to_string(), - version: 0, - text: src, - }, - }, - ); - - // Mock change file content - server.notification::( - lsp_types::DidChangeTextDocumentParams { - text_document: lsp_types::VersionedTextDocumentIdentifier { - uri: url.clone(), - version: 1, - }, - content_changes: vec![lsp_types::TextDocumentContentChangeEvent { - range: None, - range_length: None, - text: r#"a = "demo" - -schema Name: - name: str - -schema Person: - n: Name - -p2 = Person { - n: Name{ - name: a - } -}"# - .to_string(), - }], - }, - ); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - // Mock trigger find references - let r: Request = Request::new( - id.into(), - "textDocument/references".to_string(), - ReferenceParams { - text_document_position: TextDocumentPositionParams { - text_document: TextDocumentIdentifier { uri: url.clone() }, - position: Position::new(0, 1), - }, - work_done_progress_params: Default::default(), - partial_result_params: Default::default(), - context: ReferenceContext { - include_declaration: true, - }, - }, - ); - - // Send request and wait for it's response - let res = server.send_and_receive(r); - assert_eq!( - res.result.unwrap(), - to_json(vec![ - Location { - uri: url.clone(), - range: Range { - start: Position::new(0, 0), - end: Position::new(0, 1), - }, - }, - Location { - uri: url.clone(), - range: Range { - start: Position::new(10, 14), - end: Position::new(10, 15), - }, - }, - ]) - .unwrap() - ); -} - -#[test] -fn rename_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("rename_test"); - let path = root.clone(); - let main_path = root.clone(); - let path = path.join("pkg").join("vars.k"); - let main_path = main_path.join("main.k"); - - let path = path.to_str().unwrap(); - let src = std::fs::read_to_string(path).unwrap(); - let initialize_params = InitializeParams { - workspace_folders: Some(vec![WorkspaceFolder { - uri: Url::from_file_path(root.clone()).unwrap(), - name: "test".to_string(), - }]), - ..Default::default() - }; - let server = Project {}.server(initialize_params); - - wait_async!(); - - let url = Url::from_file_path(path).unwrap(); - let main_url = Url::from_file_path(main_path).unwrap(); - - // Mock open file - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: url.clone(), - language_id: "KCL".to_string(), - version: 0, - text: src, - }, - }, - ); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - let new_name = String::from("Person2"); - let r: Request = Request::new( - id.into(), - "textDocument/rename".to_string(), - RenameParams { - text_document_position: TextDocumentPositionParams { - text_document: TextDocumentIdentifier { uri: url.clone() }, - position: Position::new(0, 7), - }, - new_name: new_name.clone(), - work_done_progress_params: Default::default(), - }, - ); - - // Send request and wait for it's response - let res = server.send_and_receive(r); - let expect = WorkspaceEdit { - changes: Some(HashMap::from_iter(vec![ - ( - url.clone(), - vec![ - TextEdit { - range: Range { - start: Position::new(0, 7), - end: Position::new(0, 13), - }, - new_text: new_name.clone(), - }, - TextEdit { - range: Range { - start: Position::new(4, 7), - end: Position::new(4, 13), - }, - new_text: new_name.clone(), - }, - TextEdit { - range: Range { - start: Position::new(9, 8), - end: Position::new(9, 14), - }, - new_text: new_name.clone(), - }, - ], - ), - ( - main_url.clone(), - vec![TextEdit { - range: Range { - start: Position::new(2, 11), - end: Position::new(2, 17), - }, - new_text: new_name.clone(), - }], - ), - ])), - ..Default::default() - }; - assert_eq!(res.result.unwrap(), to_json(expect).unwrap()); -} - -#[test] -fn kcl_workspace_init_kclwork_test() { - let tool: crate::state::KCLToolChain = Arc::new(RwLock::new(toolchain::default())); - let tool = Arc::clone(&tool); - - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("workspace") - .join("init"); - - let mut work = root.clone(); - work.push("work"); - - let (workspaces, failed) = - kclvm_driver::lookup_compile_workspaces(&*tool.read(), work.to_str().unwrap(), true); - - let mut expected = HashSet::new(); - - expected.insert(WorkSpaceKind::Folder( - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("workspace") - .join("init") - .join("work") - .join("a"), - )); - - expected.insert(WorkSpaceKind::Folder( - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("workspace") - .join("init") - .join("work") - .join("b"), - )); - - expected.insert(WorkSpaceKind::File( - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("workspace") - .join("init") - .join("work") - .join("c.k"), - )); - - assert_eq!(expected, workspaces.keys().cloned().collect()); - - assert!(failed.is_some()); - assert!(failed.unwrap().is_empty()); -} - -#[test] -fn kcl_workspace_init_kclmod_test() { - let tool: crate::state::KCLToolChain = Arc::new(RwLock::new(toolchain::default())); - let tool = Arc::clone(&tool); - - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("workspace") - .join("init"); - - let mut work = root.clone(); - work.push("mod"); - - let mut main = work.clone(); - main.push("main.k"); - - let (workspaces, failed) = - kclvm_driver::lookup_compile_workspaces(&*tool.read(), work.to_str().unwrap(), true); - - let mut expected = HashSet::new(); - - expected.insert(WorkSpaceKind::ModFile( - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("workspace") - .join("init") - .join("mod") - .join("kcl.mod"), - )); - - assert_eq!(expected, workspaces.keys().cloned().collect()); - assert_eq!( - vec![main.to_str().unwrap().to_string()], - workspaces.values().next().unwrap().0 - ); - assert!(failed.is_none()); -} - -#[test] -fn kcl_workspace_init_settings_file_test() { - let tool: crate::state::KCLToolChain = Arc::new(RwLock::new(toolchain::default())); - let tool = Arc::clone(&tool); - - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("workspace") - .join("init"); - - let mut work = root.clone(); - work.push("setting"); - - let mut a = work.clone(); - a.push("a.k"); - - let (workspaces, failed) = - kclvm_driver::lookup_compile_workspaces(&*tool.read(), work.to_str().unwrap(), true); - - let mut expected = HashSet::new(); - - expected.insert(WorkSpaceKind::SettingFile( - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("workspace") - .join("init") - .join("setting") - .join("kcl.yaml"), - )); - - assert_eq!(expected, workspaces.keys().cloned().collect()); - assert!(failed.is_none()); - assert_eq!( - vec![a.file_name().unwrap().to_str().unwrap().to_string()], - workspaces.values().next().unwrap().0 - ); -} - -#[test] -fn kcl_workspace_init_folder_test() { - let tool: crate::state::KCLToolChain = Arc::new(RwLock::new(toolchain::default())); - let tool = Arc::clone(&tool); - - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("workspace") - .join("init"); - - let mut work = root.clone(); - work.push("folder"); - - let (workspaces, failed) = - kclvm_driver::lookup_compile_workspaces(&*tool.read(), work.to_str().unwrap(), true); - - let mut expected = HashSet::new(); - - expected.insert(WorkSpaceKind::Folder( - PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("workspace") - .join("init") - .join("folder"), - )); - - assert_eq!(expected, workspaces.keys().cloned().collect()); - - assert!(failed.is_none()); -} - -#[test] -fn init_workspace_sema_token_test() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("src") - .join("test_data") - .join("workspace") - .join("init") - .join("folder"); - - let mut a_path = root.clone(); - a_path.push("a.k"); - - let mut c_path = root.clone(); - c_path.push("sub"); - c_path.push("c.k"); - - let a_path = a_path.to_str().unwrap(); - let c_path = c_path.to_str().unwrap(); - let a_src = std::fs::read_to_string(a_path).unwrap(); - let c_src = std::fs::read_to_string(c_path).unwrap(); - let initialize_params = InitializeParams { - workspace_folders: Some(vec![WorkspaceFolder { - uri: Url::from_file_path(root.clone()).unwrap(), - name: "test".to_string(), - }]), - ..Default::default() - }; - let server = Project {}.server(initialize_params); - - let a_url = Url::from_file_path(a_path).unwrap(); - let c_url = Url::from_file_path(c_path).unwrap(); - - // Mock open file in init workspace - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: a_url.clone(), - language_id: "KCL".to_string(), - version: 0, - text: a_src, - }, - }, - ); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - let r: Request = Request::new( - id.into(), - "textDocument/semanticTokens/full".to_string(), - SemanticTokensParams { - text_document: TextDocumentIdentifier { uri: a_url }, - work_done_progress_params: WorkDoneProgressParams { - work_done_token: None, - }, - partial_result_params: PartialResultParams { - partial_result_token: None, - }, - }, - ); - - let res = server.send_and_receive(r); - assert!(res.result.is_some()); - - // Mock open file not in init workspace - server.notification::( - lsp_types::DidOpenTextDocumentParams { - text_document: TextDocumentItem { - uri: c_url.clone(), - language_id: "KCL".to_string(), - version: 0, - text: c_src, - }, - }, - ); - - let id = server.next_request_id.get(); - server.next_request_id.set(id.wrapping_add(1)); - - let r: Request = Request::new( - id.into(), - "textDocument/semanticTokens/full".to_string(), - SemanticTokensParams { - text_document: TextDocumentIdentifier { uri: c_url }, - work_done_progress_params: WorkDoneProgressParams { - work_done_token: None, - }, - partial_result_params: PartialResultParams { - partial_result_token: None, - }, - }, - ); - - let res = server.send_and_receive(r); - assert!(res.result.is_some()); -} - -#[test] -fn pkg_mod_test() { - let (_file, _program, diags, _gs, _) = - compile_test_file("src/test_data/workspace/pkg_mod_test/test/main.k"); - assert_eq!(diags.iter().filter(|diag| diag.is_error()).count(), 0); -} - -#[test] -fn aug_assign_without_define() { - let (_file, _program, diags, _gs, _) = - compile_test_file("src/test_data/error_code/aug_assign/aug_assign.k"); - assert_eq!(diags.len(), 1); -} diff --git a/kclvm/tools/src/LSP/src/util.rs b/kclvm/tools/src/LSP/src/util.rs deleted file mode 100644 index 42d092a1a..000000000 --- a/kclvm/tools/src/LSP/src/util.rs +++ /dev/null @@ -1,667 +0,0 @@ -use kclvm_ast::ast::{ - ConfigEntry, Expr, Identifier, MemberOrIndex, Node, NodeRef, PosTuple, Program, SchemaStmt, - Stmt, Type, -}; -use kclvm_ast::node_ref; -use kclvm_ast::pos::ContainsPos; - -use kclvm_error::Position as KCLPos; -use kclvm_parser::entry::get_dir_files; - -use crate::from_lsp; -use crate::state::KCLVfs; -use lsp_types::Url; -use parking_lot::RwLockReadGuard; -use ra_ap_vfs::{FileId, Vfs}; -use serde::{de::DeserializeOwned, Serialize}; - -use std::fs; -use std::path::{Path, PathBuf}; - -/// Deserializes a `T` from a json value. -pub(crate) fn from_json( - what: &'static str, - json: serde_json::Value, -) -> anyhow::Result { - T::deserialize(&json) - .map_err(|e| anyhow::anyhow!("could not deserialize {}: {}: {}", what, e, json)) -} - -/// Converts the `T` to a json value -pub(crate) fn to_json(value: T) -> anyhow::Result { - serde_json::to_value(value).map_err(|e| anyhow::anyhow!("could not serialize to json: {}", e)) -} - -/// Get the filename from the given VFS using the file id. -pub(crate) fn get_file_name(vfs: RwLockReadGuard, file_id: FileId) -> anyhow::Result { - if let Some(path) = vfs.file_path(file_id).as_path() { - Ok(path - .as_ref() - .to_str() - .ok_or(anyhow::anyhow!("Failed to get file file"))? - .to_string()) - } else { - Err(anyhow::anyhow!( - "{} isn't on the file system.", - vfs.file_path(file_id) - )) - } -} - -/// Update text with TextDocumentContentChangeEvent param -pub(crate) fn apply_document_changes( - old_text: &mut String, - content_changes: Vec, -) { - for change in content_changes { - match change.range { - Some(range) => { - let range = from_lsp::text_range(old_text, range); - old_text.replace_range(range, &change.text); - } - None => { - *old_text = change.text; - } - } - } -} - -pub(crate) fn load_files_code_from_vfs( - files: &[&str], - vfs: &KCLVfs, -) -> anyhow::Result> { - let mut res = vec![]; - let vfs = &mut vfs.read(); - for file in files { - let url = Url::from_file_path(file) - .map_err(|_| anyhow::anyhow!("can't convert file to url: {}", file))?; - let path = from_lsp::abs_path(&url)?; - match vfs.file_id(&path.clone().into()) { - Some(id) => { - // Load code from vfs if exist - res.push(String::from_utf8(vfs.file_contents(id).to_vec()).unwrap()); - } - None => { - // In order to ensure that k_file corresponds to k_code, load the code from the file system if not exist - let p: &Path = path.as_ref(); - if p.is_file() { - res.push( - fs::read_to_string(path) - .map_err(|_| anyhow::anyhow!("can't convert file to url: {}", file))?, - ); - } else if p.is_dir() { - let k_files = get_dir_files(p.to_str().unwrap(), false) - .map_err(|_| anyhow::anyhow!("can't get dir files: {} ", file))?; - for k_file in k_files { - let k_file_path = Path::new(k_file.as_str()); - res.push( - fs::read_to_string(k_file_path).map_err(|_| { - anyhow::anyhow!("can't convert file to url: {}", file) - })?, - ); - } - } - } - } - } - Ok(res) -} - -pub(crate) fn filter_kcl_config_file(paths: &[PathBuf]) -> Vec { - paths - .iter() - .filter(|p| { - p.file_name().map(|n| n.to_str().unwrap()) == Some(kclvm_config::modfile::KCL_MOD_FILE) - || p.file_name().map(|n| n.to_str().unwrap()) - == Some(kclvm_config::settings::DEFAULT_SETTING_FILE) - }) - .map(|p| p.clone()) - .collect() -} - -macro_rules! walk_if_contains { - ($expr: expr, $pos: expr, $schema_def: expr) => { - if $expr.contains_pos($pos) { - return inner_most_expr(&$expr, &$pos, $schema_def); - } - }; -} - -macro_rules! walk_if_contains_with_new_expr { - ($expr: expr, $pos: expr, $schema_def: expr, $kind: expr) => { - if $expr.contains_pos($pos) { - walk_if_contains!( - Node::node_with_pos( - $kind($expr.node.clone()), - ( - $expr.filename.clone(), - $expr.line, - $expr.column, - $expr.end_line, - $expr.end_column, - ), - ), - $pos, - $schema_def - ); - } - }; -} - -macro_rules! walk_option_if_contains { - ($opt: expr, $pos: expr, $schema_def: expr) => { - if let Some(expr) = &$opt { - walk_if_contains!(expr, $pos, $schema_def) - } - }; -} - -macro_rules! walk_list_if_contains { - ($list: expr, $pos: expr, $schema_def: expr) => { - for elem in &$list { - walk_if_contains!(elem, $pos, $schema_def) - } - }; -} - -fn transfer_ident_names(names: Vec, pos: &PosTuple) -> Vec> { - let mut new_names = vec![]; - let mut col = pos.2; - for name in &names { - let mut name_pos = pos.clone(); - name_pos.2 = col; - name_pos.4 = col + name.len() as u64; - new_names.push(Node::node_with_pos(name.clone(), name_pos)); - col = col + name.len() as u64 + ".".len() as u64; - } - new_names -} - -/// Recursively finds the inner most expr and its schema_def expr if in a schema expr(e.g., schema_attr and schema_expr) -/// in a stmt according to the position. -pub(crate) fn inner_most_expr_in_stmt( - stmt: &Stmt, - pos: &KCLPos, - schema_def: Option>, -) -> (Option>, Option>) { - match stmt { - Stmt::Assign(assign_stmt) => { - if let Some(ty) = &assign_stmt.ty { - if ty.contains_pos(pos) { - return (build_identifier_from_ty_string(ty, pos), schema_def); - } - } - walk_if_contains!(assign_stmt.value, pos, schema_def); - - for expr in &assign_stmt.targets { - walk_if_contains_with_new_expr!(expr, pos, schema_def, Expr::Target); - } - (None, schema_def) - } - Stmt::TypeAlias(type_alias_stmt) => { - walk_if_contains_with_new_expr!( - type_alias_stmt.type_name, - pos, - schema_def, - Expr::Identifier - ); - (None, schema_def) - } - Stmt::Expr(expr_stmt) => { - walk_list_if_contains!(expr_stmt.exprs, pos, schema_def); - (None, schema_def) - } - Stmt::Unification(unification_stmt) => { - walk_if_contains_with_new_expr!( - unification_stmt.target, - pos, - schema_def, - Expr::Identifier - ); - - walk_if_contains_with_new_expr!(unification_stmt.value, pos, schema_def, Expr::Schema); - - (None, schema_def) - } - Stmt::AugAssign(aug_assign_stmt) => { - walk_if_contains!(aug_assign_stmt.value, pos, schema_def); - walk_if_contains_with_new_expr!(aug_assign_stmt.target, pos, schema_def, Expr::Target); - (None, schema_def) - } - Stmt::Assert(assert_stmt) => { - walk_if_contains!(assert_stmt.test, pos, schema_def); - walk_option_if_contains!(assert_stmt.if_cond, pos, schema_def); - walk_option_if_contains!(assert_stmt.msg, pos, schema_def); - (None, schema_def) - } - Stmt::If(if_stmt) => { - walk_if_contains!(if_stmt.cond, pos, schema_def); - for stmt in &if_stmt.body { - if stmt.contains_pos(pos) { - return inner_most_expr_in_stmt(&stmt.node, pos, schema_def); - } - } - for stmt in &if_stmt.orelse { - if stmt.contains_pos(pos) { - return inner_most_expr_in_stmt(&stmt.node, pos, schema_def); - } - } - (None, schema_def) - } - Stmt::Schema(schema_stmt) => { - walk_if_contains!( - Node::node_with_pos( - Expr::Identifier(Identifier { - names: transfer_ident_names( - vec![schema_stmt.name.node.clone()], - &( - schema_stmt.name.filename.clone(), - schema_stmt.name.line, - schema_stmt.name.column, - schema_stmt.name.end_line, - schema_stmt.name.end_column, - ), - ), - pkgpath: "".to_string(), - ctx: kclvm_ast::ast::ExprContext::Load, - }), - ( - schema_stmt.name.filename.clone(), - schema_stmt.name.line, - schema_stmt.name.column, - schema_stmt.name.end_line, - schema_stmt.name.end_column, - ), - ), - pos, - schema_def - ); - if let Some(parent_id) = &schema_stmt.parent_name { - walk_if_contains_with_new_expr!(parent_id, pos, schema_def, Expr::Identifier); - } - if let Some(host) = &schema_stmt.for_host_name { - walk_if_contains_with_new_expr!(host, pos, schema_def, Expr::Identifier); - } - for mixin in &schema_stmt.mixins { - walk_if_contains_with_new_expr!(mixin, pos, schema_def, Expr::Identifier); - } - for stmt in &schema_stmt.body { - if stmt.contains_pos(pos) { - return inner_most_expr_in_stmt(&stmt.node, pos, schema_def); - } - } - for decorator in &schema_stmt.decorators { - walk_if_contains_with_new_expr!(decorator, pos, schema_def, Expr::Call); - } - for check in &schema_stmt.checks { - walk_if_contains_with_new_expr!(check, pos, schema_def, Expr::Check); - } - (None, schema_def) - } - Stmt::SchemaAttr(schema_attr_expr) => { - walk_if_contains!( - Node::node_with_pos( - Expr::Identifier(Identifier { - names: vec![*schema_attr_expr.name.clone()], - pkgpath: "".to_string(), - ctx: kclvm_ast::ast::ExprContext::Load, - }), - ( - schema_attr_expr.name.filename.clone(), - schema_attr_expr.name.line, - schema_attr_expr.name.column, - schema_attr_expr.name.end_line, - schema_attr_expr.name.end_column, - ), - ), - pos, - schema_def - ); - if schema_attr_expr.ty.contains_pos(pos) { - return ( - build_identifier_from_ty_string(&schema_attr_expr.ty, pos), - schema_def, - ); - } - walk_option_if_contains!(schema_attr_expr.value, pos, schema_def); - for decorator in &schema_attr_expr.decorators { - walk_if_contains_with_new_expr!(decorator, pos, schema_def, Expr::Call); - } - (None, schema_def) - } - Stmt::Rule(rule_stmt) => { - for parent_id in &rule_stmt.parent_rules { - walk_if_contains_with_new_expr!(parent_id, pos, schema_def, Expr::Identifier); - } - for decorator in &rule_stmt.decorators { - walk_if_contains_with_new_expr!(decorator, pos, schema_def, Expr::Call); - } - for check in &rule_stmt.checks { - walk_if_contains_with_new_expr!(check, pos, schema_def, Expr::Check); - } - (None, schema_def) - } - Stmt::Import(_) => (None, schema_def), - } -} - -/// Recursively finds the inner most expr and its schema_def expr if in a schema expr(e.g., schema_attr in schema_expr) -/// in a expr according to the position. -pub(crate) fn inner_most_expr( - expr: &Node, - pos: &KCLPos, - schema_def: Option>, -) -> (Option>, Option>) { - if !expr.contains_pos(pos) { - return (None, None); - } - match &expr.node { - Expr::Identifier(_) => (Some(expr.clone()), schema_def), - Expr::Target(target) => { - for path in &target.paths { - if let MemberOrIndex::Index(index) = path { - if index.contains_pos(pos) { - return (Some(*index.clone()), schema_def); - } - } - } - (Some(expr.clone()), schema_def) - } - Expr::Selector(select_expr) => { - walk_if_contains!(select_expr.value, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::Schema(schema_expr) => { - walk_if_contains_with_new_expr!(schema_expr.name, pos, schema_def, Expr::Identifier); - walk_list_if_contains!(schema_expr.args, pos, schema_def); - - for kwargs in &schema_expr.kwargs { - walk_if_contains_with_new_expr!(kwargs, pos, schema_def, Expr::Keyword); - } - if schema_expr.config.contains_pos(pos) { - return inner_most_expr(&schema_expr.config, pos, Some(expr.clone())); - } - (Some(expr.clone()), schema_def) - } - Expr::Config(config_expr) => { - for item in &config_expr.items { - if item.contains_pos(pos) { - return inner_most_expr_in_config_entry(item, pos, schema_def); - } - } - (Some(expr.clone()), schema_def) - } - Expr::Unary(unary_expr) => { - walk_if_contains!(unary_expr.operand, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::Binary(binary_expr) => { - walk_if_contains!(binary_expr.left, pos, schema_def); - walk_if_contains!(binary_expr.right, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::If(if_expr) => { - walk_if_contains!(if_expr.body, pos, schema_def); - walk_if_contains!(if_expr.cond, pos, schema_def); - walk_if_contains!(if_expr.orelse, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::Call(call_expr) => { - walk_list_if_contains!(call_expr.args, pos, schema_def); - for keyword in &call_expr.keywords { - walk_if_contains_with_new_expr!(keyword, pos, schema_def, Expr::Keyword); - } - walk_if_contains!(call_expr.func, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::Paren(paren_expr) => { - walk_if_contains!(paren_expr.expr, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::Quant(quant_expr) => { - walk_if_contains!(quant_expr.target, pos, schema_def); - for var in &quant_expr.variables { - walk_if_contains_with_new_expr!(var, pos, schema_def, Expr::Identifier); - } - walk_if_contains!(quant_expr.test, pos, schema_def); - walk_option_if_contains!(quant_expr.if_cond, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::List(list_expr) => { - walk_list_if_contains!(list_expr.elts, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::ListIfItem(list_if_item_expr) => { - walk_if_contains!(list_if_item_expr.if_cond, pos, schema_def); - walk_list_if_contains!(list_if_item_expr.exprs, pos, schema_def); - walk_option_if_contains!(list_if_item_expr.orelse, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::ListComp(list_comp_expr) => { - walk_if_contains!(list_comp_expr.elt, pos, schema_def); - for comp_clause in &list_comp_expr.generators { - walk_if_contains_with_new_expr!(comp_clause, pos, schema_def, Expr::CompClause); - } - (Some(expr.clone()), schema_def) - } - Expr::Starred(starred_exor) => { - walk_if_contains!(starred_exor.value, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::DictComp(dict_comp) => { - walk_option_if_contains!(dict_comp.entry.key, pos, schema_def); - walk_if_contains!(dict_comp.entry.value, pos, schema_def); - - for generator in &dict_comp.generators { - if generator.contains_pos(pos) { - walk_if_contains_with_new_expr!(generator, pos, schema_def, Expr::CompClause); - } - } - (Some(expr.clone()), schema_def) - } - Expr::ConfigIfEntry(config_if_entry_expr) => { - walk_if_contains!(config_if_entry_expr.if_cond, pos, schema_def); - for item in &config_if_entry_expr.items { - if item.contains_pos(pos) { - return inner_most_expr_in_config_entry(item, pos, schema_def); - } - } - walk_option_if_contains!(config_if_entry_expr.orelse, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::CompClause(comp_clause) => { - for target in &comp_clause.targets { - walk_if_contains_with_new_expr!(target, pos, schema_def, Expr::Identifier); - } - walk_if_contains!(comp_clause.iter, pos, schema_def); - walk_list_if_contains!(comp_clause.ifs, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::Check(check_expr) => { - walk_if_contains!(check_expr.test, pos, schema_def); - walk_option_if_contains!(check_expr.if_cond, pos, schema_def); - walk_option_if_contains!(check_expr.msg, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::Lambda(lambda_expr) => { - if let Some(args) = &lambda_expr.args { - walk_if_contains_with_new_expr!(args, pos, schema_def, Expr::Arguments); - } - for stmt in &lambda_expr.body { - if stmt.contains_pos(pos) { - return inner_most_expr_in_stmt(&stmt.node, pos, schema_def); - } - } - - (Some(expr.clone()), schema_def) - } - Expr::Subscript(subscript_expr) => { - walk_if_contains!(subscript_expr.value, pos, schema_def); - walk_option_if_contains!(subscript_expr.index, pos, schema_def); - walk_option_if_contains!(subscript_expr.lower, pos, schema_def); - walk_option_if_contains!(subscript_expr.upper, pos, schema_def); - walk_option_if_contains!(subscript_expr.step, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::Keyword(keyword) => { - walk_if_contains_with_new_expr!(keyword.arg, pos, schema_def, Expr::Identifier); - walk_option_if_contains!(keyword.value, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::Arguments(argument) => { - for arg in &argument.args { - walk_if_contains_with_new_expr!(arg, pos, schema_def, Expr::Identifier); - } - for default in &argument.defaults { - walk_option_if_contains!(default, pos, schema_def); - } - for ty in argument.ty_list.iter().flatten() { - if ty.contains_pos(pos) { - return ( - Some(build_identifier_from_string(&node_ref!( - ty.node.to_string(), - ty.pos() - ))), - schema_def, - ); - } - } - (Some(expr.clone()), schema_def) - } - Expr::Compare(compare_expr) => { - walk_if_contains!(compare_expr.left, pos, schema_def); - walk_list_if_contains!(compare_expr.comparators, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::NumberLit(_) => (Some(expr.clone()), schema_def), - Expr::StringLit(_) => (Some(expr.clone()), schema_def), - Expr::NameConstantLit(_) => (Some(expr.clone()), schema_def), - Expr::JoinedString(joined_string) => { - walk_list_if_contains!(joined_string.values, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::FormattedValue(formatted_value) => { - walk_if_contains!(formatted_value.value, pos, schema_def); - (Some(expr.clone()), schema_def) - } - Expr::Missing(_) => (Some(expr.clone()), schema_def), - } -} - -fn inner_most_expr_in_config_entry( - config_entry: &Node, - pos: &KCLPos, - schema_def: Option>, -) -> (Option>, Option>) { - if let Some(key) = &config_entry.node.key { - if key.contains_pos(pos) { - return inner_most_expr(key, pos, schema_def); - } - } - if config_entry.node.value.contains_pos(pos) { - inner_most_expr(&config_entry.node.value, pos, None) - } else { - (None, schema_def) - } -} - -pub(crate) fn is_in_docstring( - program: &Program, - pos: &KCLPos, -) -> Option<(NodeRef, SchemaStmt)> { - match program.pos_to_stmt(pos) { - Some(node) => match node.node.clone() { - Stmt::Schema(schema) => match schema.doc { - Some(ref doc) => { - if doc.contains_pos(pos) { - Some((doc.clone(), schema)) - } else { - None - } - } - None => None, - }, - _ => None, - }, - None => None, - } -} - -/// Build a temp identifier expr with string -fn build_identifier_from_string(s: &NodeRef) -> Node { - Node::node_with_pos( - Expr::Identifier(Identifier { - names: transfer_ident_names( - vec![s.node.clone()], - &( - s.filename.clone(), - s.line, - s.column, - s.end_line, - s.end_column, - ), - ), - pkgpath: "".to_string(), - ctx: kclvm_ast::ast::ExprContext::Load, - }), - ( - s.filename.clone(), - s.line, - s.column, - s.end_line, - s.end_column, - ), - ) -} - -/// Build a temp identifier expr with string -fn build_identifier_from_ty_string(ty: &NodeRef, pos: &KCLPos) -> Option> { - if !ty.contains_pos(pos) { - return None; - } - match &ty.node { - Type::Any => None, - Type::Named(id) => Some(Node::node_with_pos( - Expr::Identifier(id.clone()), - ( - ty.filename.clone(), - ty.line, - ty.column, - ty.end_line, - ty.end_column, - ), - )), - Type::Basic(_) => None, - Type::List(list_ty) => { - if let Some(inner) = &list_ty.inner_type { - if inner.contains_pos(pos) { - return build_identifier_from_ty_string(inner, pos); - } - } - None - } - Type::Dict(dict_ty) => { - if let Some(key_ty) = &dict_ty.key_type { - if key_ty.contains_pos(pos) { - return build_identifier_from_ty_string(key_ty, pos); - } - } - if let Some(value_ty) = &dict_ty.value_type { - if value_ty.contains_pos(pos) { - return build_identifier_from_ty_string(value_ty, pos); - } - } - None - } - Type::Union(union_ty) => { - for ty in &union_ty.type_elements { - if ty.contains_pos(pos) { - return build_identifier_from_ty_string(ty, pos); - } - } - None - } - Type::Literal(_) => None, - Type::Function(_) => None, - } -} diff --git a/kclvm/tools/src/fix/mod.rs b/kclvm/tools/src/fix/mod.rs deleted file mode 100644 index 8d9b8abef..000000000 --- a/kclvm/tools/src/fix/mod.rs +++ /dev/null @@ -1,171 +0,0 @@ -mod replace; -#[cfg(test)] -mod tests; -use anyhow::{ensure, Error}; -use kclvm_error::{diagnostic::Range as KCLRange, Diagnostic}; -use std::collections::HashMap; -use std::fs; -use std::ops::Range; - -/// A structure for handling code fixes. -pub struct CodeFix { - data: replace::Data, -} - -impl CodeFix { - pub fn new(s: &str) -> CodeFix { - CodeFix { - data: replace::Data::new(s.as_bytes()), - } - } - - pub fn apply(&mut self, suggestion: &Suggestion) -> Result<(), Error> { - let snippet = &suggestion.replacement.snippet; - self.data.replace_range( - snippet.range.start, - snippet.range.end.saturating_sub(1), - suggestion.replacement.replacement.as_bytes(), - )?; - Ok(()) - } - - pub fn finish(&self) -> Result { - Ok(String::from_utf8(self.data.to_vec())?) - } -} - -#[derive(Debug, Clone, Hash, PartialEq, Eq)] -/// An error/warning and possible solutions for fixing it -pub struct Suggestion { - pub message: String, - pub replacement: Replacement, -} - -#[derive(Debug, Clone, Hash, PartialEq, Eq)] -pub struct Replacement { - pub snippet: Snippet, - pub replacement: String, -} - -#[derive(Debug, Clone, Hash, PartialEq, Eq)] -pub struct Snippet { - pub file_name: String, - pub range: Range, -} - -pub fn diag_to_suggestion( - diag: Diagnostic, - files: &mut HashMap, -) -> anyhow::Result> { - let mut suggestions = vec![]; - - for msg in &diag.messages { - let replacements = msg - .suggested_replacement - .clone() - .unwrap_or_else(|| vec!["".to_string()]); - let replacement_str = replacements.first().cloned().unwrap_or_default(); - - let file_name = msg.range.0.filename.clone(); - let src = match files.get(&file_name) { - Some(src) => src.clone(), - None => { - let src = fs::read_to_string(&file_name).expect("Unable to read file"); - files.insert(file_name.clone(), src.clone()); - src - } - }; - - suggestions.push(Suggestion { - message: msg.message.clone(), - replacement: Replacement { - snippet: Snippet { - file_name, - range: text_range(src.as_str(), &msg.range)?, - }, - replacement: replacement_str, - }, - }); - } - Ok(suggestions) -} - -fn is_newline_at_index(s: &str, index: usize) -> bool { - let length = s.len(); - - if index >= length { - return false; - } - - let bytes = s.as_bytes(); - - if bytes[index] == b'\n' { - return true; - } - #[cfg(target_os = "windows")] - if bytes[index] == b'\r' && index + 1 < length && bytes[index + 1] == b'\n' { - return true; - } - - false -} - -pub(crate) fn text_range(text: &str, range: &KCLRange) -> anyhow::Result, Error> { - let mut lines_length = vec![]; - let lines_text: Vec<&str> = text.split('\n').collect(); - let mut pre_total_length = 0; - - for line in &lines_text { - lines_length.push(pre_total_length); - pre_total_length += line.len() + "\n".len(); - } - - ensure!( - (range.0.line as usize) <= lines_length.len() - && (range.1.line as usize) <= lines_length.len() - ); - - // The KCL diagnostic line is 1-based and the column is 0-based. - let start = - lines_length.get(range.0.line as usize - 1).unwrap() + range.0.column.unwrap_or(0) as usize; - let mut end = - lines_length.get(range.1.line as usize - 1).unwrap() + range.1.column.unwrap_or(0) as usize; - - if is_newline_at_index(text, end) { - if cfg!(windows) { - end += "\r\n".len() - } else { - end += "\n".len() - } - } - - Ok(Range { start, end }) -} - -pub fn fix(diags: Vec) -> Result<(), Error> { - let mut suggestions = vec![]; - let mut source_code = HashMap::new(); - for diag in diags { - suggestions.extend(diag_to_suggestion(diag, &mut source_code)?) - } - - let mut files = HashMap::new(); - for suggestion in suggestions { - let file = suggestion.replacement.snippet.file_name.clone(); - files.entry(file).or_insert_with(Vec::new).push(suggestion); - } - - for (source_file, suggestions) in &files { - println!("fix file: {:?}", source_file); - let source = fs::read_to_string(source_file)?; - let mut fix = CodeFix::new(&source); - for suggestion in suggestions.iter() { - if let Err(e) = fix.apply(suggestion) { - eprintln!("Failed to apply suggestion to {}: {}", source_file, e); - } - } - let fixes = fix.finish()?; - fs::write(source_file, fixes)?; - } - Ok(()) -} diff --git a/kclvm/tools/src/format/mod.rs b/kclvm/tools/src/format/mod.rs deleted file mode 100644 index d716e424b..000000000 --- a/kclvm/tools/src/format/mod.rs +++ /dev/null @@ -1,94 +0,0 @@ -//! [kclvm_tools::format] module mainly contains some functions of language formatting, -//! the main API function is `format`, which accepts a path to be formatted and -//! formatted options. -//! -//! The basic principle is to call the [kclvm_parser::parse_file] function to parse the -//! AST Module, and then use the AST printer [kclvm_tools::printer::print_ast_module] -//! to print it as source code string. -use anyhow::Result; -use kclvm_ast_pretty::print_ast_module; -use kclvm_parser::get_kcl_files; -use std::path::Path; - -use kclvm_parser::{parse_file_force_errors, parse_single_file}; - -#[cfg(test)] -mod tests; - -/// FormatOptions contains two options: -/// - is_stdout: whether to output the formatted result to stdout. -/// - recursively: whether to recursively traverse a folder and format all KCL files in it. -/// - omit_errors: whether to omit the parse errors when format the KCL code. -#[derive(Debug, Default)] -pub struct FormatOptions { - pub is_stdout: bool, - pub recursively: bool, - pub omit_errors: bool, -} - -/// Formats kcl file or directory path contains kcl files and -/// returns the changed file paths. -/// -/// # Examples -/// -/// ```no_run -/// use kclvm_tools::format::{format, FormatOptions}; -/// -/// // Format a single file. -/// format("path_to_a_single_file.k", &FormatOptions::default()).unwrap(); -/// // Format a folder contains kcl files -/// format("path_to_a_folder", &FormatOptions::default()).unwrap(); -/// ``` -pub fn format>(path: P, opts: &FormatOptions) -> Result> { - let mut changed_paths: Vec = vec![]; - let path_ref = path.as_ref(); - if path_ref.is_dir() { - for file in &get_kcl_files(path, opts.recursively)? { - if format_file(file, opts)? { - changed_paths.push(file.clone()) - } - } - } else if path_ref.is_file() { - let file = path_ref.to_str().unwrap().to_string(); - if format_file(&file, opts)? { - changed_paths.push(file) - } - } - if opts.is_stdout { - let n = changed_paths.len(); - println!( - "KCL format done and {} {} formatted:", - n, - if n <= 1 { "file was" } else { "files were" } - ); - for p in &changed_paths { - println!("{}", p); - } - } - Ok(changed_paths) -} - -/// Formats a file and returns whether the file has been formatted and modified. -pub fn format_file(file: &str, opts: &FormatOptions) -> Result { - let src = std::fs::read_to_string(file)?; - let (source, is_formatted) = format_source(file, &src, opts)?; - if opts.is_stdout { - println!("{}", source); - } else { - std::fs::write(file, &source)? - } - Ok(is_formatted) -} - -/// Formats a code source and returns the formatted source and -/// whether the source is changed. -pub fn format_source(file: &str, src: &str, opts: &FormatOptions) -> Result<(String, bool)> { - let module = if opts.omit_errors { - parse_single_file(file, Some(src.to_string()))?.module - } else { - parse_file_force_errors(file, Some(src.to_string()))? - }; - let formatted_src = print_ast_module(&module); - let is_formatted = src != formatted_src; - Ok((formatted_src, is_formatted)) -} diff --git a/kclvm/tools/src/format/tests.rs b/kclvm/tools/src/format/tests.rs deleted file mode 100644 index bb37ec305..000000000 --- a/kclvm/tools/src/format/tests.rs +++ /dev/null @@ -1,234 +0,0 @@ -use super::*; -use kclvm_parser::parse_file_force_errors; -use pretty_assertions::assert_eq; -use walkdir::WalkDir; - -const FILE_INPUT_SUFFIX: &str = ".input"; -const FILE_OUTPUT_SUFFIX: &str = ".golden"; -const TEST_CASES: &[&str; 23] = &[ - "assert", - "check", - "blankline", - "breakline", - "codelayout", - "collection_if", - "comment", - "comp_for", - "empty", - "import", - "import_only", - "indent", - "inline_comment", - "lambda", - "quant", - "schema", - "string", - "type_alias", - "unary", - "union_types", - "layout_import_stmt", - "different_stmts_line_breaks", - "trailing_comment_collection", - // "list_dict_schema_expr", -]; - -fn read_data(data_name: &str) -> (String, String) { - let src = std::fs::read_to_string(format!( - "./src/format/test_data/format_data/{}{}", - data_name, FILE_INPUT_SUFFIX - )) - .unwrap(); - - ( - format_source("", &src, &Default::default()).unwrap().0, - std::fs::read_to_string(format!( - "./src/format/test_data/format_data/{}{}", - data_name, FILE_OUTPUT_SUFFIX - )) - .unwrap(), - ) -} - -#[test] -fn test_format_source() { - for case in TEST_CASES { - let (data_input, data_output) = read_data(case); - #[cfg(target_os = "windows")] - let data_output = data_output.replace("\r\n", "\n"); - assert_eq!(data_input, data_output, "Test failed on {}", case); - } -} - -#[test] -fn test_format_single_file() { - assert!(format( - "./src/format/test_data/format_path_data/single_file.k", - &FormatOptions::default() - ) - .is_ok()); -} - -#[test] -fn test_format_folder() { - assert!(format( - "./src/format/test_data/format_path_data/folder", - &FormatOptions::default() - ) - .is_ok()); -} - -#[test] -fn test_format_with_stdout_option() { - let opts = FormatOptions { - is_stdout: true, - recursively: false, - omit_errors: false, - }; - let changed_files = format("./src/format/test_data/format_path_data/if.k", &opts).unwrap(); - assert_eq!(changed_files.len(), 1); - let changed_files = format("./src/format/test_data/format_path_data/", &opts).unwrap(); - assert_eq!(changed_files.len(), 1); - let opts = FormatOptions { - is_stdout: true, - recursively: true, - omit_errors: false, - }; - let changed_files = format("./src/format/test_data/format_path_data/", &opts).unwrap(); - assert_eq!(changed_files.len(), 2); -} - -#[test] -fn test_format_with_omit_error_option() { - let opts = FormatOptions { - is_stdout: false, - recursively: false, - omit_errors: true, - }; - let cases = [ - ( - r#"x = { -a: { -b: 1 -c: 2 -} -d: 3 -} -"#, - r#"x = { - a: { - b: 1 - c: 2 - } - d: 3 -} -"#, - ), - ( - r#"x = { -a: { - b: 1 - c: 2 -} -} -"#, - r#"x = { - a: { - b: 1 - c: 2 - } -} -"#, - ), - ( - r#"x = { - a: 1 - b: 2 - c: 3 -} -"#, - r#"x = { - a: 1 - b: 2 - c: 3 -} -"#, - ), - ( - r#"x = { - a: 1 - b: 2 - c: 3 -} -"#, - r#"x = { - a: 1 - b: 2 - c: 3 -} -"#, - ), - ]; - for (code, expected_code) in cases { - let (actual_code, _) = format_source("error_indent.k", code, &opts).unwrap(); - assert_eq!(actual_code, expected_code); - } -} - -#[test] -fn test_format_integration_konfig() -> Result<()> { - let konfig_path = Path::new(".") - .canonicalize()? - .parent() - .unwrap() - .parent() - .unwrap() - .join("test") - .join("integration") - .join("konfig"); - let files = get_files(konfig_path, true, true, ".k"); - for file in &files { - // Skip test and hidden files. - if file.ends_with("_test.k") || file.starts_with('_') { - continue; - } - assert!( - parse_file_force_errors(file, None).is_ok(), - "file {} test format failed", - file - ); - let src = std::fs::read_to_string(file)?; - let (formatted_src, _) = format_source("", &src, &Default::default())?; - let parse_result = parse_file_force_errors("test.k", Some(formatted_src.clone() + "\n")); - assert!( - parse_result.is_ok(), - "file {} test format failed, the formatted source is\n{}\n the parse error is\n{}", - file, - formatted_src, - parse_result.err().unwrap(), - ); - } - Ok(()) -} - -/// Get kcl files from path. -fn get_files>( - path: P, - recursively: bool, - sorted: bool, - suffix: &str, -) -> Vec { - let mut files = vec![]; - for entry in WalkDir::new(path).into_iter().filter_map(|e| e.ok()) { - let path = entry.path(); - if path.is_file() { - let file = path.to_str().unwrap(); - if file.ends_with(suffix) && (recursively || entry.depth() == 1) { - files.push(file.to_string()) - } - } - } - if sorted { - files.sort(); - } - files -} diff --git a/kclvm/tools/src/lint/mod.rs b/kclvm/tools/src/lint/mod.rs deleted file mode 100644 index 470d4de90..000000000 --- a/kclvm/tools/src/lint/mod.rs +++ /dev/null @@ -1,97 +0,0 @@ -use std::sync::Arc; - -use kclvm_error::{Diagnostic, Handler}; -use kclvm_parser::{load_program, LoadProgramOptions, ParseSession}; -use kclvm_primitives::IndexSet; -use kclvm_runtime::PanicInfo; -use kclvm_sema::resolver::resolve_program_with_opts; -#[cfg(test)] -mod tests; - -/// KCL Lint tools API, check a set of files, skips execute, divides and returns diagnostics into error and warning -/// -/// # Parameters -/// -/// `file`: [&str] -/// The File that need to be check -/// -/// `opts`: Option -/// The compilation parameters of KCL, same as the compilation process -/// -/// # Returns -/// -/// result: (IndexSet, IndexSet) -/// Error and warning diagenostics. -/// -/// # Examples -/// -/// ```no_run -/// use kclvm_tools::lint::lint_files; -/// let (errors, warnings) = lint_files(&["test.k"], None); -/// ``` -/// -/// - test.k -/// -/// ```kcl -/// import math -/// schema Person: -/// age: int -/// ``` -/// -/// - return -/// ```no_check -/// error: [] -/// warning: [ -/// Diagnostic { -/// level: Warning -/// messages: [Message { -/// range: ( -/// Position { -/// filename: test.k, -/// line: 1, -/// column: None, -/// }, -/// Position { -/// filename: test.k, -/// line: 1, -/// column: None, -/// }, -/// ), -/// style: Style::Line, -/// message: "Module 'math' imported but unused", -/// note: Some("Consider removing this statement".to_string()), -/// }], -/// code: Some, -/// } -/// ] -/// ``` -pub fn lint_files( - files: &[&str], - opts: Option, -) -> (IndexSet, IndexSet) { - // Parse AST program. - let sess = Arc::new(ParseSession::default()); - let mut opts = opts.unwrap_or_default(); - opts.load_plugins = true; - let mut program = match load_program(sess.clone(), files, Some(opts), None) { - Ok(p) => p.program, - Err(err_str) => { - return Handler::default() - .add_panic_info(&PanicInfo::from(err_str.to_string())) - .classification(); - } - }; - sess.append_diagnostic( - resolve_program_with_opts( - &mut program, - kclvm_sema::resolver::Options { - merge_program: false, - ..Default::default() - }, - None, - ) - .handler - .diagnostics, - ) - .classification() -} diff --git a/kclvm/tools/src/testing/mod.rs b/kclvm/tools/src/testing/mod.rs deleted file mode 100644 index 0e02b00b7..000000000 --- a/kclvm/tools/src/testing/mod.rs +++ /dev/null @@ -1,58 +0,0 @@ -//! [kclvm_tools::testing] module mainly contains some functions of language testing tool. -//! -//! The basic principle of the testing tool is to search for test files in the KCL package -//! that have the suffix "_test.k" and do not start with "_". These test files will be regard -//! as test suites. Within these files, any lambda literals starting with "test_" will be -//! considered as test cases, but these lambda functions should not have any parameters. -//! To perform the testing, the tool compiles the test suite file and its dependencies into an -//! [kclvm_runner::Artifact], which is regard as a new compilation entry point. Then, -//! it executes each test case separately and collects information about the test cases, -//! such as the execution time and whether the test passes or fails. -pub use crate::testing::suite::{load_test_suites, TestSuite}; -use anyhow::{Error, Result}; -use kclvm_primitives::IndexMap; -use kclvm_runner::ExecProgramArgs; -use std::time::Duration; - -mod suite; - -#[cfg(test)] -mod tests; - -/// Trait for running tests. -pub trait TestRun { - type Options; - type Result; - - /// Run the test with the given options and return the result. - fn run(&self, opts: &Self::Options) -> Result; -} - -/// Represents the result of a test. -#[derive(Debug, Default)] -pub struct TestResult { - /// This field stores test case information in an [IndexMap], where the key is a [String] and the value is a [TestCaseInfo] struct. - pub info: IndexMap, -} - -/// Represents information about a test case. -#[derive(Debug, Default)] -pub struct TestCaseInfo { - /// This field stores the log message of the test. - pub log_message: String, - /// This field stores the error associated with the test case, if any. - pub error: Option, - /// This field stores the duration of the test case. - pub duration: Duration, -} - -/// Represents options for running tests. -#[derive(Debug, Default, Clone)] -pub struct TestOptions { - /// This field stores the execution program arguments. - pub exec_args: ExecProgramArgs, - /// This field stores a regular expression for filtering tests to run. - pub run_regexp: String, - /// This field determines whether the test run should stop on the first failure. - pub fail_fast: bool, -} diff --git a/kclvm/tools/src/testing/tests.rs b/kclvm/tools/src/testing/tests.rs deleted file mode 100644 index f183f3bda..000000000 --- a/kclvm/tools/src/testing/tests.rs +++ /dev/null @@ -1,49 +0,0 @@ -use kclvm_ast::ast::Argument; -use kclvm_runner::ExecProgramArgs; - -use crate::testing::TestRun; - -use super::{load_test_suites, TestOptions}; -use std::path::Path; - -#[test] -fn test_load_test_suites_and_run() { - let opts = TestOptions { - exec_args: ExecProgramArgs { - args: vec![Argument { - name: "a".to_string(), - value: "\"a\"".to_string(), - }], - ..Default::default() - }, - ..Default::default() - }; - let suites = load_test_suites( - Path::new(".") - .join("src") - .join("testing") - .join("test_data") - .join("module") - .join("pkg") - .to_str() - .unwrap(), - &opts, - ) - .unwrap(); - assert_eq!(suites.len(), 1); - assert_eq!(suites[0].cases.len(), 3); - let test_result = suites[0].run(&opts).unwrap(); - assert_eq!(test_result.info.len(), 3); - assert!(test_result.info[0].error.is_none()); - assert!(test_result.info[1] - .error - .as_ref() - .unwrap() - .to_string() - .contains("Error"),); - assert!( - test_result.info[2].error.is_none(), - "{:?}", - test_result.info[2].error - ); -} diff --git a/kclvm/tools/src/util/tests.rs b/kclvm/tools/src/util/tests.rs deleted file mode 100644 index f135367a0..000000000 --- a/kclvm/tools/src/util/tests.rs +++ /dev/null @@ -1,257 +0,0 @@ -use std::path::PathBuf; - -use anyhow::{Context, Result}; - -const CARGO_DIR: &str = env!("CARGO_MANIFEST_DIR"); -const REL_PATH: &str = "src/util/test_datas"; -const FILE_TEST_CASES: &[&str] = &["test"]; - -const FILE_EXTENSIONS: &[&str] = &[".json", ".yaml"]; - -const JSON_STR_TEST_CASES: &[&str] = &[r#"{ - "name": "John Doe", - "age": 43, - "address": { - "street": "10 Downing Street", - "city": "London" - }, - "phones": [ - "+44 1234567", - "+44 2345678" - ] -} -"#]; - -const YAML_STR_TEST_CASES: &[&str] = &[r#"languages: - - Ruby - - Perl - - Python -websites: - YAML: yaml.org - Ruby: ruby-lang.org - Python: python.org - Perl: use.perl.org -"#]; - -fn construct_full_path(path: &str) -> Result { - let mut cargo_file_path = PathBuf::from(CARGO_DIR); - cargo_file_path.push(REL_PATH); - cargo_file_path.push(path); - Ok(cargo_file_path - .to_str() - .with_context(|| format!("No such file or directory '{}'", path))? - .to_string()) -} - -mod test_loader { - mod test_data_loader { - use regex::Regex; - - use crate::util::{ - loader::{DataLoader, Loader, LoaderKind}, - tests::{ - construct_full_path, FILE_EXTENSIONS, FILE_TEST_CASES, JSON_STR_TEST_CASES, - YAML_STR_TEST_CASES, - }, - }; - - fn data_loader_from_file(loader_kind: LoaderKind, file_path: &str) -> DataLoader { - let test_case_path = construct_full_path(file_path).unwrap(); - - DataLoader::new_with_file_path(loader_kind, &test_case_path).unwrap() - } - - fn data_loader_from_str(loader_kind: LoaderKind, s: &str) -> DataLoader { - DataLoader::new_with_str(loader_kind, s).unwrap() - } - - #[test] - fn test_new_with_file_path_json() { - for test_case in FILE_TEST_CASES { - let json_loader = data_loader_from_file( - LoaderKind::JSON, - &format!("{}{}", test_case, FILE_EXTENSIONS[0]), - ); - - #[cfg(not(target_os = "windows"))] - let got_data = json_loader.get_data(); - #[cfg(target_os = "windows")] - let got_data = json_loader.get_data().replace("\r\n", "\n"); - - assert_eq!( - got_data, - r#"{ - "name": "John Doe", - "age": 43, - "address": { - "street": "10 Downing Street", - "city": "London" - }, - "phones": [ - "+44 1234567", - "+44 2345678" - ] -} -"# - ); - } - } - - #[test] - fn test_new_with_str_json() { - for test_case in JSON_STR_TEST_CASES { - let json_loader = data_loader_from_str(LoaderKind::JSON, test_case); - assert_eq!(json_loader.get_data(), *test_case); - } - } - - #[test] - fn test_new_with_file_path_yaml() { - for test_case in FILE_TEST_CASES { - let yaml_loader = data_loader_from_file( - LoaderKind::YAML, - &format!("{}{}", test_case, FILE_EXTENSIONS[1]), - ); - - #[cfg(not(target_os = "windows"))] - let got_data = yaml_loader.get_data(); - #[cfg(target_os = "windows")] - let got_data = yaml_loader.get_data().replace("\r\n", "\n"); - - assert_eq!( - got_data, - r#"languages: - - Ruby - - Perl - - Python -websites: - YAML: yaml.org - Ruby: ruby-lang.org - Python: python.org - Perl: use.perl.org -"# - ); - } - } - - #[test] - fn test_new_with_str_yaml() { - for test_case in YAML_STR_TEST_CASES { - let yaml_loader = data_loader_from_str(LoaderKind::JSON, test_case); - assert_eq!(yaml_loader.get_data(), *test_case); - } - } - - #[test] - fn test_load() { - let yaml_loader = data_loader_from_file( - LoaderKind::YAML, - &format!("{}{}", FILE_TEST_CASES[0], FILE_EXTENSIONS[1]), - ); - - let got_yaml = - >::load(&yaml_loader).unwrap(); - let expect_yaml: serde_yaml_ng::Value = - serde_yaml_ng::from_str(yaml_loader.get_data()).unwrap(); - - assert_eq!(got_yaml, expect_yaml); - - let json_loader = data_loader_from_file( - LoaderKind::JSON, - &format!("{}{}", FILE_TEST_CASES[0], FILE_EXTENSIONS[0]), - ); - - let got_json = >::load(&json_loader).unwrap(); - let expect_json: serde_json::Value = - serde_json::from_str(json_loader.get_data()).unwrap(); - - assert_eq!(got_json, expect_json); - } - - #[test] - fn test_load_invalid() { - let yaml_loader = data_loader_from_file( - LoaderKind::YAML, - &format!("{}{}", FILE_TEST_CASES[0], FILE_EXTENSIONS[1]), - ); - - match >::load(&yaml_loader) { - Ok(_) => { - panic!("unreachable") - } - Err(err) => { - assert_eq!(format!("{:?}", err), "Failed to String to Json Value"); - } - } - - let json_loader = data_loader_from_file( - LoaderKind::JSON, - &format!("{}{}", FILE_TEST_CASES[0], FILE_EXTENSIONS[0]), - ); - - match >::load(&json_loader) { - Ok(_) => { - panic!("unreachable") - } - Err(err) => { - assert_eq!(format!("{:?}", err), "Failed to String to Yaml Value"); - } - } - } - - #[test] - fn new_with_file_path_invalid() { - match DataLoader::new_with_file_path(LoaderKind::JSON, "invalid file path") { - Ok(_) => { - panic!("unreachable") - } - Err(err) => { - assert!( - Regex::new(r"^Failed to Load 'invalid file path'\n\nCaused by:.*") - .unwrap() - .is_match(&format!("{:?}", err)) - ); - } - }; - } - - #[test] - fn test_invalid_file() { - let invalid_json_file_path = construct_full_path("test_invalid.json").unwrap(); - let json_loader = - DataLoader::new_with_file_path(LoaderKind::JSON, &invalid_json_file_path).unwrap(); - - match >::load(&json_loader) { - Ok(_) => { - panic!("unreachable") - } - Err(err) => { - #[cfg(not(target_os = "windows"))] - let got_err = format!("{:?}", err); - #[cfg(target_os = "windows")] - let got_err = format!("{:?}", err).replace("\r\n", "\n"); - - assert_eq!(got_err, "Failed to String 'languages:\n - Ruby\n - Perl\n - Python \nwebsites:\n YAML: yaml.org \n Ruby: ruby-lang.org \n Python: python.org \n Perl: use.perl.org' to Json\n\nCaused by:\n expected value at line 1 column 1"); - } - } - - let invalid_yaml_file_path = construct_full_path("test_invalid.yaml").unwrap(); - let yaml_loader = - DataLoader::new_with_file_path(LoaderKind::YAML, &invalid_yaml_file_path).unwrap(); - - match >::load(&yaml_loader) { - Ok(_) => { - panic!("unreachable") - } - Err(err) => { - #[cfg(not(target_os = "windows"))] - let got_err = format!("{:?}", err); - #[cfg(target_os = "windows")] - let got_err = format!("{:?}", err).replace("\r\n", "\n"); - - assert_eq!(got_err, "Failed to String '\"name\": \"John Doe\",\ninvalid\n' to Yaml\n\nCaused by:\n did not find expected key at line 1 column 19, while parsing a block mapping"); - } - } - } - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-2.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-2.snap deleted file mode 100644 index 4f1c36430..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-2.snap +++ /dev/null @@ -1,159 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "/simple.k.json", - "line": 1, - "node": { - "args": [], - "config": { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "/simple.k.json", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "/simple.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 9, - "end_line": 3, - "filename": "/simple.k.json", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"age\"", - "type": "StringLit", - "value": "age" - } - }, - "operation": "Union", - "value": { - "column": 11, - "end_column": 13, - "end_line": 3, - "filename": "/simple.k.json", - "line": 3, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 18 - } - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "/simple.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 13, - "end_line": 4, - "filename": "/simple.k.json", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"message\"", - "type": "StringLit", - "value": "message" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 30, - "end_line": 4, - "filename": "/simple.k.json", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"This is Alice\"", - "type": "StringLit", - "value": "This is Alice" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "/simple.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 2, - "filename": "/simple.k.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"name\"", - "type": "StringLit", - "value": "name" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 19, - "end_line": 2, - "filename": "/simple.k.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"Alice\"", - "type": "StringLit", - "value": "Alice" - } - } - } - } - ], - "type": "Config" - } - }, - "kwargs": [], - "name": { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "/simple.k.json", - "line": 1, - "node": { - "ctx": "Load", - "names": [ - { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "/simple.k.json", - "line": 1, - "node": "simple" - } - ], - "pkgpath": "" - } - }, - "type": "Schema" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-3.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-3.snap deleted file mode 100644 index 19165aa64..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-3.snap +++ /dev/null @@ -1,19 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 1, - "filename": "/plain_value.k.json", - "line": 1, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 1 - } - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-4.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-4.snap deleted file mode 100644 index d235d60bb..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-4.snap +++ /dev/null @@ -1,172 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 7, - "filename": "/list.k.json", - "line": 1, - "node": { - "ctx": "Load", - "elts": [ - { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "/list.k.json", - "line": 2, - "node": { - "args": [], - "config": { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "/list.k.json", - "line": 2, - "node": { - "items": [ - { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "/list.k.json", - "line": 2, - "node": { - "key": { - "column": 8, - "end_column": 13, - "end_line": 4, - "filename": "/list.k.json", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"age\"", - "type": "StringLit", - "value": "age" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 17, - "end_line": 4, - "filename": "/list.k.json", - "line": 4, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 18 - } - } - } - } - }, - { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "/list.k.json", - "line": 2, - "node": { - "key": { - "column": 8, - "end_column": 17, - "end_line": 5, - "filename": "/list.k.json", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"message\"", - "type": "StringLit", - "value": "message" - } - }, - "operation": "Union", - "value": { - "column": 19, - "end_column": 34, - "end_line": 5, - "filename": "/list.k.json", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"This is Alice\"", - "type": "StringLit", - "value": "This is Alice" - } - } - } - }, - { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "/list.k.json", - "line": 2, - "node": { - "key": { - "column": 8, - "end_column": 14, - "end_line": 3, - "filename": "/list.k.json", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"name\"", - "type": "StringLit", - "value": "name" - } - }, - "operation": "Union", - "value": { - "column": 16, - "end_column": 23, - "end_line": 3, - "filename": "/list.k.json", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"Alice\"", - "type": "StringLit", - "value": "Alice" - } - } - } - } - ], - "type": "Config" - } - }, - "kwargs": [], - "name": { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "/list.k.json", - "line": 2, - "node": { - "ctx": "Load", - "names": [ - { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "/list.k.json", - "line": 2, - "node": "list" - } - ], - "pkgpath": "" - } - }, - "type": "Schema" - } - } - ], - "type": "List" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-5.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-5.snap deleted file mode 100644 index 4e27587c0..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-5.snap +++ /dev/null @@ -1,420 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "args": [], - "config": { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 9, - "end_line": 3, - "filename": "/complex.k.json", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"age\"", - "type": "StringLit", - "value": "age" - } - }, - "operation": "Union", - "value": { - "column": 11, - "end_column": 13, - "end_line": 3, - "filename": "/complex.k.json", - "line": 3, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 18 - } - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 5, - "filename": "/complex.k.json", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"data\"", - "type": "StringLit", - "value": "data" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 5, - "end_line": 8, - "filename": "/complex.k.json", - "line": 5, - "node": { - "items": [ - { - "column": 12, - "end_column": 5, - "end_line": 8, - "filename": "/complex.k.json", - "line": 5, - "node": { - "key": { - "column": 8, - "end_column": 12, - "end_line": 6, - "filename": "/complex.k.json", - "line": 6, - "node": { - "is_long_string": false, - "raw_value": "\"id\"", - "type": "StringLit", - "value": "id" - } - }, - "operation": "Union", - "value": { - "column": 14, - "end_column": 15, - "end_line": 6, - "filename": "/complex.k.json", - "line": 6, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 1 - } - } - } - } - }, - { - "column": 12, - "end_column": 5, - "end_line": 8, - "filename": "/complex.k.json", - "line": 5, - "node": { - "key": { - "column": 8, - "end_column": 15, - "end_line": 7, - "filename": "/complex.k.json", - "line": 7, - "node": { - "is_long_string": false, - "raw_value": "\"value\"", - "type": "StringLit", - "value": "value" - } - }, - "operation": "Union", - "value": { - "column": 17, - "end_column": 25, - "end_line": 7, - "filename": "/complex.k.json", - "line": 7, - "node": { - "is_long_string": false, - "raw_value": "\"value1\"", - "type": "StringLit", - "value": "value1" - } - } - } - } - ], - "type": "Config" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 8, - "end_line": 12, - "filename": "/complex.k.json", - "line": 12, - "node": { - "is_long_string": false, - "raw_value": "\"hc\"", - "type": "StringLit", - "value": "hc" - } - }, - "operation": "Union", - "value": { - "column": 10, - "end_column": 19, - "end_line": 12, - "filename": "/complex.k.json", - "line": 12, - "node": { - "ctx": "Load", - "elts": [ - { - "column": 11, - "end_column": 12, - "end_line": 12, - "filename": "/complex.k.json", - "line": 12, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 1 - } - } - }, - { - "column": 14, - "end_column": 15, - "end_line": 12, - "filename": "/complex.k.json", - "line": 12, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 2 - } - } - }, - { - "column": 17, - "end_column": 18, - "end_line": 12, - "filename": "/complex.k.json", - "line": 12, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 3 - } - } - } - ], - "type": "List" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 12, - "end_line": 9, - "filename": "/complex.k.json", - "line": 9, - "node": { - "is_long_string": false, - "raw_value": "\"labels\"", - "type": "StringLit", - "value": "labels" - } - }, - "operation": "Union", - "value": { - "column": 14, - "end_column": 5, - "end_line": 11, - "filename": "/complex.k.json", - "line": 9, - "node": { - "items": [ - { - "column": 14, - "end_column": 5, - "end_line": 11, - "filename": "/complex.k.json", - "line": 9, - "node": { - "key": { - "column": 8, - "end_column": 13, - "end_line": 10, - "filename": "/complex.k.json", - "line": 10, - "node": { - "is_long_string": false, - "raw_value": "\"key\"", - "type": "StringLit", - "value": "key" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 22, - "end_line": 10, - "filename": "/complex.k.json", - "line": 10, - "node": { - "is_long_string": false, - "raw_value": "\"value\"", - "type": "StringLit", - "value": "value" - } - } - } - } - ], - "type": "Config" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 13, - "end_line": 4, - "filename": "/complex.k.json", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"message\"", - "type": "StringLit", - "value": "message" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 30, - "end_line": 4, - "filename": "/complex.k.json", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"This is Alice\"", - "type": "StringLit", - "value": "This is Alice" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 2, - "filename": "/complex.k.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"name\"", - "type": "StringLit", - "value": "name" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 19, - "end_line": 2, - "filename": "/complex.k.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"Alice\"", - "type": "StringLit", - "value": "Alice" - } - } - } - } - ], - "type": "Config" - } - }, - "kwargs": [], - "name": { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "ctx": "Load", - "names": [ - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": "complex" - } - ], - "pkgpath": "" - } - }, - "type": "Schema" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-6.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-6.snap deleted file mode 100644 index b4c6df045..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-6.snap +++ /dev/null @@ -1,83 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_null.json", - "line": 1, - "node": { - "args": [], - "config": { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_null.json", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_null.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 16, - "end_line": 2, - "filename": "/only_with_null.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"null_value\"", - "type": "StringLit", - "value": "null_value" - } - }, - "operation": "Union", - "value": { - "column": 18, - "end_column": 22, - "end_line": 2, - "filename": "/only_with_null.json", - "line": 2, - "node": { - "type": "NameConstantLit", - "value": "None" - } - } - } - } - ], - "type": "Config" - } - }, - "kwargs": [], - "name": { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_null.json", - "line": 1, - "node": { - "ctx": "Load", - "names": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_null.json", - "line": 1, - "node": "only_with_null" - } - ], - "pkgpath": "" - } - }, - "type": "Schema" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-7.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-7.snap deleted file mode 100644 index f854f561b..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-7.snap +++ /dev/null @@ -1,83 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_bool.json", - "line": 1, - "node": { - "args": [], - "config": { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_bool.json", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_bool.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 2, - "filename": "/only_with_bool.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"flag\"", - "type": "StringLit", - "value": "flag" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 16, - "end_line": 2, - "filename": "/only_with_bool.json", - "line": 2, - "node": { - "type": "NameConstantLit", - "value": "True" - } - } - } - } - ], - "type": "Config" - } - }, - "kwargs": [], - "name": { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_bool.json", - "line": 1, - "node": { - "ctx": "Load", - "names": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_bool.json", - "line": 1, - "node": "only_with_bool" - } - ], - "pkgpath": "" - } - }, - "type": "Schema" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-8.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-8.snap deleted file mode 100644 index 13a23a65e..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath-8.snap +++ /dev/null @@ -1,87 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_float.json", - "line": 1, - "node": { - "args": [], - "config": { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_float.json", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_float.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 17, - "end_line": 2, - "filename": "/only_with_float.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"float_value\"", - "type": "StringLit", - "value": "float_value" - } - }, - "operation": "Union", - "value": { - "column": 19, - "end_column": 23, - "end_line": 2, - "filename": "/only_with_float.json", - "line": 2, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Float", - "value": 0.33 - } - } - } - } - } - ], - "type": "Config" - } - }, - "kwargs": [], - "name": { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_float.json", - "line": 1, - "node": { - "ctx": "Load", - "names": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_float.json", - "line": 1, - "node": "only_with_float" - } - ], - "pkgpath": "" - } - }, - "type": "Schema" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath.snap deleted file mode 100644 index b45462c7d..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_filepath.snap +++ /dev/null @@ -1,292 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "/test.k.json", - "line": 1, - "node": { - "args": [], - "config": { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "/test.k.json", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "/test.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 13, - "end_line": 4, - "filename": "/test.k.json", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"address\"", - "type": "StringLit", - "value": "address" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 5, - "end_line": 7, - "filename": "/test.k.json", - "line": 4, - "node": { - "items": [ - { - "column": 15, - "end_column": 5, - "end_line": 7, - "filename": "/test.k.json", - "line": 4, - "node": { - "key": { - "column": 8, - "end_column": 14, - "end_line": 6, - "filename": "/test.k.json", - "line": 6, - "node": { - "is_long_string": false, - "raw_value": "\"city\"", - "type": "StringLit", - "value": "city" - } - }, - "operation": "Union", - "value": { - "column": 16, - "end_column": 24, - "end_line": 6, - "filename": "/test.k.json", - "line": 6, - "node": { - "is_long_string": false, - "raw_value": "\"London\"", - "type": "StringLit", - "value": "London" - } - } - } - }, - { - "column": 15, - "end_column": 5, - "end_line": 7, - "filename": "/test.k.json", - "line": 4, - "node": { - "key": { - "column": 8, - "end_column": 16, - "end_line": 5, - "filename": "/test.k.json", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"street\"", - "type": "StringLit", - "value": "street" - } - }, - "operation": "Union", - "value": { - "column": 18, - "end_column": 37, - "end_line": 5, - "filename": "/test.k.json", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"10 Downing Street\"", - "type": "StringLit", - "value": "10 Downing Street" - } - } - } - } - ], - "type": "Config" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "/test.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 9, - "end_line": 3, - "filename": "/test.k.json", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"age\"", - "type": "StringLit", - "value": "age" - } - }, - "operation": "Union", - "value": { - "column": 11, - "end_column": 13, - "end_line": 3, - "filename": "/test.k.json", - "line": 3, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 43 - } - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "/test.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 2, - "filename": "/test.k.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"name\"", - "type": "StringLit", - "value": "name" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 22, - "end_line": 2, - "filename": "/test.k.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"John Doe\"", - "type": "StringLit", - "value": "John Doe" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "/test.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 12, - "end_line": 8, - "filename": "/test.k.json", - "line": 8, - "node": { - "is_long_string": false, - "raw_value": "\"phones\"", - "type": "StringLit", - "value": "phones" - } - }, - "operation": "Union", - "value": { - "column": 14, - "end_column": 5, - "end_line": 11, - "filename": "/test.k.json", - "line": 8, - "node": { - "ctx": "Load", - "elts": [ - { - "column": 8, - "end_column": 21, - "end_line": 9, - "filename": "/test.k.json", - "line": 9, - "node": { - "is_long_string": false, - "raw_value": "\"+44 1234567\"", - "type": "StringLit", - "value": "+44 1234567" - } - }, - { - "column": 8, - "end_column": 21, - "end_line": 10, - "filename": "/test.k.json", - "line": 10, - "node": { - "is_long_string": false, - "raw_value": "\"+44 2345678\"", - "type": "StringLit", - "value": "+44 2345678" - } - } - ], - "type": "List" - } - } - } - } - ], - "type": "Config" - } - }, - "kwargs": [], - "name": { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "/test.k.json", - "line": 1, - "node": { - "ctx": "Load", - "names": [ - { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "/test.k.json", - "line": 1, - "node": "test" - } - ], - "pkgpath": "" - } - }, - "type": "Schema" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-2.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-2.snap deleted file mode 100644 index a063aa90f..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-2.snap +++ /dev/null @@ -1,159 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "", - "line": 1, - "node": { - "args": [], - "config": { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 9, - "end_line": 3, - "filename": "", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"age\"", - "type": "StringLit", - "value": "age" - } - }, - "operation": "Union", - "value": { - "column": 11, - "end_column": 13, - "end_line": 3, - "filename": "", - "line": 3, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 18 - } - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 13, - "end_line": 4, - "filename": "", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"message\"", - "type": "StringLit", - "value": "message" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 30, - "end_line": 4, - "filename": "", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"This is Alice\"", - "type": "StringLit", - "value": "This is Alice" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 2, - "filename": "", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"name\"", - "type": "StringLit", - "value": "name" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 19, - "end_line": 2, - "filename": "", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"Alice\"", - "type": "StringLit", - "value": "Alice" - } - } - } - } - ], - "type": "Config" - } - }, - "kwargs": [], - "name": { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "", - "line": 1, - "node": { - "ctx": "Load", - "names": [ - { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "", - "line": 1, - "node": "simple" - } - ], - "pkgpath": "" - } - }, - "type": "Schema" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-3.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-3.snap deleted file mode 100644 index 1d2ef3c01..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-3.snap +++ /dev/null @@ -1,19 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 1, - "filename": "", - "line": 1, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 1 - } - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-4.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-4.snap deleted file mode 100644 index 2ed630993..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-4.snap +++ /dev/null @@ -1,172 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 7, - "filename": "", - "line": 1, - "node": { - "ctx": "Load", - "elts": [ - { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "", - "line": 2, - "node": { - "args": [], - "config": { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "", - "line": 2, - "node": { - "items": [ - { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "", - "line": 2, - "node": { - "key": { - "column": 8, - "end_column": 13, - "end_line": 4, - "filename": "", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"age\"", - "type": "StringLit", - "value": "age" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 17, - "end_line": 4, - "filename": "", - "line": 4, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 18 - } - } - } - } - }, - { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "", - "line": 2, - "node": { - "key": { - "column": 8, - "end_column": 17, - "end_line": 5, - "filename": "", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"message\"", - "type": "StringLit", - "value": "message" - } - }, - "operation": "Union", - "value": { - "column": 19, - "end_column": 34, - "end_line": 5, - "filename": "", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"This is Alice\"", - "type": "StringLit", - "value": "This is Alice" - } - } - } - }, - { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "", - "line": 2, - "node": { - "key": { - "column": 8, - "end_column": 14, - "end_line": 3, - "filename": "", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"name\"", - "type": "StringLit", - "value": "name" - } - }, - "operation": "Union", - "value": { - "column": 16, - "end_column": 23, - "end_line": 3, - "filename": "", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"Alice\"", - "type": "StringLit", - "value": "Alice" - } - } - } - } - ], - "type": "Config" - } - }, - "kwargs": [], - "name": { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "", - "line": 2, - "node": { - "ctx": "Load", - "names": [ - { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "", - "line": 2, - "node": "list" - } - ], - "pkgpath": "" - } - }, - "type": "Schema" - } - } - ], - "type": "List" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-5.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-5.snap deleted file mode 100644 index 5ce3d0ea9..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-5.snap +++ /dev/null @@ -1,420 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "", - "line": 1, - "node": { - "args": [], - "config": { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 9, - "end_line": 3, - "filename": "", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"age\"", - "type": "StringLit", - "value": "age" - } - }, - "operation": "Union", - "value": { - "column": 11, - "end_column": 13, - "end_line": 3, - "filename": "", - "line": 3, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 18 - } - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 5, - "filename": "", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"data\"", - "type": "StringLit", - "value": "data" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 5, - "end_line": 8, - "filename": "", - "line": 5, - "node": { - "items": [ - { - "column": 12, - "end_column": 5, - "end_line": 8, - "filename": "", - "line": 5, - "node": { - "key": { - "column": 8, - "end_column": 12, - "end_line": 6, - "filename": "", - "line": 6, - "node": { - "is_long_string": false, - "raw_value": "\"id\"", - "type": "StringLit", - "value": "id" - } - }, - "operation": "Union", - "value": { - "column": 14, - "end_column": 15, - "end_line": 6, - "filename": "", - "line": 6, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 1 - } - } - } - } - }, - { - "column": 12, - "end_column": 5, - "end_line": 8, - "filename": "", - "line": 5, - "node": { - "key": { - "column": 8, - "end_column": 15, - "end_line": 7, - "filename": "", - "line": 7, - "node": { - "is_long_string": false, - "raw_value": "\"value\"", - "type": "StringLit", - "value": "value" - } - }, - "operation": "Union", - "value": { - "column": 17, - "end_column": 25, - "end_line": 7, - "filename": "", - "line": 7, - "node": { - "is_long_string": false, - "raw_value": "\"value1\"", - "type": "StringLit", - "value": "value1" - } - } - } - } - ], - "type": "Config" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 8, - "end_line": 12, - "filename": "", - "line": 12, - "node": { - "is_long_string": false, - "raw_value": "\"hc\"", - "type": "StringLit", - "value": "hc" - } - }, - "operation": "Union", - "value": { - "column": 10, - "end_column": 19, - "end_line": 12, - "filename": "", - "line": 12, - "node": { - "ctx": "Load", - "elts": [ - { - "column": 11, - "end_column": 12, - "end_line": 12, - "filename": "", - "line": 12, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 1 - } - } - }, - { - "column": 14, - "end_column": 15, - "end_line": 12, - "filename": "", - "line": 12, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 2 - } - } - }, - { - "column": 17, - "end_column": 18, - "end_line": 12, - "filename": "", - "line": 12, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 3 - } - } - } - ], - "type": "List" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 12, - "end_line": 9, - "filename": "", - "line": 9, - "node": { - "is_long_string": false, - "raw_value": "\"labels\"", - "type": "StringLit", - "value": "labels" - } - }, - "operation": "Union", - "value": { - "column": 14, - "end_column": 5, - "end_line": 11, - "filename": "", - "line": 9, - "node": { - "items": [ - { - "column": 14, - "end_column": 5, - "end_line": 11, - "filename": "", - "line": 9, - "node": { - "key": { - "column": 8, - "end_column": 13, - "end_line": 10, - "filename": "", - "line": 10, - "node": { - "is_long_string": false, - "raw_value": "\"key\"", - "type": "StringLit", - "value": "key" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 22, - "end_line": 10, - "filename": "", - "line": 10, - "node": { - "is_long_string": false, - "raw_value": "\"value\"", - "type": "StringLit", - "value": "value" - } - } - } - } - ], - "type": "Config" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 13, - "end_line": 4, - "filename": "", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"message\"", - "type": "StringLit", - "value": "message" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 30, - "end_line": 4, - "filename": "", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"This is Alice\"", - "type": "StringLit", - "value": "This is Alice" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 2, - "filename": "", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"name\"", - "type": "StringLit", - "value": "name" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 19, - "end_line": 2, - "filename": "", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"Alice\"", - "type": "StringLit", - "value": "Alice" - } - } - } - } - ], - "type": "Config" - } - }, - "kwargs": [], - "name": { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "", - "line": 1, - "node": { - "ctx": "Load", - "names": [ - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "", - "line": 1, - "node": "complex" - } - ], - "pkgpath": "" - } - }, - "type": "Schema" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-6.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-6.snap deleted file mode 100644 index a13001bb6..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-6.snap +++ /dev/null @@ -1,83 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": { - "args": [], - "config": { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 16, - "end_line": 2, - "filename": "", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"null_value\"", - "type": "StringLit", - "value": "null_value" - } - }, - "operation": "Union", - "value": { - "column": 18, - "end_column": 22, - "end_line": 2, - "filename": "", - "line": 2, - "node": { - "type": "NameConstantLit", - "value": "None" - } - } - } - } - ], - "type": "Config" - } - }, - "kwargs": [], - "name": { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": { - "ctx": "Load", - "names": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": "only_with_null" - } - ], - "pkgpath": "" - } - }, - "type": "Schema" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-7.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-7.snap deleted file mode 100644 index 41b75418e..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-7.snap +++ /dev/null @@ -1,83 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": { - "args": [], - "config": { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 2, - "filename": "", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"flag\"", - "type": "StringLit", - "value": "flag" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 16, - "end_line": 2, - "filename": "", - "line": 2, - "node": { - "type": "NameConstantLit", - "value": "True" - } - } - } - } - ], - "type": "Config" - } - }, - "kwargs": [], - "name": { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": { - "ctx": "Load", - "names": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": "only_with_bool" - } - ], - "pkgpath": "" - } - }, - "type": "Schema" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-8.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-8.snap deleted file mode 100644 index 5d2391c89..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str-8.snap +++ /dev/null @@ -1,87 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": { - "args": [], - "config": { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 17, - "end_line": 2, - "filename": "", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"float_value\"", - "type": "StringLit", - "value": "float_value" - } - }, - "operation": "Union", - "value": { - "column": 19, - "end_column": 23, - "end_line": 2, - "filename": "", - "line": 2, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Float", - "value": 0.33 - } - } - } - } - } - ], - "type": "Config" - } - }, - "kwargs": [], - "name": { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": { - "ctx": "Load", - "names": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "", - "line": 1, - "node": "only_with_float" - } - ], - "pkgpath": "" - } - }, - "type": "Schema" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str.snap deleted file mode 100644 index 5c11935d5..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_json_with_str.snap +++ /dev/null @@ -1,292 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "", - "line": 1, - "node": { - "args": [], - "config": { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 13, - "end_line": 4, - "filename": "", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"address\"", - "type": "StringLit", - "value": "address" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 5, - "end_line": 7, - "filename": "", - "line": 4, - "node": { - "items": [ - { - "column": 15, - "end_column": 5, - "end_line": 7, - "filename": "", - "line": 4, - "node": { - "key": { - "column": 8, - "end_column": 14, - "end_line": 6, - "filename": "", - "line": 6, - "node": { - "is_long_string": false, - "raw_value": "\"city\"", - "type": "StringLit", - "value": "city" - } - }, - "operation": "Union", - "value": { - "column": 16, - "end_column": 24, - "end_line": 6, - "filename": "", - "line": 6, - "node": { - "is_long_string": false, - "raw_value": "\"London\"", - "type": "StringLit", - "value": "London" - } - } - } - }, - { - "column": 15, - "end_column": 5, - "end_line": 7, - "filename": "", - "line": 4, - "node": { - "key": { - "column": 8, - "end_column": 16, - "end_line": 5, - "filename": "", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"street\"", - "type": "StringLit", - "value": "street" - } - }, - "operation": "Union", - "value": { - "column": 18, - "end_column": 37, - "end_line": 5, - "filename": "", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"10 Downing Street\"", - "type": "StringLit", - "value": "10 Downing Street" - } - } - } - } - ], - "type": "Config" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 9, - "end_line": 3, - "filename": "", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"age\"", - "type": "StringLit", - "value": "age" - } - }, - "operation": "Union", - "value": { - "column": 11, - "end_column": 13, - "end_line": 3, - "filename": "", - "line": 3, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 43 - } - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 2, - "filename": "", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"name\"", - "type": "StringLit", - "value": "name" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 22, - "end_line": 2, - "filename": "", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"John Doe\"", - "type": "StringLit", - "value": "John Doe" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 12, - "end_line": 8, - "filename": "", - "line": 8, - "node": { - "is_long_string": false, - "raw_value": "\"phones\"", - "type": "StringLit", - "value": "phones" - } - }, - "operation": "Union", - "value": { - "column": 14, - "end_column": 5, - "end_line": 11, - "filename": "", - "line": 8, - "node": { - "ctx": "Load", - "elts": [ - { - "column": 8, - "end_column": 21, - "end_line": 9, - "filename": "", - "line": 9, - "node": { - "is_long_string": false, - "raw_value": "\"+44 1234567\"", - "type": "StringLit", - "value": "+44 1234567" - } - }, - { - "column": 8, - "end_column": 21, - "end_line": 10, - "filename": "", - "line": 10, - "node": { - "is_long_string": false, - "raw_value": "\"+44 2345678\"", - "type": "StringLit", - "value": "+44 2345678" - } - } - ], - "type": "List" - } - } - } - } - ], - "type": "Config" - } - }, - "kwargs": [], - "name": { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "", - "line": 1, - "node": { - "ctx": "Load", - "names": [ - { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "", - "line": 1, - "node": "test" - } - ], - "pkgpath": "" - } - }, - "type": "Schema" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-2.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-2.snap deleted file mode 100644 index b9305a4e6..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-2.snap +++ /dev/null @@ -1,126 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "/simple.k.json", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "/simple.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 9, - "end_line": 3, - "filename": "/simple.k.json", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"age\"", - "type": "StringLit", - "value": "age" - } - }, - "operation": "Union", - "value": { - "column": 11, - "end_column": 13, - "end_line": 3, - "filename": "/simple.k.json", - "line": 3, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 18 - } - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "/simple.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 13, - "end_line": 4, - "filename": "/simple.k.json", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"message\"", - "type": "StringLit", - "value": "message" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 30, - "end_line": 4, - "filename": "/simple.k.json", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"This is Alice\"", - "type": "StringLit", - "value": "This is Alice" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 5, - "filename": "/simple.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 2, - "filename": "/simple.k.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"name\"", - "type": "StringLit", - "value": "name" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 19, - "end_line": 2, - "filename": "/simple.k.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"Alice\"", - "type": "StringLit", - "value": "Alice" - } - } - } - } - ], - "type": "Config" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-3.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-3.snap deleted file mode 100644 index 19165aa64..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-3.snap +++ /dev/null @@ -1,19 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 1, - "filename": "/plain_value.k.json", - "line": 1, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 1 - } - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-4.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-4.snap deleted file mode 100644 index ffb0c638c..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-4.snap +++ /dev/null @@ -1,139 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 7, - "filename": "/list.k.json", - "line": 1, - "node": { - "ctx": "Load", - "elts": [ - { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "/list.k.json", - "line": 2, - "node": { - "items": [ - { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "/list.k.json", - "line": 2, - "node": { - "key": { - "column": 8, - "end_column": 13, - "end_line": 4, - "filename": "/list.k.json", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"age\"", - "type": "StringLit", - "value": "age" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 17, - "end_line": 4, - "filename": "/list.k.json", - "line": 4, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 18 - } - } - } - } - }, - { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "/list.k.json", - "line": 2, - "node": { - "key": { - "column": 8, - "end_column": 17, - "end_line": 5, - "filename": "/list.k.json", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"message\"", - "type": "StringLit", - "value": "message" - } - }, - "operation": "Union", - "value": { - "column": 19, - "end_column": 34, - "end_line": 5, - "filename": "/list.k.json", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"This is Alice\"", - "type": "StringLit", - "value": "This is Alice" - } - } - } - }, - { - "column": 4, - "end_column": 5, - "end_line": 6, - "filename": "/list.k.json", - "line": 2, - "node": { - "key": { - "column": 8, - "end_column": 14, - "end_line": 3, - "filename": "/list.k.json", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"name\"", - "type": "StringLit", - "value": "name" - } - }, - "operation": "Union", - "value": { - "column": 16, - "end_column": 23, - "end_line": 3, - "filename": "/list.k.json", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"Alice\"", - "type": "StringLit", - "value": "Alice" - } - } - } - } - ], - "type": "Config" - } - } - ], - "type": "List" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-5.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-5.snap deleted file mode 100644 index 33bff5b22..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-5.snap +++ /dev/null @@ -1,387 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 9, - "end_line": 3, - "filename": "/complex.k.json", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"age\"", - "type": "StringLit", - "value": "age" - } - }, - "operation": "Union", - "value": { - "column": 11, - "end_column": 13, - "end_line": 3, - "filename": "/complex.k.json", - "line": 3, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 18 - } - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 5, - "filename": "/complex.k.json", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"data\"", - "type": "StringLit", - "value": "data" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 5, - "end_line": 8, - "filename": "/complex.k.json", - "line": 5, - "node": { - "items": [ - { - "column": 12, - "end_column": 5, - "end_line": 8, - "filename": "/complex.k.json", - "line": 5, - "node": { - "key": { - "column": 8, - "end_column": 12, - "end_line": 6, - "filename": "/complex.k.json", - "line": 6, - "node": { - "is_long_string": false, - "raw_value": "\"id\"", - "type": "StringLit", - "value": "id" - } - }, - "operation": "Union", - "value": { - "column": 14, - "end_column": 15, - "end_line": 6, - "filename": "/complex.k.json", - "line": 6, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 1 - } - } - } - } - }, - { - "column": 12, - "end_column": 5, - "end_line": 8, - "filename": "/complex.k.json", - "line": 5, - "node": { - "key": { - "column": 8, - "end_column": 15, - "end_line": 7, - "filename": "/complex.k.json", - "line": 7, - "node": { - "is_long_string": false, - "raw_value": "\"value\"", - "type": "StringLit", - "value": "value" - } - }, - "operation": "Union", - "value": { - "column": 17, - "end_column": 25, - "end_line": 7, - "filename": "/complex.k.json", - "line": 7, - "node": { - "is_long_string": false, - "raw_value": "\"value1\"", - "type": "StringLit", - "value": "value1" - } - } - } - } - ], - "type": "Config" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 8, - "end_line": 12, - "filename": "/complex.k.json", - "line": 12, - "node": { - "is_long_string": false, - "raw_value": "\"hc\"", - "type": "StringLit", - "value": "hc" - } - }, - "operation": "Union", - "value": { - "column": 10, - "end_column": 19, - "end_line": 12, - "filename": "/complex.k.json", - "line": 12, - "node": { - "ctx": "Load", - "elts": [ - { - "column": 11, - "end_column": 12, - "end_line": 12, - "filename": "/complex.k.json", - "line": 12, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 1 - } - } - }, - { - "column": 14, - "end_column": 15, - "end_line": 12, - "filename": "/complex.k.json", - "line": 12, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 2 - } - } - }, - { - "column": 17, - "end_column": 18, - "end_line": 12, - "filename": "/complex.k.json", - "line": 12, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 3 - } - } - } - ], - "type": "List" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 12, - "end_line": 9, - "filename": "/complex.k.json", - "line": 9, - "node": { - "is_long_string": false, - "raw_value": "\"labels\"", - "type": "StringLit", - "value": "labels" - } - }, - "operation": "Union", - "value": { - "column": 14, - "end_column": 5, - "end_line": 11, - "filename": "/complex.k.json", - "line": 9, - "node": { - "items": [ - { - "column": 14, - "end_column": 5, - "end_line": 11, - "filename": "/complex.k.json", - "line": 9, - "node": { - "key": { - "column": 8, - "end_column": 13, - "end_line": 10, - "filename": "/complex.k.json", - "line": 10, - "node": { - "is_long_string": false, - "raw_value": "\"key\"", - "type": "StringLit", - "value": "key" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 22, - "end_line": 10, - "filename": "/complex.k.json", - "line": 10, - "node": { - "is_long_string": false, - "raw_value": "\"value\"", - "type": "StringLit", - "value": "value" - } - } - } - } - ], - "type": "Config" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 13, - "end_line": 4, - "filename": "/complex.k.json", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"message\"", - "type": "StringLit", - "value": "message" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 30, - "end_line": 4, - "filename": "/complex.k.json", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"This is Alice\"", - "type": "StringLit", - "value": "This is Alice" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 13, - "filename": "/complex.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 2, - "filename": "/complex.k.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"name\"", - "type": "StringLit", - "value": "name" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 19, - "end_line": 2, - "filename": "/complex.k.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"Alice\"", - "type": "StringLit", - "value": "Alice" - } - } - } - } - ], - "type": "Config" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-6.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-6.snap deleted file mode 100644 index 72f2a5a52..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-6.snap +++ /dev/null @@ -1,50 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_null.json", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_null.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 16, - "end_line": 2, - "filename": "/only_with_null.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"null_value\"", - "type": "StringLit", - "value": "null_value" - } - }, - "operation": "Union", - "value": { - "column": 18, - "end_column": 22, - "end_line": 2, - "filename": "/only_with_null.json", - "line": 2, - "node": { - "type": "NameConstantLit", - "value": "None" - } - } - } - } - ], - "type": "Config" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-7.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-7.snap deleted file mode 100644 index 39c2625f4..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-7.snap +++ /dev/null @@ -1,50 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_bool.json", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_bool.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 2, - "filename": "/only_with_bool.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"flag\"", - "type": "StringLit", - "value": "flag" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 16, - "end_line": 2, - "filename": "/only_with_bool.json", - "line": 2, - "node": { - "type": "NameConstantLit", - "value": "True" - } - } - } - } - ], - "type": "Config" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-8.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-8.snap deleted file mode 100644 index d33ba3462..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name-8.snap +++ /dev/null @@ -1,54 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_float.json", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 3, - "filename": "/only_with_float.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 17, - "end_line": 2, - "filename": "/only_with_float.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"float_value\"", - "type": "StringLit", - "value": "float_value" - } - }, - "operation": "Union", - "value": { - "column": 19, - "end_column": 23, - "end_line": 2, - "filename": "/only_with_float.json", - "line": 2, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Float", - "value": 0.33 - } - } - } - } - } - ], - "type": "Config" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name.snap deleted file mode 100644 index e9fb5ad11..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_json_no_schema_name.snap +++ /dev/null @@ -1,259 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_json_str ---- -{ - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "/test.k.json", - "line": 1, - "node": { - "items": [ - { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "/test.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 13, - "end_line": 4, - "filename": "/test.k.json", - "line": 4, - "node": { - "is_long_string": false, - "raw_value": "\"address\"", - "type": "StringLit", - "value": "address" - } - }, - "operation": "Union", - "value": { - "column": 15, - "end_column": 5, - "end_line": 7, - "filename": "/test.k.json", - "line": 4, - "node": { - "items": [ - { - "column": 15, - "end_column": 5, - "end_line": 7, - "filename": "/test.k.json", - "line": 4, - "node": { - "key": { - "column": 8, - "end_column": 14, - "end_line": 6, - "filename": "/test.k.json", - "line": 6, - "node": { - "is_long_string": false, - "raw_value": "\"city\"", - "type": "StringLit", - "value": "city" - } - }, - "operation": "Union", - "value": { - "column": 16, - "end_column": 24, - "end_line": 6, - "filename": "/test.k.json", - "line": 6, - "node": { - "is_long_string": false, - "raw_value": "\"London\"", - "type": "StringLit", - "value": "London" - } - } - } - }, - { - "column": 15, - "end_column": 5, - "end_line": 7, - "filename": "/test.k.json", - "line": 4, - "node": { - "key": { - "column": 8, - "end_column": 16, - "end_line": 5, - "filename": "/test.k.json", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"street\"", - "type": "StringLit", - "value": "street" - } - }, - "operation": "Union", - "value": { - "column": 18, - "end_column": 37, - "end_line": 5, - "filename": "/test.k.json", - "line": 5, - "node": { - "is_long_string": false, - "raw_value": "\"10 Downing Street\"", - "type": "StringLit", - "value": "10 Downing Street" - } - } - } - } - ], - "type": "Config" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "/test.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 9, - "end_line": 3, - "filename": "/test.k.json", - "line": 3, - "node": { - "is_long_string": false, - "raw_value": "\"age\"", - "type": "StringLit", - "value": "age" - } - }, - "operation": "Union", - "value": { - "column": 11, - "end_column": 13, - "end_line": 3, - "filename": "/test.k.json", - "line": 3, - "node": { - "binary_suffix": null, - "type": "NumberLit", - "value": { - "type": "Int", - "value": 43 - } - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "/test.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 10, - "end_line": 2, - "filename": "/test.k.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"name\"", - "type": "StringLit", - "value": "name" - } - }, - "operation": "Union", - "value": { - "column": 12, - "end_column": 22, - "end_line": 2, - "filename": "/test.k.json", - "line": 2, - "node": { - "is_long_string": false, - "raw_value": "\"John Doe\"", - "type": "StringLit", - "value": "John Doe" - } - } - } - }, - { - "column": 0, - "end_column": 1, - "end_line": 12, - "filename": "/test.k.json", - "line": 1, - "node": { - "key": { - "column": 4, - "end_column": 12, - "end_line": 8, - "filename": "/test.k.json", - "line": 8, - "node": { - "is_long_string": false, - "raw_value": "\"phones\"", - "type": "StringLit", - "value": "phones" - } - }, - "operation": "Union", - "value": { - "column": 14, - "end_column": 5, - "end_line": 11, - "filename": "/test.k.json", - "line": 8, - "node": { - "ctx": "Load", - "elts": [ - { - "column": 8, - "end_column": 21, - "end_line": 9, - "filename": "/test.k.json", - "line": 9, - "node": { - "is_long_string": false, - "raw_value": "\"+44 1234567\"", - "type": "StringLit", - "value": "+44 1234567" - } - }, - { - "column": 8, - "end_column": 21, - "end_line": 10, - "filename": "/test.k.json", - "line": 10, - "node": { - "is_long_string": false, - "raw_value": "\"+44 2345678\"", - "type": "StringLit", - "value": "+44 2345678" - } - } - ], - "type": "List" - } - } - } - } - ], - "type": "Config" - } -} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-2.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-2.snap deleted file mode 100644 index 5bb8cc69b..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-2.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"name\"","value":"name"},"filename":"/simple.k.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Alice,\"","value":"Alice,"},"filename":"/simple.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"age\"","value":"age"},"filename":"/simple.k.yaml","line":2,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"18,\"","value":"18,"},"filename":"/simple.k.yaml","line":2,"column":5,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"message\"","value":"message"},"filename":"/simple.k.yaml","line":3,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"This is Alice\"","value":"This is Alice"},"filename":"/simple.k.yaml","line":3,"column":9,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}]},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-3.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-3.snap deleted file mode 100644 index 0a462296b..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-3.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":1}},"filename":"/plain_value.k.yaml","line":1,"column":0,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-4.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-4.snap deleted file mode 100644 index 73de0030d..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-4.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"List","elts":[{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"name\"","value":"name"},"filename":"/list.k.yaml","line":1,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Alice\"","value":"Alice"},"filename":"/list.k.yaml","line":1,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"age\"","value":"age"},"filename":"/list.k.yaml","line":2,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":18}},"filename":"/list.k.yaml","line":2,"column":7,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"message\"","value":"message"},"filename":"/list.k.yaml","line":3,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"This is Alice\"","value":"This is Alice"},"filename":"/list.k.yaml","line":3,"column":11,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0}]},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0}],"ctx":"Load"},"filename":"/list.k.yaml","line":1,"column":0,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-5.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-5.snap deleted file mode 100644 index 725b9bbad..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-5.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"name\"","value":"name"},"filename":"/complex.k.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Alice\"","value":"Alice"},"filename":"/complex.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"age\"","value":"age"},"filename":"/complex.k.yaml","line":2,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":18}},"filename":"/complex.k.yaml","line":2,"column":5,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"message\"","value":"message"},"filename":"/complex.k.yaml","line":3,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"This is Alice\"","value":"This is Alice"},"filename":"/complex.k.yaml","line":3,"column":9,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"data\"","value":"data"},"filename":"/complex.k.yaml","line":4,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"id\"","value":"id"},"filename":"/complex.k.yaml","line":5,"column":4,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":1}},"filename":"/complex.k.yaml","line":5,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":5,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"value\"","value":"value"},"filename":"/complex.k.yaml","line":6,"column":4,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"value1\"","value":"value1"},"filename":"/complex.k.yaml","line":6,"column":11,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":5,"column":6,"end_line":0,"end_column":0}]},"filename":"/complex.k.yaml","line":5,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"labels\"","value":"labels"},"filename":"/complex.k.yaml","line":7,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"key\"","value":"key"},"filename":"/complex.k.yaml","line":8,"column":4,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"value\"","value":"value"},"filename":"/complex.k.yaml","line":8,"column":9,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":8,"column":7,"end_line":0,"end_column":0}]},"filename":"/complex.k.yaml","line":8,"column":7,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"hc\"","value":"hc"},"filename":"/complex.k.yaml","line":9,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"List","elts":[{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":1}},"filename":"/complex.k.yaml","line":10,"column":6,"end_line":0,"end_column":0},{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":2}},"filename":"/complex.k.yaml","line":11,"column":6,"end_line":0,"end_column":0},{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":3}},"filename":"/complex.k.yaml","line":12,"column":6,"end_line":0,"end_column":0}],"ctx":"Load"},"filename":"/complex.k.yaml","line":10,"column":4,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}]},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-6.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-6.snap deleted file mode 100644 index 964bf7bea..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-6.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"null_val\"","value":"null_val"},"filename":"/only_with_null.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NameConstantLit","value":"None"},"filename":"/only_with_null.yaml","line":1,"column":10,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/only_with_null.yaml","line":1,"column":8,"end_line":0,"end_column":0}]},"filename":"/only_with_null.yaml","line":1,"column":8,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-7.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-7.snap deleted file mode 100644 index fbfca6d63..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-7.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"bool_val\"","value":"bool_val"},"filename":"/only_with_bool.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NameConstantLit","value":"True"},"filename":"/only_with_bool.yaml","line":1,"column":10,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/only_with_bool.yaml","line":1,"column":8,"end_line":0,"end_column":0}]},"filename":"/only_with_bool.yaml","line":1,"column":8,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-8.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-8.snap deleted file mode 100644 index bddd79005..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name-8.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"float_val\"","value":"float_val"},"filename":"/only_with_float.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Float","value":0.33}},"filename":"/only_with_float.yaml","line":1,"column":11,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/only_with_float.yaml","line":1,"column":9,"end_line":0,"end_column":0}]},"filename":"/only_with_float.yaml","line":1,"column":9,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name.snap deleted file mode 100644 index d457141bd..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_with_yaml_no_schema_name.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"languages\"","value":"languages"},"filename":"/test.k.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"List","elts":[{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Ruby\"","value":"Ruby"},"filename":"/test.k.yaml","line":2,"column":4,"end_line":0,"end_column":0},{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Perl\"","value":"Perl"},"filename":"/test.k.yaml","line":3,"column":4,"end_line":0,"end_column":0},{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Python\"","value":"Python"},"filename":"/test.k.yaml","line":4,"column":4,"end_line":0,"end_column":0}],"ctx":"Load"},"filename":"/test.k.yaml","line":2,"column":2,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"websites\"","value":"websites"},"filename":"/test.k.yaml","line":5,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"YAML\"","value":"YAML"},"filename":"/test.k.yaml","line":6,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"yaml.org\"","value":"yaml.org"},"filename":"/test.k.yaml","line":6,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Ruby\"","value":"Ruby"},"filename":"/test.k.yaml","line":7,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"ruby-lang.org\"","value":"ruby-lang.org"},"filename":"/test.k.yaml","line":7,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Python\"","value":"Python"},"filename":"/test.k.yaml","line":8,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"python.org\"","value":"python.org"},"filename":"/test.k.yaml","line":8,"column":10,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Perl\"","value":"Perl"},"filename":"/test.k.yaml","line":9,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"use.perl.org\"","value":"use.perl.org"},"filename":"/test.k.yaml","line":9,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0}]},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0}]},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-2.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-2.snap deleted file mode 100644 index 70c7813dc..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-2.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"Schema","name":{"node":{"names":[{"node":"simple","filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}],"pkgpath":"","ctx":"Load"},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},"args":[],"kwargs":[],"config":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"name\"","value":"name"},"filename":"/simple.k.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Alice,\"","value":"Alice,"},"filename":"/simple.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"age\"","value":"age"},"filename":"/simple.k.yaml","line":2,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"18,\"","value":"18,"},"filename":"/simple.k.yaml","line":2,"column":5,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"message\"","value":"message"},"filename":"/simple.k.yaml","line":3,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"This is Alice\"","value":"This is Alice"},"filename":"/simple.k.yaml","line":3,"column":9,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}]},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}},"filename":"/simple.k.yaml","line":1,"column":4,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-3.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-3.snap deleted file mode 100644 index 0a462296b..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-3.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":1}},"filename":"/plain_value.k.yaml","line":1,"column":0,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-4.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-4.snap deleted file mode 100644 index 542d11746..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-4.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"List","elts":[{"node":{"type":"Schema","name":{"node":{"names":[{"node":"list","filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0}],"pkgpath":"","ctx":"Load"},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},"args":[],"kwargs":[],"config":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"name\"","value":"name"},"filename":"/list.k.yaml","line":1,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Alice\"","value":"Alice"},"filename":"/list.k.yaml","line":1,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"age\"","value":"age"},"filename":"/list.k.yaml","line":2,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":18}},"filename":"/list.k.yaml","line":2,"column":7,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"message\"","value":"message"},"filename":"/list.k.yaml","line":3,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"This is Alice\"","value":"This is Alice"},"filename":"/list.k.yaml","line":3,"column":11,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0}]},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0}},"filename":"/list.k.yaml","line":1,"column":6,"end_line":0,"end_column":0}],"ctx":"Load"},"filename":"/list.k.yaml","line":1,"column":0,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-5.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-5.snap deleted file mode 100644 index b870affed..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-5.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"Schema","name":{"node":{"names":[{"node":"complex","filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}],"pkgpath":"","ctx":"Load"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},"args":[],"kwargs":[],"config":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"name\"","value":"name"},"filename":"/complex.k.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Alice\"","value":"Alice"},"filename":"/complex.k.yaml","line":1,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"age\"","value":"age"},"filename":"/complex.k.yaml","line":2,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":18}},"filename":"/complex.k.yaml","line":2,"column":5,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"message\"","value":"message"},"filename":"/complex.k.yaml","line":3,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"This is Alice\"","value":"This is Alice"},"filename":"/complex.k.yaml","line":3,"column":9,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"data\"","value":"data"},"filename":"/complex.k.yaml","line":4,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"id\"","value":"id"},"filename":"/complex.k.yaml","line":5,"column":4,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":1}},"filename":"/complex.k.yaml","line":5,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":5,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"value\"","value":"value"},"filename":"/complex.k.yaml","line":6,"column":4,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"value1\"","value":"value1"},"filename":"/complex.k.yaml","line":6,"column":11,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":5,"column":6,"end_line":0,"end_column":0}]},"filename":"/complex.k.yaml","line":5,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"labels\"","value":"labels"},"filename":"/complex.k.yaml","line":7,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"key\"","value":"key"},"filename":"/complex.k.yaml","line":8,"column":4,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"value\"","value":"value"},"filename":"/complex.k.yaml","line":8,"column":9,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":8,"column":7,"end_line":0,"end_column":0}]},"filename":"/complex.k.yaml","line":8,"column":7,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"hc\"","value":"hc"},"filename":"/complex.k.yaml","line":9,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"List","elts":[{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":1}},"filename":"/complex.k.yaml","line":10,"column":6,"end_line":0,"end_column":0},{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":2}},"filename":"/complex.k.yaml","line":11,"column":6,"end_line":0,"end_column":0},{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Int","value":3}},"filename":"/complex.k.yaml","line":12,"column":6,"end_line":0,"end_column":0}],"ctx":"Load"},"filename":"/complex.k.yaml","line":10,"column":4,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}]},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0}},"filename":"/complex.k.yaml","line":1,"column":4,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-6.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-6.snap deleted file mode 100644 index 06cc63172..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-6.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"Schema","name":{"node":{"names":[{"node":"only_with_null","filename":"/only_with_null.yaml","line":1,"column":8,"end_line":0,"end_column":0}],"pkgpath":"","ctx":"Load"},"filename":"/only_with_null.yaml","line":1,"column":8,"end_line":0,"end_column":0},"args":[],"kwargs":[],"config":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"null_val\"","value":"null_val"},"filename":"/only_with_null.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NameConstantLit","value":"None"},"filename":"/only_with_null.yaml","line":1,"column":10,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/only_with_null.yaml","line":1,"column":8,"end_line":0,"end_column":0}]},"filename":"/only_with_null.yaml","line":1,"column":8,"end_line":0,"end_column":0}},"filename":"/only_with_null.yaml","line":1,"column":8,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-7.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-7.snap deleted file mode 100644 index 79ad51025..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-7.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"Schema","name":{"node":{"names":[{"node":"only_with_bool","filename":"/only_with_bool.yaml","line":1,"column":8,"end_line":0,"end_column":0}],"pkgpath":"","ctx":"Load"},"filename":"/only_with_bool.yaml","line":1,"column":8,"end_line":0,"end_column":0},"args":[],"kwargs":[],"config":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"bool_val\"","value":"bool_val"},"filename":"/only_with_bool.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NameConstantLit","value":"True"},"filename":"/only_with_bool.yaml","line":1,"column":10,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/only_with_bool.yaml","line":1,"column":8,"end_line":0,"end_column":0}]},"filename":"/only_with_bool.yaml","line":1,"column":8,"end_line":0,"end_column":0}},"filename":"/only_with_bool.yaml","line":1,"column":8,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-8.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-8.snap deleted file mode 100644 index c99e38db8..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml-8.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"Schema","name":{"node":{"names":[{"node":"only_with_float","filename":"/only_with_float.yaml","line":1,"column":9,"end_line":0,"end_column":0}],"pkgpath":"","ctx":"Load"},"filename":"/only_with_float.yaml","line":1,"column":9,"end_line":0,"end_column":0},"args":[],"kwargs":[],"config":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"float_val\"","value":"float_val"},"filename":"/only_with_float.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"NumberLit","binary_suffix":null,"value":{"type":"Float","value":0.33}},"filename":"/only_with_float.yaml","line":1,"column":11,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/only_with_float.yaml","line":1,"column":9,"end_line":0,"end_column":0}]},"filename":"/only_with_float.yaml","line":1,"column":9,"end_line":0,"end_column":0}},"filename":"/only_with_float.yaml","line":1,"column":9,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml.snap b/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml.snap deleted file mode 100644 index 4e062d1df..000000000 --- a/kclvm/tools/src/vet/snapshots/kclvm_tools__vet__tests__test_expr_builder__build_yaml.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: tools/src/vet/tests.rs -expression: got_ast_yaml_str ---- -{"node":{"type":"Schema","name":{"node":{"names":[{"node":"test","filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0}],"pkgpath":"","ctx":"Load"},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0},"args":[],"kwargs":[],"config":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"languages\"","value":"languages"},"filename":"/test.k.yaml","line":1,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"List","elts":[{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Ruby\"","value":"Ruby"},"filename":"/test.k.yaml","line":2,"column":4,"end_line":0,"end_column":0},{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Perl\"","value":"Perl"},"filename":"/test.k.yaml","line":3,"column":4,"end_line":0,"end_column":0},{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Python\"","value":"Python"},"filename":"/test.k.yaml","line":4,"column":4,"end_line":0,"end_column":0}],"ctx":"Load"},"filename":"/test.k.yaml","line":2,"column":2,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"websites\"","value":"websites"},"filename":"/test.k.yaml","line":5,"column":0,"end_line":0,"end_column":0},"value":{"node":{"type":"Config","items":[{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"YAML\"","value":"YAML"},"filename":"/test.k.yaml","line":6,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"yaml.org\"","value":"yaml.org"},"filename":"/test.k.yaml","line":6,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Ruby\"","value":"Ruby"},"filename":"/test.k.yaml","line":7,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"ruby-lang.org\"","value":"ruby-lang.org"},"filename":"/test.k.yaml","line":7,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Python\"","value":"Python"},"filename":"/test.k.yaml","line":8,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"python.org\"","value":"python.org"},"filename":"/test.k.yaml","line":8,"column":10,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},{"node":{"key":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"Perl\"","value":"Perl"},"filename":"/test.k.yaml","line":9,"column":2,"end_line":0,"end_column":0},"value":{"node":{"type":"StringLit","is_long_string":false,"raw_value":"\"use.perl.org\"","value":"use.perl.org"},"filename":"/test.k.yaml","line":9,"column":8,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0}]},"filename":"/test.k.yaml","line":6,"column":6,"end_line":0,"end_column":0},"operation":"Union"},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0}]},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0}},"filename":"/test.k.yaml","line":1,"column":9,"end_line":0,"end_column":0} diff --git a/kclvm/tools/src/vet/tests.rs b/kclvm/tools/src/vet/tests.rs deleted file mode 100644 index b20222eea..000000000 --- a/kclvm/tools/src/vet/tests.rs +++ /dev/null @@ -1,639 +0,0 @@ -use std::path::{Path, PathBuf}; - -use anyhow::{Context, Result}; - -use crate::util::loader::LoaderKind; - -const CARGO_DIR: &str = env!("CARGO_MANIFEST_DIR"); -pub(crate) fn rel_path() -> String { - Path::new("src") - .join("vet") - .join("test_datas") - .display() - .to_string() -} - -const TEST_CASES: &[&str] = &[ - "test.k", - "simple.k", - "plain_value.k", - "list.k", - "complex.k", - "only_with_null", - "only_with_bool", - "only_with_float", -]; - -const SCHEMA_NAMES: &[&str] = &[ - "test", - "simple", - "plain_value", - "list", - "complex", - "only_with_null", - "only_with_bool", - "only_with_float", -]; - -const FILE_EXTENSIONS: &[&str] = &["json", "yaml", "ast.json", "ast.yaml", "k"]; - -const LOADER_KIND: [&LoaderKind; 2] = [&LoaderKind::JSON, &LoaderKind::YAML]; - -const INVALID_FILE_RESULT: &[&str] = &[ -"Failed to Load JSON\n\nCaused by:\n 0: Failed to String 'languages:\n - Ruby\n ' to Json\n 1: expected value at line 1 column 1", -"Failed to Load YAML\n\nCaused by:\n 0: Failed to String '{\n \"name\": \"John Doe\",\n \"city\": \"London\"\n invalid\n \n ' to Yaml\n 1: while parsing a flow mapping, did not find expected ',' or '}' at line 4 column 1" -]; - -fn construct_full_path(path: &str) -> Result { - let mut cargo_file_path = PathBuf::from(CARGO_DIR); - cargo_file_path.push(&rel_path()); - cargo_file_path.push(path); - Ok(cargo_file_path - .to_str() - .with_context(|| format!("No such file or directory '{}'", path))? - .to_string()) -} - -mod test_expr_builder { - use regex::Regex; - - use crate::{ - util::loader::LoaderKind, - vet::{ - expr_builder::ExprBuilder, - tests::{ - construct_full_path, deal_windows_filepath, FILE_EXTENSIONS, INVALID_FILE_RESULT, - LOADER_KIND, SCHEMA_NAMES, TEST_CASES, - }, - }, - }; - use std::panic; - #[cfg(not(target_os = "windows"))] - use std::{fs, path::Path}; - - #[test] - #[cfg(not(target_os = "windows"))] - fn test_build_with_json_no_schema_name() { - for test_name in TEST_CASES { - let file_path = construct_full_path(&format!( - "{}.{}", - Path::new(FILE_EXTENSIONS[0]).join(test_name).display(), - FILE_EXTENSIONS[0] - )) - .unwrap(); - let expr_builder = - ExprBuilder::new_with_file_path(*LOADER_KIND[0], file_path.clone()).unwrap(); - let expr_ast = expr_builder.build(None).unwrap(); - let got_ast_json = serde_json::to_value(&expr_ast).unwrap(); - - let got_ast_json_str = serde_json::to_string_pretty(&got_ast_json) - .unwrap() - .replace( - &deal_windows_filepath(construct_full_path("json").unwrap(), |s| { - s.replace('\\', "\\\\") - }), - "", - ); - - insta::assert_snapshot!(got_ast_json_str); - } - } - - #[test] - fn test_build_with_yaml_no_schema_name() { - for test_name in TEST_CASES { - let file_path = construct_full_path(&format!( - "{}/{}.{}", - FILE_EXTENSIONS[1], test_name, FILE_EXTENSIONS[1] - )) - .unwrap(); - let expr_builder = - ExprBuilder::new_with_file_path(*LOADER_KIND[1], file_path.clone()).unwrap(); - let expr_ast = expr_builder.build(None).unwrap(); - let got_ast_yaml = serde_yaml_ng::to_value(&expr_ast).unwrap(); - - let got_ast_yaml_str = serde_json::to_string(&got_ast_yaml).unwrap().replace( - &deal_windows_filepath(construct_full_path("yaml").unwrap(), |s| { - s.replace('\\', "\\\\") - }), - "", - ); - - insta::assert_snapshot!(got_ast_yaml_str) - } - } - - #[test] - #[cfg(not(target_os = "windows"))] - /// Test `expr_builder.build()` with input json files. - fn test_build_json_with_filepath() { - for i in 0..TEST_CASES.len() { - let file_path = - construct_full_path(&format!("{1}/{0}.{1}", TEST_CASES[i], FILE_EXTENSIONS[0])) - .unwrap(); - let expr_builder = ExprBuilder::new_with_file_path(*LOADER_KIND[0], file_path).unwrap(); - let expr_ast = expr_builder - .build(Some(SCHEMA_NAMES[i].to_string())) - .unwrap(); - let got_ast_json = serde_json::to_value(&expr_ast).unwrap(); - - let got_ast_json_str = serde_json::to_string_pretty(&got_ast_json) - .unwrap() - .replace( - &deal_windows_filepath(construct_full_path("json").unwrap(), |s| { - s.replace('\\', "\\\\") - }), - "", - ); - - insta::assert_snapshot!(got_ast_json_str); - } - } - - #[test] - #[cfg(not(target_os = "windows"))] - /// Test `expr_builder.build()` with input json files. - fn test_build_json_with_str() { - for i in 0..TEST_CASES.len() { - let file_path = - construct_full_path(&format!("{1}/{0}.{1}", TEST_CASES[i], FILE_EXTENSIONS[0])) - .unwrap(); - - let content = fs::read_to_string(file_path).unwrap(); - - let expr_builder = ExprBuilder::new_with_str(*LOADER_KIND[0], content).unwrap(); - let expr_ast = expr_builder - .build(Some(SCHEMA_NAMES[i].to_string())) - .unwrap(); - let got_ast_json = serde_json::to_value(&expr_ast).unwrap(); - - let got_ast_json_str = serde_json::to_string_pretty(&got_ast_json) - .unwrap() - .replace( - &deal_windows_filepath(construct_full_path("json").unwrap(), |s| { - s.replace('\\', "\\\\") - }), - "", - ); - - insta::assert_snapshot!(got_ast_json_str); - } - } - - #[test] - /// Test `expr_builder.build()` with input yaml files. - fn test_build_yaml() { - for i in 0..TEST_CASES.len() { - let file_path = - construct_full_path(&format!("{1}/{0}.{1}", TEST_CASES[i], FILE_EXTENSIONS[1])) - .unwrap(); - let expr_builder = ExprBuilder::new_with_file_path(*LOADER_KIND[1], file_path).unwrap(); - let expr_ast = expr_builder - .build(Some(SCHEMA_NAMES[i].to_string())) - .unwrap(); - let got_ast_yaml = serde_yaml_ng::to_value(&expr_ast).unwrap(); - - let got_ast_yaml_str = serde_json::to_string(&got_ast_yaml).unwrap().replace( - &deal_windows_filepath(construct_full_path("yaml").unwrap(), |s| { - s.replace('\\', "\\\\") - }), - "", - ); - - insta::assert_snapshot!(got_ast_yaml_str); - } - } - - #[test] - /// Test `expr_builder.build()` with input invalid json/yaml files. - fn test_build_with_invalid() { - for i in 0..2 { - let file_path = construct_full_path(&format!( - "invalid/{}.{}", - "test_invalid", FILE_EXTENSIONS[i] - )) - .unwrap(); - let expr_builder = ExprBuilder::new_with_file_path(*LOADER_KIND[i], file_path).unwrap(); - match expr_builder.build(None) { - Ok(_) => { - panic!("This test case should be failed.") - } - Err(err) => { - #[cfg(not(target_os = "windows"))] - let got_err = format!("{:?}", err); - #[cfg(target_os = "windows")] - let got_err = format!("{:?}", err).replace("\r\n", "\n"); - - assert_eq!(got_err, INVALID_FILE_RESULT[i]); - } - }; - } - } - - #[test] - /// Test `expr_builder.build()` with files that do not exist. - fn test_build_with_noexist_file() { - for i in 0..2 { - let file_path = construct_full_path(&format!( - "json/{}.{}", - "test_json_not_exist", FILE_EXTENSIONS[i] - )) - .unwrap(); - match ExprBuilder::new_with_file_path(*LOADER_KIND[i], file_path.clone()) { - Ok(_) => { - panic!("This test case should be failed.") - } - Err(err) => { - assert!(Regex::new( - r"^Failed to Load '.*'\n\nCaused by:\n 0: Failed to Load '.*'\n .*" - ) - .unwrap() - .is_match(&format!("{:?}", err))) - } - }; - } - } - - #[test] - /// Test `expr_builder.build()` with yaml files and json data loader. - fn test_build_with_yaml_file_with_json_kind() { - let file_path = construct_full_path(&format!("yaml/{}", "test.k.yaml")).unwrap(); - let expr_builder = ExprBuilder::new_with_file_path(LoaderKind::JSON, file_path).unwrap(); - - match expr_builder.build(None) { - Ok(_) => { - panic!("This test case should be failed.") - } - Err(err) => { - #[cfg(not(target_os = "windows"))] - let got_err = format!("{:?}", err); - #[cfg(target_os = "windows")] - let got_err = format!("{:?}", err).replace("\r\n", "\n"); - - assert_eq!( - got_err, - "Failed to Load JSON\n\nCaused by:\n 0: Failed to String 'languages:\n - Ruby\n - Perl\n - Python \n websites:\n YAML: yaml.org \n Ruby: ruby-lang.org \n Python: python.org \n Perl: use.perl.org\n ' to Json\n 1: expected value at line 1 column 1" - ) - } - } - } - - #[test] - fn test_unsupported_u64_json() { - // unsupported u64 json - let file_path = construct_full_path("invalid/unsupported/json_with_u64.json").unwrap(); - let expr_builder = ExprBuilder::new_with_file_path(*LOADER_KIND[0], file_path).unwrap(); - match expr_builder.build(None) { - Ok(_) => { - panic!("unreachable") - } - Err(err) => { - assert_eq!(format!("{:?}", err), "Failed to Load JSON\n\nCaused by:\n 0: Failed to load the validated file\n 1: Failed to load the validated file, Unsupported Unsigned 64"); - } - }; - } - - #[test] - fn test_unsupported_u64_yaml() { - // unsupported u64 yaml - let file_path = construct_full_path("invalid/unsupported/yaml_with_u64.yaml").unwrap(); - let expr_builder = ExprBuilder::new_with_file_path(*LOADER_KIND[1], file_path).unwrap(); - match expr_builder.build(None) { - Ok(_) => { - panic!("unreachable") - } - Err(err) => { - assert_eq!(format!("{:?}", err), "Failed to Load YAML\n\nCaused by:\n 0: Failed to load the validated file\n 1: Failed to load the validated file, Unsupported Number Type"); - } - }; - } -} - -mod test_validater { - use std::{ - fs, panic, - path::{Path, PathBuf}, - }; - - use crate::{ - util::loader::LoaderKind, - vet::{ - tests::deal_windows_filepath, - validator::{validate, ValidateOption}, - }, - }; - - use super::{construct_full_path, LOADER_KIND}; - - const KCL_TEST_CASES: &[&str] = &[ - "test.k", - "simple.k", - "list.k", - "plain_value.k", - "complex.k", - "with_import.k", - ]; - const KCL_TEST_CASES_WITH_CODE: &[&str] = - &["test.k", "simple.k", "list.k", "plain_value.k", "complex.k"]; - const VALIDATED_FILE_TYPE: &[&str] = &["json", "yaml"]; - - #[test] - fn test_validator() { - test_validate(); - println!("test_validate - PASS"); - test_invalid_validate_only_code(); - println!("test_invalid_validate_only_code - PASS"); - test_validate_with_invalid_kcl_path(); - println!("test_validate_with_invalid_kcl_path - PASS"); - test_validate_with_invalid_file_path(); - println!("test_validate_with_invalid_file_path - PASS"); - test_validate_with_invalid_file_type(); - println!("test_validate_with_invalid_file_type - PASS"); - test_invalid_validate_with_json_pos(); - println!("test_invalid_validate_with_json_pos - PASS"); - test_invalid_validate_with_yaml_pos(); - println!("test_invalid_validate_with_yaml_pos - PASS"); - } - - fn test_validate() { - for (i, file_suffix) in VALIDATED_FILE_TYPE.iter().enumerate() { - for case in KCL_TEST_CASES { - let validated_file_path = construct_full_path(&format!( - "{}.{}", - Path::new("validate_cases").join(case).display(), - file_suffix - )) - .unwrap(); - - let kcl_file_path = construct_full_path( - &Path::new("validate_cases").join(case).display().to_string(), - ) - .unwrap(); - - let opt = ValidateOption::new( - None, - "value".to_string(), - validated_file_path.clone(), - *LOADER_KIND[i], - Some(kcl_file_path.to_string()), - None, - Default::default(), - ); - - match validate(opt) { - Ok(res) => assert!(res), - Err(err) => unreachable!("{:?}", err), - } - } - } - } - - fn test_invalid_validate_with_json_pos() { - let root_path = PathBuf::from(construct_full_path("invalid_vet_cases_json").unwrap()) - .canonicalize() - .unwrap(); - for (i, _) in VALIDATED_FILE_TYPE.iter().enumerate() { - for case in KCL_TEST_CASES { - let validated_file_path = construct_full_path(&format!( - "{}.{}", - Path::new("invalid_vet_cases_json").join(case).display(), - "json" - )) - .unwrap(); - - let kcl_code = fs::read_to_string( - construct_full_path( - &Path::new("invalid_vet_cases_json") - .join(case) - .display() - .to_string(), - ) - .unwrap(), - ) - .expect("Something went wrong reading the file"); - - let kcl_path = construct_full_path( - &Path::new("invalid_vet_cases_json") - .join(case) - .display() - .to_string(), - ) - .unwrap(); - - let opt = ValidateOption::new( - None, - "value".to_string(), - validated_file_path.clone(), - *LOADER_KIND[i], - Some(kcl_path), - Some(kcl_code), - Default::default(), - ); - - let result = validate(opt).unwrap_err(); - println!("{}", result); - assert!( - result.to_string().replace('\\', "").contains( - &deal_windows_filepath(root_path.join(case).display().to_string(), |s| { - s.replace('\\', "\\\\") - }) - .replace('\\', "") - ), - "{result}" - ); - } - } - } - - fn test_invalid_validate_with_yaml_pos() { - let root_path = PathBuf::from(construct_full_path("invalid_vet_cases_yaml").unwrap()) - .canonicalize() - .unwrap(); - for case in KCL_TEST_CASES { - let validated_file_path = construct_full_path(&format!( - "{}.{}", - Path::new("invalid_vet_cases_yaml").join(case).display(), - "yaml" - )) - .unwrap(); - - let kcl_code = fs::read_to_string( - construct_full_path( - &Path::new("invalid_vet_cases_yaml") - .join(case) - .display() - .to_string(), - ) - .unwrap(), - ) - .expect("Something went wrong reading the file"); - - let kcl_path = construct_full_path( - &Path::new("invalid_vet_cases_yaml") - .join(case) - .display() - .to_string(), - ) - .unwrap(); - - let opt = ValidateOption::new( - None, - "value".to_string(), - validated_file_path.clone(), - LoaderKind::YAML, - Some(kcl_path), - Some(kcl_code), - Default::default(), - ); - - let result = validate(opt).unwrap_err(); - println!("{}", result); - assert!( - result.to_string().replace('\\', "").contains( - &deal_windows_filepath(root_path.join(case).display().to_string(), |s| { - s.replace('\\', "\\\\") - }) - .replace('\\', "") - ), - "{result}" - ); - } - } - - #[test] - fn test_invalid_validate_only_code() { - for (i, file_suffix) in VALIDATED_FILE_TYPE.iter().enumerate() { - for case in KCL_TEST_CASES_WITH_CODE { - let validated_file_path = construct_full_path(&format!( - "{}.{}", - Path::new("invalid_validate_cases").join(case).display(), - file_suffix - )) - .unwrap(); - - let kcl_code = fs::read_to_string( - construct_full_path( - &Path::new("invalid_validate_cases") - .join(case) - .display() - .to_string(), - ) - .unwrap(), - ) - .expect("Something went wrong reading the file"); - - let opt = ValidateOption::new( - None, - "value".to_string(), - validated_file_path.clone(), - *LOADER_KIND[i], - None, - Some(kcl_code), - Default::default(), - ); - - let result = validate(opt).unwrap_err(); - assert!(result.to_string().contains("Error"), "{result}"); - } - } - } - - fn test_validate_with_invalid_kcl_path() { - let opt = ValidateOption::new( - None, - "value".to_string(), - "The validated file path is invalid".to_string(), - LoaderKind::JSON, - None, - None, - Default::default(), - ); - - match validate(opt) { - Ok(_) => { - panic!("unreachable") - } - Err(err) => { - assert_eq!( - err.to_string(), - "Cannot find the kcl file, please check the file path validationTempKCLCode.k" - ); - } - } - } - - fn test_validate_with_invalid_file_path() { - let kcl_code = fs::read_to_string( - construct_full_path(&format!("{}/{}", "validate_cases", "test.k")).unwrap(), - ) - .expect("Something went wrong reading the file"); - - let opt = ValidateOption::new( - None, - "value".to_string(), - "invalid/file/path".to_string(), - LoaderKind::JSON, - None, - Some(kcl_code), - Default::default(), - ); - - match validate(opt) { - Ok(_) => { - panic!("unreachable") - } - Err(err) => { - assert_eq!(err.to_string(), "Failed to Load 'invalid/file/path'") - } - } - } - - fn test_validate_with_invalid_file_type() { - let kcl_code = fs::read_to_string( - construct_full_path(&format!("{}/{}", "validate_cases", "test.k")).unwrap(), - ) - .expect("Something went wrong reading the file"); - - let validated_file_path = - construct_full_path(&format!("{}/{}", "validate_cases", "test.k.yaml")).unwrap(); - - let opt = ValidateOption::new( - None, - "value".to_string(), - validated_file_path, - LoaderKind::JSON, - None, - Some(kcl_code), - Default::default(), - ); - - match validate(opt) { - Ok(_) => { - panic!("unreachable") - } - Err(err) => { - assert_eq!(err.to_string(), "Failed to Load JSON") - } - } - } -} - -/// Deal with windows filepath -#[allow(unused)] -fn deal_windows_filepath(filepath: String, transform: F) -> String -where - F: FnOnce(String) -> String, -{ - #[cfg(not(target_os = "windows"))] - return filepath; - #[cfg(target_os = "windows")] - { - use kclvm_utils::path::PathPrefix; - let path = PathBuf::from(filepath) - .canonicalize() - .unwrap() - .display() - .to_string(); - return transform(Path::new(&path).adjust_canonicalization()); - } -} diff --git a/kclvm/utils/Cargo.toml b/kclvm/utils/Cargo.toml deleted file mode 100644 index de90c6049..000000000 --- a/kclvm/utils/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "kclvm-utils" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -anyhow = "1" -regex = "1.3" - - -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] -fslock = "0.2.1" diff --git a/kclvm/utils/src/path.rs b/kclvm/utils/src/path.rs deleted file mode 100644 index baa27ba78..000000000 --- a/kclvm/utils/src/path.rs +++ /dev/null @@ -1,151 +0,0 @@ -//! This file primarily offers utils for working with file paths, -//! enabling them to be automatically formatted according to the OS. - -use std::path::Path; - -/// Util methods for file path prefixes -pub trait PathPrefix { - /// In the Windows system, the file path returned by method [`canonicalize()`], - /// in rust [`PathBuf`] or [`Path`], will include the '\\?\' character, - /// which is prepared for the Windows API. - /// - /// Paths containing "\\?\" may sometimes result in the file being unable to be found. - /// As such, [`adjust_canonicalization()`] is required to remove this '\\?\'. - /// On non-Windows systems, this method does not make any modifications to the file path. - /// - /// For more information about "\\?\", - /// see https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#short-vs-long-names - fn adjust_canonicalization(&self) -> String; -} - -impl

PathPrefix for P -where - P: AsRef, -{ - #[cfg(not(target_os = "windows"))] - /// On non-Windows systems, this method does not make any modifications to the file path. - /// - /// # Examples - /// - /// ```rust - /// use std::path::Path; - /// use kclvm_utils::path::PathPrefix; - /// - /// let path = Path::new(".").canonicalize().unwrap(); - /// assert_eq!( - /// path.clone().adjust_canonicalization(), - /// path.display().to_string() - /// ); - /// ``` - fn adjust_canonicalization(&self) -> String { - self.as_ref().display().to_string() - } - - #[cfg(target_os = "windows")] - /// For kclvm on windows, the "\\?\ " will cause the obj file to not be found when linking by "cl.exe". - /// - /// Slicing this path directly is not a good solution, - /// we will find a more fluent way to solve this problem in the future. @zongz - /// Note: On windows systems, a file path that is too long may cause "cl.exe" to crash. - /// For more information, see doc in trait [`PathPrefix`]. - /// - /// # Examples - /// - /// ```rust - /// use std::path::Path; - /// use kclvm_utils::path::PathPrefix; - /// - /// let path = Path::new(".").canonicalize().unwrap(); - /// assert!(path.display().to_string().contains("\\\\?\\")); - /// assert!(!path.adjust_canonicalization().contains("\\\\?\\")); - /// ``` - fn adjust_canonicalization(&self) -> String { - const VERBATIM_PREFIX: &str = r#"\\?\"#; - const ESCAPE_VERBATIM_PREFIX: &str = r#"\\\\?\\"#; - let p = self.as_ref().display().to_string(); - if p.starts_with(VERBATIM_PREFIX) { - p[VERBATIM_PREFIX.len()..].to_string() - } else if p.starts_with(ESCAPE_VERBATIM_PREFIX) { - p[ESCAPE_VERBATIM_PREFIX.len()..].to_string() - } else { - p - } - } -} - -/// Convert windows drive letter to upcase -pub fn convert_windows_drive_letter(path: &str) -> String { - #[cfg(target_os = "windows")] - { - let regex = regex::Regex::new(r"(?i)^\\\\\?\\[a-z]:\\").unwrap(); - const VERBATIM_PREFIX: &str = r#"\\?\"#; - let mut p = path.to_string(); - if p.starts_with(VERBATIM_PREFIX) && regex.is_match(&p) { - let drive_letter = p[VERBATIM_PREFIX.len()..VERBATIM_PREFIX.len() + 1].to_string(); - p.replace_range( - VERBATIM_PREFIX.len()..VERBATIM_PREFIX.len() + 1, - &drive_letter.to_uppercase(), - ); - } - let regex = regex::Regex::new(r"[a-z]:\\").unwrap(); - if regex.is_match(&p) { - let drive_letter = p[0..1].to_string(); - p.replace_range(0..1, &drive_letter.to_uppercase()); - } - p - } - #[cfg(not(target_os = "windows"))] - { - path.to_owned() - } -} - -#[test] -fn test_convert_drive_letter() { - #[cfg(target_os = "windows")] - { - let path = r"\\?\d:\xx"; - assert_eq!(convert_windows_drive_letter(path), r"\\?\D:\xx".to_string()); - - let path = r"d:\xx"; - assert_eq!(convert_windows_drive_letter(path), r"D:\xx".to_string()); - } - #[cfg(not(target_os = "windows"))] - { - let path = r".\xx"; - assert_eq!(convert_windows_drive_letter(path), path.to_string()); - } -} - -#[test] -#[cfg(target_os = "windows")] -fn test_adjust_canonicalization() { - let path = Path::new(".").canonicalize().unwrap(); - assert!(path.display().to_string().contains("\\\\?\\")); - assert!(!path.adjust_canonicalization().contains("\\\\?\\")); -} - -#[test] -#[cfg(not(target_os = "windows"))] -fn test_adjust_canonicalization1() { - let path = Path::new(".").canonicalize().unwrap(); - assert_eq!( - path.clone().adjust_canonicalization(), - path.display().to_string() - ); -} - -#[inline] -pub fn is_dir(path: &str) -> bool { - std::path::Path::new(path).is_dir() -} - -#[inline] -pub fn is_absolute(path: &str) -> bool { - std::path::Path::new(path).is_absolute() -} - -#[inline] -pub fn path_exist(path: &str) -> bool { - std::path::Path::new(path).exists() -} diff --git a/kclvm/version/Cargo.lock b/kclvm/version/Cargo.lock deleted file mode 100644 index 4c730005b..000000000 --- a/kclvm/version/Cargo.lock +++ /dev/null @@ -1,7 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "kclvm-version" -version = "0.1.0" diff --git a/kclvm/version/Cargo.toml b/kclvm/version/Cargo.toml deleted file mode 100644 index ec35707f1..000000000 --- a/kclvm/version/Cargo.toml +++ /dev/null @@ -1,11 +0,0 @@ -[package] -name = "kclvm-version" -version = "0.11.2" -edition = "2021" - -[build-dependencies] -vergen-gitcl = { version = "1.0.0", features = ["rustc"] } - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] diff --git a/kclvm/version/src/lib.rs b/kclvm/version/src/lib.rs deleted file mode 100644 index 978285988..000000000 --- a/kclvm/version/src/lib.rs +++ /dev/null @@ -1,29 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -pub const VERSION: &str = include_str!("./../../../VERSION"); -pub const CHECK_SUM: &str = "c020ab3eb4b9179219d6837a57f5d323"; -pub const GIT_SHA: &str = env!("VERGEN_GIT_SHA"); -pub const HOST_TRIPLE: &str = env!("VERGEN_RUSTC_HOST_TRIPLE"); - -/// Get KCL full version string with the format `{version}-{check_sum}`. -#[inline] -pub fn get_version_string() -> String { - format!("{}-{}", VERSION, CHECK_SUM) -} - -/// Get KCL build git sha. -#[inline] -pub fn get_git_sha() -> &'static str { - option_env!("KCL_BUILD_GIT_SHA").unwrap_or_else(|| GIT_SHA) -} - -/// Get version info including version string, platform. -#[inline] -pub fn get_version_info() -> String { - format!( - "Version: {}\r\nPlatform: {}\r\nGitCommit: {}", - get_version_string(), - HOST_TRIPLE, - get_git_sha(), - ) -} diff --git a/run.sh b/run.sh deleted file mode 100755 index fae2cc480..000000000 --- a/run.sh +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env bash - -# Environment -getSystemInfo() { - arch=$(uname -m) - case $arch in - armv7*) arch="arm";; - aarch64) arch="arm64";; - x86_64) arch="amd64";; - esac - - os=$(echo `uname`|tr '[:upper:]' '[:lower:]') -} - -getSystemInfo -topdir=$PWD -version=v$(cat VERSION) - -# Options -help_message=$(cat <<-END - Usage: - run.sh -h - Print this help message. - run.sh -a [action] - Perform an action. - run.sh - Perform an action interactively. - Available actions: - build - Build the KCL package. - release - Create a releasing for the KCL package. -END -) -action= -while getopts "a:h:s:" opt; do - case $opt in - a) - action="$OPTARG" - ;; - h) - echo "$help_message" - exit 1 - ;; - s) - sslpath="$OPTARG" - ;; - \?) echo "Invalid option -$OPTARG" - ;; - esac -done - -if [ "$action" == "" ]; then - PS3='Please select the action: ' - options=("build" "release") - select action in "${options[@]}" - do - case $action in - "build") - break - ;; - "release") - break - ;; - *) echo "Invalid action $REPLY:$action" - exit 1 - break - ;; - esac - done -fi - -topdir=$topdir version=$version sslpath=$sslpath $topdir/scripts/$action.sh diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 000000000..2fe8665e9 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,3 @@ +newline_style = "Unix" +use_field_init_shorthand = true +use_try_shorthand = true diff --git a/samples/README.md b/samples/README.md deleted file mode 100644 index f75459356..000000000 --- a/samples/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Examples - -More examples can be found at [here](https://github.com/kcl-lang/kcl-lang.io/tree/main/examples). diff --git a/samples/fib.k b/samples/fib.k deleted file mode 100644 index 96926c055..000000000 --- a/samples/fib.k +++ /dev/null @@ -1,14 +0,0 @@ -schema Fib: - n1 = n - 1 - n2 = n1 - 1 - n: int - value: int - - if n <= 1: - value = 1 - elif n == 2: - value = 1 - else: - value = Fib {n = n1}.value + Fib {n = n2}.value - -fib8 = Fib {n = 8}.value diff --git a/samples/hello.k b/samples/hello.k deleted file mode 100644 index 00df92b0c..000000000 --- a/samples/hello.k +++ /dev/null @@ -1,11 +0,0 @@ -name = "kcl" -age = 1 - -schema Person: - name: str = "kcl" - age: int = 1 - -x0 = Person {} -x1 = Person { - age = 101 -} diff --git a/samples/kubernetes.k b/samples/kubernetes.k deleted file mode 100644 index 357c2d2d5..000000000 --- a/samples/kubernetes.k +++ /dev/null @@ -1,18 +0,0 @@ -apiVersion = "apps/v1" -kind = "Deployment" -metadata = { - name = "nginx" - labels.app = "nginx" -} -spec = { - replicas = 3 - selector.matchLabels = metadata.labels - template.metadata.labels = metadata.labels - template.spec.containers = [ - { - name = metadata.name - image = "${metadata.name}:1.14.2" - ports = [{ containerPort = 80 }] - } - ] -} diff --git a/samples/math.k b/samples/math.k deleted file mode 100644 index d62071862..000000000 --- a/samples/math.k +++ /dev/null @@ -1,3 +0,0 @@ -import math - -a = math.log10(100) # 2 diff --git a/scripts/build-windows/.gitignore b/scripts/.gitignore similarity index 100% rename from scripts/build-windows/.gitignore rename to scripts/.gitignore diff --git a/scripts/build-llvm/build.ps1 b/scripts/build-llvm/build.ps1 deleted file mode 100755 index 62277b859..000000000 --- a/scripts/build-llvm/build.ps1 +++ /dev/null @@ -1,69 +0,0 @@ -$LLVM_VERSION = $args[0] -$LLVM_REPO_URL = $args[1] - -if ([string]::IsNullOrEmpty($LLVM_REPO_URL)) { - $LLVM_REPO_URL = "https://github.com/llvm/llvm-project.git" -} - -if ([string]::IsNullOrEmpty($LLVM_VERSION)) { - Write-Output "Usage: $PSCommandPath " - Write-Output "" - Write-Output "# Arguments" - Write-Output " llvm-version The name of a LLVM release branch without the 'release/' prefix" - Write-Output " llvm-repository-url The URL used to clone LLVM sources (default: https://github.com/llvm/llvm-project.git)" - - exit 1 -} - -# Clone the LLVM project. -if (-not (Test-Path -Path "llvm-project" -PathType Container)) { - git clone "$LLVM_REPO_URL" llvm-project -} - -Set-Location llvm-project -git fetch origin -git checkout "release/$LLVM_VERSION" -git reset --hard origin/"release/$LLVM_VERSION" - -# Create a directory to build the project. -New-Item -Path "build" -Force -ItemType "directory" -Set-Location build - -# Create a directory to receive the complete installation. -New-Item -Path "install" -Force -ItemType "directory" - -# Adjust compilation based on the OS. -$CMAKE_ARGUMENTS = "" - -# Adjust cross compilation -$CROSS_COMPILE = "" - -# Run `cmake` to configure the project. -cmake ` - -G "Visual Studio 16 2019" ` - -DCMAKE_BUILD_TYPE=MinSizeRel ` - -DCMAKE_INSTALL_PREFIX=destdir ` - -DLLVM_ENABLE_PROJECTS="clang;lld" ` - -DLLVM_ENABLE_TERMINFO=OFF ` - -DLLVM_ENABLE_ZLIB=OFF ` - -DLLVM_INCLUDE_DOCS=OFF ` - -DLLVM_INCLUDE_EXAMPLES=OFF ` - -DLLVM_INCLUDE_GO_TESTS=OFF ` - -DLLVM_INCLUDE_TESTS=OFF ` - -DLLVM_INCLUDE_TOOLS=ON ` - -DLLVM_INCLUDE_UTILS=OFF ` - -DLLVM_OPTIMIZED_TABLEGEN=ON ` - -DLLVM_TARGETS_TO_BUILD="X86;AArch64" ` - $CROSS_COMPILE ` - $CMAKE_ARGUMENTS ` - ../llvm - -# Showtime! -cmake --build . --config Release - -# Not using DESTDIR here, quote from -# https://cmake.org/cmake/help/latest/envvar/DESTDIR.html -# > `DESTDIR` may not be used on Windows because installation prefix -# > usually contains a drive letter like in `C:/Program Files` which cannot -# > be prepended with some other prefix. -cmake --install . --strip --config Release diff --git a/scripts/build-llvm/build.sh b/scripts/build-llvm/build.sh deleted file mode 100755 index 56f05da22..000000000 --- a/scripts/build-llvm/build.sh +++ /dev/null @@ -1,84 +0,0 @@ -#!/bin/bash - -# Display all commands before executing them. -set -o errexit -set -o errtrace - -LLVM_VERSION=$1 -LLVM_REPO_URL=${2:-https://github.com/llvm/llvm-project.git} -LLVM_CROSS="$3" - -if [[ -z "$LLVM_REPO_URL" || -z "$LLVM_VERSION" ]] -then - echo "Usage: $0 [aarch64]" - echo - echo "# Arguments" - echo " llvm-version The name of a LLVM release branch without the 'release/' prefix" - echo " llvm-repository-url The URL used to clone LLVM sources (default: https://github.com/llvm/llvm-project.git)" - echo " aarch64 To cross-compile an aarch64 version of LLVM" - - exit 1 -fi - -# Clone the LLVM project. -if [ ! -d llvm-project ] -then - git clone "$LLVM_REPO_URL" llvm-project -fi - - -cd llvm-project -git fetch origin -git checkout "release/$LLVM_VERSION" -git reset --hard origin/"release/$LLVM_VERSION" - -# Create a directory to build the project. -mkdir -p build -cd build - -# Create a directory to receive the complete installation. -mkdir -p install - -# Adjust compilation based on the OS. -CMAKE_ARGUMENTS="" - -case "${OSTYPE}" in - darwin*) ;; - linux*) ;; - *) ;; -esac - -# Adjust cross compilation -CROSS_COMPILE="" - -case "${LLVM_CROSS}" in - aarch64*) CROSS_COMPILE="-DLLVM_HOST_TRIPLE=aarch64-linux-gnu" ;; - *) ;; -esac - -# Run `cmake` to configure the project. -cmake \ - -G "Unix Makefiles" \ - -DCMAKE_BUILD_TYPE=MinSizeRel \ - -DCMAKE_INSTALL_PREFIX="/" \ - -DLLVM_ENABLE_PROJECTS="clang;lld" \ - -DLLVM_ENABLE_TERMINFO=OFF \ - -DLLVM_ENABLE_ZLIB=OFF \ - -DLLVM_INCLUDE_DOCS=OFF \ - -DLLVM_INCLUDE_EXAMPLES=OFF \ - -DLLVM_INCLUDE_GO_TESTS=OFF \ - -DLLVM_INCLUDE_TESTS=OFF \ - -DLLVM_INCLUDE_TOOLS=ON \ - -DLLVM_INCLUDE_UTILS=OFF \ - -DLLVM_OPTIMIZED_TABLEGEN=ON \ - -DLLVM_TARGETS_TO_BUILD="X86;AArch64" \ - "${CROSS_COMPILE}" \ - "${CMAKE_ARGUMENTS}" \ - ../llvm - -# Showtime! -cmake --build . --config MinSizeRel -DESTDIR=destdir cmake --install . --strip --config MinSizeRel - -# move usr/bin/* to bin/ or llvm-config will be broken -mv destdir/usr/bin/* destdir/bin/ diff --git a/scripts/build-windows/build.ps1 b/scripts/build-windows/build.ps1 deleted file mode 100644 index c6f81258a..000000000 --- a/scripts/build-windows/build.ps1 +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright The KCL Authors. All rights reserved. - -Set-Location $PSScriptRoot -# 1. Install kclvm_cli_cdylib.dll -Set-Location "..\..\kclvm" -# cargo build --release --features llvm -cargo build --release -Set-Location $PSScriptRoot - -New-Item -ErrorAction Ignore -Path ".\_output" -ItemType "directory" -New-Item -ErrorAction Ignore -Path ".\_output\kclvm-windows" -ItemType "directory" -New-Item -ErrorAction Ignore -Path ".\_output\kclvm-windows\bin" -ItemType "directory" - -Copy-Item -Path "..\..\kclvm\target\release\kclvm_cli_cdylib.dll" -Destination ".\_output\kclvm-windows\bin\kclvm_cli_cdylib.dll" -Force -Copy-Item -Path "..\..\kclvm\target\release\kclvm_cli_cdylib.dll.lib" -Destination ".\_output\kclvm-windows\bin\kclvm_cli_cdylib.lib" -Force -Copy-Item -Path "..\..\kclvm\target\release\kclvm_cli_cdylib.dll.lib" -Destination "..\..\kclvm\target\release\kclvm_cli_cdylib.lib" -Force - -Set-Location $PSScriptRoot -# 2. Install kclvm CLI -Set-Location "..\..\cli" -cargo build --release -Set-Location $PSScriptRoot -Copy-Item -Path "..\..\cli\target\release\kclvm_cli.exe" -Destination ".\_output\kclvm-windows\bin\" -Force - -Set-Location $PSScriptRoot -# 3. Install kcl language server -Set-Location "..\..\kclvm\tools\src\LSP" -cargo build --release -Set-Location $PSScriptRoot -Copy-Item -Path "..\..\kclvm\target\release\kcl-language-server.exe" -Destination ".\_output\kclvm-windows\bin\" - -Set-Location $PSScriptRoot -# Install hello.k -Copy-Item -Path "..\..\samples\hello.k" -Destination ".\_output\kclvm-windows" -Force - -# Run KCL files -.\_output\kclvm-windows\bin\kclvm_cli.exe run ..\..\samples\fib.k -.\_output\kclvm-windows\bin\kclvm_cli.exe run ..\..\samples\hello.k -.\_output\kclvm-windows\bin\kclvm_cli.exe run ..\..\samples\kubernetes.k -.\_output\kclvm-windows\bin\kclvm_cli.exe run ..\..\samples\math.k diff --git a/scripts/build-windows/clean.ps1 b/scripts/build-windows/clean.ps1 deleted file mode 100644 index 0088729bf..000000000 --- a/scripts/build-windows/clean.ps1 +++ /dev/null @@ -1,10 +0,0 @@ -# Copyright The KCL Authors. All rights reserved. - -Set-Location $PSScriptRoot - -Remove-Item -Recurse -Force "_output" -Remove-Item -Recurse -Force "*.obj" -Remove-Item -Recurse -Force "*.exp" -Remove-Item -Recurse -Force "*.lib" -Remove-Item -Recurse -Force "*.dll" -Remove-Item -Force "*.zip" diff --git a/scripts/build.ps1 b/scripts/build.ps1 new file mode 100644 index 000000000..cf9fab46e --- /dev/null +++ b/scripts/build.ps1 @@ -0,0 +1,30 @@ +# Copyright The KCL Authors. All rights reserved. + +Set-Location $PSScriptRoot +# 1. Install kcl.dll +Set-Location "..\" +cargo build --release +Set-Location $PSScriptRoot + +New-Item -ErrorAction Ignore -Path ".\_output" -ItemType "directory" +New-Item -ErrorAction Ignore -Path ".\_output\core" -ItemType "directory" + +Copy-Item -Path "..\target\release\kcl.dll" -Destination ".\_output\core\kcl.dll" -Force +Copy-Item -Path "..\target\release\kcl.dll.lib" -Destination ".\_output\core\kcl.lib" -Force +Copy-Item -Path "..\target\release\kcl.dll.lib" -Destination "..\target\release\kcl.lib" -Force + +Set-Location $PSScriptRoot +# 2. Install kcl language server +Set-Location "..\" +cargo build --release --manifest-path crates/tools/src/LSP/Cargo.toml +Set-Location $PSScriptRoot +Copy-Item -Path "..\target\release\kcl-language-server.exe" -Destination ".\_output\core\" + +Set-Location $PSScriptRoot +# 3. Install libkcl CLI +Set-Location "..\" +cargo build --release --manifest-path crates/cli/Cargo.toml +Set-Location $PSScriptRoot +Copy-Item -Path "..\target\release\libkcl.exe" -Destination ".\_output\core\" -Force + +Set-Location $PSScriptRoot diff --git a/scripts/build.sh b/scripts/build.sh index c9a2dfb88..a4470070a 100755 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -19,19 +19,13 @@ getSystemInfo() { getSystemInfo prepare_dirs () { - install_dir="$topdir/_build/dist/$os/kclvm" - mkdir -p "$install_dir/bin" + install_dir="_build/dist/$os/core" + mkdir -p "$install_dir" } prepare_dirs # 1. Build kcl native library - -cd $topdir/kclvm -export PATH=$PATH:/root/.cargo/bin:/usr/lib/llvm-12/bin -# Enable the llvm feature -# cargo build --release --features llvm -# Disable the llvm feature cargo build --release ## Switch dll file extension according to os. @@ -47,33 +41,26 @@ case $os in ;; esac -## Copy libkclvm_cli lib to the build folder - -if [ -e $topdir/kclvm/target/release/libkclvm_cli_cdylib.$dll_extension ]; then - touch $install_dir/bin/libkclvm_cli_cdylib.$dll_extension - rm $install_dir/bin/libkclvm_cli_cdylib.$dll_extension - cp $topdir/kclvm/target/release/libkclvm_cli_cdylib.$dll_extension $install_dir/bin/libkclvm_cli_cdylib.$dll_extension +## Copy kcl lib to the build folder +if [ -e target/release/libkcl.$dll_extension ]; then + touch $install_dir/libkcl.$dll_extension + rm $install_dir/libkcl.$dll_extension + cp target/release/libkcl.$dll_extension $install_dir/libkcl.$dll_extension fi ## 2. Build KCL language server binary +cargo build --release --manifest-path crates/tools/src/LSP/Cargo.toml -cd $topdir/kclvm/tools/src/LSP -cargo build --release - -touch $install_dir/bin/kcl-language-server -rm $install_dir/bin/kcl-language-server -cp $topdir/kclvm/target/release/kcl-language-server $install_dir/bin/kcl-language-server +touch $install_dir/kcl-language-server +rm $install_dir/kcl-language-server +cp target/release/kcl-language-server $install_dir/kcl-language-server ## 3. Build CLI +cargo build --release --manifest-path crates/cli/Cargo.toml -cd $topdir/cli -cargo build --release - -touch $install_dir/bin/kclvm_cli -rm $install_dir/bin/kclvm_cli -cp ./target/release/kclvm_cli $install_dir/bin/kclvm_cli - -cd $topdir +touch $install_dir/libkcl +rm $install_dir/libkcl +cp ./target/release/libkcl $install_dir/libkcl # Print the summary. echo "================ Summary ================" diff --git a/scripts/docker/kcl-builder-alpine/Dockerfile b/scripts/docker/kcl-builder-alpine/Dockerfile deleted file mode 100644 index de36fdca0..000000000 --- a/scripts/docker/kcl-builder-alpine/Dockerfile +++ /dev/null @@ -1,50 +0,0 @@ -# Copyright The KCL Authors. All rights reserved. - -FROM alpine:latest - -# set timezone -RUN apk add --no-cache tzdata \ - && cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \ - && echo 'Asia/Shanghai' >/etc/timezone - -# update repositories and install required packages -RUN apk add --no-cache \ - make \ - wget \ - git \ - ca-certificates \ - clang \ - llvm \ - libffi-dev \ - go \ - python3 \ - python3-dev \ - py3-pip - -# set environment variables -ENV GOPATH=/go \ - GOLANG_VERSION=1.20.5 \ - PATH="/root/.cargo/bin:${PATH}" \ - CARGO_NET_GIT_FETCH_WITH_CLI=true - -# install rust and cargo -RUN wget -qO- https://sh.rustup.rs | bash -s -- -y --default-toolchain 1.84.1 \ - && echo 'source $HOME/.cargo/env' >> $HOME/.ashrc \ - && . $HOME/.cargo/env \ - && cargo version \ - && rustc --version - -# install go tools -RUN go install golang.org/x/lint/golint@latest \ - && go install golang.org/x/tools/cmd/goimports@latest \ - && go install github.com/t-yuki/gocover-cobertura@latest \ - && go install github.com/jstemmer/go-junit-report@latest - -RUN rm -rf /root/.cache/go-build \ - && rm -rf /go/pkg/mod \ - && rm -rf /go/pkg/sumdb \ - && rm -rf /var/cache/apk/* - -WORKDIR /root - -CMD ["ash"] diff --git a/scripts/docker/kcl-builder-alpine/Makefile b/scripts/docker/kcl-builder-alpine/Makefile deleted file mode 100644 index 3a633c80c..000000000 --- a/scripts/docker/kcl-builder-alpine/Makefile +++ /dev/null @@ -1,30 +0,0 @@ -# Copyright The KCL Authors. All rights reserved. - -PWD:=$(shell pwd) - -BUILDER_IMAGE:=kcllang/kcl-builder-alpine - -# export DOCKER_DEFAULT_PLATFORM=linux/amd64 -# or -# --platform linux/amd64 - -RUN_IN_DOCKER:=docker run -it --rm --platform linux/amd64 -RUN_IN_DOCKER+=-v ~/.ssh:/root/.ssh -RUN_IN_DOCKER+=-v ~/.gitconfig:/root/.gitconfig -RUN_IN_DOCKER+=-v ~/go/pkg/mod:/go/pkg/mod - -kcl-builder: - docker build --platform linux/amd64 -t ${BUILDER_IMAGE} . - @echo "ok" - -publish-builder: - # docker login --username= - - # make kcl-builder - docker push ${BUILDER_IMAGE} - @echo "push ${BUILDER_IMAGE} ok" - -sh-in-builder: - ${RUN_IN_DOCKER} -v ${PWD}/../../..:/root/kclvm -w /root ${BUILDER_IMAGE} sh - -clean: diff --git a/scripts/docker/kcl-builder-arm64/Dockerfile b/scripts/docker/kcl-builder-arm64/Dockerfile deleted file mode 100644 index 5caf70256..000000000 --- a/scripts/docker/kcl-builder-arm64/Dockerfile +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright The KCL Authors. All rights reserved. -# Builder for ghcr.io/kcl-lang/kcl-builder-arm64 image - -FROM arm64v8/ubuntu:20.04 - -#RUN uname -a -#RUN cat /etc/os-release - -RUN apt-get update - -RUN apt-get install -y curl make gcc git zlib1g-dev -RUN apt install -y pkg-config libssl-dev - -# rust -RUN curl https://sh.rustup.rs -sSf | bash -s -- -y --default-toolchain 1.84.1 -ENV CARGO_NET_GIT_FETCH_WITH_CLI=true - -RUN cargo version -RUN rustc --version - -# clang12 -RUN apt-get install -y clang-12 lld-12 -RUN ln -sf /usr/bin/clang-12 /usr/bin/clang -RUN ln -sf /usr/bin/wasm-ld-12 /usr/bin/wasm-ld - -WORKDIR /root - -CMD ["bash"] diff --git a/scripts/docker/kcl-builder-centos7/Dockerfile b/scripts/docker/kcl-builder-centos7/Dockerfile deleted file mode 100644 index d3c456124..000000000 --- a/scripts/docker/kcl-builder-centos7/Dockerfile +++ /dev/null @@ -1,94 +0,0 @@ -# Copyright The KCL Authors. All rights reserved. - -FROM centos:centos7 - -# macOS M1 --platform linux/amd64 -# try fix "Problem with the SSL CA cert (path? access rights?)" -# https://issueexplorer.com/issue/docker/for-mac/5912 -# https://access.redhat.com/articles/2050743 -RUN touch /etc/sysconfig/64bit_strstr_via_64bit_strstr_sse2_unaligned - -# --------------------------------------------------------------------------------- -# Please note: The following steps are to install the dependency packages -# needed to compile CPython for centos7, see the -# [Python official website](https://devguide.python.org/setup/#install-dependencies) -# for details. When the version of CPython used becomes higher, -# please pay attention to update the installation dependencies. -# --------------------------------------------------------------------------------- - -# Some language environments and plug-ins related to development and compilation, -# such as git, CPython compilation, etc. -RUN yum groupinstall -y "Development Tools" -# Compiler and tool chain required to compile CPython such as gcc, make, sqlite3, ctype, struct, etc. -RUN yum install -y gcc patch libffi-devel python-devel zlib-devel bzip2-devel ncurses-devel sqlite-devel -RUN yum install -y libpcap-devel xz-devel readline-devel tk-devel gdbm-devel db4-deve -# Install the system libraries required by python3 for UNIX based systems -RUN yum -y install yum-utils -RUN yum-builddep -y python3 -# The python zlib module dependency package is required when compiling the python source code, -# in order to use the modules that require zlib, such as setuptools, etc. -RUN yum install -y zlib* -# The python ssl module dependency package is required when compiling the python source code, -# in order to use the modules that require ssl, such as pip3, twine, etc. -RUN yum install -y openssl-devel - -# Install which -RUN yum install -y which - -# Install wget -RUN yum install -y wget - -# Install git-2.x -# RUN yum -y install https://packages.endpoint.com/rhel/7/os/x86_64/endpoint-repo-1.7-1.x86_64.rpm -# RUN yum -y install git - -# rust -# https://www.rust-lang.org/tools/install -RUN curl https://sh.rustup.rs -sSf | bash -s -- -y --default-toolchain 1.84.1 -ENV PATH="/root/.cargo/bin:${PATH}" -ENV CARGO_NET_GIT_FETCH_WITH_CLI=true - -RUN cargo version -RUN rustc --version - -# wasm -RUN rustup target add wasm32-unknown-unknown - -# Install clang7 and llvm7 -# https://www.softwarecollections.org/en/scls/rhscl/llvm-toolset-7.0/ -# -# 1. Install a package with repository for your system: -# On CentOS, install package centos-release-scl available in CentOS repository: -# $ sudo yum install centos-release-scl -# -# On RHEL, enable RHSCL repository for you system: -# $ sudo yum-config-manager --enable rhel-server-rhscl-7-rpms -# -# 2. Install the collection: -# $ sudo yum install llvm-toolset-7.0 -# -# 3. Start using software collections: -# $ scl enable llvm-toolset-7.0 bash - -RUN yum -y install centos-release-scl -RUN yum-config-manager --enable rhel-server-rhscl-7-rpms -RUN yum -y install llvm-toolset-7.0 -RUN yum -y install llvm-toolset-7.0\* -RUN scl enable llvm-toolset-7.0 bash - -# Install gcc7 -RUN yum -y install devtoolset-7* -RUN scl enable devtoolset-7 bash -RUN gcc -v - -# rpm -ql llvm-toolset-7.0-clang.x86_64 -# /opt/rh/llvm-toolset-7.0/root/usr/lib64/libLLVM-7.so -ENV LD_LIBRARY_PATH="/opt/rh/llvm-toolset-7.0/root/usr/lib64:${LD_LIBRARY_PATH}" -ENV PATH="/opt/rh/llvm-toolset-7.0/root/usr/bin:${PATH}" - -RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime -RUN echo 'Asia/Shanghai' >/etc/timezone - -WORKDIR /root - -CMD ["bash"] diff --git a/scripts/docker/kcl-builder-centos7/Makefile b/scripts/docker/kcl-builder-centos7/Makefile deleted file mode 100644 index 264e80492..000000000 --- a/scripts/docker/kcl-builder-centos7/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright The KCL Authors. All rights reserved. - -PWD:=$(shell pwd) - -BUILDER_IMAGE:=kcllang/kcl-builder:centos7 - -# export DOCKER_DEFAULT_PLATFORM=linux/amd64 -# or -# --platform linux/amd64 - -RUN_IN_DOCKER:=docker run -it --rm --platform linux/amd64 -RUN_IN_DOCKER+=-v ~/.ssh:/root/.ssh -RUN_IN_DOCKER+=-v ~/.gitconfig:/root/.gitconfig -RUN_IN_DOCKER+=-v ~/go/pkg/mod:/go/pkg/mod - -kcl-builder: - docker build --platform linux/amd64 -t ${BUILDER_IMAGE} . - @echo "ok" - -publish-builder: - # https://docker.inc.com/ - # docker login --username= - - # make kcl-builder - docker push ${BUILDER_IMAGE} - @echo "push ${BUILDER_IMAGE} ok" - -sh: - ${RUN_IN_DOCKER} -v ${PWD}/../../..:/root/kclvm -w /root ${BUILDER_IMAGE} bash - -clean: diff --git a/scripts/docker/kcl-builder-centos8/Dockerfile b/scripts/docker/kcl-builder-centos8/Dockerfile deleted file mode 100644 index dfb51eef9..000000000 --- a/scripts/docker/kcl-builder-centos8/Dockerfile +++ /dev/null @@ -1,76 +0,0 @@ -# Copyright The KCL Authors. All rights reserved. - -FROM centos:centos8 - -# macOS M1 --platform linux/amd64 -# try fix "Problem with the SSL CA cert (path? access rights?)" -# https://issueexplorer.com/issue/docker/for-mac/5912 -# https://access.redhat.com/articles/2050743 -RUN touch /etc/sysconfig/64bit_strstr_via_64bit_strstr_sse2_unaligned - -# https://forketyfork.medium.com/centos-8-no-urls-in-mirrorlist-error-3f87c3466faa -RUN sed -i -e "s|mirrorlist=|#mirrorlist=|g" /etc/yum.repos.d/CentOS-* -RUN sed -i -e "s|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g" /etc/yum.repos.d/CentOS-* - -RUN yum -y install make -RUN yum -y install which -RUN yum -y install wget -RUN yum -y install git - -# ca-certificates -RUN yum -y install ca-certificates - -# rust-1.54.0 -# cargo 1.54.0 -# RUN yum -y install rust cargo rustfmt -RUN curl https://sh.rustup.rs -sSf | bash -s -- -y --default-toolchain 1.84.1 -RUN echo 'source $HOME/.cargo/env' >> $HOME/.bashrc - -ENV PATH="/root/.cargo/bin:${PATH}" -ENV CARGO_NET_GIT_FETCH_WITH_CLI=true - -RUN cargo version -RUN rustc --version - -# clang-12 -RUN yum -y install clang -RUN clang --version - -# llvm-12 -RUN yum -y install llvm-devel -RUN yum -y install libffi-devel -RUN ln -s /usr/lib64/libtinfo.so.6 /usr/lib64/libtinfo.so - -# golang 1.19+ -RUN mkdir -p /root/download && cd /root/download \ - && wget https://dl.google.com/go/go1.20.5.linux-amd64.tar.gz \ - && tar -zxvf go1.20.5.linux-amd64.tar.gz \ - && mv ./go /usr/local/go1.20.5 -RUN ln -sf /usr/local/go1.20.5/bin/go /usr/bin/go -RUN rm -rf /root/download - -ENV GOPATH=/go -ENV GOLANG_VERSION=1.20.5 - -RUN go install golang.org/x/lint/golint@latest -RUN go install golang.org/x/tools/cmd/goimports@latest -# RUN go install honnef.co/go/tools/cmd/...@latest - -RUN go install github.com/t-yuki/gocover-cobertura@latest -RUN go install github.com/jstemmer/go-junit-report@latest - -RUN rm -rf /go/pkg/mod -RUN rm -rf /go/pkg/sumdb - -# /usr/lib64/python3.9 -RUN yum -y install python39-devel -RUN python3 -m pip install pytest - -RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime -RUN echo 'Asia/Shanghai' >/etc/timezone - -RUN mkdir -p /root/.cargo && touch /root/.cargo/env - -WORKDIR /root - -CMD ["bash"] diff --git a/scripts/docker/kcl-builder-centos8/Makefile b/scripts/docker/kcl-builder-centos8/Makefile deleted file mode 100644 index b5ed668aa..000000000 --- a/scripts/docker/kcl-builder-centos8/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright The KCL Authors. All rights reserved. - -PWD:=$(shell pwd) - -BUILDER_IMAGE:=kcllang/kcl-builder:centos8 - -# export DOCKER_DEFAULT_PLATFORM=linux/amd64 -# or -# --platform linux/amd64 - -RUN_IN_DOCKER:=docker run -it --rm --platform linux/amd64 -RUN_IN_DOCKER+=-v ~/.ssh:/root/.ssh -RUN_IN_DOCKER+=-v ~/.gitconfig:/root/.gitconfig -RUN_IN_DOCKER+=-v ~/go/pkg/mod:/go/pkg/mod - -kcl-builder: - docker build --platform linux/amd64 -t ${BUILDER_IMAGE} . - @echo "ok" - -publish-builder: - # https://docker.inc.com/ - # docker login --username= - - # make kcl-builder - docker push ${BUILDER_IMAGE} - @echo "push ${BUILDER_IMAGE} ok" - -sh-in-builder: - ${RUN_IN_DOCKER} -v ${PWD}/../../..:/root/kclvm -w /root ${BUILDER_IMAGE} bash - -clean: diff --git a/scripts/docker/kcl-builder-fedora39/Dockerfile b/scripts/docker/kcl-builder-fedora39/Dockerfile deleted file mode 100644 index ccf3a9be8..000000000 --- a/scripts/docker/kcl-builder-fedora39/Dockerfile +++ /dev/null @@ -1,46 +0,0 @@ -# Copyright The KCL Authors. All rights reserved. - -FROM fedora:39 - -# Fix SSL CA cert issue -RUN touch /etc/sysconfig/64bit_strstr_via_64bit_strstr_sse2_unaligned - -# Fix mirrorlist issue -RUN sed -i -e "s|metalink=|#metalink=|g" /etc/yum.repos.d/fedora*.repo -RUN sed -i -e "s|#baseurl=http://download.example/pub/fedora/linux|baseurl=https://dl.fedoraproject.org/pub/fedora/linux|g" /etc/yum.repos.d/fedora*.repo - -# install necessary packages -RUN dnf -y install make which wget git ca-certificates clang llvm-devel libffi-devel python3-devel - -# rust -RUN curl https://sh.rustup.rs -sSf | bash -s -- -y --default-toolchain 1.84.0 - echo 'source $HOME/.cargo/env' >> $HOME/.bashrc -ENV PATH="/root/.cargo/bin:${PATH}" -ENV CARGO_NET_GIT_FETCH_WITH_CLI=true - -# go -RUN mkdir -p /root/download && cd /root/download \ - && wget https://dl.google.com/go/go1.20.5.linux-amd64.tar.gz \ - && tar -zxvf go1.20.5.linux-amd64.tar.gz \ - && mv ./go /usr/local/go1.20.5 -RUN ln -sf /usr/local/go1.20.5/bin/go /usr/bin/go -RUN rm -rf /root/download -ENV GOPATH=/go -ENV GOLANG_VERSION=1.20.5 - -# go tools -RUN go install golang.org/x/lint/golint@latest \ - && go install golang.org/x/tools/cmd/goimports@latest \ - && go install github.com/t-yuki/gocover-cobertura@latest \ - && go install github.com/jstemmer/go-junit-report@latest - -RUN python3 -m pip install pytest - -RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime -RUN echo 'Asia/Shanghai' >/etc/timezone - -RUN mkdir -p /root/.cargo && touch /root/.cargo/env - -WORKDIR /root - -CMD ["bash"] diff --git a/scripts/docker/kcl-builder-fedora39/Makefile b/scripts/docker/kcl-builder-fedora39/Makefile deleted file mode 100644 index fadde5364..000000000 --- a/scripts/docker/kcl-builder-fedora39/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -PWD := $(shell pwd) - -BUILDER_IMAGE := kcllang/kcl-builder-fedora39 - -RUN_IN_DOCKER:=docker run -it --rm --platform linux/amd64 -RUN_IN_DOCKER+=-v ~/.ssh:/root/.ssh -RUN_IN_DOCKER+=-v ~/.gitconfig:/root/.gitconfig -RUN_IN_DOCKER+=-v ~/go/pkg/mod:/go/pkg/mod - -kcl-builder: - docker build --platform linux/amd64 -t ${BUILDER_IMAGE} . - @echo "ok" - -publish-builder: - # https://docker.inc.com/ - # docker login --username= - - # make kcl-builder - docker push ${BUILDER_IMAGE} - @echo "push ${BUILDER_IMAGE} ok" - -sh-in-builder: - ${RUN_IN_DOCKER} -v ${PWD}/../../..:/root/kclvm -w /root ${BUILDER_IMAGE} bash - -clean: \ No newline at end of file diff --git a/scripts/docker/kcl-builder/Dockerfile b/scripts/docker/kcl-builder/Dockerfile deleted file mode 100644 index 422ed5d6a..000000000 --- a/scripts/docker/kcl-builder/Dockerfile +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright The KCL Authors. All rights reserved. - -FROM ghcr.io/zong-zhe/ubuntu:22.04 - -#RUN uname -a -#RUN cat /etc/os-release - -RUN apt-get update - -RUN apt-get install -y git wget curl -RUN apt-get install -y make gcc patch g++ swig -RUN apt-get install -y python3-dev libffi-dev -# SSL module deps sed by python3 -RUN apt-get install -y zlib1g-dev ncurses-dev build-essential libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev - -# python-3.9 -RUN mkdir -p /root/download && cd /root/download \ - && wget https://www.python.org/ftp/python/3.9.10/Python-3.9.10.tgz \ - && tar -xzf Python-3.9.10.tgz \ - && cd Python-3.9.10 \ - && LANG=C.UTF-8 ./configure \ - --prefix=/usr/local/python3.9 \ - --enable-optimizations \ - --with-ssl \ - && make install -RUN ln -sf /usr/local/python3.9/bin/python3.9 /usr/bin/python3 -RUN ln -sf /usr/local/python3.9/bin/python3.9 /usr/bin/python3.9 - -# rust -# https://www.rust-lang.org/tools/install -RUN curl https://sh.rustup.rs -sSf | bash -s -- -y --default-toolchain 1.84.1 -ENV PATH="/root/.cargo/bin:${PATH}" -ENV CARGO_NET_GIT_FETCH_WITH_CLI=true - -RUN cargo version -RUN rustc --version - -# wasm -RUN rustup target add wasm32-unknown-unknown - -# clang12 -RUN apt-get install -y clang-12 lld-12 -RUN ln -sf /usr/bin/clang-12 /usr/bin/clang -RUN ln -sf /usr/bin/wasm-ld-12 /usr/bin/wasm-ld - -# golang 1.20+ -RUN mkdir -p /root/download && cd /root/download \ - && wget https://dl.google.com/go/go1.20.5.linux-amd64.tar.gz \ - && tar -zxvf go1.20.5.linux-amd64.tar.gz \ - && mv ./go /usr/local/go1.20.5 -RUN ln -sf /usr/local/go1.20.5/bin/go /usr/bin/go - -ENV GOPATH=/go -ENV GOLANG_VERSION=1.20.5 - -RUN go install golang.org/x/lint/golint@latest -RUN go install golang.org/x/tools/cmd/goimports@latest -RUN go install honnef.co/go/tools/cmd/...@latest - -RUN go install github.com/t-yuki/gocover-cobertura@latest -RUN go install github.com/jstemmer/go-junit-report@latest - -RUN rm -rf /go/pkg/mod -RUN rm -rf /go/pkg/sumdb - -RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime -RUN echo 'Asia/Shanghai' >/etc/timezone - -WORKDIR /root - -CMD ["bash"] diff --git a/scripts/docker/kcl-builder/Makefile b/scripts/docker/kcl-builder/Makefile deleted file mode 100644 index 4e3f78a68..000000000 --- a/scripts/docker/kcl-builder/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright The KCL Authors. All rights reserved. - -PWD:=$(shell pwd) - -BUILDER_IMAGE:=kcllang/kcl-builder - -# export DOCKER_DEFAULT_PLATFORM=linux/amd64 -# or -# --platform linux/amd64 - -RUN_IN_DOCKER:=docker run -it --rm --platform linux/amd64 -RUN_IN_DOCKER+=-v ~/.ssh:/root/.ssh -RUN_IN_DOCKER+=-v ~/.gitconfig:/root/.gitconfig -RUN_IN_DOCKER+=-v ~/go/pkg/mod:/go/pkg/mod - -kcl-builder: - docker build --platform linux/amd64 -t ${BUILDER_IMAGE} . - @echo "ok" - -publish-builder: - # https://docker.inc.com/ - # docker login --username= - - # make kcl-builder - docker push ${BUILDER_IMAGE} - @echo "push ${BUILDER_IMAGE} ok" - -sh: - ${RUN_IN_DOCKER} -v ${PWD}/../../..:/root/kclvm -w /root ${BUILDER_IMAGE} bash - -clean: diff --git a/scripts/release.sh b/scripts/release.sh index ad660bd1e..ee1489cbf 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -23,16 +23,16 @@ getSystemInfo echo "[info] os: $os" echo "[info] arch: $arch" echo "[info] version: $version" -release_file="kclvm-$version-$os-$arch.tar.gz" -release_path="$topdir/_build" -package_dir="$topdir/_build/dist/$os" -install_dir="kclvm" +release_file="kcl-$version-$os-$arch.tar.gz" +release_path="_build" +package_dir="_build/dist/$os" +install_dir="core" cd $package_dir tar -czvf $release_file $install_dir - -mv $package_dir/$release_file $release_path/$release_file +cd ../../.. +ls -l "$package_dir/$release_file" # Print the summary. echo "================ Summary ================" -echo " $release_path/$release_file has been created" +echo " $package_dir/$release_file has been created" diff --git a/scripts/tag.sh b/scripts/tag.sh deleted file mode 100755 index b9286c58e..000000000 --- a/scripts/tag.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env sh -set -e -if [ "$1" == "" ]; then - echo usage: "$0 VERSION" -fi -git tag $1 -git push origin $1 -gh release create $1 --draft --generate-notes --title "$1 Release" diff --git a/test/grammar/attr_operator/schema_inside/override/test_2/main.k b/test/grammar/attr_operator/schema_inside/override/test_2/main.k deleted file mode 100644 index 1c1ca35b5..000000000 --- a/test/grammar/attr_operator/schema_inside/override/test_2/main.k +++ /dev/null @@ -1,13 +0,0 @@ -schema Config: - name: str - args: [str] - -schema Data: - config: Config { - name = "config" - args: ["kcl", "-d"] - args = ["kclvm"] - name = "kclvm" - } - -data = Data {} diff --git a/test/grammar/attr_operator/schema_inside/override/test_2/stdout.golden b/test/grammar/attr_operator/schema_inside/override/test_2/stdout.golden deleted file mode 100644 index 3506f2d82..000000000 --- a/test/grammar/attr_operator/schema_inside/override/test_2/stdout.golden +++ /dev/null @@ -1,5 +0,0 @@ -data: - config: - name: kclvm - args: - - kclvm diff --git a/test/grammar/attr_operator/schema_inside/override/test_3/main.k b/test/grammar/attr_operator/schema_inside/override/test_3/main.k deleted file mode 100644 index d988ec61c..000000000 --- a/test/grammar/attr_operator/schema_inside/override/test_3/main.k +++ /dev/null @@ -1,14 +0,0 @@ -schema Config: - name: str - args: [str] - -schema Data: - _config: Config { - name = "config" - args: ["kcl", "-d"] - args = ["kclvm"] - name = "kclvm" - } - config: Config = _config | {name = "override"} - -data = Data {} diff --git a/test/grammar/attr_operator/schema_inside/override/test_3/stdout.golden b/test/grammar/attr_operator/schema_inside/override/test_3/stdout.golden deleted file mode 100644 index f93216f52..000000000 --- a/test/grammar/attr_operator/schema_inside/override/test_3/stdout.golden +++ /dev/null @@ -1,5 +0,0 @@ -data: - config: - name: override - args: - - kclvm diff --git a/test/grammar/datatype/range_check_float/overflow/number_0/stderr.golden b/test/grammar/datatype/range_check_float/overflow/number_0/stderr.golden deleted file mode 100644 index 4e89012b0..000000000 --- a/test/grammar/datatype/range_check_float/overflow/number_0/stderr.golden +++ /dev/null @@ -1,9 +0,0 @@ -error[E3M38]: EvaluationError - --> ${CWD}/main.k:8:1 - | -8 | a = uplimit * (100 + epsilon) - | 3.4e+40: A 32-bit floating point number overflow - | -note: backtrace: - 0: kclvm_main - at ${CWD}/main.k:8 \ No newline at end of file diff --git a/test/grammar/datatype/range_check_int/augment_assign_fail_0/stderr.golden b/test/grammar/datatype/range_check_int/augment_assign_fail_0/stderr.golden deleted file mode 100644 index 597779eb5..000000000 --- a/test/grammar/datatype/range_check_int/augment_assign_fail_0/stderr.golden +++ /dev/null @@ -1,9 +0,0 @@ -error[E3M38]: EvaluationError - --> ${CWD}/main.k:2:1 - | -2 | _a += 1 - | 2147483648: A 32 bit integer overflow - | -note: backtrace: - 0: kclvm_main - at ${CWD}/main.k:2 \ No newline at end of file diff --git a/test/grammar/datatype/range_check_int/augment_assign_fail_1/stderr.golden b/test/grammar/datatype/range_check_int/augment_assign_fail_1/stderr.golden deleted file mode 100644 index 3af756538..000000000 --- a/test/grammar/datatype/range_check_int/augment_assign_fail_1/stderr.golden +++ /dev/null @@ -1,9 +0,0 @@ -error[E3M38]: EvaluationError - --> ${CWD}/main.k:2:1 - | -2 | _a += 1 - | 9223372036854775808: A 64 bit integer overflow - | -note: backtrace: - 0: kclvm_main - at ${CWD}/main.k:2 \ No newline at end of file diff --git a/test/grammar/datatype/range_check_int/augment_assign_fail_2/stderr.golden b/test/grammar/datatype/range_check_int/augment_assign_fail_2/stderr.golden deleted file mode 100644 index 3af756538..000000000 --- a/test/grammar/datatype/range_check_int/augment_assign_fail_2/stderr.golden +++ /dev/null @@ -1,9 +0,0 @@ -error[E3M38]: EvaluationError - --> ${CWD}/main.k:2:1 - | -2 | _a += 1 - | 9223372036854775808: A 64 bit integer overflow - | -note: backtrace: - 0: kclvm_main - at ${CWD}/main.k:2 \ No newline at end of file diff --git a/test/grammar/datatype/range_check_int/augment_assign_fail_3/stderr.golden b/test/grammar/datatype/range_check_int/augment_assign_fail_3/stderr.golden deleted file mode 100644 index 597779eb5..000000000 --- a/test/grammar/datatype/range_check_int/augment_assign_fail_3/stderr.golden +++ /dev/null @@ -1,9 +0,0 @@ -error[E3M38]: EvaluationError - --> ${CWD}/main.k:2:1 - | -2 | _a += 1 - | 2147483648: A 32 bit integer overflow - | -note: backtrace: - 0: kclvm_main - at ${CWD}/main.k:2 \ No newline at end of file diff --git a/test/integration/konfig b/test/integration/konfig deleted file mode 160000 index 9f8ec32b7..000000000 --- a/test/integration/konfig +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 9f8ec32b7785b00da4979f95072eceda4b7afdab diff --git a/test/integration/test_konfig.bat b/test/integration/test_konfig.bat deleted file mode 100644 index 7dc24bc9d..000000000 --- a/test/integration/test_konfig.bat +++ /dev/null @@ -1,5 +0,0 @@ -cd %~dp0 - -python3 -m pip install --upgrade pip -python3 -m pip install kclvm pytest pytest-xdist -python3 -m pytest -vv -n 10 diff --git a/test/integration/test_konfig_kcl.py b/test/integration/test_konfig_kcl.py deleted file mode 100644 index ed99a55a3..000000000 --- a/test/integration/test_konfig_kcl.py +++ /dev/null @@ -1,123 +0,0 @@ -""" -this testing framework is developed based on pytest. -see quick start of pytest: https://docs.pytest.org/en/latest/example/simple.html - -""" -import os -import subprocess -from pathlib import Path - -import pytest -from ruamel.yaml import YAML -from collections.abc import Mapping, Sequence - -TEST_FILE = "kcl.yaml" -CI_TEST_DIR = "ci-test" -STDOUT_GOLDEN = "stdout.golden.yaml" -SETTINGS_FILE = "settings.yaml" - -ROOT_STR = "konfig" -ROOT = str(Path(__file__).parent.joinpath(ROOT_STR)) - -yaml = YAML(typ="unsafe", pure=True) - - -def find_test_dirs(): - result = [] - root_dirs = [ROOT] - for root_dir in root_dirs: - for root, _, files in os.walk(root_dir): - for name in files: - if name == TEST_FILE: - result.append(root) - return result - - -def compare_results(result, golden_result): - """Convert result and golden_result string to string lines with line ending stripped, then compare.""" - result = [ - r - for r in list(yaml.load_all(result)) - if r and r.get("kind") != "SecretProviderClass" - ] - # Convert kusion compile spec to kcl result - expected = [ - r - for r in list(yaml.load_all(golden_result))[0] - if r["attributes"] - # Remove CRDs - and not r["id"].startswith("apiextensions.k8s.io/v1:CustomResourceDefinition") - ] - print(len(result), len(expected)) - assert compare_unordered_yaml_objects(result, expected) - - -def compare_unordered_yaml_objects(result, golden_result): - """Comparing the contents of two YAML objects for equality in an unordered manner""" - if isinstance(result, Mapping) and isinstance(golden_result, Mapping): - if result.keys() != golden_result.keys(): - return False - for key in result.keys(): - if not compare_unordered_yaml_objects(result[key], golden_result[key]): - return False - - return True - elif isinstance(result, Sequence) and isinstance(golden_result, Sequence): - if len(result) != len(golden_result): - return False - for item in result: - if item not in golden_result: - return False - for item in golden_result: - if item not in result: - return False - return True - else: - return result == golden_result - - -def has_settings_file(directory): - settings_file = directory / SETTINGS_FILE - return settings_file.is_file() - - -print("##### K Language Grammar Test Suite #####") -test_dirs = find_test_dirs() -pwd = str(Path(__file__).parent.parent.parent) -os.environ["PYTHONPATH"] = pwd - - -@pytest.mark.parametrize("test_dir", test_dirs) -def test_konfigs(test_dir): - print(f"Testing {test_dir}") - test_dir = Path(test_dir) - kcl_file_name = test_dir / TEST_FILE - ci_test_dir = test_dir / CI_TEST_DIR - if not ci_test_dir.is_dir(): - # Skip invalid test cases - return - golden_file = ci_test_dir / STDOUT_GOLDEN - if not golden_file.is_file(): - # Skip invalid test cases - return - kcl_command = ["kcl"] - if has_settings_file(ci_test_dir): - kcl_command.append("-Y") - kcl_command.append(f"{CI_TEST_DIR}/{SETTINGS_FILE}") - kcl_command.append(f"kcl.yaml") - else: - kcl_command.append(f"{TEST_FILE}") - process = subprocess.run( - kcl_command, capture_output=True, cwd=test_dir, env=dict(os.environ) - ) - stdout, stderr = process.stdout, process.stderr - print(f"STDOUT:\n{stdout.decode()}") - assert ( - process.returncode == 0 and len(stderr) == 0 - ), f"Error executing file {kcl_file_name}.\nexit code = {process.returncode}\nstderr = {stderr}" - if process.returncode == 0 and len(stderr) == 0: - try: - with open(golden_file, "r") as golden: - compare_results(stdout.decode(), golden) - except FileNotFoundError: - raise Exception(f"Error reading expected result from file {golden_file}") diff --git a/test/grammar/assert/assert_if/assert_if_0/main.k b/tests/grammar/assert/assert_if/assert_if_0/main.k similarity index 100% rename from test/grammar/assert/assert_if/assert_if_0/main.k rename to tests/grammar/assert/assert_if/assert_if_0/main.k diff --git a/test/grammar/assert/assert_if/assert_if_0/stdout.golden b/tests/grammar/assert/assert_if/assert_if_0/stdout.golden similarity index 100% rename from test/grammar/assert/assert_if/assert_if_0/stdout.golden rename to tests/grammar/assert/assert_if/assert_if_0/stdout.golden diff --git a/test/grammar/assert/assert_if/assert_if_1/main.k b/tests/grammar/assert/assert_if/assert_if_1/main.k similarity index 100% rename from test/grammar/assert/assert_if/assert_if_1/main.k rename to tests/grammar/assert/assert_if/assert_if_1/main.k diff --git a/test/grammar/assert/assert_if/assert_if_1/stdout.golden b/tests/grammar/assert/assert_if/assert_if_1/stdout.golden similarity index 100% rename from test/grammar/assert/assert_if/assert_if_1/stdout.golden rename to tests/grammar/assert/assert_if/assert_if_1/stdout.golden diff --git a/test/grammar/assert/assert_if/assert_if_2/main.k b/tests/grammar/assert/assert_if/assert_if_2/main.k similarity index 100% rename from test/grammar/assert/assert_if/assert_if_2/main.k rename to tests/grammar/assert/assert_if/assert_if_2/main.k diff --git a/test/grammar/assert/assert_if/assert_if_2/stdout.golden b/tests/grammar/assert/assert_if/assert_if_2/stdout.golden similarity index 100% rename from test/grammar/assert/assert_if/assert_if_2/stdout.golden rename to tests/grammar/assert/assert_if/assert_if_2/stdout.golden diff --git a/test/grammar/assert/invalid/fail_0/main.k b/tests/grammar/assert/invalid/fail_0/main.k similarity index 100% rename from test/grammar/assert/invalid/fail_0/main.k rename to tests/grammar/assert/invalid/fail_0/main.k diff --git a/test/grammar/assert/invalid/fail_0/stderr.golden b/tests/grammar/assert/invalid/fail_0/stderr.golden similarity index 100% rename from test/grammar/assert/invalid/fail_0/stderr.golden rename to tests/grammar/assert/invalid/fail_0/stderr.golden diff --git a/test/grammar/assert/invalid/fail_1/main.k b/tests/grammar/assert/invalid/fail_1/main.k similarity index 100% rename from test/grammar/assert/invalid/fail_1/main.k rename to tests/grammar/assert/invalid/fail_1/main.k diff --git a/test/grammar/assert/invalid/fail_1/stderr.golden b/tests/grammar/assert/invalid/fail_1/stderr.golden similarity index 100% rename from test/grammar/assert/invalid/fail_1/stderr.golden rename to tests/grammar/assert/invalid/fail_1/stderr.golden diff --git a/test/grammar/assert/invalid/fail_2/main.k b/tests/grammar/assert/invalid/fail_2/main.k similarity index 100% rename from test/grammar/assert/invalid/fail_2/main.k rename to tests/grammar/assert/invalid/fail_2/main.k diff --git a/test/grammar/assert/invalid/fail_2/stderr.golden b/tests/grammar/assert/invalid/fail_2/stderr.golden similarity index 100% rename from test/grammar/assert/invalid/fail_2/stderr.golden rename to tests/grammar/assert/invalid/fail_2/stderr.golden diff --git a/test/grammar/assert/invalid/fail_3/main.k b/tests/grammar/assert/invalid/fail_3/main.k similarity index 100% rename from test/grammar/assert/invalid/fail_3/main.k rename to tests/grammar/assert/invalid/fail_3/main.k diff --git a/test/grammar/assert/invalid/fail_3/stderr.golden b/tests/grammar/assert/invalid/fail_3/stderr.golden similarity index 100% rename from test/grammar/assert/invalid/fail_3/stderr.golden rename to tests/grammar/assert/invalid/fail_3/stderr.golden diff --git a/test/grammar/assert/valid/valid_0/main.k b/tests/grammar/assert/valid/valid_0/main.k similarity index 100% rename from test/grammar/assert/valid/valid_0/main.k rename to tests/grammar/assert/valid/valid_0/main.k diff --git a/test/grammar/assert/valid/valid_0/stdout.golden b/tests/grammar/assert/valid/valid_0/stdout.golden similarity index 100% rename from test/grammar/assert/valid/valid_0/stdout.golden rename to tests/grammar/assert/valid/valid_0/stdout.golden diff --git a/test/grammar/assert/valid/valid_1/main.k b/tests/grammar/assert/valid/valid_1/main.k similarity index 100% rename from test/grammar/assert/valid/valid_1/main.k rename to tests/grammar/assert/valid/valid_1/main.k diff --git a/test/grammar/assert/valid/valid_1/stdout.golden b/tests/grammar/assert/valid/valid_1/stdout.golden similarity index 100% rename from test/grammar/assert/valid/valid_1/stdout.golden rename to tests/grammar/assert/valid/valid_1/stdout.golden diff --git a/test/grammar/assign/assign_0/main.k b/tests/grammar/assign/assign_0/main.k similarity index 100% rename from test/grammar/assign/assign_0/main.k rename to tests/grammar/assign/assign_0/main.k diff --git a/test/grammar/assign/assign_0/stdout.golden b/tests/grammar/assign/assign_0/stdout.golden similarity index 100% rename from test/grammar/assign/assign_0/stdout.golden rename to tests/grammar/assign/assign_0/stdout.golden diff --git a/test/grammar/assign/assign_1/main.k b/tests/grammar/assign/assign_1/main.k similarity index 100% rename from test/grammar/assign/assign_1/main.k rename to tests/grammar/assign/assign_1/main.k diff --git a/test/grammar/assign/assign_1/stdout.golden b/tests/grammar/assign/assign_1/stdout.golden similarity index 100% rename from test/grammar/assign/assign_1/stdout.golden rename to tests/grammar/assign/assign_1/stdout.golden diff --git a/test/grammar/assign/assign_fail_0/main.k b/tests/grammar/assign/assign_fail_0/main.k similarity index 100% rename from test/grammar/assign/assign_fail_0/main.k rename to tests/grammar/assign/assign_fail_0/main.k diff --git a/test/grammar/assign/assign_fail_0/stderr.golden b/tests/grammar/assign/assign_fail_0/stderr.golden similarity index 100% rename from test/grammar/assign/assign_fail_0/stderr.golden rename to tests/grammar/assign/assign_fail_0/stderr.golden diff --git a/test/grammar/assign/assign_fail_1/main.k b/tests/grammar/assign/assign_fail_1/main.k similarity index 100% rename from test/grammar/assign/assign_fail_1/main.k rename to tests/grammar/assign/assign_fail_1/main.k diff --git a/test/grammar/assign/assign_fail_1/stderr.golden b/tests/grammar/assign/assign_fail_1/stderr.golden similarity index 100% rename from test/grammar/assign/assign_fail_1/stderr.golden rename to tests/grammar/assign/assign_fail_1/stderr.golden diff --git a/test/grammar/assign/assign_fail_2/main.k b/tests/grammar/assign/assign_fail_2/main.k similarity index 100% rename from test/grammar/assign/assign_fail_2/main.k rename to tests/grammar/assign/assign_fail_2/main.k diff --git a/test/grammar/assign/assign_fail_2/stderr.golden b/tests/grammar/assign/assign_fail_2/stderr.golden similarity index 100% rename from test/grammar/assign/assign_fail_2/stderr.golden rename to tests/grammar/assign/assign_fail_2/stderr.golden diff --git a/test/grammar/assign/assign_fail_3/main.k b/tests/grammar/assign/assign_fail_3/main.k similarity index 100% rename from test/grammar/assign/assign_fail_3/main.k rename to tests/grammar/assign/assign_fail_3/main.k diff --git a/test/grammar/assign/assign_fail_3/stderr.golden b/tests/grammar/assign/assign_fail_3/stderr.golden similarity index 100% rename from test/grammar/assign/assign_fail_3/stderr.golden rename to tests/grammar/assign/assign_fail_3/stderr.golden diff --git a/test/grammar/assign/assign_fail_4/main.k b/tests/grammar/assign/assign_fail_4/main.k similarity index 100% rename from test/grammar/assign/assign_fail_4/main.k rename to tests/grammar/assign/assign_fail_4/main.k diff --git a/test/grammar/assign/assign_fail_4/stderr.golden b/tests/grammar/assign/assign_fail_4/stderr.golden similarity index 100% rename from test/grammar/assign/assign_fail_4/stderr.golden rename to tests/grammar/assign/assign_fail_4/stderr.golden diff --git a/test/grammar/assign/assign_fail_5/main.k b/tests/grammar/assign/assign_fail_5/main.k similarity index 100% rename from test/grammar/assign/assign_fail_5/main.k rename to tests/grammar/assign/assign_fail_5/main.k diff --git a/test/grammar/assign/assign_fail_5/stderr.golden b/tests/grammar/assign/assign_fail_5/stderr.golden similarity index 100% rename from test/grammar/assign/assign_fail_5/stderr.golden rename to tests/grammar/assign/assign_fail_5/stderr.golden diff --git a/test/grammar/assign/assign_fail_6/main.k b/tests/grammar/assign/assign_fail_6/main.k similarity index 100% rename from test/grammar/assign/assign_fail_6/main.k rename to tests/grammar/assign/assign_fail_6/main.k diff --git a/test/grammar/assign/assign_fail_6/stderr.golden b/tests/grammar/assign/assign_fail_6/stderr.golden similarity index 100% rename from test/grammar/assign/assign_fail_6/stderr.golden rename to tests/grammar/assign/assign_fail_6/stderr.golden diff --git a/test/grammar/attr_operator/config_inside/insert/dict_0/main.k b/tests/grammar/attr_operator/config_inside/insert/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_0/main.k rename to tests/grammar/attr_operator/config_inside/insert/dict_0/main.k diff --git a/test/grammar/attr_operator/config_inside/insert/dict_0/stdout.golden b/tests/grammar/attr_operator/config_inside/insert/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_0/stdout.golden rename to tests/grammar/attr_operator/config_inside/insert/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/insert/dict_1/main.k b/tests/grammar/attr_operator/config_inside/insert/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_1/main.k rename to tests/grammar/attr_operator/config_inside/insert/dict_1/main.k diff --git a/test/grammar/attr_operator/config_inside/insert/dict_1/stdout.golden b/tests/grammar/attr_operator/config_inside/insert/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_1/stdout.golden rename to tests/grammar/attr_operator/config_inside/insert/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/insert/dict_2/main.k b/tests/grammar/attr_operator/config_inside/insert/dict_2/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_2/main.k rename to tests/grammar/attr_operator/config_inside/insert/dict_2/main.k diff --git a/test/grammar/attr_operator/config_inside/insert/dict_2/stdout.golden b/tests/grammar/attr_operator/config_inside/insert/dict_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_2/stdout.golden rename to tests/grammar/attr_operator/config_inside/insert/dict_2/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/insert/dict_3/main.k b/tests/grammar/attr_operator/config_inside/insert/dict_3/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_3/main.k rename to tests/grammar/attr_operator/config_inside/insert/dict_3/main.k diff --git a/test/grammar/attr_operator/config_inside/insert/dict_3/stdout.golden b/tests/grammar/attr_operator/config_inside/insert/dict_3/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_3/stdout.golden rename to tests/grammar/attr_operator/config_inside/insert/dict_3/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/insert/dict_4/main.k b/tests/grammar/attr_operator/config_inside/insert/dict_4/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_4/main.k rename to tests/grammar/attr_operator/config_inside/insert/dict_4/main.k diff --git a/test/grammar/attr_operator/config_inside/insert/dict_4/stdout.golden b/tests/grammar/attr_operator/config_inside/insert/dict_4/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_4/stdout.golden rename to tests/grammar/attr_operator/config_inside/insert/dict_4/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/insert/dict_5/main.k b/tests/grammar/attr_operator/config_inside/insert/dict_5/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_5/main.k rename to tests/grammar/attr_operator/config_inside/insert/dict_5/main.k diff --git a/test/grammar/attr_operator/config_inside/insert/dict_5/stdout.golden b/tests/grammar/attr_operator/config_inside/insert/dict_5/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_5/stdout.golden rename to tests/grammar/attr_operator/config_inside/insert/dict_5/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/insert/dict_6/main.k b/tests/grammar/attr_operator/config_inside/insert/dict_6/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_6/main.k rename to tests/grammar/attr_operator/config_inside/insert/dict_6/main.k diff --git a/test/grammar/attr_operator/config_inside/insert/dict_6/stdout.golden b/tests/grammar/attr_operator/config_inside/insert/dict_6/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_6/stdout.golden rename to tests/grammar/attr_operator/config_inside/insert/dict_6/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/insert/dict_fail_0/main.k b/tests/grammar/attr_operator/config_inside/insert/dict_fail_0/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_fail_0/main.k rename to tests/grammar/attr_operator/config_inside/insert/dict_fail_0/main.k diff --git a/test/grammar/attr_operator/config_inside/insert/dict_fail_0/stderr.golden b/tests/grammar/attr_operator/config_inside/insert/dict_fail_0/stderr.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/dict_fail_0/stderr.golden rename to tests/grammar/attr_operator/config_inside/insert/dict_fail_0/stderr.golden diff --git a/test/grammar/attr_operator/config_inside/insert/schema_0/main.k b/tests/grammar/attr_operator/config_inside/insert/schema_0/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/schema_0/main.k rename to tests/grammar/attr_operator/config_inside/insert/schema_0/main.k diff --git a/test/grammar/attr_operator/config_inside/insert/schema_0/stdout.golden b/tests/grammar/attr_operator/config_inside/insert/schema_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/schema_0/stdout.golden rename to tests/grammar/attr_operator/config_inside/insert/schema_0/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/insert/schema_1/main.k b/tests/grammar/attr_operator/config_inside/insert/schema_1/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/schema_1/main.k rename to tests/grammar/attr_operator/config_inside/insert/schema_1/main.k diff --git a/test/grammar/attr_operator/config_inside/insert/schema_1/stdout.golden b/tests/grammar/attr_operator/config_inside/insert/schema_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/schema_1/stdout.golden rename to tests/grammar/attr_operator/config_inside/insert/schema_1/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/insert/schema_2/main.k b/tests/grammar/attr_operator/config_inside/insert/schema_2/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/schema_2/main.k rename to tests/grammar/attr_operator/config_inside/insert/schema_2/main.k diff --git a/test/grammar/attr_operator/config_inside/insert/schema_2/stdout.golden b/tests/grammar/attr_operator/config_inside/insert/schema_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/schema_2/stdout.golden rename to tests/grammar/attr_operator/config_inside/insert/schema_2/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/insert/schema_3/main.k b/tests/grammar/attr_operator/config_inside/insert/schema_3/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/schema_3/main.k rename to tests/grammar/attr_operator/config_inside/insert/schema_3/main.k diff --git a/test/grammar/attr_operator/config_inside/insert/schema_3/stdout.golden b/tests/grammar/attr_operator/config_inside/insert/schema_3/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/insert/schema_3/stdout.golden rename to tests/grammar/attr_operator/config_inside/insert/schema_3/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/override/dict_0/main.k b/tests/grammar/attr_operator/config_inside/override/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/override/dict_0/main.k rename to tests/grammar/attr_operator/config_inside/override/dict_0/main.k diff --git a/test/grammar/attr_operator/config_inside/override/dict_0/stdout.golden b/tests/grammar/attr_operator/config_inside/override/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/override/dict_0/stdout.golden rename to tests/grammar/attr_operator/config_inside/override/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/override/dict_1/main.k b/tests/grammar/attr_operator/config_inside/override/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/override/dict_1/main.k rename to tests/grammar/attr_operator/config_inside/override/dict_1/main.k diff --git a/test/grammar/attr_operator/config_inside/override/dict_1/stdout.golden b/tests/grammar/attr_operator/config_inside/override/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/override/dict_1/stdout.golden rename to tests/grammar/attr_operator/config_inside/override/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/override/schema_0/main.k b/tests/grammar/attr_operator/config_inside/override/schema_0/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/override/schema_0/main.k rename to tests/grammar/attr_operator/config_inside/override/schema_0/main.k diff --git a/test/grammar/attr_operator/config_inside/override/schema_0/stdout.golden b/tests/grammar/attr_operator/config_inside/override/schema_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/override/schema_0/stdout.golden rename to tests/grammar/attr_operator/config_inside/override/schema_0/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/override/schema_1/main.k b/tests/grammar/attr_operator/config_inside/override/schema_1/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/override/schema_1/main.k rename to tests/grammar/attr_operator/config_inside/override/schema_1/main.k diff --git a/test/grammar/attr_operator/config_inside/override/schema_1/stdout.golden b/tests/grammar/attr_operator/config_inside/override/schema_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/override/schema_1/stdout.golden rename to tests/grammar/attr_operator/config_inside/override/schema_1/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/override/schema_2/main.k b/tests/grammar/attr_operator/config_inside/override/schema_2/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/override/schema_2/main.k rename to tests/grammar/attr_operator/config_inside/override/schema_2/main.k diff --git a/test/grammar/attr_operator/config_inside/override/schema_2/stdout.golden b/tests/grammar/attr_operator/config_inside/override/schema_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/override/schema_2/stdout.golden rename to tests/grammar/attr_operator/config_inside/override/schema_2/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/unification/dict_0/main.k b/tests/grammar/attr_operator/config_inside/unification/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/unification/dict_0/main.k rename to tests/grammar/attr_operator/config_inside/unification/dict_0/main.k diff --git a/test/grammar/attr_operator/config_inside/unification/dict_0/stdout.golden b/tests/grammar/attr_operator/config_inside/unification/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/unification/dict_0/stdout.golden rename to tests/grammar/attr_operator/config_inside/unification/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/unification/dict_1/main.k b/tests/grammar/attr_operator/config_inside/unification/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/unification/dict_1/main.k rename to tests/grammar/attr_operator/config_inside/unification/dict_1/main.k diff --git a/test/grammar/attr_operator/config_inside/unification/dict_1/stdout.golden b/tests/grammar/attr_operator/config_inside/unification/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/unification/dict_1/stdout.golden rename to tests/grammar/attr_operator/config_inside/unification/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/unification/schema_0/main.k b/tests/grammar/attr_operator/config_inside/unification/schema_0/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/unification/schema_0/main.k rename to tests/grammar/attr_operator/config_inside/unification/schema_0/main.k diff --git a/test/grammar/attr_operator/config_inside/unification/schema_0/stdout.golden b/tests/grammar/attr_operator/config_inside/unification/schema_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/unification/schema_0/stdout.golden rename to tests/grammar/attr_operator/config_inside/unification/schema_0/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/unification/schema_1/main.k b/tests/grammar/attr_operator/config_inside/unification/schema_1/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/unification/schema_1/main.k rename to tests/grammar/attr_operator/config_inside/unification/schema_1/main.k diff --git a/test/grammar/attr_operator/config_inside/unification/schema_1/stdout.golden b/tests/grammar/attr_operator/config_inside/unification/schema_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/unification/schema_1/stdout.golden rename to tests/grammar/attr_operator/config_inside/unification/schema_1/stdout.golden diff --git a/test/grammar/attr_operator/config_inside/unification/schema_2/main.k b/tests/grammar/attr_operator/config_inside/unification/schema_2/main.k similarity index 100% rename from test/grammar/attr_operator/config_inside/unification/schema_2/main.k rename to tests/grammar/attr_operator/config_inside/unification/schema_2/main.k diff --git a/test/grammar/attr_operator/config_inside/unification/schema_2/stdout.golden b/tests/grammar/attr_operator/config_inside/unification/schema_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/config_inside/unification/schema_2/stdout.golden rename to tests/grammar/attr_operator/config_inside/unification/schema_2/stdout.golden diff --git a/test/grammar/attr_operator/if_entry/insert/dict_0/main.k b/tests/grammar/attr_operator/if_entry/insert/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/if_entry/insert/dict_0/main.k rename to tests/grammar/attr_operator/if_entry/insert/dict_0/main.k diff --git a/test/grammar/attr_operator/if_entry/insert/dict_0/stdout.golden b/tests/grammar/attr_operator/if_entry/insert/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/if_entry/insert/dict_0/stdout.golden rename to tests/grammar/attr_operator/if_entry/insert/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/if_entry/insert/dict_1/main.k b/tests/grammar/attr_operator/if_entry/insert/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/if_entry/insert/dict_1/main.k rename to tests/grammar/attr_operator/if_entry/insert/dict_1/main.k diff --git a/test/grammar/attr_operator/if_entry/insert/dict_1/stdout.golden b/tests/grammar/attr_operator/if_entry/insert/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/if_entry/insert/dict_1/stdout.golden rename to tests/grammar/attr_operator/if_entry/insert/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/if_entry/insert/dict_2/main.k b/tests/grammar/attr_operator/if_entry/insert/dict_2/main.k similarity index 100% rename from test/grammar/attr_operator/if_entry/insert/dict_2/main.k rename to tests/grammar/attr_operator/if_entry/insert/dict_2/main.k diff --git a/test/grammar/attr_operator/if_entry/insert/dict_2/stdout.golden b/tests/grammar/attr_operator/if_entry/insert/dict_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/if_entry/insert/dict_2/stdout.golden rename to tests/grammar/attr_operator/if_entry/insert/dict_2/stdout.golden diff --git a/test/grammar/attr_operator/if_entry/insert/dict_3/main.k b/tests/grammar/attr_operator/if_entry/insert/dict_3/main.k similarity index 100% rename from test/grammar/attr_operator/if_entry/insert/dict_3/main.k rename to tests/grammar/attr_operator/if_entry/insert/dict_3/main.k diff --git a/test/grammar/attr_operator/if_entry/insert/dict_3/stdout.golden b/tests/grammar/attr_operator/if_entry/insert/dict_3/stdout.golden similarity index 100% rename from test/grammar/attr_operator/if_entry/insert/dict_3/stdout.golden rename to tests/grammar/attr_operator/if_entry/insert/dict_3/stdout.golden diff --git a/test/grammar/attr_operator/if_entry/override/dict_0/main.k b/tests/grammar/attr_operator/if_entry/override/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/if_entry/override/dict_0/main.k rename to tests/grammar/attr_operator/if_entry/override/dict_0/main.k diff --git a/test/grammar/attr_operator/if_entry/override/dict_0/stdout.golden b/tests/grammar/attr_operator/if_entry/override/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/if_entry/override/dict_0/stdout.golden rename to tests/grammar/attr_operator/if_entry/override/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/if_entry/override/dict_1/main.k b/tests/grammar/attr_operator/if_entry/override/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/if_entry/override/dict_1/main.k rename to tests/grammar/attr_operator/if_entry/override/dict_1/main.k diff --git a/test/grammar/attr_operator/if_entry/override/dict_1/stdout.golden b/tests/grammar/attr_operator/if_entry/override/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/if_entry/override/dict_1/stdout.golden rename to tests/grammar/attr_operator/if_entry/override/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/if_entry/override/dict_2/main.k b/tests/grammar/attr_operator/if_entry/override/dict_2/main.k similarity index 100% rename from test/grammar/attr_operator/if_entry/override/dict_2/main.k rename to tests/grammar/attr_operator/if_entry/override/dict_2/main.k diff --git a/test/grammar/attr_operator/if_entry/override/dict_2/stdout.golden b/tests/grammar/attr_operator/if_entry/override/dict_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/if_entry/override/dict_2/stdout.golden rename to tests/grammar/attr_operator/if_entry/override/dict_2/stdout.golden diff --git a/test/grammar/attr_operator/if_entry/unification/dict_0/main.k b/tests/grammar/attr_operator/if_entry/unification/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/if_entry/unification/dict_0/main.k rename to tests/grammar/attr_operator/if_entry/unification/dict_0/main.k diff --git a/test/grammar/attr_operator/if_entry/unification/dict_0/stdout.golden b/tests/grammar/attr_operator/if_entry/unification/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/if_entry/unification/dict_0/stdout.golden rename to tests/grammar/attr_operator/if_entry/unification/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/if_entry/unification/dict_1/main.k b/tests/grammar/attr_operator/if_entry/unification/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/if_entry/unification/dict_1/main.k rename to tests/grammar/attr_operator/if_entry/unification/dict_1/main.k diff --git a/test/grammar/attr_operator/if_entry/unification/dict_1/stdout.golden b/tests/grammar/attr_operator/if_entry/unification/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/if_entry/unification/dict_1/stdout.golden rename to tests/grammar/attr_operator/if_entry/unification/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/if_entry/unification/dict_2/main.k b/tests/grammar/attr_operator/if_entry/unification/dict_2/main.k similarity index 100% rename from test/grammar/attr_operator/if_entry/unification/dict_2/main.k rename to tests/grammar/attr_operator/if_entry/unification/dict_2/main.k diff --git a/test/grammar/attr_operator/if_entry/unification/dict_2/stdout.golden b/tests/grammar/attr_operator/if_entry/unification/dict_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/if_entry/unification/dict_2/stdout.golden rename to tests/grammar/attr_operator/if_entry/unification/dict_2/stdout.golden diff --git a/test/grammar/attr_operator/list_index/insert/insert_0/main.k b/tests/grammar/attr_operator/list_index/insert/insert_0/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/insert/insert_0/main.k rename to tests/grammar/attr_operator/list_index/insert/insert_0/main.k diff --git a/test/grammar/attr_operator/list_index/insert/insert_0/stdout.golden b/tests/grammar/attr_operator/list_index/insert/insert_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/list_index/insert/insert_0/stdout.golden rename to tests/grammar/attr_operator/list_index/insert/insert_0/stdout.golden diff --git a/test/grammar/attr_operator/list_index/insert/insert_1/main.k b/tests/grammar/attr_operator/list_index/insert/insert_1/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/insert/insert_1/main.k rename to tests/grammar/attr_operator/list_index/insert/insert_1/main.k diff --git a/test/grammar/attr_operator/list_index/insert/insert_1/stdout.golden b/tests/grammar/attr_operator/list_index/insert/insert_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/list_index/insert/insert_1/stdout.golden rename to tests/grammar/attr_operator/list_index/insert/insert_1/stdout.golden diff --git a/test/grammar/attr_operator/list_index/insert/insert_2/main.k b/tests/grammar/attr_operator/list_index/insert/insert_2/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/insert/insert_2/main.k rename to tests/grammar/attr_operator/list_index/insert/insert_2/main.k diff --git a/test/grammar/attr_operator/list_index/insert/insert_2/stdout.golden b/tests/grammar/attr_operator/list_index/insert/insert_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/list_index/insert/insert_2/stdout.golden rename to tests/grammar/attr_operator/list_index/insert/insert_2/stdout.golden diff --git a/test/grammar/attr_operator/list_index/insert/insert_3/main.k b/tests/grammar/attr_operator/list_index/insert/insert_3/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/insert/insert_3/main.k rename to tests/grammar/attr_operator/list_index/insert/insert_3/main.k diff --git a/test/grammar/attr_operator/list_index/insert/insert_3/stdout.golden b/tests/grammar/attr_operator/list_index/insert/insert_3/stdout.golden similarity index 100% rename from test/grammar/attr_operator/list_index/insert/insert_3/stdout.golden rename to tests/grammar/attr_operator/list_index/insert/insert_3/stdout.golden diff --git a/test/grammar/attr_operator/list_index/insert/insert_fail_0/main.k b/tests/grammar/attr_operator/list_index/insert/insert_fail_0/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/insert/insert_fail_0/main.k rename to tests/grammar/attr_operator/list_index/insert/insert_fail_0/main.k diff --git a/test/grammar/attr_operator/list_index/insert/insert_fail_0/stderr.golden b/tests/grammar/attr_operator/list_index/insert/insert_fail_0/stderr.golden similarity index 100% rename from test/grammar/attr_operator/list_index/insert/insert_fail_0/stderr.golden rename to tests/grammar/attr_operator/list_index/insert/insert_fail_0/stderr.golden diff --git a/test/grammar/attr_operator/list_index/insert/insert_fail_1/main.k b/tests/grammar/attr_operator/list_index/insert/insert_fail_1/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/insert/insert_fail_1/main.k rename to tests/grammar/attr_operator/list_index/insert/insert_fail_1/main.k diff --git a/test/grammar/attr_operator/list_index/insert/insert_fail_1/stderr.golden b/tests/grammar/attr_operator/list_index/insert/insert_fail_1/stderr.golden similarity index 100% rename from test/grammar/attr_operator/list_index/insert/insert_fail_1/stderr.golden rename to tests/grammar/attr_operator/list_index/insert/insert_fail_1/stderr.golden diff --git a/test/grammar/attr_operator/list_index/insert/insert_fail_2/main.k b/tests/grammar/attr_operator/list_index/insert/insert_fail_2/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/insert/insert_fail_2/main.k rename to tests/grammar/attr_operator/list_index/insert/insert_fail_2/main.k diff --git a/test/grammar/attr_operator/list_index/insert/insert_fail_2/stderr.golden b/tests/grammar/attr_operator/list_index/insert/insert_fail_2/stderr.golden similarity index 100% rename from test/grammar/attr_operator/list_index/insert/insert_fail_2/stderr.golden rename to tests/grammar/attr_operator/list_index/insert/insert_fail_2/stderr.golden diff --git a/test/grammar/attr_operator/list_index/override/override_0/main.k b/tests/grammar/attr_operator/list_index/override/override_0/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/override/override_0/main.k rename to tests/grammar/attr_operator/list_index/override/override_0/main.k diff --git a/test/grammar/attr_operator/list_index/override/override_0/stdout.golden b/tests/grammar/attr_operator/list_index/override/override_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/list_index/override/override_0/stdout.golden rename to tests/grammar/attr_operator/list_index/override/override_0/stdout.golden diff --git a/test/grammar/attr_operator/list_index/override/override_1/main.k b/tests/grammar/attr_operator/list_index/override/override_1/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/override/override_1/main.k rename to tests/grammar/attr_operator/list_index/override/override_1/main.k diff --git a/test/grammar/attr_operator/list_index/override/override_1/stdout.golden b/tests/grammar/attr_operator/list_index/override/override_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/list_index/override/override_1/stdout.golden rename to tests/grammar/attr_operator/list_index/override/override_1/stdout.golden diff --git a/test/grammar/attr_operator/list_index/override/override_fail_0/main.k b/tests/grammar/attr_operator/list_index/override/override_fail_0/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/override/override_fail_0/main.k rename to tests/grammar/attr_operator/list_index/override/override_fail_0/main.k diff --git a/test/grammar/attr_operator/list_index/override/override_fail_0/stderr.golden b/tests/grammar/attr_operator/list_index/override/override_fail_0/stderr.golden similarity index 100% rename from test/grammar/attr_operator/list_index/override/override_fail_0/stderr.golden rename to tests/grammar/attr_operator/list_index/override/override_fail_0/stderr.golden diff --git a/test/grammar/attr_operator/list_index/override/override_fail_1/main.k b/tests/grammar/attr_operator/list_index/override/override_fail_1/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/override/override_fail_1/main.k rename to tests/grammar/attr_operator/list_index/override/override_fail_1/main.k diff --git a/test/grammar/attr_operator/list_index/override/override_fail_1/stderr.golden b/tests/grammar/attr_operator/list_index/override/override_fail_1/stderr.golden similarity index 100% rename from test/grammar/attr_operator/list_index/override/override_fail_1/stderr.golden rename to tests/grammar/attr_operator/list_index/override/override_fail_1/stderr.golden diff --git a/test/grammar/attr_operator/list_index/override/override_fail_2/main.k b/tests/grammar/attr_operator/list_index/override/override_fail_2/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/override/override_fail_2/main.k rename to tests/grammar/attr_operator/list_index/override/override_fail_2/main.k diff --git a/test/grammar/attr_operator/list_index/override/override_fail_2/stderr.golden b/tests/grammar/attr_operator/list_index/override/override_fail_2/stderr.golden similarity index 100% rename from test/grammar/attr_operator/list_index/override/override_fail_2/stderr.golden rename to tests/grammar/attr_operator/list_index/override/override_fail_2/stderr.golden diff --git a/test/grammar/attr_operator/list_index/unification/unification_0/main.k b/tests/grammar/attr_operator/list_index/unification/unification_0/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/unification/unification_0/main.k rename to tests/grammar/attr_operator/list_index/unification/unification_0/main.k diff --git a/test/grammar/attr_operator/list_index/unification/unification_0/stdout.golden b/tests/grammar/attr_operator/list_index/unification/unification_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/list_index/unification/unification_0/stdout.golden rename to tests/grammar/attr_operator/list_index/unification/unification_0/stdout.golden diff --git a/test/grammar/attr_operator/list_index/unification/unification_1/main.k b/tests/grammar/attr_operator/list_index/unification/unification_1/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/unification/unification_1/main.k rename to tests/grammar/attr_operator/list_index/unification/unification_1/main.k diff --git a/test/grammar/attr_operator/list_index/unification/unification_1/stdout.golden b/tests/grammar/attr_operator/list_index/unification/unification_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/list_index/unification/unification_1/stdout.golden rename to tests/grammar/attr_operator/list_index/unification/unification_1/stdout.golden diff --git a/test/grammar/attr_operator/list_index/unification/unification_fail_0/main.k b/tests/grammar/attr_operator/list_index/unification/unification_fail_0/main.k similarity index 100% rename from test/grammar/attr_operator/list_index/unification/unification_fail_0/main.k rename to tests/grammar/attr_operator/list_index/unification/unification_fail_0/main.k diff --git a/test/grammar/attr_operator/list_index/unification/unification_fail_0/stderr.golden b/tests/grammar/attr_operator/list_index/unification/unification_fail_0/stderr.golden similarity index 100% rename from test/grammar/attr_operator/list_index/unification/unification_fail_0/stderr.golden rename to tests/grammar/attr_operator/list_index/unification/unification_fail_0/stderr.golden diff --git a/test/grammar/attr_operator/nest_var/insert/dict_0/main.k b/tests/grammar/attr_operator/nest_var/insert/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/nest_var/insert/dict_0/main.k rename to tests/grammar/attr_operator/nest_var/insert/dict_0/main.k diff --git a/test/grammar/attr_operator/nest_var/insert/dict_0/stdout.golden b/tests/grammar/attr_operator/nest_var/insert/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/nest_var/insert/dict_0/stdout.golden rename to tests/grammar/attr_operator/nest_var/insert/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/nest_var/insert/dict_1/main.k b/tests/grammar/attr_operator/nest_var/insert/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/nest_var/insert/dict_1/main.k rename to tests/grammar/attr_operator/nest_var/insert/dict_1/main.k diff --git a/test/grammar/attr_operator/nest_var/insert/dict_1/stdout.golden b/tests/grammar/attr_operator/nest_var/insert/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/nest_var/insert/dict_1/stdout.golden rename to tests/grammar/attr_operator/nest_var/insert/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/nest_var/insert/dict_2/main.k b/tests/grammar/attr_operator/nest_var/insert/dict_2/main.k similarity index 100% rename from test/grammar/attr_operator/nest_var/insert/dict_2/main.k rename to tests/grammar/attr_operator/nest_var/insert/dict_2/main.k diff --git a/test/grammar/attr_operator/nest_var/insert/dict_2/stdout.golden b/tests/grammar/attr_operator/nest_var/insert/dict_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/nest_var/insert/dict_2/stdout.golden rename to tests/grammar/attr_operator/nest_var/insert/dict_2/stdout.golden diff --git a/test/grammar/attr_operator/nest_var/override/dict_0/main.k b/tests/grammar/attr_operator/nest_var/override/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/nest_var/override/dict_0/main.k rename to tests/grammar/attr_operator/nest_var/override/dict_0/main.k diff --git a/test/grammar/attr_operator/nest_var/override/dict_0/stdout.golden b/tests/grammar/attr_operator/nest_var/override/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/nest_var/override/dict_0/stdout.golden rename to tests/grammar/attr_operator/nest_var/override/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/nest_var/override/dict_1/main.k b/tests/grammar/attr_operator/nest_var/override/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/nest_var/override/dict_1/main.k rename to tests/grammar/attr_operator/nest_var/override/dict_1/main.k diff --git a/test/grammar/attr_operator/nest_var/override/dict_1/stdout.golden b/tests/grammar/attr_operator/nest_var/override/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/nest_var/override/dict_1/stdout.golden rename to tests/grammar/attr_operator/nest_var/override/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/nest_var/override/dict_2/main.k b/tests/grammar/attr_operator/nest_var/override/dict_2/main.k similarity index 100% rename from test/grammar/attr_operator/nest_var/override/dict_2/main.k rename to tests/grammar/attr_operator/nest_var/override/dict_2/main.k diff --git a/test/grammar/attr_operator/nest_var/override/dict_2/stdout.golden b/tests/grammar/attr_operator/nest_var/override/dict_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/nest_var/override/dict_2/stdout.golden rename to tests/grammar/attr_operator/nest_var/override/dict_2/stdout.golden diff --git a/test/grammar/attr_operator/nest_var/unification/dict_0/main.k b/tests/grammar/attr_operator/nest_var/unification/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/nest_var/unification/dict_0/main.k rename to tests/grammar/attr_operator/nest_var/unification/dict_0/main.k diff --git a/test/grammar/attr_operator/nest_var/unification/dict_0/stdout.golden b/tests/grammar/attr_operator/nest_var/unification/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/nest_var/unification/dict_0/stdout.golden rename to tests/grammar/attr_operator/nest_var/unification/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/nest_var/unification/dict_1/main.k b/tests/grammar/attr_operator/nest_var/unification/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/nest_var/unification/dict_1/main.k rename to tests/grammar/attr_operator/nest_var/unification/dict_1/main.k diff --git a/test/grammar/attr_operator/nest_var/unification/dict_1/stdout.golden b/tests/grammar/attr_operator/nest_var/unification/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/nest_var/unification/dict_1/stdout.golden rename to tests/grammar/attr_operator/nest_var/unification/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/nest_var/unification/dict_2/main.k b/tests/grammar/attr_operator/nest_var/unification/dict_2/main.k similarity index 100% rename from test/grammar/attr_operator/nest_var/unification/dict_2/main.k rename to tests/grammar/attr_operator/nest_var/unification/dict_2/main.k diff --git a/test/grammar/attr_operator/nest_var/unification/dict_2/stdout.golden b/tests/grammar/attr_operator/nest_var/unification/dict_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/nest_var/unification/dict_2/stdout.golden rename to tests/grammar/attr_operator/nest_var/unification/dict_2/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/insert/test_0/main.k b/tests/grammar/attr_operator/schema_inside/insert/test_0/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_0/main.k rename to tests/grammar/attr_operator/schema_inside/insert/test_0/main.k diff --git a/test/grammar/attr_operator/schema_inside/insert/test_0/stdout.golden b/tests/grammar/attr_operator/schema_inside/insert/test_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_0/stdout.golden rename to tests/grammar/attr_operator/schema_inside/insert/test_0/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/insert/test_1/main.k b/tests/grammar/attr_operator/schema_inside/insert/test_1/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_1/main.k rename to tests/grammar/attr_operator/schema_inside/insert/test_1/main.k diff --git a/test/grammar/attr_operator/schema_inside/insert/test_1/stdout.golden b/tests/grammar/attr_operator/schema_inside/insert/test_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_1/stdout.golden rename to tests/grammar/attr_operator/schema_inside/insert/test_1/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/insert/test_2/main.k b/tests/grammar/attr_operator/schema_inside/insert/test_2/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_2/main.k rename to tests/grammar/attr_operator/schema_inside/insert/test_2/main.k diff --git a/test/grammar/attr_operator/schema_inside/insert/test_2/stdout.golden b/tests/grammar/attr_operator/schema_inside/insert/test_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_2/stdout.golden rename to tests/grammar/attr_operator/schema_inside/insert/test_2/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/insert/test_3/main.k b/tests/grammar/attr_operator/schema_inside/insert/test_3/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_3/main.k rename to tests/grammar/attr_operator/schema_inside/insert/test_3/main.k diff --git a/test/grammar/attr_operator/schema_inside/insert/test_3/stdout.golden b/tests/grammar/attr_operator/schema_inside/insert/test_3/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_3/stdout.golden rename to tests/grammar/attr_operator/schema_inside/insert/test_3/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/insert/test_4/main.k b/tests/grammar/attr_operator/schema_inside/insert/test_4/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_4/main.k rename to tests/grammar/attr_operator/schema_inside/insert/test_4/main.k diff --git a/test/grammar/attr_operator/schema_inside/insert/test_4/stdout.golden b/tests/grammar/attr_operator/schema_inside/insert/test_4/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_4/stdout.golden rename to tests/grammar/attr_operator/schema_inside/insert/test_4/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/insert/test_5/main.k b/tests/grammar/attr_operator/schema_inside/insert/test_5/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_5/main.k rename to tests/grammar/attr_operator/schema_inside/insert/test_5/main.k diff --git a/test/grammar/attr_operator/schema_inside/insert/test_5/stdout.golden b/tests/grammar/attr_operator/schema_inside/insert/test_5/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_5/stdout.golden rename to tests/grammar/attr_operator/schema_inside/insert/test_5/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/insert/test_6/main.k b/tests/grammar/attr_operator/schema_inside/insert/test_6/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_6/main.k rename to tests/grammar/attr_operator/schema_inside/insert/test_6/main.k diff --git a/test/grammar/attr_operator/schema_inside/insert/test_6/stdout.golden b/tests/grammar/attr_operator/schema_inside/insert/test_6/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_6/stdout.golden rename to tests/grammar/attr_operator/schema_inside/insert/test_6/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/insert/test_7/main.k b/tests/grammar/attr_operator/schema_inside/insert/test_7/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_7/main.k rename to tests/grammar/attr_operator/schema_inside/insert/test_7/main.k diff --git a/test/grammar/attr_operator/schema_inside/insert/test_7/stdout.golden b/tests/grammar/attr_operator/schema_inside/insert/test_7/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_7/stdout.golden rename to tests/grammar/attr_operator/schema_inside/insert/test_7/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/insert/test_8/main.k b/tests/grammar/attr_operator/schema_inside/insert/test_8/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_8/main.k rename to tests/grammar/attr_operator/schema_inside/insert/test_8/main.k diff --git a/test/grammar/attr_operator/schema_inside/insert/test_8/stdout.golden b/tests/grammar/attr_operator/schema_inside/insert/test_8/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/insert/test_8/stdout.golden rename to tests/grammar/attr_operator/schema_inside/insert/test_8/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/override/test_0/main.k b/tests/grammar/attr_operator/schema_inside/override/test_0/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/override/test_0/main.k rename to tests/grammar/attr_operator/schema_inside/override/test_0/main.k diff --git a/test/grammar/attr_operator/schema_inside/override/test_0/stdout.golden b/tests/grammar/attr_operator/schema_inside/override/test_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/override/test_0/stdout.golden rename to tests/grammar/attr_operator/schema_inside/override/test_0/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/override/test_1/main.k b/tests/grammar/attr_operator/schema_inside/override/test_1/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/override/test_1/main.k rename to tests/grammar/attr_operator/schema_inside/override/test_1/main.k diff --git a/test/grammar/attr_operator/schema_inside/override/test_1/stdout.golden b/tests/grammar/attr_operator/schema_inside/override/test_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/override/test_1/stdout.golden rename to tests/grammar/attr_operator/schema_inside/override/test_1/stdout.golden diff --git a/tests/grammar/attr_operator/schema_inside/override/test_2/main.k b/tests/grammar/attr_operator/schema_inside/override/test_2/main.k new file mode 100644 index 000000000..da36ccfce --- /dev/null +++ b/tests/grammar/attr_operator/schema_inside/override/test_2/main.k @@ -0,0 +1,13 @@ +schema Config: + name: str + args: [str] + +schema Data: + config: Config { + name = "config" + args: ["kcl", "-d"] + args = ["kcl"] + name = "kcl" + } + +data = Data {} diff --git a/tests/grammar/attr_operator/schema_inside/override/test_2/stdout.golden b/tests/grammar/attr_operator/schema_inside/override/test_2/stdout.golden new file mode 100644 index 000000000..0be9e0fb3 --- /dev/null +++ b/tests/grammar/attr_operator/schema_inside/override/test_2/stdout.golden @@ -0,0 +1,5 @@ +data: + config: + name: kcl + args: + - kcl diff --git a/tests/grammar/attr_operator/schema_inside/override/test_3/main.k b/tests/grammar/attr_operator/schema_inside/override/test_3/main.k new file mode 100644 index 000000000..13561294e --- /dev/null +++ b/tests/grammar/attr_operator/schema_inside/override/test_3/main.k @@ -0,0 +1,14 @@ +schema Config: + name: str + args: [str] + +schema Data: + _config: Config { + name = "config" + args: ["kcl", "-d"] + args = ["kcl"] + name = "kcl" + } + config: Config = _config | {name = "override"} + +data = Data {} diff --git a/tests/grammar/attr_operator/schema_inside/override/test_3/stdout.golden b/tests/grammar/attr_operator/schema_inside/override/test_3/stdout.golden new file mode 100644 index 000000000..5ee5428ce --- /dev/null +++ b/tests/grammar/attr_operator/schema_inside/override/test_3/stdout.golden @@ -0,0 +1,5 @@ +data: + config: + name: override + args: + - kcl diff --git a/test/grammar/attr_operator/schema_inside/unification/test_0/main.k b/tests/grammar/attr_operator/schema_inside/unification/test_0/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/unification/test_0/main.k rename to tests/grammar/attr_operator/schema_inside/unification/test_0/main.k diff --git a/test/grammar/attr_operator/schema_inside/unification/test_0/stdout.golden b/tests/grammar/attr_operator/schema_inside/unification/test_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/unification/test_0/stdout.golden rename to tests/grammar/attr_operator/schema_inside/unification/test_0/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/unification/test_1/main.k b/tests/grammar/attr_operator/schema_inside/unification/test_1/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/unification/test_1/main.k rename to tests/grammar/attr_operator/schema_inside/unification/test_1/main.k diff --git a/test/grammar/attr_operator/schema_inside/unification/test_1/stdout.golden b/tests/grammar/attr_operator/schema_inside/unification/test_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/unification/test_1/stdout.golden rename to tests/grammar/attr_operator/schema_inside/unification/test_1/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/unification/test_2/main.k b/tests/grammar/attr_operator/schema_inside/unification/test_2/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/unification/test_2/main.k rename to tests/grammar/attr_operator/schema_inside/unification/test_2/main.k diff --git a/test/grammar/attr_operator/schema_inside/unification/test_2/stdout.golden b/tests/grammar/attr_operator/schema_inside/unification/test_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/unification/test_2/stdout.golden rename to tests/grammar/attr_operator/schema_inside/unification/test_2/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/unification/test_3/main.k b/tests/grammar/attr_operator/schema_inside/unification/test_3/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/unification/test_3/main.k rename to tests/grammar/attr_operator/schema_inside/unification/test_3/main.k diff --git a/test/grammar/attr_operator/schema_inside/unification/test_3/stdout.golden b/tests/grammar/attr_operator/schema_inside/unification/test_3/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/unification/test_3/stdout.golden rename to tests/grammar/attr_operator/schema_inside/unification/test_3/stdout.golden diff --git a/test/grammar/attr_operator/schema_inside/unification/test_4/main.k b/tests/grammar/attr_operator/schema_inside/unification/test_4/main.k similarity index 100% rename from test/grammar/attr_operator/schema_inside/unification/test_4/main.k rename to tests/grammar/attr_operator/schema_inside/unification/test_4/main.k diff --git a/test/grammar/attr_operator/schema_inside/unification/test_4/stdout.golden b/tests/grammar/attr_operator/schema_inside/unification/test_4/stdout.golden similarity index 100% rename from test/grammar/attr_operator/schema_inside/unification/test_4/stdout.golden rename to tests/grammar/attr_operator/schema_inside/unification/test_4/stdout.golden diff --git a/test/grammar/attr_operator/single_config/insert/dict_0/main.k b/tests/grammar/attr_operator/single_config/insert/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/single_config/insert/dict_0/main.k rename to tests/grammar/attr_operator/single_config/insert/dict_0/main.k diff --git a/test/grammar/attr_operator/single_config/insert/dict_0/stdout.golden b/tests/grammar/attr_operator/single_config/insert/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/single_config/insert/dict_0/stdout.golden rename to tests/grammar/attr_operator/single_config/insert/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/single_config/insert/dict_1/main.k b/tests/grammar/attr_operator/single_config/insert/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/single_config/insert/dict_1/main.k rename to tests/grammar/attr_operator/single_config/insert/dict_1/main.k diff --git a/test/grammar/attr_operator/single_config/insert/dict_1/stdout.golden b/tests/grammar/attr_operator/single_config/insert/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/single_config/insert/dict_1/stdout.golden rename to tests/grammar/attr_operator/single_config/insert/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/single_config/insert/schema_0/main.k b/tests/grammar/attr_operator/single_config/insert/schema_0/main.k similarity index 100% rename from test/grammar/attr_operator/single_config/insert/schema_0/main.k rename to tests/grammar/attr_operator/single_config/insert/schema_0/main.k diff --git a/test/grammar/attr_operator/single_config/insert/schema_0/stdout.golden b/tests/grammar/attr_operator/single_config/insert/schema_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/single_config/insert/schema_0/stdout.golden rename to tests/grammar/attr_operator/single_config/insert/schema_0/stdout.golden diff --git a/test/grammar/attr_operator/single_config/insert/schema_1/main.k b/tests/grammar/attr_operator/single_config/insert/schema_1/main.k similarity index 100% rename from test/grammar/attr_operator/single_config/insert/schema_1/main.k rename to tests/grammar/attr_operator/single_config/insert/schema_1/main.k diff --git a/test/grammar/attr_operator/single_config/insert/schema_1/stdout.golden b/tests/grammar/attr_operator/single_config/insert/schema_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/single_config/insert/schema_1/stdout.golden rename to tests/grammar/attr_operator/single_config/insert/schema_1/stdout.golden diff --git a/test/grammar/attr_operator/single_config/override/dict_0/main.k b/tests/grammar/attr_operator/single_config/override/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/single_config/override/dict_0/main.k rename to tests/grammar/attr_operator/single_config/override/dict_0/main.k diff --git a/test/grammar/attr_operator/single_config/override/dict_0/stdout.golden b/tests/grammar/attr_operator/single_config/override/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/single_config/override/dict_0/stdout.golden rename to tests/grammar/attr_operator/single_config/override/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/single_config/override/dict_1/main.k b/tests/grammar/attr_operator/single_config/override/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/single_config/override/dict_1/main.k rename to tests/grammar/attr_operator/single_config/override/dict_1/main.k diff --git a/test/grammar/attr_operator/single_config/override/dict_1/stdout.golden b/tests/grammar/attr_operator/single_config/override/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/single_config/override/dict_1/stdout.golden rename to tests/grammar/attr_operator/single_config/override/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/single_config/override/schema_0/main.k b/tests/grammar/attr_operator/single_config/override/schema_0/main.k similarity index 100% rename from test/grammar/attr_operator/single_config/override/schema_0/main.k rename to tests/grammar/attr_operator/single_config/override/schema_0/main.k diff --git a/test/grammar/attr_operator/single_config/override/schema_0/stdout.golden b/tests/grammar/attr_operator/single_config/override/schema_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/single_config/override/schema_0/stdout.golden rename to tests/grammar/attr_operator/single_config/override/schema_0/stdout.golden diff --git a/test/grammar/attr_operator/single_config/override/schema_1/main.k b/tests/grammar/attr_operator/single_config/override/schema_1/main.k similarity index 100% rename from test/grammar/attr_operator/single_config/override/schema_1/main.k rename to tests/grammar/attr_operator/single_config/override/schema_1/main.k diff --git a/test/grammar/attr_operator/single_config/override/schema_1/stdout.golden b/tests/grammar/attr_operator/single_config/override/schema_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/single_config/override/schema_1/stdout.golden rename to tests/grammar/attr_operator/single_config/override/schema_1/stdout.golden diff --git a/test/grammar/attr_operator/single_config/unification/dict_0/main.k b/tests/grammar/attr_operator/single_config/unification/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/single_config/unification/dict_0/main.k rename to tests/grammar/attr_operator/single_config/unification/dict_0/main.k diff --git a/test/grammar/attr_operator/single_config/unification/dict_0/stdout.golden b/tests/grammar/attr_operator/single_config/unification/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/single_config/unification/dict_0/stdout.golden rename to tests/grammar/attr_operator/single_config/unification/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/single_config/unification/dict_1/main.k b/tests/grammar/attr_operator/single_config/unification/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/single_config/unification/dict_1/main.k rename to tests/grammar/attr_operator/single_config/unification/dict_1/main.k diff --git a/test/grammar/attr_operator/single_config/unification/dict_1/stdout.golden b/tests/grammar/attr_operator/single_config/unification/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/single_config/unification/dict_1/stdout.golden rename to tests/grammar/attr_operator/single_config/unification/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/single_config/unification/schema_0/main.k b/tests/grammar/attr_operator/single_config/unification/schema_0/main.k similarity index 100% rename from test/grammar/attr_operator/single_config/unification/schema_0/main.k rename to tests/grammar/attr_operator/single_config/unification/schema_0/main.k diff --git a/test/grammar/attr_operator/single_config/unification/schema_0/stdout.golden b/tests/grammar/attr_operator/single_config/unification/schema_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/single_config/unification/schema_0/stdout.golden rename to tests/grammar/attr_operator/single_config/unification/schema_0/stdout.golden diff --git a/test/grammar/attr_operator/single_config/unification/schema_1/main.k b/tests/grammar/attr_operator/single_config/unification/schema_1/main.k similarity index 100% rename from test/grammar/attr_operator/single_config/unification/schema_1/main.k rename to tests/grammar/attr_operator/single_config/unification/schema_1/main.k diff --git a/test/grammar/attr_operator/single_config/unification/schema_1/stdout.golden b/tests/grammar/attr_operator/single_config/unification/schema_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/single_config/unification/schema_1/stdout.golden rename to tests/grammar/attr_operator/single_config/unification/schema_1/stdout.golden diff --git a/test/grammar/attr_operator/top_level/insert/test_0/main.k b/tests/grammar/attr_operator/top_level/insert/test_0/main.k similarity index 100% rename from test/grammar/attr_operator/top_level/insert/test_0/main.k rename to tests/grammar/attr_operator/top_level/insert/test_0/main.k diff --git a/test/grammar/attr_operator/top_level/insert/test_0/stdout.golden b/tests/grammar/attr_operator/top_level/insert/test_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/top_level/insert/test_0/stdout.golden rename to tests/grammar/attr_operator/top_level/insert/test_0/stdout.golden diff --git a/test/grammar/attr_operator/top_level/insert/test_1/main.k b/tests/grammar/attr_operator/top_level/insert/test_1/main.k similarity index 100% rename from test/grammar/attr_operator/top_level/insert/test_1/main.k rename to tests/grammar/attr_operator/top_level/insert/test_1/main.k diff --git a/test/grammar/attr_operator/top_level/insert/test_1/stdout.golden b/tests/grammar/attr_operator/top_level/insert/test_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/top_level/insert/test_1/stdout.golden rename to tests/grammar/attr_operator/top_level/insert/test_1/stdout.golden diff --git a/test/grammar/attr_operator/top_level/insert/test_2/main.k b/tests/grammar/attr_operator/top_level/insert/test_2/main.k similarity index 100% rename from test/grammar/attr_operator/top_level/insert/test_2/main.k rename to tests/grammar/attr_operator/top_level/insert/test_2/main.k diff --git a/test/grammar/attr_operator/top_level/insert/test_2/stdout.golden b/tests/grammar/attr_operator/top_level/insert/test_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/top_level/insert/test_2/stdout.golden rename to tests/grammar/attr_operator/top_level/insert/test_2/stdout.golden diff --git a/test/grammar/attr_operator/top_level/insert/test_3/main.k b/tests/grammar/attr_operator/top_level/insert/test_3/main.k similarity index 100% rename from test/grammar/attr_operator/top_level/insert/test_3/main.k rename to tests/grammar/attr_operator/top_level/insert/test_3/main.k diff --git a/test/grammar/attr_operator/top_level/insert/test_3/stdout.golden b/tests/grammar/attr_operator/top_level/insert/test_3/stdout.golden similarity index 100% rename from test/grammar/attr_operator/top_level/insert/test_3/stdout.golden rename to tests/grammar/attr_operator/top_level/insert/test_3/stdout.golden diff --git a/test/grammar/attr_operator/top_level/override/test_0/main.k b/tests/grammar/attr_operator/top_level/override/test_0/main.k similarity index 100% rename from test/grammar/attr_operator/top_level/override/test_0/main.k rename to tests/grammar/attr_operator/top_level/override/test_0/main.k diff --git a/test/grammar/attr_operator/top_level/override/test_0/stdout.golden b/tests/grammar/attr_operator/top_level/override/test_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/top_level/override/test_0/stdout.golden rename to tests/grammar/attr_operator/top_level/override/test_0/stdout.golden diff --git a/test/grammar/attr_operator/top_level/override/test_1/main.k b/tests/grammar/attr_operator/top_level/override/test_1/main.k similarity index 100% rename from test/grammar/attr_operator/top_level/override/test_1/main.k rename to tests/grammar/attr_operator/top_level/override/test_1/main.k diff --git a/test/grammar/attr_operator/top_level/override/test_1/stdout.golden b/tests/grammar/attr_operator/top_level/override/test_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/top_level/override/test_1/stdout.golden rename to tests/grammar/attr_operator/top_level/override/test_1/stdout.golden diff --git a/test/grammar/attr_operator/top_level/unification/test_0/main.k b/tests/grammar/attr_operator/top_level/unification/test_0/main.k similarity index 100% rename from test/grammar/attr_operator/top_level/unification/test_0/main.k rename to tests/grammar/attr_operator/top_level/unification/test_0/main.k diff --git a/test/grammar/attr_operator/top_level/unification/test_0/stdout.golden b/tests/grammar/attr_operator/top_level/unification/test_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/top_level/unification/test_0/stdout.golden rename to tests/grammar/attr_operator/top_level/unification/test_0/stdout.golden diff --git a/test/grammar/attr_operator/top_level/unification/test_1/main.k b/tests/grammar/attr_operator/top_level/unification/test_1/main.k similarity index 100% rename from test/grammar/attr_operator/top_level/unification/test_1/main.k rename to tests/grammar/attr_operator/top_level/unification/test_1/main.k diff --git a/test/grammar/attr_operator/top_level/unification/test_1/stdout.golden b/tests/grammar/attr_operator/top_level/unification/test_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/top_level/unification/test_1/stdout.golden rename to tests/grammar/attr_operator/top_level/unification/test_1/stdout.golden diff --git a/test/grammar/attr_operator/unpack/insert/dict_0/main.k b/tests/grammar/attr_operator/unpack/insert/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/unpack/insert/dict_0/main.k rename to tests/grammar/attr_operator/unpack/insert/dict_0/main.k diff --git a/test/grammar/attr_operator/unpack/insert/dict_0/stdout.golden b/tests/grammar/attr_operator/unpack/insert/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/unpack/insert/dict_0/stdout.golden rename to tests/grammar/attr_operator/unpack/insert/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/unpack/insert/dict_1/main.k b/tests/grammar/attr_operator/unpack/insert/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/unpack/insert/dict_1/main.k rename to tests/grammar/attr_operator/unpack/insert/dict_1/main.k diff --git a/test/grammar/attr_operator/unpack/insert/dict_1/stdout.golden b/tests/grammar/attr_operator/unpack/insert/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/unpack/insert/dict_1/stdout.golden rename to tests/grammar/attr_operator/unpack/insert/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/unpack/insert/dict_2/main.k b/tests/grammar/attr_operator/unpack/insert/dict_2/main.k similarity index 100% rename from test/grammar/attr_operator/unpack/insert/dict_2/main.k rename to tests/grammar/attr_operator/unpack/insert/dict_2/main.k diff --git a/test/grammar/attr_operator/unpack/insert/dict_2/stdout.golden b/tests/grammar/attr_operator/unpack/insert/dict_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/unpack/insert/dict_2/stdout.golden rename to tests/grammar/attr_operator/unpack/insert/dict_2/stdout.golden diff --git a/test/grammar/attr_operator/unpack/override/dict_0/main.k b/tests/grammar/attr_operator/unpack/override/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/unpack/override/dict_0/main.k rename to tests/grammar/attr_operator/unpack/override/dict_0/main.k diff --git a/test/grammar/attr_operator/unpack/override/dict_0/stdout.golden b/tests/grammar/attr_operator/unpack/override/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/unpack/override/dict_0/stdout.golden rename to tests/grammar/attr_operator/unpack/override/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/unpack/override/dict_1/main.k b/tests/grammar/attr_operator/unpack/override/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/unpack/override/dict_1/main.k rename to tests/grammar/attr_operator/unpack/override/dict_1/main.k diff --git a/test/grammar/attr_operator/unpack/override/dict_1/stdout.golden b/tests/grammar/attr_operator/unpack/override/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/unpack/override/dict_1/stdout.golden rename to tests/grammar/attr_operator/unpack/override/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/unpack/override/dict_2/main.k b/tests/grammar/attr_operator/unpack/override/dict_2/main.k similarity index 100% rename from test/grammar/attr_operator/unpack/override/dict_2/main.k rename to tests/grammar/attr_operator/unpack/override/dict_2/main.k diff --git a/test/grammar/attr_operator/unpack/override/dict_2/stdout.golden b/tests/grammar/attr_operator/unpack/override/dict_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/unpack/override/dict_2/stdout.golden rename to tests/grammar/attr_operator/unpack/override/dict_2/stdout.golden diff --git a/test/grammar/attr_operator/unpack/unification/dict_0/main.k b/tests/grammar/attr_operator/unpack/unification/dict_0/main.k similarity index 100% rename from test/grammar/attr_operator/unpack/unification/dict_0/main.k rename to tests/grammar/attr_operator/unpack/unification/dict_0/main.k diff --git a/test/grammar/attr_operator/unpack/unification/dict_0/stdout.golden b/tests/grammar/attr_operator/unpack/unification/dict_0/stdout.golden similarity index 100% rename from test/grammar/attr_operator/unpack/unification/dict_0/stdout.golden rename to tests/grammar/attr_operator/unpack/unification/dict_0/stdout.golden diff --git a/test/grammar/attr_operator/unpack/unification/dict_1/main.k b/tests/grammar/attr_operator/unpack/unification/dict_1/main.k similarity index 100% rename from test/grammar/attr_operator/unpack/unification/dict_1/main.k rename to tests/grammar/attr_operator/unpack/unification/dict_1/main.k diff --git a/test/grammar/attr_operator/unpack/unification/dict_1/stdout.golden b/tests/grammar/attr_operator/unpack/unification/dict_1/stdout.golden similarity index 100% rename from test/grammar/attr_operator/unpack/unification/dict_1/stdout.golden rename to tests/grammar/attr_operator/unpack/unification/dict_1/stdout.golden diff --git a/test/grammar/attr_operator/unpack/unification/dict_2/main.k b/tests/grammar/attr_operator/unpack/unification/dict_2/main.k similarity index 100% rename from test/grammar/attr_operator/unpack/unification/dict_2/main.k rename to tests/grammar/attr_operator/unpack/unification/dict_2/main.k diff --git a/test/grammar/attr_operator/unpack/unification/dict_2/stdout.golden b/tests/grammar/attr_operator/unpack/unification/dict_2/stdout.golden similarity index 100% rename from test/grammar/attr_operator/unpack/unification/dict_2/stdout.golden rename to tests/grammar/attr_operator/unpack/unification/dict_2/stdout.golden diff --git a/test/grammar/builtins/base32/decode/main.k b/tests/grammar/builtins/base32/decode/main.k similarity index 100% rename from test/grammar/builtins/base32/decode/main.k rename to tests/grammar/builtins/base32/decode/main.k diff --git a/test/grammar/builtins/base32/decode/stdout.golden b/tests/grammar/builtins/base32/decode/stdout.golden similarity index 100% rename from test/grammar/builtins/base32/decode/stdout.golden rename to tests/grammar/builtins/base32/decode/stdout.golden diff --git a/test/grammar/builtins/base32/encode/main.k b/tests/grammar/builtins/base32/encode/main.k similarity index 100% rename from test/grammar/builtins/base32/encode/main.k rename to tests/grammar/builtins/base32/encode/main.k diff --git a/test/grammar/builtins/base32/encode/stdout.golden b/tests/grammar/builtins/base32/encode/stdout.golden similarity index 100% rename from test/grammar/builtins/base32/encode/stdout.golden rename to tests/grammar/builtins/base32/encode/stdout.golden diff --git a/test/grammar/builtins/base64/decode/main.k b/tests/grammar/builtins/base64/decode/main.k similarity index 100% rename from test/grammar/builtins/base64/decode/main.k rename to tests/grammar/builtins/base64/decode/main.k diff --git a/test/grammar/builtins/base64/decode/stdout.golden b/tests/grammar/builtins/base64/decode/stdout.golden similarity index 100% rename from test/grammar/builtins/base64/decode/stdout.golden rename to tests/grammar/builtins/base64/decode/stdout.golden diff --git a/test/grammar/builtins/base64/encode/main.k b/tests/grammar/builtins/base64/encode/main.k similarity index 100% rename from test/grammar/builtins/base64/encode/main.k rename to tests/grammar/builtins/base64/encode/main.k diff --git a/test/grammar/builtins/base64/encode/stdout.golden b/tests/grammar/builtins/base64/encode/stdout.golden similarity index 100% rename from test/grammar/builtins/base64/encode/stdout.golden rename to tests/grammar/builtins/base64/encode/stdout.golden diff --git a/test/grammar/builtins/bool/main.k b/tests/grammar/builtins/bool/main.k similarity index 100% rename from test/grammar/builtins/bool/main.k rename to tests/grammar/builtins/bool/main.k diff --git a/test/grammar/builtins/bool/stdout.golden b/tests/grammar/builtins/bool/stdout.golden similarity index 100% rename from test/grammar/builtins/bool/stdout.golden rename to tests/grammar/builtins/bool/stdout.golden diff --git a/test/grammar/builtins/crypto/blake/blake3/main.k b/tests/grammar/builtins/crypto/blake/blake3/main.k similarity index 100% rename from test/grammar/builtins/crypto/blake/blake3/main.k rename to tests/grammar/builtins/crypto/blake/blake3/main.k diff --git a/test/grammar/builtins/crypto/blake/blake3/stdout.golden b/tests/grammar/builtins/crypto/blake/blake3/stdout.golden similarity index 100% rename from test/grammar/builtins/crypto/blake/blake3/stdout.golden rename to tests/grammar/builtins/crypto/blake/blake3/stdout.golden diff --git a/test/grammar/builtins/crypto/md5/main.k b/tests/grammar/builtins/crypto/md5/main.k similarity index 100% rename from test/grammar/builtins/crypto/md5/main.k rename to tests/grammar/builtins/crypto/md5/main.k diff --git a/test/grammar/builtins/crypto/md5/stdout.golden b/tests/grammar/builtins/crypto/md5/stdout.golden similarity index 100% rename from test/grammar/builtins/crypto/md5/stdout.golden rename to tests/grammar/builtins/crypto/md5/stdout.golden diff --git a/test/grammar/builtins/crypto/sha/filesha256/main.k b/tests/grammar/builtins/crypto/sha/filesha256/main.k similarity index 100% rename from test/grammar/builtins/crypto/sha/filesha256/main.k rename to tests/grammar/builtins/crypto/sha/filesha256/main.k diff --git a/test/grammar/builtins/crypto/sha/filesha256/stdout.golden b/tests/grammar/builtins/crypto/sha/filesha256/stdout.golden similarity index 100% rename from test/grammar/builtins/crypto/sha/filesha256/stdout.golden rename to tests/grammar/builtins/crypto/sha/filesha256/stdout.golden diff --git a/test/grammar/builtins/crypto/sha/filesha256/test.txt b/tests/grammar/builtins/crypto/sha/filesha256/test.txt similarity index 100% rename from test/grammar/builtins/crypto/sha/filesha256/test.txt rename to tests/grammar/builtins/crypto/sha/filesha256/test.txt diff --git a/test/grammar/builtins/crypto/sha/sha1/main.k b/tests/grammar/builtins/crypto/sha/sha1/main.k similarity index 100% rename from test/grammar/builtins/crypto/sha/sha1/main.k rename to tests/grammar/builtins/crypto/sha/sha1/main.k diff --git a/test/grammar/builtins/crypto/sha/sha1/stdout.golden b/tests/grammar/builtins/crypto/sha/sha1/stdout.golden similarity index 100% rename from test/grammar/builtins/crypto/sha/sha1/stdout.golden rename to tests/grammar/builtins/crypto/sha/sha1/stdout.golden diff --git a/test/grammar/builtins/crypto/sha/sha224/main.k b/tests/grammar/builtins/crypto/sha/sha224/main.k similarity index 100% rename from test/grammar/builtins/crypto/sha/sha224/main.k rename to tests/grammar/builtins/crypto/sha/sha224/main.k diff --git a/test/grammar/builtins/crypto/sha/sha224/stdout.golden b/tests/grammar/builtins/crypto/sha/sha224/stdout.golden similarity index 100% rename from test/grammar/builtins/crypto/sha/sha224/stdout.golden rename to tests/grammar/builtins/crypto/sha/sha224/stdout.golden diff --git a/test/grammar/builtins/crypto/sha/sha256/main.k b/tests/grammar/builtins/crypto/sha/sha256/main.k similarity index 100% rename from test/grammar/builtins/crypto/sha/sha256/main.k rename to tests/grammar/builtins/crypto/sha/sha256/main.k diff --git a/test/grammar/builtins/crypto/sha/sha256/stdout.golden b/tests/grammar/builtins/crypto/sha/sha256/stdout.golden similarity index 100% rename from test/grammar/builtins/crypto/sha/sha256/stdout.golden rename to tests/grammar/builtins/crypto/sha/sha256/stdout.golden diff --git a/test/grammar/builtins/crypto/sha/sha384/main.k b/tests/grammar/builtins/crypto/sha/sha384/main.k similarity index 100% rename from test/grammar/builtins/crypto/sha/sha384/main.k rename to tests/grammar/builtins/crypto/sha/sha384/main.k diff --git a/test/grammar/builtins/crypto/sha/sha384/stdout.golden b/tests/grammar/builtins/crypto/sha/sha384/stdout.golden similarity index 100% rename from test/grammar/builtins/crypto/sha/sha384/stdout.golden rename to tests/grammar/builtins/crypto/sha/sha384/stdout.golden diff --git a/test/grammar/builtins/crypto/sha/sha512/main.k b/tests/grammar/builtins/crypto/sha/sha512/main.k similarity index 100% rename from test/grammar/builtins/crypto/sha/sha512/main.k rename to tests/grammar/builtins/crypto/sha/sha512/main.k diff --git a/test/grammar/builtins/crypto/sha/sha512/stdout.golden b/tests/grammar/builtins/crypto/sha/sha512/stdout.golden similarity index 100% rename from test/grammar/builtins/crypto/sha/sha512/stdout.golden rename to tests/grammar/builtins/crypto/sha/sha512/stdout.golden diff --git a/test/grammar/builtins/datetime/date/main.k b/tests/grammar/builtins/datetime/date/main.k similarity index 100% rename from test/grammar/builtins/datetime/date/main.k rename to tests/grammar/builtins/datetime/date/main.k diff --git a/test/grammar/builtins/datetime/date/stdout.golden b/tests/grammar/builtins/datetime/date/stdout.golden similarity index 100% rename from test/grammar/builtins/datetime/date/stdout.golden rename to tests/grammar/builtins/datetime/date/stdout.golden diff --git a/test/grammar/builtins/datetime/now/main.k b/tests/grammar/builtins/datetime/now/main.k similarity index 100% rename from test/grammar/builtins/datetime/now/main.k rename to tests/grammar/builtins/datetime/now/main.k diff --git a/test/grammar/builtins/datetime/now/stdout.golden b/tests/grammar/builtins/datetime/now/stdout.golden similarity index 100% rename from test/grammar/builtins/datetime/now/stdout.golden rename to tests/grammar/builtins/datetime/now/stdout.golden diff --git a/test/grammar/builtins/datetime/ticks/main.k b/tests/grammar/builtins/datetime/ticks/main.k similarity index 100% rename from test/grammar/builtins/datetime/ticks/main.k rename to tests/grammar/builtins/datetime/ticks/main.k diff --git a/test/grammar/builtins/datetime/ticks/stdout.golden b/tests/grammar/builtins/datetime/ticks/stdout.golden similarity index 100% rename from test/grammar/builtins/datetime/ticks/stdout.golden rename to tests/grammar/builtins/datetime/ticks/stdout.golden diff --git a/test/grammar/builtins/datetime/today/main.k b/tests/grammar/builtins/datetime/today/main.k similarity index 100% rename from test/grammar/builtins/datetime/today/main.k rename to tests/grammar/builtins/datetime/today/main.k diff --git a/test/grammar/builtins/datetime/today/stdout.golden b/tests/grammar/builtins/datetime/today/stdout.golden similarity index 100% rename from test/grammar/builtins/datetime/today/stdout.golden rename to tests/grammar/builtins/datetime/today/stdout.golden diff --git a/test/grammar/builtins/datetime/validate/main.k b/tests/grammar/builtins/datetime/validate/main.k similarity index 100% rename from test/grammar/builtins/datetime/validate/main.k rename to tests/grammar/builtins/datetime/validate/main.k diff --git a/test/grammar/builtins/datetime/validate/stdout.golden b/tests/grammar/builtins/datetime/validate/stdout.golden similarity index 100% rename from test/grammar/builtins/datetime/validate/stdout.golden rename to tests/grammar/builtins/datetime/validate/stdout.golden diff --git a/test/grammar/builtins/default/abs/main.k b/tests/grammar/builtins/default/abs/main.k similarity index 100% rename from test/grammar/builtins/default/abs/main.k rename to tests/grammar/builtins/default/abs/main.k diff --git a/test/grammar/builtins/default/abs/stdout.golden b/tests/grammar/builtins/default/abs/stdout.golden similarity index 100% rename from test/grammar/builtins/default/abs/stdout.golden rename to tests/grammar/builtins/default/abs/stdout.golden diff --git a/test/grammar/builtins/default/all/main.k b/tests/grammar/builtins/default/all/main.k similarity index 100% rename from test/grammar/builtins/default/all/main.k rename to tests/grammar/builtins/default/all/main.k diff --git a/test/grammar/builtins/default/all/stdout.golden b/tests/grammar/builtins/default/all/stdout.golden similarity index 100% rename from test/grammar/builtins/default/all/stdout.golden rename to tests/grammar/builtins/default/all/stdout.golden diff --git a/test/grammar/builtins/default/any/main.k b/tests/grammar/builtins/default/any/main.k similarity index 100% rename from test/grammar/builtins/default/any/main.k rename to tests/grammar/builtins/default/any/main.k diff --git a/test/grammar/builtins/default/any/stdout.golden b/tests/grammar/builtins/default/any/stdout.golden similarity index 100% rename from test/grammar/builtins/default/any/stdout.golden rename to tests/grammar/builtins/default/any/stdout.golden diff --git a/test/grammar/builtins/default/bin/main.k b/tests/grammar/builtins/default/bin/main.k similarity index 100% rename from test/grammar/builtins/default/bin/main.k rename to tests/grammar/builtins/default/bin/main.k diff --git a/test/grammar/builtins/default/bin/stdout.golden b/tests/grammar/builtins/default/bin/stdout.golden similarity index 100% rename from test/grammar/builtins/default/bin/stdout.golden rename to tests/grammar/builtins/default/bin/stdout.golden diff --git a/test/grammar/builtins/default/hex/main.k b/tests/grammar/builtins/default/hex/main.k similarity index 100% rename from test/grammar/builtins/default/hex/main.k rename to tests/grammar/builtins/default/hex/main.k diff --git a/test/grammar/builtins/default/hex/stdout.golden b/tests/grammar/builtins/default/hex/stdout.golden similarity index 100% rename from test/grammar/builtins/default/hex/stdout.golden rename to tests/grammar/builtins/default/hex/stdout.golden diff --git a/test/grammar/builtins/default/isnullable/main.k b/tests/grammar/builtins/default/isnullable/main.k similarity index 100% rename from test/grammar/builtins/default/isnullable/main.k rename to tests/grammar/builtins/default/isnullable/main.k diff --git a/test/grammar/builtins/default/isnullable/stdout.golden b/tests/grammar/builtins/default/isnullable/stdout.golden similarity index 100% rename from test/grammar/builtins/default/isnullable/stdout.golden rename to tests/grammar/builtins/default/isnullable/stdout.golden diff --git a/test/grammar/builtins/default/isunique/main.k b/tests/grammar/builtins/default/isunique/main.k similarity index 100% rename from test/grammar/builtins/default/isunique/main.k rename to tests/grammar/builtins/default/isunique/main.k diff --git a/test/grammar/builtins/default/isunique/stdout.golden b/tests/grammar/builtins/default/isunique/stdout.golden similarity index 100% rename from test/grammar/builtins/default/isunique/stdout.golden rename to tests/grammar/builtins/default/isunique/stdout.golden diff --git a/test/grammar/builtins/default/len/main.k b/tests/grammar/builtins/default/len/main.k similarity index 100% rename from test/grammar/builtins/default/len/main.k rename to tests/grammar/builtins/default/len/main.k diff --git a/test/grammar/builtins/default/len/stdout.golden b/tests/grammar/builtins/default/len/stdout.golden similarity index 100% rename from test/grammar/builtins/default/len/stdout.golden rename to tests/grammar/builtins/default/len/stdout.golden diff --git a/test/grammar/builtins/default/max/main.k b/tests/grammar/builtins/default/max/main.k similarity index 100% rename from test/grammar/builtins/default/max/main.k rename to tests/grammar/builtins/default/max/main.k diff --git a/test/grammar/builtins/default/max/stdout.golden b/tests/grammar/builtins/default/max/stdout.golden similarity index 100% rename from test/grammar/builtins/default/max/stdout.golden rename to tests/grammar/builtins/default/max/stdout.golden diff --git a/test/grammar/builtins/default/min/main.k b/tests/grammar/builtins/default/min/main.k similarity index 100% rename from test/grammar/builtins/default/min/main.k rename to tests/grammar/builtins/default/min/main.k diff --git a/test/grammar/builtins/default/min/stdout.golden b/tests/grammar/builtins/default/min/stdout.golden similarity index 100% rename from test/grammar/builtins/default/min/stdout.golden rename to tests/grammar/builtins/default/min/stdout.golden diff --git a/test/grammar/builtins/default/multiplyof/main.k b/tests/grammar/builtins/default/multiplyof/main.k similarity index 100% rename from test/grammar/builtins/default/multiplyof/main.k rename to tests/grammar/builtins/default/multiplyof/main.k diff --git a/test/grammar/builtins/default/multiplyof/stdout.golden b/tests/grammar/builtins/default/multiplyof/stdout.golden similarity index 100% rename from test/grammar/builtins/default/multiplyof/stdout.golden rename to tests/grammar/builtins/default/multiplyof/stdout.golden diff --git a/test/grammar/builtins/default/oct/main.k b/tests/grammar/builtins/default/oct/main.k similarity index 100% rename from test/grammar/builtins/default/oct/main.k rename to tests/grammar/builtins/default/oct/main.k diff --git a/test/grammar/builtins/default/oct/stdout.golden b/tests/grammar/builtins/default/oct/stdout.golden similarity index 100% rename from test/grammar/builtins/default/oct/stdout.golden rename to tests/grammar/builtins/default/oct/stdout.golden diff --git a/test/grammar/builtins/default/ord/main.k b/tests/grammar/builtins/default/ord/main.k similarity index 100% rename from test/grammar/builtins/default/ord/main.k rename to tests/grammar/builtins/default/ord/main.k diff --git a/test/grammar/builtins/default/ord/stdout.golden b/tests/grammar/builtins/default/ord/stdout.golden similarity index 100% rename from test/grammar/builtins/default/ord/stdout.golden rename to tests/grammar/builtins/default/ord/stdout.golden diff --git a/test/grammar/builtins/default/pow/main.k b/tests/grammar/builtins/default/pow/main.k similarity index 100% rename from test/grammar/builtins/default/pow/main.k rename to tests/grammar/builtins/default/pow/main.k diff --git a/test/grammar/builtins/default/pow/stdout.golden b/tests/grammar/builtins/default/pow/stdout.golden similarity index 100% rename from test/grammar/builtins/default/pow/stdout.golden rename to tests/grammar/builtins/default/pow/stdout.golden diff --git a/test/grammar/builtins/default/print/dict/main.k b/tests/grammar/builtins/default/print/dict/main.k similarity index 100% rename from test/grammar/builtins/default/print/dict/main.k rename to tests/grammar/builtins/default/print/dict/main.k diff --git a/test/grammar/builtins/default/print/dict/stdout.golden b/tests/grammar/builtins/default/print/dict/stdout.golden similarity index 100% rename from test/grammar/builtins/default/print/dict/stdout.golden rename to tests/grammar/builtins/default/print/dict/stdout.golden diff --git a/test/grammar/builtins/default/print/hello_world/main.k b/tests/grammar/builtins/default/print/hello_world/main.k similarity index 100% rename from test/grammar/builtins/default/print/hello_world/main.k rename to tests/grammar/builtins/default/print/hello_world/main.k diff --git a/test/grammar/builtins/default/print/hello_world/stdout.golden b/tests/grammar/builtins/default/print/hello_world/stdout.golden similarity index 100% rename from test/grammar/builtins/default/print/hello_world/stdout.golden rename to tests/grammar/builtins/default/print/hello_world/stdout.golden diff --git a/test/grammar/builtins/default/print/multiple_arguments_0/main.k b/tests/grammar/builtins/default/print/multiple_arguments_0/main.k similarity index 100% rename from test/grammar/builtins/default/print/multiple_arguments_0/main.k rename to tests/grammar/builtins/default/print/multiple_arguments_0/main.k diff --git a/test/grammar/builtins/default/print/multiple_arguments_0/stdout.golden b/tests/grammar/builtins/default/print/multiple_arguments_0/stdout.golden similarity index 100% rename from test/grammar/builtins/default/print/multiple_arguments_0/stdout.golden rename to tests/grammar/builtins/default/print/multiple_arguments_0/stdout.golden diff --git a/test/grammar/builtins/default/print/multiple_arguments_1/main.k b/tests/grammar/builtins/default/print/multiple_arguments_1/main.k similarity index 100% rename from test/grammar/builtins/default/print/multiple_arguments_1/main.k rename to tests/grammar/builtins/default/print/multiple_arguments_1/main.k diff --git a/test/grammar/builtins/default/print/multiple_arguments_1/stdout.golden b/tests/grammar/builtins/default/print/multiple_arguments_1/stdout.golden similarity index 100% rename from test/grammar/builtins/default/print/multiple_arguments_1/stdout.golden rename to tests/grammar/builtins/default/print/multiple_arguments_1/stdout.golden diff --git a/test/grammar/builtins/default/range/main.k b/tests/grammar/builtins/default/range/main.k similarity index 100% rename from test/grammar/builtins/default/range/main.k rename to tests/grammar/builtins/default/range/main.k diff --git a/test/grammar/builtins/default/range/stdout.golden b/tests/grammar/builtins/default/range/stdout.golden similarity index 100% rename from test/grammar/builtins/default/range/stdout.golden rename to tests/grammar/builtins/default/range/stdout.golden diff --git a/test/grammar/builtins/default/round/main.k b/tests/grammar/builtins/default/round/main.k similarity index 100% rename from test/grammar/builtins/default/round/main.k rename to tests/grammar/builtins/default/round/main.k diff --git a/test/grammar/builtins/default/round/stdout.golden b/tests/grammar/builtins/default/round/stdout.golden similarity index 100% rename from test/grammar/builtins/default/round/stdout.golden rename to tests/grammar/builtins/default/round/stdout.golden diff --git a/test/grammar/builtins/default/sorted/main.k b/tests/grammar/builtins/default/sorted/main.k similarity index 100% rename from test/grammar/builtins/default/sorted/main.k rename to tests/grammar/builtins/default/sorted/main.k diff --git a/test/grammar/builtins/default/sorted/stdout.golden b/tests/grammar/builtins/default/sorted/stdout.golden similarity index 100% rename from test/grammar/builtins/default/sorted/stdout.golden rename to tests/grammar/builtins/default/sorted/stdout.golden diff --git a/test/grammar/builtins/default/sum/main.k b/tests/grammar/builtins/default/sum/main.k similarity index 100% rename from test/grammar/builtins/default/sum/main.k rename to tests/grammar/builtins/default/sum/main.k diff --git a/test/grammar/builtins/default/sum/stdout.golden b/tests/grammar/builtins/default/sum/stdout.golden similarity index 100% rename from test/grammar/builtins/default/sum/stdout.golden rename to tests/grammar/builtins/default/sum/stdout.golden diff --git a/test/grammar/builtins/default/zip/main.k b/tests/grammar/builtins/default/zip/main.k similarity index 100% rename from test/grammar/builtins/default/zip/main.k rename to tests/grammar/builtins/default/zip/main.k diff --git a/test/grammar/builtins/default/zip/stdout.golden b/tests/grammar/builtins/default/zip/stdout.golden similarity index 100% rename from test/grammar/builtins/default/zip/stdout.golden rename to tests/grammar/builtins/default/zip/stdout.golden diff --git a/test/grammar/builtins/file/cp/main.k b/tests/grammar/builtins/file/cp/main.k similarity index 100% rename from test/grammar/builtins/file/cp/main.k rename to tests/grammar/builtins/file/cp/main.k diff --git a/test/grammar/builtins/file/cp/stderr.golden b/tests/grammar/builtins/file/cp/stderr.golden similarity index 100% rename from test/grammar/builtins/file/cp/stderr.golden rename to tests/grammar/builtins/file/cp/stderr.golden diff --git a/test/grammar/builtins/file/current/main.k b/tests/grammar/builtins/file/current/main.k similarity index 100% rename from test/grammar/builtins/file/current/main.k rename to tests/grammar/builtins/file/current/main.k diff --git a/test/grammar/builtins/file/current/stdout.golden b/tests/grammar/builtins/file/current/stdout.golden similarity index 100% rename from test/grammar/builtins/file/current/stdout.golden rename to tests/grammar/builtins/file/current/stdout.golden diff --git a/test/grammar/builtins/file/delete/main.k b/tests/grammar/builtins/file/delete/main.k similarity index 100% rename from test/grammar/builtins/file/delete/main.k rename to tests/grammar/builtins/file/delete/main.k diff --git a/test/grammar/builtins/file/delete/stderr.golden b/tests/grammar/builtins/file/delete/stderr.golden similarity index 100% rename from test/grammar/builtins/file/delete/stderr.golden rename to tests/grammar/builtins/file/delete/stderr.golden diff --git a/test/grammar/builtins/file/exists/a.k b/tests/grammar/builtins/file/exists/a.k similarity index 100% rename from test/grammar/builtins/file/exists/a.k rename to tests/grammar/builtins/file/exists/a.k diff --git a/test/grammar/builtins/file/exists/main.k b/tests/grammar/builtins/file/exists/main.k similarity index 100% rename from test/grammar/builtins/file/exists/main.k rename to tests/grammar/builtins/file/exists/main.k diff --git a/test/grammar/builtins/file/exists/stdout.golden b/tests/grammar/builtins/file/exists/stdout.golden similarity index 100% rename from test/grammar/builtins/file/exists/stdout.golden rename to tests/grammar/builtins/file/exists/stdout.golden diff --git a/test/grammar/builtins/file/glob/main.k b/tests/grammar/builtins/file/glob/main.k similarity index 100% rename from test/grammar/builtins/file/glob/main.k rename to tests/grammar/builtins/file/glob/main.k diff --git a/test/grammar/builtins/file/glob/stdout.golden b/tests/grammar/builtins/file/glob/stdout.golden similarity index 100% rename from test/grammar/builtins/file/glob/stdout.golden rename to tests/grammar/builtins/file/glob/stdout.golden diff --git a/test/grammar/builtins/file/glob/test1.json b/tests/grammar/builtins/file/glob/test1.json similarity index 100% rename from test/grammar/builtins/file/glob/test1.json rename to tests/grammar/builtins/file/glob/test1.json diff --git a/test/grammar/builtins/file/glob/test2.json b/tests/grammar/builtins/file/glob/test2.json similarity index 100% rename from test/grammar/builtins/file/glob/test2.json rename to tests/grammar/builtins/file/glob/test2.json diff --git a/test/grammar/builtins/file/glob/test3.json b/tests/grammar/builtins/file/glob/test3.json similarity index 100% rename from test/grammar/builtins/file/glob/test3.json rename to tests/grammar/builtins/file/glob/test3.json diff --git a/test/grammar/builtins/file/load_file_invalid/main.k b/tests/grammar/builtins/file/load_file_invalid/main.k similarity index 100% rename from test/grammar/builtins/file/load_file_invalid/main.k rename to tests/grammar/builtins/file/load_file_invalid/main.k diff --git a/test/grammar/builtins/file/load_file_invalid/stderr.golden b/tests/grammar/builtins/file/load_file_invalid/stderr.golden similarity index 100% rename from test/grammar/builtins/file/load_file_invalid/stderr.golden rename to tests/grammar/builtins/file/load_file_invalid/stderr.golden diff --git a/test/grammar/builtins/file/load_json/main.k b/tests/grammar/builtins/file/load_json/main.k similarity index 100% rename from test/grammar/builtins/file/load_json/main.k rename to tests/grammar/builtins/file/load_json/main.k diff --git a/test/grammar/builtins/file/load_json/stdout.golden b/tests/grammar/builtins/file/load_json/stdout.golden similarity index 100% rename from test/grammar/builtins/file/load_json/stdout.golden rename to tests/grammar/builtins/file/load_json/stdout.golden diff --git a/test/grammar/builtins/file/load_json/test.json b/tests/grammar/builtins/file/load_json/test.json similarity index 100% rename from test/grammar/builtins/file/load_json/test.json rename to tests/grammar/builtins/file/load_json/test.json diff --git a/test/grammar/builtins/file/load_txt/main.k b/tests/grammar/builtins/file/load_txt/main.k similarity index 100% rename from test/grammar/builtins/file/load_txt/main.k rename to tests/grammar/builtins/file/load_txt/main.k diff --git a/test/grammar/builtins/file/load_txt/stdout.golden b/tests/grammar/builtins/file/load_txt/stdout.golden similarity index 100% rename from test/grammar/builtins/file/load_txt/stdout.golden rename to tests/grammar/builtins/file/load_txt/stdout.golden diff --git a/test/grammar/builtins/file/load_txt/test.txt b/tests/grammar/builtins/file/load_txt/test.txt similarity index 100% rename from test/grammar/builtins/file/load_txt/test.txt rename to tests/grammar/builtins/file/load_txt/test.txt diff --git a/test/grammar/builtins/file/load_yaml/main.k b/tests/grammar/builtins/file/load_yaml/main.k similarity index 100% rename from test/grammar/builtins/file/load_yaml/main.k rename to tests/grammar/builtins/file/load_yaml/main.k diff --git a/test/grammar/builtins/file/load_yaml/stdout.golden b/tests/grammar/builtins/file/load_yaml/stdout.golden similarity index 100% rename from test/grammar/builtins/file/load_yaml/stdout.golden rename to tests/grammar/builtins/file/load_yaml/stdout.golden diff --git a/test/grammar/builtins/file/load_yaml/test.yaml b/tests/grammar/builtins/file/load_yaml/test.yaml similarity index 100% rename from test/grammar/builtins/file/load_yaml/test.yaml rename to tests/grammar/builtins/file/load_yaml/test.yaml diff --git a/test/grammar/builtins/file/mkdir/main.k b/tests/grammar/builtins/file/mkdir/main.k similarity index 100% rename from test/grammar/builtins/file/mkdir/main.k rename to tests/grammar/builtins/file/mkdir/main.k diff --git a/test/grammar/builtins/file/mkdir/stdout.golden b/tests/grammar/builtins/file/mkdir/stdout.golden similarity index 100% rename from test/grammar/builtins/file/mkdir/stdout.golden rename to tests/grammar/builtins/file/mkdir/stdout.golden diff --git a/test/grammar/builtins/file/mod_root/main.k b/tests/grammar/builtins/file/mod_root/main.k similarity index 100% rename from test/grammar/builtins/file/mod_root/main.k rename to tests/grammar/builtins/file/mod_root/main.k diff --git a/test/grammar/builtins/file/mod_root/stdout.golden b/tests/grammar/builtins/file/mod_root/stdout.golden similarity index 100% rename from test/grammar/builtins/file/mod_root/stdout.golden rename to tests/grammar/builtins/file/mod_root/stdout.golden diff --git a/test/grammar/builtins/file/mod_root/test.json b/tests/grammar/builtins/file/mod_root/test.json similarity index 100% rename from test/grammar/builtins/file/mod_root/test.json rename to tests/grammar/builtins/file/mod_root/test.json diff --git a/test/grammar/builtins/file/mod_root_sub/kcl.mod b/tests/grammar/builtins/file/mod_root_sub/kcl.mod similarity index 100% rename from test/grammar/builtins/file/mod_root_sub/kcl.mod rename to tests/grammar/builtins/file/mod_root_sub/kcl.mod diff --git a/test/grammar/builtins/file/mod_root_sub/stdout.golden b/tests/grammar/builtins/file/mod_root_sub/stdout.golden similarity index 100% rename from test/grammar/builtins/file/mod_root_sub/stdout.golden rename to tests/grammar/builtins/file/mod_root_sub/stdout.golden diff --git a/test/grammar/builtins/file/mod_root_sub/sub/main.k b/tests/grammar/builtins/file/mod_root_sub/sub/main.k similarity index 100% rename from test/grammar/builtins/file/mod_root_sub/sub/main.k rename to tests/grammar/builtins/file/mod_root_sub/sub/main.k diff --git a/test/grammar/builtins/file/mod_root_sub/test.json b/tests/grammar/builtins/file/mod_root_sub/test.json similarity index 100% rename from test/grammar/builtins/file/mod_root_sub/test.json rename to tests/grammar/builtins/file/mod_root_sub/test.json diff --git a/test/grammar/builtins/file/mv/main.k b/tests/grammar/builtins/file/mv/main.k similarity index 100% rename from test/grammar/builtins/file/mv/main.k rename to tests/grammar/builtins/file/mv/main.k diff --git a/test/grammar/builtins/file/mv/stderr.golden b/tests/grammar/builtins/file/mv/stderr.golden similarity index 100% rename from test/grammar/builtins/file/mv/stderr.golden rename to tests/grammar/builtins/file/mv/stderr.golden diff --git a/test/grammar/builtins/file/size/main.k b/tests/grammar/builtins/file/size/main.k similarity index 100% rename from test/grammar/builtins/file/size/main.k rename to tests/grammar/builtins/file/size/main.k diff --git a/test/grammar/builtins/file/size/stderr.golden b/tests/grammar/builtins/file/size/stderr.golden similarity index 100% rename from test/grammar/builtins/file/size/stderr.golden rename to tests/grammar/builtins/file/size/stderr.golden diff --git a/test/grammar/builtins/file/size/test_file.txt b/tests/grammar/builtins/file/size/test_file.txt similarity index 100% rename from test/grammar/builtins/file/size/test_file.txt rename to tests/grammar/builtins/file/size/test_file.txt diff --git a/test/grammar/builtins/file/workdir/main.k b/tests/grammar/builtins/file/workdir/main.k similarity index 100% rename from test/grammar/builtins/file/workdir/main.k rename to tests/grammar/builtins/file/workdir/main.k diff --git a/test/grammar/builtins/file/workdir/stdout.golden b/tests/grammar/builtins/file/workdir/stdout.golden similarity index 100% rename from test/grammar/builtins/file/workdir/stdout.golden rename to tests/grammar/builtins/file/workdir/stdout.golden diff --git a/test/grammar/builtins/file/workdir_sub/kcl.mod b/tests/grammar/builtins/file/workdir_sub/kcl.mod similarity index 100% rename from test/grammar/builtins/file/workdir_sub/kcl.mod rename to tests/grammar/builtins/file/workdir_sub/kcl.mod diff --git a/test/grammar/builtins/file/workdir_sub/stdout.golden b/tests/grammar/builtins/file/workdir_sub/stdout.golden similarity index 100% rename from test/grammar/builtins/file/workdir_sub/stdout.golden rename to tests/grammar/builtins/file/workdir_sub/stdout.golden diff --git a/test/grammar/builtins/file/workdir_sub/sub/main.k b/tests/grammar/builtins/file/workdir_sub/sub/main.k similarity index 100% rename from test/grammar/builtins/file/workdir_sub/sub/main.k rename to tests/grammar/builtins/file/workdir_sub/sub/main.k diff --git a/test/grammar/builtins/file/workdir_sub/test.json b/tests/grammar/builtins/file/workdir_sub/test.json similarity index 100% rename from test/grammar/builtins/file/workdir_sub/test.json rename to tests/grammar/builtins/file/workdir_sub/test.json diff --git a/test/grammar/builtins/file/write/main.k b/tests/grammar/builtins/file/write/main.k similarity index 100% rename from test/grammar/builtins/file/write/main.k rename to tests/grammar/builtins/file/write/main.k diff --git a/test/grammar/builtins/file/write/stdout.golden b/tests/grammar/builtins/file/write/stdout.golden similarity index 100% rename from test/grammar/builtins/file/write/stdout.golden rename to tests/grammar/builtins/file/write/stdout.golden diff --git a/test/grammar/builtins/file/write/test_file.txt b/tests/grammar/builtins/file/write/test_file.txt similarity index 100% rename from test/grammar/builtins/file/write/test_file.txt rename to tests/grammar/builtins/file/write/test_file.txt diff --git a/test/grammar/builtins/float/create/main.k b/tests/grammar/builtins/float/create/main.k similarity index 100% rename from test/grammar/builtins/float/create/main.k rename to tests/grammar/builtins/float/create/main.k diff --git a/test/grammar/builtins/float/create/stdout.golden b/tests/grammar/builtins/float/create/stdout.golden similarity index 100% rename from test/grammar/builtins/float/create/stdout.golden rename to tests/grammar/builtins/float/create/stdout.golden diff --git a/test/grammar/builtins/int/binary_prefix/main.k b/tests/grammar/builtins/int/binary_prefix/main.k similarity index 100% rename from test/grammar/builtins/int/binary_prefix/main.k rename to tests/grammar/builtins/int/binary_prefix/main.k diff --git a/test/grammar/builtins/int/binary_prefix/stdout.golden b/tests/grammar/builtins/int/binary_prefix/stdout.golden similarity index 100% rename from test/grammar/builtins/int/binary_prefix/stdout.golden rename to tests/grammar/builtins/int/binary_prefix/stdout.golden diff --git a/test/grammar/builtins/int/create/main.k b/tests/grammar/builtins/int/create/main.k similarity index 100% rename from test/grammar/builtins/int/create/main.k rename to tests/grammar/builtins/int/create/main.k diff --git a/test/grammar/builtins/int/create/stdout.golden b/tests/grammar/builtins/int/create/stdout.golden similarity index 100% rename from test/grammar/builtins/int/create/stdout.golden rename to tests/grammar/builtins/int/create/stdout.golden diff --git a/test/grammar/builtins/json/decode/main.k b/tests/grammar/builtins/json/decode/main.k similarity index 100% rename from test/grammar/builtins/json/decode/main.k rename to tests/grammar/builtins/json/decode/main.k diff --git a/test/grammar/builtins/json/decode/stdout.golden b/tests/grammar/builtins/json/decode/stdout.golden similarity index 100% rename from test/grammar/builtins/json/decode/stdout.golden rename to tests/grammar/builtins/json/decode/stdout.golden diff --git a/test/grammar/builtins/json/dump_to_file_0/0.json b/tests/grammar/builtins/json/dump_to_file_0/0.json similarity index 100% rename from test/grammar/builtins/json/dump_to_file_0/0.json rename to tests/grammar/builtins/json/dump_to_file_0/0.json diff --git a/test/grammar/builtins/json/dump_to_file_0/1.json b/tests/grammar/builtins/json/dump_to_file_0/1.json similarity index 100% rename from test/grammar/builtins/json/dump_to_file_0/1.json rename to tests/grammar/builtins/json/dump_to_file_0/1.json diff --git a/test/grammar/builtins/json/dump_to_file_0/2.json b/tests/grammar/builtins/json/dump_to_file_0/2.json similarity index 100% rename from test/grammar/builtins/json/dump_to_file_0/2.json rename to tests/grammar/builtins/json/dump_to_file_0/2.json diff --git a/test/grammar/builtins/json/dump_to_file_0/3.json b/tests/grammar/builtins/json/dump_to_file_0/3.json similarity index 100% rename from test/grammar/builtins/json/dump_to_file_0/3.json rename to tests/grammar/builtins/json/dump_to_file_0/3.json diff --git a/test/grammar/builtins/json/dump_to_file_0/4.json b/tests/grammar/builtins/json/dump_to_file_0/4.json similarity index 100% rename from test/grammar/builtins/json/dump_to_file_0/4.json rename to tests/grammar/builtins/json/dump_to_file_0/4.json diff --git a/test/grammar/builtins/json/dump_to_file_0/5.json b/tests/grammar/builtins/json/dump_to_file_0/5.json similarity index 100% rename from test/grammar/builtins/json/dump_to_file_0/5.json rename to tests/grammar/builtins/json/dump_to_file_0/5.json diff --git a/test/grammar/builtins/json/dump_to_file_0/main.k b/tests/grammar/builtins/json/dump_to_file_0/main.k similarity index 100% rename from test/grammar/builtins/json/dump_to_file_0/main.k rename to tests/grammar/builtins/json/dump_to_file_0/main.k diff --git a/test/grammar/builtins/json/dump_to_file_0/stdout.golden b/tests/grammar/builtins/json/dump_to_file_0/stdout.golden similarity index 100% rename from test/grammar/builtins/json/dump_to_file_0/stdout.golden rename to tests/grammar/builtins/json/dump_to_file_0/stdout.golden diff --git a/test/grammar/builtins/json/dump_to_file_1/0.yaml b/tests/grammar/builtins/json/dump_to_file_1/0.yaml similarity index 100% rename from test/grammar/builtins/json/dump_to_file_1/0.yaml rename to tests/grammar/builtins/json/dump_to_file_1/0.yaml diff --git a/test/grammar/builtins/json/dump_to_file_1/1.yaml b/tests/grammar/builtins/json/dump_to_file_1/1.yaml similarity index 100% rename from test/grammar/builtins/json/dump_to_file_1/1.yaml rename to tests/grammar/builtins/json/dump_to_file_1/1.yaml diff --git a/test/grammar/builtins/json/dump_to_file_1/2.yaml b/tests/grammar/builtins/json/dump_to_file_1/2.yaml similarity index 100% rename from test/grammar/builtins/json/dump_to_file_1/2.yaml rename to tests/grammar/builtins/json/dump_to_file_1/2.yaml diff --git a/test/grammar/builtins/json/dump_to_file_1/3.yaml b/tests/grammar/builtins/json/dump_to_file_1/3.yaml similarity index 100% rename from test/grammar/builtins/json/dump_to_file_1/3.yaml rename to tests/grammar/builtins/json/dump_to_file_1/3.yaml diff --git a/test/grammar/builtins/json/dump_to_file_1/4.yaml b/tests/grammar/builtins/json/dump_to_file_1/4.yaml similarity index 100% rename from test/grammar/builtins/json/dump_to_file_1/4.yaml rename to tests/grammar/builtins/json/dump_to_file_1/4.yaml diff --git a/test/grammar/builtins/json/dump_to_file_1/5.yaml b/tests/grammar/builtins/json/dump_to_file_1/5.yaml similarity index 100% rename from test/grammar/builtins/json/dump_to_file_1/5.yaml rename to tests/grammar/builtins/json/dump_to_file_1/5.yaml diff --git a/test/grammar/builtins/json/dump_to_file_1/main.k b/tests/grammar/builtins/json/dump_to_file_1/main.k similarity index 100% rename from test/grammar/builtins/json/dump_to_file_1/main.k rename to tests/grammar/builtins/json/dump_to_file_1/main.k diff --git a/test/grammar/builtins/json/dump_to_file_1/stdout.golden b/tests/grammar/builtins/json/dump_to_file_1/stdout.golden similarity index 100% rename from test/grammar/builtins/json/dump_to_file_1/stdout.golden rename to tests/grammar/builtins/json/dump_to_file_1/stdout.golden diff --git a/test/grammar/builtins/json/encode_0/main.k b/tests/grammar/builtins/json/encode_0/main.k similarity index 100% rename from test/grammar/builtins/json/encode_0/main.k rename to tests/grammar/builtins/json/encode_0/main.k diff --git a/test/grammar/builtins/json/encode_0/stdout.golden b/tests/grammar/builtins/json/encode_0/stdout.golden similarity index 100% rename from test/grammar/builtins/json/encode_0/stdout.golden rename to tests/grammar/builtins/json/encode_0/stdout.golden diff --git a/test/grammar/builtins/json/encode_1/main.k b/tests/grammar/builtins/json/encode_1/main.k similarity index 100% rename from test/grammar/builtins/json/encode_1/main.k rename to tests/grammar/builtins/json/encode_1/main.k diff --git a/test/grammar/builtins/json/encode_1/stdout.golden b/tests/grammar/builtins/json/encode_1/stdout.golden similarity index 100% rename from test/grammar/builtins/json/encode_1/stdout.golden rename to tests/grammar/builtins/json/encode_1/stdout.golden diff --git a/test/grammar/builtins/json/encode_2/main.k b/tests/grammar/builtins/json/encode_2/main.k similarity index 100% rename from test/grammar/builtins/json/encode_2/main.k rename to tests/grammar/builtins/json/encode_2/main.k diff --git a/test/grammar/builtins/json/encode_2/stdout.golden b/tests/grammar/builtins/json/encode_2/stdout.golden similarity index 100% rename from test/grammar/builtins/json/encode_2/stdout.golden rename to tests/grammar/builtins/json/encode_2/stdout.golden diff --git a/test/grammar/builtins/json/output_0/main.k b/tests/grammar/builtins/json/output_0/main.k similarity index 100% rename from test/grammar/builtins/json/output_0/main.k rename to tests/grammar/builtins/json/output_0/main.k diff --git a/test/grammar/builtins/json/output_0/stdout.golden b/tests/grammar/builtins/json/output_0/stdout.golden similarity index 100% rename from test/grammar/builtins/json/output_0/stdout.golden rename to tests/grammar/builtins/json/output_0/stdout.golden diff --git a/test/grammar/builtins/json/output_1/main.k b/tests/grammar/builtins/json/output_1/main.k similarity index 100% rename from test/grammar/builtins/json/output_1/main.k rename to tests/grammar/builtins/json/output_1/main.k diff --git a/test/grammar/builtins/json/output_1/out.json b/tests/grammar/builtins/json/output_1/out.json similarity index 100% rename from test/grammar/builtins/json/output_1/out.json rename to tests/grammar/builtins/json/output_1/out.json diff --git a/test/grammar/builtins/json/output_1/stdout.golden b/tests/grammar/builtins/json/output_1/stdout.golden similarity index 100% rename from test/grammar/builtins/json/output_1/stdout.golden rename to tests/grammar/builtins/json/output_1/stdout.golden diff --git a/test/grammar/builtins/json/output_2/main.k b/tests/grammar/builtins/json/output_2/main.k similarity index 100% rename from test/grammar/builtins/json/output_2/main.k rename to tests/grammar/builtins/json/output_2/main.k diff --git a/test/grammar/builtins/json/output_2/stdout.golden b/tests/grammar/builtins/json/output_2/stdout.golden similarity index 100% rename from test/grammar/builtins/json/output_2/stdout.golden rename to tests/grammar/builtins/json/output_2/stdout.golden diff --git a/test/grammar/builtins/json/validate/main.k b/tests/grammar/builtins/json/validate/main.k similarity index 100% rename from test/grammar/builtins/json/validate/main.k rename to tests/grammar/builtins/json/validate/main.k diff --git a/test/grammar/builtins/json/validate/stdout.golden b/tests/grammar/builtins/json/validate/stdout.golden similarity index 100% rename from test/grammar/builtins/json/validate/stdout.golden rename to tests/grammar/builtins/json/validate/stdout.golden diff --git a/test/grammar/builtins/manifests/yaml_stream/config/main.k b/tests/grammar/builtins/manifests/yaml_stream/config/main.k similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/config/main.k rename to tests/grammar/builtins/manifests/yaml_stream/config/main.k diff --git a/test/grammar/builtins/manifests/yaml_stream/config/stdout.golden b/tests/grammar/builtins/manifests/yaml_stream/config/stdout.golden similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/config/stdout.golden rename to tests/grammar/builtins/manifests/yaml_stream/config/stdout.golden diff --git a/test/grammar/builtins/manifests/yaml_stream/config_ignore_none/main.k b/tests/grammar/builtins/manifests/yaml_stream/config_ignore_none/main.k similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/config_ignore_none/main.k rename to tests/grammar/builtins/manifests/yaml_stream/config_ignore_none/main.k diff --git a/test/grammar/builtins/manifests/yaml_stream/config_ignore_none/stdout.golden b/tests/grammar/builtins/manifests/yaml_stream/config_ignore_none/stdout.golden similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/config_ignore_none/stdout.golden rename to tests/grammar/builtins/manifests/yaml_stream/config_ignore_none/stdout.golden diff --git a/test/grammar/builtins/manifests/yaml_stream/config_ignore_private_false/main.k b/tests/grammar/builtins/manifests/yaml_stream/config_ignore_private_false/main.k similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/config_ignore_private_false/main.k rename to tests/grammar/builtins/manifests/yaml_stream/config_ignore_private_false/main.k diff --git a/test/grammar/builtins/manifests/yaml_stream/config_ignore_private_false/stdout.golden b/tests/grammar/builtins/manifests/yaml_stream/config_ignore_private_false/stdout.golden similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/config_ignore_private_false/stdout.golden rename to tests/grammar/builtins/manifests/yaml_stream/config_ignore_private_false/stdout.golden diff --git a/test/grammar/builtins/manifests/yaml_stream/config_ignore_private_true/main.k b/tests/grammar/builtins/manifests/yaml_stream/config_ignore_private_true/main.k similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/config_ignore_private_true/main.k rename to tests/grammar/builtins/manifests/yaml_stream/config_ignore_private_true/main.k diff --git a/test/grammar/builtins/manifests/yaml_stream/config_ignore_private_true/stdout.golden b/tests/grammar/builtins/manifests/yaml_stream/config_ignore_private_true/stdout.golden similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/config_ignore_private_true/stdout.golden rename to tests/grammar/builtins/manifests/yaml_stream/config_ignore_private_true/stdout.golden diff --git a/test/grammar/builtins/manifests/yaml_stream/config_sep/main.k b/tests/grammar/builtins/manifests/yaml_stream/config_sep/main.k similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/config_sep/main.k rename to tests/grammar/builtins/manifests/yaml_stream/config_sep/main.k diff --git a/test/grammar/builtins/manifests/yaml_stream/config_sep/stdout.golden b/tests/grammar/builtins/manifests/yaml_stream/config_sep/stdout.golden similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/config_sep/stdout.golden rename to tests/grammar/builtins/manifests/yaml_stream/config_sep/stdout.golden diff --git a/test/grammar/builtins/manifests/yaml_stream/config_sort_keys/main.k b/tests/grammar/builtins/manifests/yaml_stream/config_sort_keys/main.k similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/config_sort_keys/main.k rename to tests/grammar/builtins/manifests/yaml_stream/config_sort_keys/main.k diff --git a/test/grammar/builtins/manifests/yaml_stream/config_sort_keys/stdout.golden b/tests/grammar/builtins/manifests/yaml_stream/config_sort_keys/stdout.golden similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/config_sort_keys/stdout.golden rename to tests/grammar/builtins/manifests/yaml_stream/config_sort_keys/stdout.golden diff --git a/test/grammar/builtins/manifests/yaml_stream/list/main.k b/tests/grammar/builtins/manifests/yaml_stream/list/main.k similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/list/main.k rename to tests/grammar/builtins/manifests/yaml_stream/list/main.k diff --git a/test/grammar/builtins/manifests/yaml_stream/list/stdout.golden b/tests/grammar/builtins/manifests/yaml_stream/list/stdout.golden similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/list/stdout.golden rename to tests/grammar/builtins/manifests/yaml_stream/list/stdout.golden diff --git a/test/grammar/builtins/manifests/yaml_stream/multiple_literal_0/main.k b/tests/grammar/builtins/manifests/yaml_stream/multiple_literal_0/main.k similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/multiple_literal_0/main.k rename to tests/grammar/builtins/manifests/yaml_stream/multiple_literal_0/main.k diff --git a/test/grammar/builtins/manifests/yaml_stream/multiple_literal_0/stdout.golden b/tests/grammar/builtins/manifests/yaml_stream/multiple_literal_0/stdout.golden similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/multiple_literal_0/stdout.golden rename to tests/grammar/builtins/manifests/yaml_stream/multiple_literal_0/stdout.golden diff --git a/test/grammar/builtins/manifests/yaml_stream/multiple_literal_1/main.k b/tests/grammar/builtins/manifests/yaml_stream/multiple_literal_1/main.k similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/multiple_literal_1/main.k rename to tests/grammar/builtins/manifests/yaml_stream/multiple_literal_1/main.k diff --git a/test/grammar/builtins/manifests/yaml_stream/multiple_literal_1/stdout.golden b/tests/grammar/builtins/manifests/yaml_stream/multiple_literal_1/stdout.golden similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/multiple_literal_1/stdout.golden rename to tests/grammar/builtins/manifests/yaml_stream/multiple_literal_1/stdout.golden diff --git a/test/grammar/builtins/manifests/yaml_stream/single_literal_0/main.k b/tests/grammar/builtins/manifests/yaml_stream/single_literal_0/main.k similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/single_literal_0/main.k rename to tests/grammar/builtins/manifests/yaml_stream/single_literal_0/main.k diff --git a/test/grammar/builtins/manifests/yaml_stream/single_literal_0/stdout.golden b/tests/grammar/builtins/manifests/yaml_stream/single_literal_0/stdout.golden similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/single_literal_0/stdout.golden rename to tests/grammar/builtins/manifests/yaml_stream/single_literal_0/stdout.golden diff --git a/test/grammar/builtins/manifests/yaml_stream/single_literal_1/main.k b/tests/grammar/builtins/manifests/yaml_stream/single_literal_1/main.k similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/single_literal_1/main.k rename to tests/grammar/builtins/manifests/yaml_stream/single_literal_1/main.k diff --git a/test/grammar/builtins/manifests/yaml_stream/single_literal_1/stdout.golden b/tests/grammar/builtins/manifests/yaml_stream/single_literal_1/stdout.golden similarity index 100% rename from test/grammar/builtins/manifests/yaml_stream/single_literal_1/stdout.golden rename to tests/grammar/builtins/manifests/yaml_stream/single_literal_1/stdout.golden diff --git a/test/grammar/builtins/math/ceil/main.k b/tests/grammar/builtins/math/ceil/main.k similarity index 100% rename from test/grammar/builtins/math/ceil/main.k rename to tests/grammar/builtins/math/ceil/main.k diff --git a/test/grammar/builtins/math/ceil/stdout.golden b/tests/grammar/builtins/math/ceil/stdout.golden similarity index 100% rename from test/grammar/builtins/math/ceil/stdout.golden rename to tests/grammar/builtins/math/ceil/stdout.golden diff --git a/test/grammar/builtins/math/exp/main.k b/tests/grammar/builtins/math/exp/main.k similarity index 100% rename from test/grammar/builtins/math/exp/main.k rename to tests/grammar/builtins/math/exp/main.k diff --git a/test/grammar/builtins/math/exp/stdout.golden b/tests/grammar/builtins/math/exp/stdout.golden similarity index 100% rename from test/grammar/builtins/math/exp/stdout.golden rename to tests/grammar/builtins/math/exp/stdout.golden diff --git a/test/grammar/builtins/math/expm1/main.k b/tests/grammar/builtins/math/expm1/main.k similarity index 100% rename from test/grammar/builtins/math/expm1/main.k rename to tests/grammar/builtins/math/expm1/main.k diff --git a/test/grammar/builtins/math/expm1/stdout.golden b/tests/grammar/builtins/math/expm1/stdout.golden similarity index 100% rename from test/grammar/builtins/math/expm1/stdout.golden rename to tests/grammar/builtins/math/expm1/stdout.golden diff --git a/test/grammar/builtins/math/factorial/main.k b/tests/grammar/builtins/math/factorial/main.k similarity index 100% rename from test/grammar/builtins/math/factorial/main.k rename to tests/grammar/builtins/math/factorial/main.k diff --git a/test/grammar/builtins/math/factorial/stdout.golden b/tests/grammar/builtins/math/factorial/stdout.golden similarity index 100% rename from test/grammar/builtins/math/factorial/stdout.golden rename to tests/grammar/builtins/math/factorial/stdout.golden diff --git a/test/grammar/builtins/math/floor/main.k b/tests/grammar/builtins/math/floor/main.k similarity index 100% rename from test/grammar/builtins/math/floor/main.k rename to tests/grammar/builtins/math/floor/main.k diff --git a/test/grammar/builtins/math/floor/stdout.golden b/tests/grammar/builtins/math/floor/stdout.golden similarity index 100% rename from test/grammar/builtins/math/floor/stdout.golden rename to tests/grammar/builtins/math/floor/stdout.golden diff --git a/test/grammar/builtins/math/gcd/main.k b/tests/grammar/builtins/math/gcd/main.k similarity index 100% rename from test/grammar/builtins/math/gcd/main.k rename to tests/grammar/builtins/math/gcd/main.k diff --git a/test/grammar/builtins/math/gcd/stdout.golden b/tests/grammar/builtins/math/gcd/stdout.golden similarity index 100% rename from test/grammar/builtins/math/gcd/stdout.golden rename to tests/grammar/builtins/math/gcd/stdout.golden diff --git a/test/grammar/builtins/math/isfinite/main.k b/tests/grammar/builtins/math/isfinite/main.k similarity index 100% rename from test/grammar/builtins/math/isfinite/main.k rename to tests/grammar/builtins/math/isfinite/main.k diff --git a/test/grammar/builtins/math/isfinite/stdout.golden b/tests/grammar/builtins/math/isfinite/stdout.golden similarity index 100% rename from test/grammar/builtins/math/isfinite/stdout.golden rename to tests/grammar/builtins/math/isfinite/stdout.golden diff --git a/test/grammar/builtins/math/isinf/main.k b/tests/grammar/builtins/math/isinf/main.k similarity index 100% rename from test/grammar/builtins/math/isinf/main.k rename to tests/grammar/builtins/math/isinf/main.k diff --git a/test/grammar/builtins/math/isinf/stdout.golden b/tests/grammar/builtins/math/isinf/stdout.golden similarity index 100% rename from test/grammar/builtins/math/isinf/stdout.golden rename to tests/grammar/builtins/math/isinf/stdout.golden diff --git a/test/grammar/builtins/math/isnan/main.k b/tests/grammar/builtins/math/isnan/main.k similarity index 100% rename from test/grammar/builtins/math/isnan/main.k rename to tests/grammar/builtins/math/isnan/main.k diff --git a/test/grammar/builtins/math/isnan/stdout.golden b/tests/grammar/builtins/math/isnan/stdout.golden similarity index 100% rename from test/grammar/builtins/math/isnan/stdout.golden rename to tests/grammar/builtins/math/isnan/stdout.golden diff --git a/test/grammar/builtins/math/log/main.k b/tests/grammar/builtins/math/log/main.k similarity index 100% rename from test/grammar/builtins/math/log/main.k rename to tests/grammar/builtins/math/log/main.k diff --git a/test/grammar/builtins/math/log/stdout.golden b/tests/grammar/builtins/math/log/stdout.golden similarity index 100% rename from test/grammar/builtins/math/log/stdout.golden rename to tests/grammar/builtins/math/log/stdout.golden diff --git a/test/grammar/builtins/math/log10/main.k b/tests/grammar/builtins/math/log10/main.k similarity index 100% rename from test/grammar/builtins/math/log10/main.k rename to tests/grammar/builtins/math/log10/main.k diff --git a/test/grammar/builtins/math/log10/stdout.golden b/tests/grammar/builtins/math/log10/stdout.golden similarity index 100% rename from test/grammar/builtins/math/log10/stdout.golden rename to tests/grammar/builtins/math/log10/stdout.golden diff --git a/test/grammar/builtins/math/log1p/main.k b/tests/grammar/builtins/math/log1p/main.k similarity index 100% rename from test/grammar/builtins/math/log1p/main.k rename to tests/grammar/builtins/math/log1p/main.k diff --git a/test/grammar/builtins/math/log1p/stdout.golden b/tests/grammar/builtins/math/log1p/stdout.golden similarity index 100% rename from test/grammar/builtins/math/log1p/stdout.golden rename to tests/grammar/builtins/math/log1p/stdout.golden diff --git a/test/grammar/builtins/math/log2/main.k b/tests/grammar/builtins/math/log2/main.k similarity index 100% rename from test/grammar/builtins/math/log2/main.k rename to tests/grammar/builtins/math/log2/main.k diff --git a/test/grammar/builtins/math/log2/stdout.golden b/tests/grammar/builtins/math/log2/stdout.golden similarity index 100% rename from test/grammar/builtins/math/log2/stdout.golden rename to tests/grammar/builtins/math/log2/stdout.golden diff --git a/test/grammar/builtins/math/modf/main.k b/tests/grammar/builtins/math/modf/main.k similarity index 100% rename from test/grammar/builtins/math/modf/main.k rename to tests/grammar/builtins/math/modf/main.k diff --git a/test/grammar/builtins/math/modf/stdout.golden b/tests/grammar/builtins/math/modf/stdout.golden similarity index 100% rename from test/grammar/builtins/math/modf/stdout.golden rename to tests/grammar/builtins/math/modf/stdout.golden diff --git a/test/grammar/builtins/math/pow/main.k b/tests/grammar/builtins/math/pow/main.k similarity index 100% rename from test/grammar/builtins/math/pow/main.k rename to tests/grammar/builtins/math/pow/main.k diff --git a/test/grammar/builtins/math/pow/stdout.golden b/tests/grammar/builtins/math/pow/stdout.golden similarity index 100% rename from test/grammar/builtins/math/pow/stdout.golden rename to tests/grammar/builtins/math/pow/stdout.golden diff --git a/test/grammar/builtins/math/sqrt/main.k b/tests/grammar/builtins/math/sqrt/main.k similarity index 100% rename from test/grammar/builtins/math/sqrt/main.k rename to tests/grammar/builtins/math/sqrt/main.k diff --git a/test/grammar/builtins/math/sqrt/stdout.golden b/tests/grammar/builtins/math/sqrt/stdout.golden similarity index 100% rename from test/grammar/builtins/math/sqrt/stdout.golden rename to tests/grammar/builtins/math/sqrt/stdout.golden diff --git a/test/grammar/builtins/net/cidr/main.k b/tests/grammar/builtins/net/cidr/main.k similarity index 100% rename from test/grammar/builtins/net/cidr/main.k rename to tests/grammar/builtins/net/cidr/main.k diff --git a/test/grammar/builtins/net/cidr/stdout.golden b/tests/grammar/builtins/net/cidr/stdout.golden similarity index 100% rename from test/grammar/builtins/net/cidr/stdout.golden rename to tests/grammar/builtins/net/cidr/stdout.golden diff --git a/test/grammar/builtins/net/host_port/main.k b/tests/grammar/builtins/net/host_port/main.k similarity index 100% rename from test/grammar/builtins/net/host_port/main.k rename to tests/grammar/builtins/net/host_port/main.k diff --git a/test/grammar/builtins/net/host_port/stdout.golden b/tests/grammar/builtins/net/host_port/stdout.golden similarity index 100% rename from test/grammar/builtins/net/host_port/stdout.golden rename to tests/grammar/builtins/net/host_port/stdout.golden diff --git a/test/grammar/builtins/net/is_ip_0/main.k b/tests/grammar/builtins/net/is_ip_0/main.k similarity index 100% rename from test/grammar/builtins/net/is_ip_0/main.k rename to tests/grammar/builtins/net/is_ip_0/main.k diff --git a/test/grammar/builtins/net/is_ip_0/stdout.golden b/tests/grammar/builtins/net/is_ip_0/stdout.golden similarity index 100% rename from test/grammar/builtins/net/is_ip_0/stdout.golden rename to tests/grammar/builtins/net/is_ip_0/stdout.golden diff --git a/test/grammar/builtins/net/is_ip_1/main.k b/tests/grammar/builtins/net/is_ip_1/main.k similarity index 100% rename from test/grammar/builtins/net/is_ip_1/main.k rename to tests/grammar/builtins/net/is_ip_1/main.k diff --git a/test/grammar/builtins/net/is_ip_1/stdout.golden b/tests/grammar/builtins/net/is_ip_1/stdout.golden similarity index 100% rename from test/grammar/builtins/net/is_ip_1/stdout.golden rename to tests/grammar/builtins/net/is_ip_1/stdout.golden diff --git a/test/grammar/builtins/net/is_ip_2/main.k b/tests/grammar/builtins/net/is_ip_2/main.k similarity index 100% rename from test/grammar/builtins/net/is_ip_2/main.k rename to tests/grammar/builtins/net/is_ip_2/main.k diff --git a/test/grammar/builtins/net/is_ip_2/stdout.golden b/tests/grammar/builtins/net/is_ip_2/stdout.golden similarity index 100% rename from test/grammar/builtins/net/is_ip_2/stdout.golden rename to tests/grammar/builtins/net/is_ip_2/stdout.golden diff --git a/test/grammar/builtins/net/to_ip4/main.k b/tests/grammar/builtins/net/to_ip4/main.k similarity index 100% rename from test/grammar/builtins/net/to_ip4/main.k rename to tests/grammar/builtins/net/to_ip4/main.k diff --git a/test/grammar/builtins/net/to_ip4/stdout.golden b/tests/grammar/builtins/net/to_ip4/stdout.golden similarity index 100% rename from test/grammar/builtins/net/to_ip4/stdout.golden rename to tests/grammar/builtins/net/to_ip4/stdout.golden diff --git a/test/grammar/builtins/net/to_ip6/main.k b/tests/grammar/builtins/net/to_ip6/main.k similarity index 100% rename from test/grammar/builtins/net/to_ip6/main.k rename to tests/grammar/builtins/net/to_ip6/main.k diff --git a/test/grammar/builtins/net/to_ip6/stdout.golden b/tests/grammar/builtins/net/to_ip6/stdout.golden similarity index 100% rename from test/grammar/builtins/net/to_ip6/stdout.golden rename to tests/grammar/builtins/net/to_ip6/stdout.golden diff --git a/test/grammar/builtins/operator/operator_fail_0/main.k b/tests/grammar/builtins/operator/operator_fail_0/main.k similarity index 100% rename from test/grammar/builtins/operator/operator_fail_0/main.k rename to tests/grammar/builtins/operator/operator_fail_0/main.k diff --git a/test/grammar/builtins/operator/operator_fail_0/stderr.golden b/tests/grammar/builtins/operator/operator_fail_0/stderr.golden similarity index 100% rename from test/grammar/builtins/operator/operator_fail_0/stderr.golden rename to tests/grammar/builtins/operator/operator_fail_0/stderr.golden diff --git a/test/grammar/builtins/operator/operator_fail_1/main.k b/tests/grammar/builtins/operator/operator_fail_1/main.k similarity index 100% rename from test/grammar/builtins/operator/operator_fail_1/main.k rename to tests/grammar/builtins/operator/operator_fail_1/main.k diff --git a/test/grammar/builtins/operator/operator_fail_1/stderr.golden b/tests/grammar/builtins/operator/operator_fail_1/stderr.golden similarity index 100% rename from test/grammar/builtins/operator/operator_fail_1/stderr.golden rename to tests/grammar/builtins/operator/operator_fail_1/stderr.golden diff --git a/test/grammar/builtins/operator/operator_fail_2/main.k b/tests/grammar/builtins/operator/operator_fail_2/main.k similarity index 100% rename from test/grammar/builtins/operator/operator_fail_2/main.k rename to tests/grammar/builtins/operator/operator_fail_2/main.k diff --git a/test/grammar/builtins/operator/operator_fail_2/stderr.golden b/tests/grammar/builtins/operator/operator_fail_2/stderr.golden similarity index 100% rename from test/grammar/builtins/operator/operator_fail_2/stderr.golden rename to tests/grammar/builtins/operator/operator_fail_2/stderr.golden diff --git a/test/grammar/builtins/regex/test_0/main.k b/tests/grammar/builtins/regex/test_0/main.k similarity index 100% rename from test/grammar/builtins/regex/test_0/main.k rename to tests/grammar/builtins/regex/test_0/main.k diff --git a/test/grammar/builtins/regex/test_0/stdout.golden b/tests/grammar/builtins/regex/test_0/stdout.golden similarity index 100% rename from test/grammar/builtins/regex/test_0/stdout.golden rename to tests/grammar/builtins/regex/test_0/stdout.golden diff --git a/test/grammar/builtins/regex/test_1/main.k b/tests/grammar/builtins/regex/test_1/main.k similarity index 100% rename from test/grammar/builtins/regex/test_1/main.k rename to tests/grammar/builtins/regex/test_1/main.k diff --git a/test/grammar/builtins/regex/test_1/stdout.golden b/tests/grammar/builtins/regex/test_1/stdout.golden similarity index 100% rename from test/grammar/builtins/regex/test_1/stdout.golden rename to tests/grammar/builtins/regex/test_1/stdout.golden diff --git a/test/grammar/builtins/regex/test_2/main.k b/tests/grammar/builtins/regex/test_2/main.k similarity index 100% rename from test/grammar/builtins/regex/test_2/main.k rename to tests/grammar/builtins/regex/test_2/main.k diff --git a/test/grammar/builtins/regex/test_2/stdout.golden b/tests/grammar/builtins/regex/test_2/stdout.golden similarity index 100% rename from test/grammar/builtins/regex/test_2/stdout.golden rename to tests/grammar/builtins/regex/test_2/stdout.golden diff --git a/test/grammar/builtins/regex/test_3/main.k b/tests/grammar/builtins/regex/test_3/main.k similarity index 100% rename from test/grammar/builtins/regex/test_3/main.k rename to tests/grammar/builtins/regex/test_3/main.k diff --git a/test/grammar/builtins/regex/test_3/stdout.golden b/tests/grammar/builtins/regex/test_3/stdout.golden similarity index 100% rename from test/grammar/builtins/regex/test_3/stdout.golden rename to tests/grammar/builtins/regex/test_3/stdout.golden diff --git a/test/grammar/builtins/runtime/catch_0/main.k b/tests/grammar/builtins/runtime/catch_0/main.k similarity index 100% rename from test/grammar/builtins/runtime/catch_0/main.k rename to tests/grammar/builtins/runtime/catch_0/main.k diff --git a/test/grammar/builtins/runtime/catch_0/stdout.golden b/tests/grammar/builtins/runtime/catch_0/stdout.golden similarity index 100% rename from test/grammar/builtins/runtime/catch_0/stdout.golden rename to tests/grammar/builtins/runtime/catch_0/stdout.golden diff --git a/test/grammar/builtins/runtime/catch_1/main.k b/tests/grammar/builtins/runtime/catch_1/main.k similarity index 100% rename from test/grammar/builtins/runtime/catch_1/main.k rename to tests/grammar/builtins/runtime/catch_1/main.k diff --git a/test/grammar/builtins/runtime/catch_1/stdout.golden b/tests/grammar/builtins/runtime/catch_1/stdout.golden similarity index 100% rename from test/grammar/builtins/runtime/catch_1/stdout.golden rename to tests/grammar/builtins/runtime/catch_1/stdout.golden diff --git a/test/grammar/builtins/runtime/catch_2/main.k b/tests/grammar/builtins/runtime/catch_2/main.k similarity index 100% rename from test/grammar/builtins/runtime/catch_2/main.k rename to tests/grammar/builtins/runtime/catch_2/main.k diff --git a/test/grammar/builtins/runtime/catch_2/stdout.golden b/tests/grammar/builtins/runtime/catch_2/stdout.golden similarity index 100% rename from test/grammar/builtins/runtime/catch_2/stdout.golden rename to tests/grammar/builtins/runtime/catch_2/stdout.golden diff --git a/test/grammar/builtins/str/capitalize/main.k b/tests/grammar/builtins/str/capitalize/main.k similarity index 100% rename from test/grammar/builtins/str/capitalize/main.k rename to tests/grammar/builtins/str/capitalize/main.k diff --git a/test/grammar/builtins/str/capitalize/stdout.golden b/tests/grammar/builtins/str/capitalize/stdout.golden similarity index 100% rename from test/grammar/builtins/str/capitalize/stdout.golden rename to tests/grammar/builtins/str/capitalize/stdout.golden diff --git a/test/grammar/builtins/str/chars/main.k b/tests/grammar/builtins/str/chars/main.k similarity index 100% rename from test/grammar/builtins/str/chars/main.k rename to tests/grammar/builtins/str/chars/main.k diff --git a/test/grammar/builtins/str/chars/stdout.golden b/tests/grammar/builtins/str/chars/stdout.golden similarity index 100% rename from test/grammar/builtins/str/chars/stdout.golden rename to tests/grammar/builtins/str/chars/stdout.golden diff --git a/test/grammar/builtins/str/count/main.k b/tests/grammar/builtins/str/count/main.k similarity index 100% rename from test/grammar/builtins/str/count/main.k rename to tests/grammar/builtins/str/count/main.k diff --git a/test/grammar/builtins/str/count/stdout.golden b/tests/grammar/builtins/str/count/stdout.golden similarity index 100% rename from test/grammar/builtins/str/count/stdout.golden rename to tests/grammar/builtins/str/count/stdout.golden diff --git a/test/grammar/builtins/str/create/main.k b/tests/grammar/builtins/str/create/main.k similarity index 100% rename from test/grammar/builtins/str/create/main.k rename to tests/grammar/builtins/str/create/main.k diff --git a/test/grammar/builtins/str/create/stdout.golden b/tests/grammar/builtins/str/create/stdout.golden similarity index 100% rename from test/grammar/builtins/str/create/stdout.golden rename to tests/grammar/builtins/str/create/stdout.golden diff --git a/test/grammar/builtins/str/endswith/main.k b/tests/grammar/builtins/str/endswith/main.k similarity index 100% rename from test/grammar/builtins/str/endswith/main.k rename to tests/grammar/builtins/str/endswith/main.k diff --git a/test/grammar/builtins/str/endswith/stdout.golden b/tests/grammar/builtins/str/endswith/stdout.golden similarity index 100% rename from test/grammar/builtins/str/endswith/stdout.golden rename to tests/grammar/builtins/str/endswith/stdout.golden diff --git a/test/grammar/builtins/str/find/main.k b/tests/grammar/builtins/str/find/main.k similarity index 100% rename from test/grammar/builtins/str/find/main.k rename to tests/grammar/builtins/str/find/main.k diff --git a/test/grammar/builtins/str/find/stdout.golden b/tests/grammar/builtins/str/find/stdout.golden similarity index 100% rename from test/grammar/builtins/str/find/stdout.golden rename to tests/grammar/builtins/str/find/stdout.golden diff --git a/test/grammar/builtins/str/format/main.k b/tests/grammar/builtins/str/format/main.k similarity index 100% rename from test/grammar/builtins/str/format/main.k rename to tests/grammar/builtins/str/format/main.k diff --git a/test/grammar/builtins/str/format/stdout.golden b/tests/grammar/builtins/str/format/stdout.golden similarity index 100% rename from test/grammar/builtins/str/format/stdout.golden rename to tests/grammar/builtins/str/format/stdout.golden diff --git a/test/grammar/builtins/str/index/main.k b/tests/grammar/builtins/str/index/main.k similarity index 100% rename from test/grammar/builtins/str/index/main.k rename to tests/grammar/builtins/str/index/main.k diff --git a/test/grammar/builtins/str/index/stderr.golden b/tests/grammar/builtins/str/index/stderr.golden similarity index 100% rename from test/grammar/builtins/str/index/stderr.golden rename to tests/grammar/builtins/str/index/stderr.golden diff --git a/test/grammar/builtins/str/isalnum/main.k b/tests/grammar/builtins/str/isalnum/main.k similarity index 100% rename from test/grammar/builtins/str/isalnum/main.k rename to tests/grammar/builtins/str/isalnum/main.k diff --git a/test/grammar/builtins/str/isalnum/stdout.golden b/tests/grammar/builtins/str/isalnum/stdout.golden similarity index 100% rename from test/grammar/builtins/str/isalnum/stdout.golden rename to tests/grammar/builtins/str/isalnum/stdout.golden diff --git a/test/grammar/builtins/str/isalpha/main.k b/tests/grammar/builtins/str/isalpha/main.k similarity index 100% rename from test/grammar/builtins/str/isalpha/main.k rename to tests/grammar/builtins/str/isalpha/main.k diff --git a/test/grammar/builtins/str/isalpha/stdout.golden b/tests/grammar/builtins/str/isalpha/stdout.golden similarity index 100% rename from test/grammar/builtins/str/isalpha/stdout.golden rename to tests/grammar/builtins/str/isalpha/stdout.golden diff --git a/test/grammar/builtins/str/isdigit/main.k b/tests/grammar/builtins/str/isdigit/main.k similarity index 100% rename from test/grammar/builtins/str/isdigit/main.k rename to tests/grammar/builtins/str/isdigit/main.k diff --git a/test/grammar/builtins/str/isdigit/stdout.golden b/tests/grammar/builtins/str/isdigit/stdout.golden similarity index 100% rename from test/grammar/builtins/str/isdigit/stdout.golden rename to tests/grammar/builtins/str/isdigit/stdout.golden diff --git a/test/grammar/builtins/str/islower/main.k b/tests/grammar/builtins/str/islower/main.k similarity index 100% rename from test/grammar/builtins/str/islower/main.k rename to tests/grammar/builtins/str/islower/main.k diff --git a/test/grammar/builtins/str/islower/stdout.golden b/tests/grammar/builtins/str/islower/stdout.golden similarity index 100% rename from test/grammar/builtins/str/islower/stdout.golden rename to tests/grammar/builtins/str/islower/stdout.golden diff --git a/test/grammar/builtins/str/isspace/main.k b/tests/grammar/builtins/str/isspace/main.k similarity index 100% rename from test/grammar/builtins/str/isspace/main.k rename to tests/grammar/builtins/str/isspace/main.k diff --git a/test/grammar/builtins/str/isspace/stdout.golden b/tests/grammar/builtins/str/isspace/stdout.golden similarity index 100% rename from test/grammar/builtins/str/isspace/stdout.golden rename to tests/grammar/builtins/str/isspace/stdout.golden diff --git a/test/grammar/builtins/str/istitle/main.k b/tests/grammar/builtins/str/istitle/main.k similarity index 100% rename from test/grammar/builtins/str/istitle/main.k rename to tests/grammar/builtins/str/istitle/main.k diff --git a/test/grammar/builtins/str/istitle/stdout.golden b/tests/grammar/builtins/str/istitle/stdout.golden similarity index 100% rename from test/grammar/builtins/str/istitle/stdout.golden rename to tests/grammar/builtins/str/istitle/stdout.golden diff --git a/test/grammar/builtins/str/isupper/main.k b/tests/grammar/builtins/str/isupper/main.k similarity index 100% rename from test/grammar/builtins/str/isupper/main.k rename to tests/grammar/builtins/str/isupper/main.k diff --git a/test/grammar/builtins/str/isupper/stdout.golden b/tests/grammar/builtins/str/isupper/stdout.golden similarity index 100% rename from test/grammar/builtins/str/isupper/stdout.golden rename to tests/grammar/builtins/str/isupper/stdout.golden diff --git a/test/grammar/builtins/str/join/main.k b/tests/grammar/builtins/str/join/main.k similarity index 100% rename from test/grammar/builtins/str/join/main.k rename to tests/grammar/builtins/str/join/main.k diff --git a/test/grammar/builtins/str/join/stdout.golden b/tests/grammar/builtins/str/join/stdout.golden similarity index 100% rename from test/grammar/builtins/str/join/stdout.golden rename to tests/grammar/builtins/str/join/stdout.golden diff --git a/test/grammar/builtins/str/lower/main.k b/tests/grammar/builtins/str/lower/main.k similarity index 100% rename from test/grammar/builtins/str/lower/main.k rename to tests/grammar/builtins/str/lower/main.k diff --git a/test/grammar/builtins/str/lower/stdout.golden b/tests/grammar/builtins/str/lower/stdout.golden similarity index 100% rename from test/grammar/builtins/str/lower/stdout.golden rename to tests/grammar/builtins/str/lower/stdout.golden diff --git a/test/grammar/builtins/str/lstrip/main.k b/tests/grammar/builtins/str/lstrip/main.k similarity index 100% rename from test/grammar/builtins/str/lstrip/main.k rename to tests/grammar/builtins/str/lstrip/main.k diff --git a/test/grammar/builtins/str/lstrip/stdout.golden b/tests/grammar/builtins/str/lstrip/stdout.golden similarity index 100% rename from test/grammar/builtins/str/lstrip/stdout.golden rename to tests/grammar/builtins/str/lstrip/stdout.golden diff --git a/test/grammar/builtins/str/replace/main.k b/tests/grammar/builtins/str/replace/main.k similarity index 100% rename from test/grammar/builtins/str/replace/main.k rename to tests/grammar/builtins/str/replace/main.k diff --git a/test/grammar/builtins/str/replace/stdout.golden b/tests/grammar/builtins/str/replace/stdout.golden similarity index 100% rename from test/grammar/builtins/str/replace/stdout.golden rename to tests/grammar/builtins/str/replace/stdout.golden diff --git a/test/grammar/builtins/str/rfind/main.k b/tests/grammar/builtins/str/rfind/main.k similarity index 100% rename from test/grammar/builtins/str/rfind/main.k rename to tests/grammar/builtins/str/rfind/main.k diff --git a/test/grammar/builtins/str/rfind/stdout.golden b/tests/grammar/builtins/str/rfind/stdout.golden similarity index 100% rename from test/grammar/builtins/str/rfind/stdout.golden rename to tests/grammar/builtins/str/rfind/stdout.golden diff --git a/test/grammar/builtins/str/rindex/main.k b/tests/grammar/builtins/str/rindex/main.k similarity index 100% rename from test/grammar/builtins/str/rindex/main.k rename to tests/grammar/builtins/str/rindex/main.k diff --git a/test/grammar/builtins/str/rindex/stderr.golden b/tests/grammar/builtins/str/rindex/stderr.golden similarity index 100% rename from test/grammar/builtins/str/rindex/stderr.golden rename to tests/grammar/builtins/str/rindex/stderr.golden diff --git a/test/grammar/builtins/str/rsplit/main.k b/tests/grammar/builtins/str/rsplit/main.k similarity index 100% rename from test/grammar/builtins/str/rsplit/main.k rename to tests/grammar/builtins/str/rsplit/main.k diff --git a/test/grammar/builtins/str/rsplit/stdout.golden b/tests/grammar/builtins/str/rsplit/stdout.golden similarity index 100% rename from test/grammar/builtins/str/rsplit/stdout.golden rename to tests/grammar/builtins/str/rsplit/stdout.golden diff --git a/test/grammar/builtins/str/rstrip/main.k b/tests/grammar/builtins/str/rstrip/main.k similarity index 100% rename from test/grammar/builtins/str/rstrip/main.k rename to tests/grammar/builtins/str/rstrip/main.k diff --git a/test/grammar/builtins/str/rstrip/stdout.golden b/tests/grammar/builtins/str/rstrip/stdout.golden similarity index 100% rename from test/grammar/builtins/str/rstrip/stdout.golden rename to tests/grammar/builtins/str/rstrip/stdout.golden diff --git a/test/grammar/builtins/str/split/main.k b/tests/grammar/builtins/str/split/main.k similarity index 100% rename from test/grammar/builtins/str/split/main.k rename to tests/grammar/builtins/str/split/main.k diff --git a/test/grammar/builtins/str/split/stdout.golden b/tests/grammar/builtins/str/split/stdout.golden similarity index 100% rename from test/grammar/builtins/str/split/stdout.golden rename to tests/grammar/builtins/str/split/stdout.golden diff --git a/test/grammar/builtins/str/splitlines/main.k b/tests/grammar/builtins/str/splitlines/main.k similarity index 100% rename from test/grammar/builtins/str/splitlines/main.k rename to tests/grammar/builtins/str/splitlines/main.k diff --git a/test/grammar/builtins/str/splitlines/stdout.golden b/tests/grammar/builtins/str/splitlines/stdout.golden similarity index 100% rename from test/grammar/builtins/str/splitlines/stdout.golden rename to tests/grammar/builtins/str/splitlines/stdout.golden diff --git a/test/grammar/builtins/str/startswith/main.k b/tests/grammar/builtins/str/startswith/main.k similarity index 100% rename from test/grammar/builtins/str/startswith/main.k rename to tests/grammar/builtins/str/startswith/main.k diff --git a/test/grammar/builtins/str/startswith/stdout.golden b/tests/grammar/builtins/str/startswith/stdout.golden similarity index 100% rename from test/grammar/builtins/str/startswith/stdout.golden rename to tests/grammar/builtins/str/startswith/stdout.golden diff --git a/test/grammar/builtins/str/strip/main.k b/tests/grammar/builtins/str/strip/main.k similarity index 100% rename from test/grammar/builtins/str/strip/main.k rename to tests/grammar/builtins/str/strip/main.k diff --git a/test/grammar/builtins/str/strip/stdout.golden b/tests/grammar/builtins/str/strip/stdout.golden similarity index 100% rename from test/grammar/builtins/str/strip/stdout.golden rename to tests/grammar/builtins/str/strip/stdout.golden diff --git a/test/grammar/builtins/str/title/main.k b/tests/grammar/builtins/str/title/main.k similarity index 100% rename from test/grammar/builtins/str/title/main.k rename to tests/grammar/builtins/str/title/main.k diff --git a/test/grammar/builtins/str/title/stdout.golden b/tests/grammar/builtins/str/title/stdout.golden similarity index 100% rename from test/grammar/builtins/str/title/stdout.golden rename to tests/grammar/builtins/str/title/stdout.golden diff --git a/test/grammar/builtins/str/upper/main.k b/tests/grammar/builtins/str/upper/main.k similarity index 100% rename from test/grammar/builtins/str/upper/main.k rename to tests/grammar/builtins/str/upper/main.k diff --git a/test/grammar/builtins/str/upper/stdout.golden b/tests/grammar/builtins/str/upper/stdout.golden similarity index 100% rename from test/grammar/builtins/str/upper/stdout.golden rename to tests/grammar/builtins/str/upper/stdout.golden diff --git a/test/grammar/builtins/template/execute_0/main.k b/tests/grammar/builtins/template/execute_0/main.k similarity index 100% rename from test/grammar/builtins/template/execute_0/main.k rename to tests/grammar/builtins/template/execute_0/main.k diff --git a/test/grammar/builtins/template/execute_0/stdout.golden b/tests/grammar/builtins/template/execute_0/stdout.golden similarity index 100% rename from test/grammar/builtins/template/execute_0/stdout.golden rename to tests/grammar/builtins/template/execute_0/stdout.golden diff --git a/test/grammar/builtins/template/execute_1/main.k b/tests/grammar/builtins/template/execute_1/main.k similarity index 100% rename from test/grammar/builtins/template/execute_1/main.k rename to tests/grammar/builtins/template/execute_1/main.k diff --git a/test/grammar/builtins/template/execute_1/stdout.golden b/tests/grammar/builtins/template/execute_1/stdout.golden similarity index 100% rename from test/grammar/builtins/template/execute_1/stdout.golden rename to tests/grammar/builtins/template/execute_1/stdout.golden diff --git a/test/grammar/builtins/template/execute_2/main.k b/tests/grammar/builtins/template/execute_2/main.k similarity index 100% rename from test/grammar/builtins/template/execute_2/main.k rename to tests/grammar/builtins/template/execute_2/main.k diff --git a/test/grammar/builtins/template/execute_2/stdout.golden b/tests/grammar/builtins/template/execute_2/stdout.golden similarity index 100% rename from test/grammar/builtins/template/execute_2/stdout.golden rename to tests/grammar/builtins/template/execute_2/stdout.golden diff --git a/test/grammar/builtins/template/html_escape_0/main.k b/tests/grammar/builtins/template/html_escape_0/main.k similarity index 100% rename from test/grammar/builtins/template/html_escape_0/main.k rename to tests/grammar/builtins/template/html_escape_0/main.k diff --git a/test/grammar/builtins/template/html_escape_0/stdout.golden b/tests/grammar/builtins/template/html_escape_0/stdout.golden similarity index 100% rename from test/grammar/builtins/template/html_escape_0/stdout.golden rename to tests/grammar/builtins/template/html_escape_0/stdout.golden diff --git a/test/grammar/builtins/typeof/typeof_01/kcl.mod b/tests/grammar/builtins/typeof/typeof_01/kcl.mod similarity index 100% rename from test/grammar/builtins/typeof/typeof_01/kcl.mod rename to tests/grammar/builtins/typeof/typeof_01/kcl.mod diff --git a/test/grammar/builtins/typeof/typeof_01/main.k b/tests/grammar/builtins/typeof/typeof_01/main.k similarity index 100% rename from test/grammar/builtins/typeof/typeof_01/main.k rename to tests/grammar/builtins/typeof/typeof_01/main.k diff --git a/test/grammar/builtins/typeof/typeof_01/stdout.golden b/tests/grammar/builtins/typeof/typeof_01/stdout.golden similarity index 100% rename from test/grammar/builtins/typeof/typeof_01/stdout.golden rename to tests/grammar/builtins/typeof/typeof_01/stdout.golden diff --git a/test/grammar/builtins/typeof/typeof_01/sub/sub.k b/tests/grammar/builtins/typeof/typeof_01/sub/sub.k similarity index 100% rename from test/grammar/builtins/typeof/typeof_01/sub/sub.k rename to tests/grammar/builtins/typeof/typeof_01/sub/sub.k diff --git a/test/grammar/builtins/typeof/typeof_02/main.k b/tests/grammar/builtins/typeof/typeof_02/main.k similarity index 100% rename from test/grammar/builtins/typeof/typeof_02/main.k rename to tests/grammar/builtins/typeof/typeof_02/main.k diff --git a/test/grammar/builtins/typeof/typeof_02/stdout.golden b/tests/grammar/builtins/typeof/typeof_02/stdout.golden similarity index 100% rename from test/grammar/builtins/typeof/typeof_02/stdout.golden rename to tests/grammar/builtins/typeof/typeof_02/stdout.golden diff --git a/test/grammar/builtins/units/constant_0/main.k b/tests/grammar/builtins/units/constant_0/main.k similarity index 100% rename from test/grammar/builtins/units/constant_0/main.k rename to tests/grammar/builtins/units/constant_0/main.k diff --git a/test/grammar/builtins/units/constant_0/stdout.golden b/tests/grammar/builtins/units/constant_0/stdout.golden similarity index 100% rename from test/grammar/builtins/units/constant_0/stdout.golden rename to tests/grammar/builtins/units/constant_0/stdout.golden diff --git a/test/grammar/builtins/units/constant_1/main.k b/tests/grammar/builtins/units/constant_1/main.k similarity index 100% rename from test/grammar/builtins/units/constant_1/main.k rename to tests/grammar/builtins/units/constant_1/main.k diff --git a/test/grammar/builtins/units/constant_1/stdout.golden b/tests/grammar/builtins/units/constant_1/stdout.golden similarity index 100% rename from test/grammar/builtins/units/constant_1/stdout.golden rename to tests/grammar/builtins/units/constant_1/stdout.golden diff --git a/test/grammar/builtins/units/to_unit_str_0/main.k b/tests/grammar/builtins/units/to_unit_str_0/main.k similarity index 100% rename from test/grammar/builtins/units/to_unit_str_0/main.k rename to tests/grammar/builtins/units/to_unit_str_0/main.k diff --git a/test/grammar/builtins/units/to_unit_str_0/stdout.golden b/tests/grammar/builtins/units/to_unit_str_0/stdout.golden similarity index 100% rename from test/grammar/builtins/units/to_unit_str_0/stdout.golden rename to tests/grammar/builtins/units/to_unit_str_0/stdout.golden diff --git a/test/grammar/builtins/units/to_unit_str_1/main.k b/tests/grammar/builtins/units/to_unit_str_1/main.k similarity index 100% rename from test/grammar/builtins/units/to_unit_str_1/main.k rename to tests/grammar/builtins/units/to_unit_str_1/main.k diff --git a/test/grammar/builtins/units/to_unit_str_1/stdout.golden b/tests/grammar/builtins/units/to_unit_str_1/stdout.golden similarity index 100% rename from test/grammar/builtins/units/to_unit_str_1/stdout.golden rename to tests/grammar/builtins/units/to_unit_str_1/stdout.golden diff --git a/test/grammar/builtins/units/to_unit_str_2/main.k b/tests/grammar/builtins/units/to_unit_str_2/main.k similarity index 100% rename from test/grammar/builtins/units/to_unit_str_2/main.k rename to tests/grammar/builtins/units/to_unit_str_2/main.k diff --git a/test/grammar/builtins/units/to_unit_str_2/stdout.golden b/tests/grammar/builtins/units/to_unit_str_2/stdout.golden similarity index 100% rename from test/grammar/builtins/units/to_unit_str_2/stdout.golden rename to tests/grammar/builtins/units/to_unit_str_2/stdout.golden diff --git a/test/grammar/builtins/units/to_unit_str_3/main.k b/tests/grammar/builtins/units/to_unit_str_3/main.k similarity index 100% rename from test/grammar/builtins/units/to_unit_str_3/main.k rename to tests/grammar/builtins/units/to_unit_str_3/main.k diff --git a/test/grammar/builtins/units/to_unit_str_3/stdout.golden b/tests/grammar/builtins/units/to_unit_str_3/stdout.golden similarity index 100% rename from test/grammar/builtins/units/to_unit_str_3/stdout.golden rename to tests/grammar/builtins/units/to_unit_str_3/stdout.golden diff --git a/test/grammar/builtins/yaml/decode/main.k b/tests/grammar/builtins/yaml/decode/main.k similarity index 100% rename from test/grammar/builtins/yaml/decode/main.k rename to tests/grammar/builtins/yaml/decode/main.k diff --git a/test/grammar/builtins/yaml/decode/stdout.golden b/tests/grammar/builtins/yaml/decode/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/decode/stdout.golden rename to tests/grammar/builtins/yaml/decode/stdout.golden diff --git a/test/grammar/builtins/yaml/decode_all_0/main.k b/tests/grammar/builtins/yaml/decode_all_0/main.k similarity index 100% rename from test/grammar/builtins/yaml/decode_all_0/main.k rename to tests/grammar/builtins/yaml/decode_all_0/main.k diff --git a/test/grammar/builtins/yaml/decode_all_0/stdout.golden b/tests/grammar/builtins/yaml/decode_all_0/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/decode_all_0/stdout.golden rename to tests/grammar/builtins/yaml/decode_all_0/stdout.golden diff --git a/test/grammar/builtins/yaml/decode_all_1/main.k b/tests/grammar/builtins/yaml/decode_all_1/main.k similarity index 100% rename from test/grammar/builtins/yaml/decode_all_1/main.k rename to tests/grammar/builtins/yaml/decode_all_1/main.k diff --git a/test/grammar/builtins/yaml/decode_all_1/stdout.golden b/tests/grammar/builtins/yaml/decode_all_1/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/decode_all_1/stdout.golden rename to tests/grammar/builtins/yaml/decode_all_1/stdout.golden diff --git a/test/grammar/builtins/yaml/decode_all_2/main.k b/tests/grammar/builtins/yaml/decode_all_2/main.k similarity index 100% rename from test/grammar/builtins/yaml/decode_all_2/main.k rename to tests/grammar/builtins/yaml/decode_all_2/main.k diff --git a/test/grammar/builtins/yaml/decode_all_2/stdout.golden b/tests/grammar/builtins/yaml/decode_all_2/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/decode_all_2/stdout.golden rename to tests/grammar/builtins/yaml/decode_all_2/stdout.golden diff --git a/test/grammar/builtins/yaml/dump_all_to_file_0/0.yaml b/tests/grammar/builtins/yaml/dump_all_to_file_0/0.yaml similarity index 100% rename from test/grammar/builtins/yaml/dump_all_to_file_0/0.yaml rename to tests/grammar/builtins/yaml/dump_all_to_file_0/0.yaml diff --git a/test/grammar/builtins/yaml/dump_all_to_file_0/main.k b/tests/grammar/builtins/yaml/dump_all_to_file_0/main.k similarity index 100% rename from test/grammar/builtins/yaml/dump_all_to_file_0/main.k rename to tests/grammar/builtins/yaml/dump_all_to_file_0/main.k diff --git a/test/grammar/builtins/yaml/dump_all_to_file_0/stdout.golden b/tests/grammar/builtins/yaml/dump_all_to_file_0/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/dump_all_to_file_0/stdout.golden rename to tests/grammar/builtins/yaml/dump_all_to_file_0/stdout.golden diff --git a/test/grammar/builtins/yaml/dump_to_file_0/0.yaml b/tests/grammar/builtins/yaml/dump_to_file_0/0.yaml similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_0/0.yaml rename to tests/grammar/builtins/yaml/dump_to_file_0/0.yaml diff --git a/test/grammar/builtins/yaml/dump_to_file_0/1.yaml b/tests/grammar/builtins/yaml/dump_to_file_0/1.yaml similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_0/1.yaml rename to tests/grammar/builtins/yaml/dump_to_file_0/1.yaml diff --git a/test/grammar/builtins/yaml/dump_to_file_0/2.yaml b/tests/grammar/builtins/yaml/dump_to_file_0/2.yaml similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_0/2.yaml rename to tests/grammar/builtins/yaml/dump_to_file_0/2.yaml diff --git a/test/grammar/builtins/yaml/dump_to_file_0/3.yaml b/tests/grammar/builtins/yaml/dump_to_file_0/3.yaml similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_0/3.yaml rename to tests/grammar/builtins/yaml/dump_to_file_0/3.yaml diff --git a/test/grammar/builtins/yaml/dump_to_file_0/4.yaml b/tests/grammar/builtins/yaml/dump_to_file_0/4.yaml similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_0/4.yaml rename to tests/grammar/builtins/yaml/dump_to_file_0/4.yaml diff --git a/test/grammar/builtins/yaml/dump_to_file_0/5.yaml b/tests/grammar/builtins/yaml/dump_to_file_0/5.yaml similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_0/5.yaml rename to tests/grammar/builtins/yaml/dump_to_file_0/5.yaml diff --git a/test/grammar/builtins/yaml/dump_to_file_0/main.k b/tests/grammar/builtins/yaml/dump_to_file_0/main.k similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_0/main.k rename to tests/grammar/builtins/yaml/dump_to_file_0/main.k diff --git a/test/grammar/builtins/yaml/dump_to_file_0/stdout.golden b/tests/grammar/builtins/yaml/dump_to_file_0/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_0/stdout.golden rename to tests/grammar/builtins/yaml/dump_to_file_0/stdout.golden diff --git a/test/grammar/builtins/yaml/dump_to_file_1/0.yaml b/tests/grammar/builtins/yaml/dump_to_file_1/0.yaml similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_1/0.yaml rename to tests/grammar/builtins/yaml/dump_to_file_1/0.yaml diff --git a/test/grammar/builtins/yaml/dump_to_file_1/1.yaml b/tests/grammar/builtins/yaml/dump_to_file_1/1.yaml similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_1/1.yaml rename to tests/grammar/builtins/yaml/dump_to_file_1/1.yaml diff --git a/test/grammar/builtins/yaml/dump_to_file_1/2.yaml b/tests/grammar/builtins/yaml/dump_to_file_1/2.yaml similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_1/2.yaml rename to tests/grammar/builtins/yaml/dump_to_file_1/2.yaml diff --git a/test/grammar/builtins/yaml/dump_to_file_1/3.yaml b/tests/grammar/builtins/yaml/dump_to_file_1/3.yaml similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_1/3.yaml rename to tests/grammar/builtins/yaml/dump_to_file_1/3.yaml diff --git a/test/grammar/builtins/yaml/dump_to_file_1/4.yaml b/tests/grammar/builtins/yaml/dump_to_file_1/4.yaml similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_1/4.yaml rename to tests/grammar/builtins/yaml/dump_to_file_1/4.yaml diff --git a/test/grammar/builtins/yaml/dump_to_file_1/5.yaml b/tests/grammar/builtins/yaml/dump_to_file_1/5.yaml similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_1/5.yaml rename to tests/grammar/builtins/yaml/dump_to_file_1/5.yaml diff --git a/test/grammar/builtins/yaml/dump_to_file_1/main.k b/tests/grammar/builtins/yaml/dump_to_file_1/main.k similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_1/main.k rename to tests/grammar/builtins/yaml/dump_to_file_1/main.k diff --git a/test/grammar/builtins/yaml/dump_to_file_1/stdout.golden b/tests/grammar/builtins/yaml/dump_to_file_1/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/dump_to_file_1/stdout.golden rename to tests/grammar/builtins/yaml/dump_to_file_1/stdout.golden diff --git a/test/grammar/builtins/yaml/encode_0/main.k b/tests/grammar/builtins/yaml/encode_0/main.k similarity index 100% rename from test/grammar/builtins/yaml/encode_0/main.k rename to tests/grammar/builtins/yaml/encode_0/main.k diff --git a/test/grammar/builtins/yaml/encode_0/stdout.golden b/tests/grammar/builtins/yaml/encode_0/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/encode_0/stdout.golden rename to tests/grammar/builtins/yaml/encode_0/stdout.golden diff --git a/test/grammar/builtins/yaml/encode_1/main.k b/tests/grammar/builtins/yaml/encode_1/main.k similarity index 100% rename from test/grammar/builtins/yaml/encode_1/main.k rename to tests/grammar/builtins/yaml/encode_1/main.k diff --git a/test/grammar/builtins/yaml/encode_1/stdout.golden b/tests/grammar/builtins/yaml/encode_1/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/encode_1/stdout.golden rename to tests/grammar/builtins/yaml/encode_1/stdout.golden diff --git a/test/grammar/builtins/yaml/encode_all_0/main.k b/tests/grammar/builtins/yaml/encode_all_0/main.k similarity index 100% rename from test/grammar/builtins/yaml/encode_all_0/main.k rename to tests/grammar/builtins/yaml/encode_all_0/main.k diff --git a/test/grammar/builtins/yaml/encode_all_0/stdout.golden b/tests/grammar/builtins/yaml/encode_all_0/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/encode_all_0/stdout.golden rename to tests/grammar/builtins/yaml/encode_all_0/stdout.golden diff --git a/test/grammar/builtins/yaml/encode_all_1/main.k b/tests/grammar/builtins/yaml/encode_all_1/main.k similarity index 100% rename from test/grammar/builtins/yaml/encode_all_1/main.k rename to tests/grammar/builtins/yaml/encode_all_1/main.k diff --git a/test/grammar/builtins/yaml/encode_all_1/stdout.golden b/tests/grammar/builtins/yaml/encode_all_1/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/encode_all_1/stdout.golden rename to tests/grammar/builtins/yaml/encode_all_1/stdout.golden diff --git a/test/grammar/builtins/yaml/encode_all_2/main.k b/tests/grammar/builtins/yaml/encode_all_2/main.k similarity index 100% rename from test/grammar/builtins/yaml/encode_all_2/main.k rename to tests/grammar/builtins/yaml/encode_all_2/main.k diff --git a/test/grammar/builtins/yaml/encode_all_2/stdout.golden b/tests/grammar/builtins/yaml/encode_all_2/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/encode_all_2/stdout.golden rename to tests/grammar/builtins/yaml/encode_all_2/stdout.golden diff --git a/test/grammar/builtins/yaml/output_0/main.k b/tests/grammar/builtins/yaml/output_0/main.k similarity index 100% rename from test/grammar/builtins/yaml/output_0/main.k rename to tests/grammar/builtins/yaml/output_0/main.k diff --git a/test/grammar/builtins/yaml/output_0/stdout.golden b/tests/grammar/builtins/yaml/output_0/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/output_0/stdout.golden rename to tests/grammar/builtins/yaml/output_0/stdout.golden diff --git a/test/grammar/builtins/yaml/output_1/main.k b/tests/grammar/builtins/yaml/output_1/main.k similarity index 100% rename from test/grammar/builtins/yaml/output_1/main.k rename to tests/grammar/builtins/yaml/output_1/main.k diff --git a/test/grammar/builtins/yaml/output_1/out.yaml b/tests/grammar/builtins/yaml/output_1/out.yaml similarity index 100% rename from test/grammar/builtins/yaml/output_1/out.yaml rename to tests/grammar/builtins/yaml/output_1/out.yaml diff --git a/test/grammar/builtins/yaml/output_1/stdout.golden b/tests/grammar/builtins/yaml/output_1/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/output_1/stdout.golden rename to tests/grammar/builtins/yaml/output_1/stdout.golden diff --git a/test/grammar/builtins/yaml/output_2/main.k b/tests/grammar/builtins/yaml/output_2/main.k similarity index 100% rename from test/grammar/builtins/yaml/output_2/main.k rename to tests/grammar/builtins/yaml/output_2/main.k diff --git a/test/grammar/builtins/yaml/output_2/stdout.golden b/tests/grammar/builtins/yaml/output_2/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/output_2/stdout.golden rename to tests/grammar/builtins/yaml/output_2/stdout.golden diff --git a/test/grammar/builtins/yaml/validate/main.k b/tests/grammar/builtins/yaml/validate/main.k similarity index 100% rename from test/grammar/builtins/yaml/validate/main.k rename to tests/grammar/builtins/yaml/validate/main.k diff --git a/test/grammar/builtins/yaml/validate/stdout.golden b/tests/grammar/builtins/yaml/validate/stdout.golden similarity index 100% rename from test/grammar/builtins/yaml/validate/stdout.golden rename to tests/grammar/builtins/yaml/validate/stdout.golden diff --git a/test/grammar/cli_config/cli_config_0/main.k b/tests/grammar/cli_config/cli_config_0/main.k similarity index 100% rename from test/grammar/cli_config/cli_config_0/main.k rename to tests/grammar/cli_config/cli_config_0/main.k diff --git a/test/grammar/cli_config/cli_config_0/settings.yaml b/tests/grammar/cli_config/cli_config_0/settings.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_0/settings.yaml rename to tests/grammar/cli_config/cli_config_0/settings.yaml diff --git a/test/grammar/cli_config/cli_config_0/stdout.golden b/tests/grammar/cli_config/cli_config_0/stdout.golden similarity index 100% rename from test/grammar/cli_config/cli_config_0/stdout.golden rename to tests/grammar/cli_config/cli_config_0/stdout.golden diff --git a/test/grammar/cli_config/cli_config_0/temp.yaml b/tests/grammar/cli_config/cli_config_0/temp.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_0/temp.yaml rename to tests/grammar/cli_config/cli_config_0/temp.yaml diff --git a/test/grammar/cli_config/cli_config_1/main.k b/tests/grammar/cli_config/cli_config_1/main.k similarity index 100% rename from test/grammar/cli_config/cli_config_1/main.k rename to tests/grammar/cli_config/cli_config_1/main.k diff --git a/test/grammar/cli_config/cli_config_1/settings.yaml b/tests/grammar/cli_config/cli_config_1/settings.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_1/settings.yaml rename to tests/grammar/cli_config/cli_config_1/settings.yaml diff --git a/test/grammar/cli_config/cli_config_1/stdout.golden b/tests/grammar/cli_config/cli_config_1/stdout.golden similarity index 100% rename from test/grammar/cli_config/cli_config_1/stdout.golden rename to tests/grammar/cli_config/cli_config_1/stdout.golden diff --git a/test/grammar/cli_config/cli_config_1/temp.yaml b/tests/grammar/cli_config/cli_config_1/temp.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_1/temp.yaml rename to tests/grammar/cli_config/cli_config_1/temp.yaml diff --git a/test/grammar/cli_config/cli_config_2/main.k b/tests/grammar/cli_config/cli_config_2/main.k similarity index 100% rename from test/grammar/cli_config/cli_config_2/main.k rename to tests/grammar/cli_config/cli_config_2/main.k diff --git a/test/grammar/cli_config/cli_config_2/settings.yaml b/tests/grammar/cli_config/cli_config_2/settings.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_2/settings.yaml rename to tests/grammar/cli_config/cli_config_2/settings.yaml diff --git a/test/grammar/cli_config/cli_config_2/stdout.golden b/tests/grammar/cli_config/cli_config_2/stdout.golden similarity index 100% rename from test/grammar/cli_config/cli_config_2/stdout.golden rename to tests/grammar/cli_config/cli_config_2/stdout.golden diff --git a/test/grammar/cli_config/cli_config_2/temp.yaml b/tests/grammar/cli_config/cli_config_2/temp.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_2/temp.yaml rename to tests/grammar/cli_config/cli_config_2/temp.yaml diff --git a/test/grammar/cli_config/cli_config_3/kcl.yaml b/tests/grammar/cli_config/cli_config_3/kcl.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_3/kcl.yaml rename to tests/grammar/cli_config/cli_config_3/kcl.yaml diff --git a/test/grammar/cli_config/cli_config_3/main.k b/tests/grammar/cli_config/cli_config_3/main.k similarity index 100% rename from test/grammar/cli_config/cli_config_3/main.k rename to tests/grammar/cli_config/cli_config_3/main.k diff --git a/test/grammar/cli_config/cli_config_3/settings.yaml b/tests/grammar/cli_config/cli_config_3/settings.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_3/settings.yaml rename to tests/grammar/cli_config/cli_config_3/settings.yaml diff --git a/test/grammar/cli_config/cli_config_3/stdout.golden b/tests/grammar/cli_config/cli_config_3/stdout.golden similarity index 100% rename from test/grammar/cli_config/cli_config_3/stdout.golden rename to tests/grammar/cli_config/cli_config_3/stdout.golden diff --git a/test/grammar/cli_config/cli_config_with_file_disable/main.k b/tests/grammar/cli_config/cli_config_with_file_disable/main.k similarity index 100% rename from test/grammar/cli_config/cli_config_with_file_disable/main.k rename to tests/grammar/cli_config/cli_config_with_file_disable/main.k diff --git a/test/grammar/cli_config/cli_config_with_file_disable/settings.yaml b/tests/grammar/cli_config/cli_config_with_file_disable/settings.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_file_disable/settings.yaml rename to tests/grammar/cli_config/cli_config_with_file_disable/settings.yaml diff --git a/test/grammar/cli_config/cli_config_with_file_disable/stdout.golden b/tests/grammar/cli_config/cli_config_with_file_disable/stdout.golden similarity index 100% rename from test/grammar/cli_config/cli_config_with_file_disable/stdout.golden rename to tests/grammar/cli_config/cli_config_with_file_disable/stdout.golden diff --git a/test/grammar/cli_config/cli_config_with_file_disable/temp.yaml b/tests/grammar/cli_config/cli_config_with_file_disable/temp.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_file_disable/temp.yaml rename to tests/grammar/cli_config/cli_config_with_file_disable/temp.yaml diff --git a/test/grammar/cli_config/cli_config_with_filepath/config.yaml b/tests/grammar/cli_config/cli_config_with_filepath/config.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_filepath/config.yaml rename to tests/grammar/cli_config/cli_config_with_filepath/config.yaml diff --git a/test/grammar/cli_config/cli_config_with_filepath/main.k b/tests/grammar/cli_config/cli_config_with_filepath/main.k similarity index 100% rename from test/grammar/cli_config/cli_config_with_filepath/main.k rename to tests/grammar/cli_config/cli_config_with_filepath/main.k diff --git a/test/grammar/cli_config/cli_config_with_filepath/settings.yaml b/tests/grammar/cli_config/cli_config_with_filepath/settings.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_filepath/settings.yaml rename to tests/grammar/cli_config/cli_config_with_filepath/settings.yaml diff --git a/test/grammar/cli_config/cli_config_with_filepath/stdout.golden b/tests/grammar/cli_config/cli_config_with_filepath/stdout.golden similarity index 100% rename from test/grammar/cli_config/cli_config_with_filepath/stdout.golden rename to tests/grammar/cli_config/cli_config_with_filepath/stdout.golden diff --git a/test/grammar/cli_config/cli_config_with_kcl_mod/config.yaml b/tests/grammar/cli_config/cli_config_with_kcl_mod/config.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_kcl_mod/config.yaml rename to tests/grammar/cli_config/cli_config_with_kcl_mod/config.yaml diff --git a/test/grammar/cli_config/cli_config_with_kcl_mod/kcl.mod b/tests/grammar/cli_config/cli_config_with_kcl_mod/kcl.mod similarity index 100% rename from test/grammar/cli_config/cli_config_with_kcl_mod/kcl.mod rename to tests/grammar/cli_config/cli_config_with_kcl_mod/kcl.mod diff --git a/test/grammar/cli_config/cli_config_with_kcl_mod/main.k b/tests/grammar/cli_config/cli_config_with_kcl_mod/main.k similarity index 100% rename from test/grammar/cli_config/cli_config_with_kcl_mod/main.k rename to tests/grammar/cli_config/cli_config_with_kcl_mod/main.k diff --git a/test/grammar/cli_config/cli_config_with_kcl_mod/pkg/pkg.k b/tests/grammar/cli_config/cli_config_with_kcl_mod/pkg/pkg.k similarity index 100% rename from test/grammar/cli_config/cli_config_with_kcl_mod/pkg/pkg.k rename to tests/grammar/cli_config/cli_config_with_kcl_mod/pkg/pkg.k diff --git a/test/grammar/cli_config/cli_config_with_kcl_mod/settings.yaml b/tests/grammar/cli_config/cli_config_with_kcl_mod/settings.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_kcl_mod/settings.yaml rename to tests/grammar/cli_config/cli_config_with_kcl_mod/settings.yaml diff --git a/test/grammar/cli_config/cli_config_with_kcl_mod/stdout.golden b/tests/grammar/cli_config/cli_config_with_kcl_mod/stdout.golden similarity index 100% rename from test/grammar/cli_config/cli_config_with_kcl_mod/stdout.golden rename to tests/grammar/cli_config/cli_config_with_kcl_mod/stdout.golden diff --git a/test/grammar/cli_config/cli_config_with_kcl_mod_0/kcl.mod b/tests/grammar/cli_config/cli_config_with_kcl_mod_0/kcl.mod similarity index 100% rename from test/grammar/cli_config/cli_config_with_kcl_mod_0/kcl.mod rename to tests/grammar/cli_config/cli_config_with_kcl_mod_0/kcl.mod diff --git a/test/grammar/cli_config/cli_config_with_kcl_mod_0/main.k b/tests/grammar/cli_config/cli_config_with_kcl_mod_0/main.k similarity index 100% rename from test/grammar/cli_config/cli_config_with_kcl_mod_0/main.k rename to tests/grammar/cli_config/cli_config_with_kcl_mod_0/main.k diff --git a/test/grammar/cli_config/cli_config_with_kcl_mod_0/pkg/pkg.k b/tests/grammar/cli_config/cli_config_with_kcl_mod_0/pkg/pkg.k similarity index 100% rename from test/grammar/cli_config/cli_config_with_kcl_mod_0/pkg/pkg.k rename to tests/grammar/cli_config/cli_config_with_kcl_mod_0/pkg/pkg.k diff --git a/test/grammar/cli_config/cli_config_with_kcl_mod_0/settings.yaml b/tests/grammar/cli_config/cli_config_with_kcl_mod_0/settings.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_kcl_mod_0/settings.yaml rename to tests/grammar/cli_config/cli_config_with_kcl_mod_0/settings.yaml diff --git a/test/grammar/cli_config/cli_config_with_kcl_mod_0/stdout.golden b/tests/grammar/cli_config/cli_config_with_kcl_mod_0/stdout.golden similarity index 100% rename from test/grammar/cli_config/cli_config_with_kcl_mod_0/stdout.golden rename to tests/grammar/cli_config/cli_config_with_kcl_mod_0/stdout.golden diff --git a/test/grammar/cli_config/cli_config_with_multifiles_0/config1.yaml b/tests/grammar/cli_config/cli_config_with_multifiles_0/config1.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_0/config1.yaml rename to tests/grammar/cli_config/cli_config_with_multifiles_0/config1.yaml diff --git a/test/grammar/cli_config/cli_config_with_multifiles_0/config2.yaml b/tests/grammar/cli_config/cli_config_with_multifiles_0/config2.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_0/config2.yaml rename to tests/grammar/cli_config/cli_config_with_multifiles_0/config2.yaml diff --git a/test/grammar/cli_config/cli_config_with_multifiles_0/main.k b/tests/grammar/cli_config/cli_config_with_multifiles_0/main.k similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_0/main.k rename to tests/grammar/cli_config/cli_config_with_multifiles_0/main.k diff --git a/test/grammar/cli_config/cli_config_with_multifiles_0/settings.yaml b/tests/grammar/cli_config/cli_config_with_multifiles_0/settings.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_0/settings.yaml rename to tests/grammar/cli_config/cli_config_with_multifiles_0/settings.yaml diff --git a/test/grammar/cli_config/cli_config_with_multifiles_0/stdout.golden b/tests/grammar/cli_config/cli_config_with_multifiles_0/stdout.golden similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_0/stdout.golden rename to tests/grammar/cli_config/cli_config_with_multifiles_0/stdout.golden diff --git a/test/grammar/cli_config/cli_config_with_multifiles_1/config1.yaml b/tests/grammar/cli_config/cli_config_with_multifiles_1/config1.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_1/config1.yaml rename to tests/grammar/cli_config/cli_config_with_multifiles_1/config1.yaml diff --git a/test/grammar/cli_config/cli_config_with_multifiles_1/config2.yaml b/tests/grammar/cli_config/cli_config_with_multifiles_1/config2.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_1/config2.yaml rename to tests/grammar/cli_config/cli_config_with_multifiles_1/config2.yaml diff --git a/test/grammar/cli_config/cli_config_with_multifiles_1/main.k b/tests/grammar/cli_config/cli_config_with_multifiles_1/main.k similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_1/main.k rename to tests/grammar/cli_config/cli_config_with_multifiles_1/main.k diff --git a/test/grammar/cli_config/cli_config_with_multifiles_1/settings.yaml b/tests/grammar/cli_config/cli_config_with_multifiles_1/settings.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_1/settings.yaml rename to tests/grammar/cli_config/cli_config_with_multifiles_1/settings.yaml diff --git a/test/grammar/cli_config/cli_config_with_multifiles_1/stdout.golden b/tests/grammar/cli_config/cli_config_with_multifiles_1/stdout.golden similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_1/stdout.golden rename to tests/grammar/cli_config/cli_config_with_multifiles_1/stdout.golden diff --git a/test/grammar/cli_config/cli_config_with_multifiles_2/config1.yaml b/tests/grammar/cli_config/cli_config_with_multifiles_2/config1.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_2/config1.yaml rename to tests/grammar/cli_config/cli_config_with_multifiles_2/config1.yaml diff --git a/test/grammar/cli_config/cli_config_with_multifiles_2/config2.yaml b/tests/grammar/cli_config/cli_config_with_multifiles_2/config2.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_2/config2.yaml rename to tests/grammar/cli_config/cli_config_with_multifiles_2/config2.yaml diff --git a/test/grammar/cli_config/cli_config_with_multifiles_2/main.k b/tests/grammar/cli_config/cli_config_with_multifiles_2/main.k similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_2/main.k rename to tests/grammar/cli_config/cli_config_with_multifiles_2/main.k diff --git a/test/grammar/cli_config/cli_config_with_multifiles_2/settings.yaml b/tests/grammar/cli_config/cli_config_with_multifiles_2/settings.yaml similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_2/settings.yaml rename to tests/grammar/cli_config/cli_config_with_multifiles_2/settings.yaml diff --git a/test/grammar/cli_config/cli_config_with_multifiles_2/stdout.golden b/tests/grammar/cli_config/cli_config_with_multifiles_2/stdout.golden similarity index 100% rename from test/grammar/cli_config/cli_config_with_multifiles_2/stdout.golden rename to tests/grammar/cli_config/cli_config_with_multifiles_2/stdout.golden diff --git a/test/grammar/cli_config/empty_cli_config/config.yaml b/tests/grammar/cli_config/empty_cli_config/config.yaml similarity index 100% rename from test/grammar/cli_config/empty_cli_config/config.yaml rename to tests/grammar/cli_config/empty_cli_config/config.yaml diff --git a/test/grammar/cli_config/empty_cli_config/main.k b/tests/grammar/cli_config/empty_cli_config/main.k similarity index 100% rename from test/grammar/cli_config/empty_cli_config/main.k rename to tests/grammar/cli_config/empty_cli_config/main.k diff --git a/test/grammar/cli_config/empty_cli_config/settings.yaml b/tests/grammar/cli_config/empty_cli_config/settings.yaml similarity index 100% rename from test/grammar/cli_config/empty_cli_config/settings.yaml rename to tests/grammar/cli_config/empty_cli_config/settings.yaml diff --git a/test/grammar/cli_config/empty_cli_config/stdout.golden b/tests/grammar/cli_config/empty_cli_config/stdout.golden similarity index 100% rename from test/grammar/cli_config/empty_cli_config/stdout.golden rename to tests/grammar/cli_config/empty_cli_config/stdout.golden diff --git a/test/grammar/comment/docstring/mixin/main.k b/tests/grammar/comment/docstring/mixin/main.k similarity index 100% rename from test/grammar/comment/docstring/mixin/main.k rename to tests/grammar/comment/docstring/mixin/main.k diff --git a/test/grammar/comment/docstring/mixin/stdout.golden b/tests/grammar/comment/docstring/mixin/stdout.golden similarity index 100% rename from test/grammar/comment/docstring/mixin/stdout.golden rename to tests/grammar/comment/docstring/mixin/stdout.golden diff --git a/test/grammar/comment/docstring/simple_0/main.k b/tests/grammar/comment/docstring/simple_0/main.k similarity index 100% rename from test/grammar/comment/docstring/simple_0/main.k rename to tests/grammar/comment/docstring/simple_0/main.k diff --git a/test/grammar/comment/docstring/simple_0/stdout.golden b/tests/grammar/comment/docstring/simple_0/stdout.golden similarity index 100% rename from test/grammar/comment/docstring/simple_0/stdout.golden rename to tests/grammar/comment/docstring/simple_0/stdout.golden diff --git a/test/grammar/comment/docstring/simple_1/main.k b/tests/grammar/comment/docstring/simple_1/main.k similarity index 100% rename from test/grammar/comment/docstring/simple_1/main.k rename to tests/grammar/comment/docstring/simple_1/main.k diff --git a/test/grammar/comment/docstring/simple_1/stdout.golden b/tests/grammar/comment/docstring/simple_1/stdout.golden similarity index 100% rename from test/grammar/comment/docstring/simple_1/stdout.golden rename to tests/grammar/comment/docstring/simple_1/stdout.golden diff --git a/test/grammar/comment/docstring/simple_2/main.k b/tests/grammar/comment/docstring/simple_2/main.k similarity index 100% rename from test/grammar/comment/docstring/simple_2/main.k rename to tests/grammar/comment/docstring/simple_2/main.k diff --git a/test/grammar/comment/docstring/simple_2/stdout.golden b/tests/grammar/comment/docstring/simple_2/stdout.golden similarity index 100% rename from test/grammar/comment/docstring/simple_2/stdout.golden rename to tests/grammar/comment/docstring/simple_2/stdout.golden diff --git a/test/grammar/comment/simple/main.k b/tests/grammar/comment/simple/main.k similarity index 100% rename from test/grammar/comment/simple/main.k rename to tests/grammar/comment/simple/main.k diff --git a/test/grammar/comment/simple/stdout.golden b/tests/grammar/comment/simple/stdout.golden similarity index 100% rename from test/grammar/comment/simple/stdout.golden rename to tests/grammar/comment/simple/stdout.golden diff --git a/test/grammar/comprehension/dict/attr_op_0/main.k b/tests/grammar/comprehension/dict/attr_op_0/main.k similarity index 100% rename from test/grammar/comprehension/dict/attr_op_0/main.k rename to tests/grammar/comprehension/dict/attr_op_0/main.k diff --git a/test/grammar/comprehension/dict/attr_op_0/stdout.golden b/tests/grammar/comprehension/dict/attr_op_0/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/attr_op_0/stdout.golden rename to tests/grammar/comprehension/dict/attr_op_0/stdout.golden diff --git a/test/grammar/comprehension/dict/attr_op_1/main.k b/tests/grammar/comprehension/dict/attr_op_1/main.k similarity index 100% rename from test/grammar/comprehension/dict/attr_op_1/main.k rename to tests/grammar/comprehension/dict/attr_op_1/main.k diff --git a/test/grammar/comprehension/dict/attr_op_1/stdout.golden b/tests/grammar/comprehension/dict/attr_op_1/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/attr_op_1/stdout.golden rename to tests/grammar/comprehension/dict/attr_op_1/stdout.golden diff --git a/test/grammar/comprehension/dict/func_call/main.k b/tests/grammar/comprehension/dict/func_call/main.k similarity index 100% rename from test/grammar/comprehension/dict/func_call/main.k rename to tests/grammar/comprehension/dict/func_call/main.k diff --git a/test/grammar/comprehension/dict/func_call/stdout.golden b/tests/grammar/comprehension/dict/func_call/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/func_call/stdout.golden rename to tests/grammar/comprehension/dict/func_call/stdout.golden diff --git a/test/grammar/comprehension/dict/if_filter/main.k b/tests/grammar/comprehension/dict/if_filter/main.k similarity index 100% rename from test/grammar/comprehension/dict/if_filter/main.k rename to tests/grammar/comprehension/dict/if_filter/main.k diff --git a/test/grammar/comprehension/dict/if_filter/stdout.golden b/tests/grammar/comprehension/dict/if_filter/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/if_filter/stdout.golden rename to tests/grammar/comprehension/dict/if_filter/stdout.golden diff --git a/test/grammar/comprehension/dict/ifelse/main.k b/tests/grammar/comprehension/dict/ifelse/main.k similarity index 100% rename from test/grammar/comprehension/dict/ifelse/main.k rename to tests/grammar/comprehension/dict/ifelse/main.k diff --git a/test/grammar/comprehension/dict/ifelse/stdout.golden b/tests/grammar/comprehension/dict/ifelse/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/ifelse/stdout.golden rename to tests/grammar/comprehension/dict/ifelse/stdout.golden diff --git a/test/grammar/comprehension/dict/indent_0/main.k b/tests/grammar/comprehension/dict/indent_0/main.k similarity index 100% rename from test/grammar/comprehension/dict/indent_0/main.k rename to tests/grammar/comprehension/dict/indent_0/main.k diff --git a/test/grammar/comprehension/dict/indent_0/stdout.golden b/tests/grammar/comprehension/dict/indent_0/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/indent_0/stdout.golden rename to tests/grammar/comprehension/dict/indent_0/stdout.golden diff --git a/test/grammar/comprehension/dict/indent_1/main.k b/tests/grammar/comprehension/dict/indent_1/main.k similarity index 100% rename from test/grammar/comprehension/dict/indent_1/main.k rename to tests/grammar/comprehension/dict/indent_1/main.k diff --git a/test/grammar/comprehension/dict/indent_1/stdout.golden b/tests/grammar/comprehension/dict/indent_1/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/indent_1/stdout.golden rename to tests/grammar/comprehension/dict/indent_1/stdout.golden diff --git a/test/grammar/comprehension/dict/indent_2/main.k b/tests/grammar/comprehension/dict/indent_2/main.k similarity index 100% rename from test/grammar/comprehension/dict/indent_2/main.k rename to tests/grammar/comprehension/dict/indent_2/main.k diff --git a/test/grammar/comprehension/dict/indent_2/stdout.golden b/tests/grammar/comprehension/dict/indent_2/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/indent_2/stdout.golden rename to tests/grammar/comprehension/dict/indent_2/stdout.golden diff --git a/test/grammar/comprehension/dict/invalid_loop_var_fail_0/main.k b/tests/grammar/comprehension/dict/invalid_loop_var_fail_0/main.k similarity index 100% rename from test/grammar/comprehension/dict/invalid_loop_var_fail_0/main.k rename to tests/grammar/comprehension/dict/invalid_loop_var_fail_0/main.k diff --git a/test/grammar/comprehension/dict/invalid_loop_var_fail_0/stderr.golden b/tests/grammar/comprehension/dict/invalid_loop_var_fail_0/stderr.golden similarity index 100% rename from test/grammar/comprehension/dict/invalid_loop_var_fail_0/stderr.golden rename to tests/grammar/comprehension/dict/invalid_loop_var_fail_0/stderr.golden diff --git a/test/grammar/comprehension/dict/invalid_loop_var_fail_1/main.k b/tests/grammar/comprehension/dict/invalid_loop_var_fail_1/main.k similarity index 100% rename from test/grammar/comprehension/dict/invalid_loop_var_fail_1/main.k rename to tests/grammar/comprehension/dict/invalid_loop_var_fail_1/main.k diff --git a/test/grammar/comprehension/dict/invalid_loop_var_fail_1/stderr.golden b/tests/grammar/comprehension/dict/invalid_loop_var_fail_1/stderr.golden similarity index 100% rename from test/grammar/comprehension/dict/invalid_loop_var_fail_1/stderr.golden rename to tests/grammar/comprehension/dict/invalid_loop_var_fail_1/stderr.golden diff --git a/test/grammar/comprehension/dict/invalid_loop_var_fail_2/main.k b/tests/grammar/comprehension/dict/invalid_loop_var_fail_2/main.k similarity index 100% rename from test/grammar/comprehension/dict/invalid_loop_var_fail_2/main.k rename to tests/grammar/comprehension/dict/invalid_loop_var_fail_2/main.k diff --git a/test/grammar/comprehension/dict/invalid_loop_var_fail_2/stderr.golden b/tests/grammar/comprehension/dict/invalid_loop_var_fail_2/stderr.golden similarity index 100% rename from test/grammar/comprehension/dict/invalid_loop_var_fail_2/stderr.golden rename to tests/grammar/comprehension/dict/invalid_loop_var_fail_2/stderr.golden diff --git a/test/grammar/comprehension/dict/local_var_as_key/main.k b/tests/grammar/comprehension/dict/local_var_as_key/main.k similarity index 100% rename from test/grammar/comprehension/dict/local_var_as_key/main.k rename to tests/grammar/comprehension/dict/local_var_as_key/main.k diff --git a/test/grammar/comprehension/dict/local_var_as_key/stdout.golden b/tests/grammar/comprehension/dict/local_var_as_key/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/local_var_as_key/stdout.golden rename to tests/grammar/comprehension/dict/local_var_as_key/stdout.golden diff --git a/test/grammar/comprehension/dict/multi_vars_0/main.k b/tests/grammar/comprehension/dict/multi_vars_0/main.k similarity index 100% rename from test/grammar/comprehension/dict/multi_vars_0/main.k rename to tests/grammar/comprehension/dict/multi_vars_0/main.k diff --git a/test/grammar/comprehension/dict/multi_vars_0/stdout.golden b/tests/grammar/comprehension/dict/multi_vars_0/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/multi_vars_0/stdout.golden rename to tests/grammar/comprehension/dict/multi_vars_0/stdout.golden diff --git a/test/grammar/comprehension/dict/multi_vars_1/main.k b/tests/grammar/comprehension/dict/multi_vars_1/main.k similarity index 100% rename from test/grammar/comprehension/dict/multi_vars_1/main.k rename to tests/grammar/comprehension/dict/multi_vars_1/main.k diff --git a/test/grammar/comprehension/dict/multi_vars_1/stdout.golden b/tests/grammar/comprehension/dict/multi_vars_1/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/multi_vars_1/stdout.golden rename to tests/grammar/comprehension/dict/multi_vars_1/stdout.golden diff --git a/test/grammar/comprehension/dict/multi_vars_2/main.k b/tests/grammar/comprehension/dict/multi_vars_2/main.k similarity index 100% rename from test/grammar/comprehension/dict/multi_vars_2/main.k rename to tests/grammar/comprehension/dict/multi_vars_2/main.k diff --git a/test/grammar/comprehension/dict/multi_vars_2/stdout.golden b/tests/grammar/comprehension/dict/multi_vars_2/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/multi_vars_2/stdout.golden rename to tests/grammar/comprehension/dict/multi_vars_2/stdout.golden diff --git a/test/grammar/comprehension/dict/nested/main.k b/tests/grammar/comprehension/dict/nested/main.k similarity index 100% rename from test/grammar/comprehension/dict/nested/main.k rename to tests/grammar/comprehension/dict/nested/main.k diff --git a/test/grammar/comprehension/dict/nested/stdout.golden b/tests/grammar/comprehension/dict/nested/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/nested/stdout.golden rename to tests/grammar/comprehension/dict/nested/stdout.golden diff --git a/test/grammar/comprehension/dict/normal_0/main.k b/tests/grammar/comprehension/dict/normal_0/main.k similarity index 100% rename from test/grammar/comprehension/dict/normal_0/main.k rename to tests/grammar/comprehension/dict/normal_0/main.k diff --git a/test/grammar/comprehension/dict/normal_0/stdout.golden b/tests/grammar/comprehension/dict/normal_0/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/normal_0/stdout.golden rename to tests/grammar/comprehension/dict/normal_0/stdout.golden diff --git a/test/grammar/comprehension/dict/type_convertion_0/main.k b/tests/grammar/comprehension/dict/type_convertion_0/main.k similarity index 100% rename from test/grammar/comprehension/dict/type_convertion_0/main.k rename to tests/grammar/comprehension/dict/type_convertion_0/main.k diff --git a/test/grammar/comprehension/dict/type_convertion_0/stdout.golden b/tests/grammar/comprehension/dict/type_convertion_0/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/type_convertion_0/stdout.golden rename to tests/grammar/comprehension/dict/type_convertion_0/stdout.golden diff --git a/test/grammar/comprehension/dict/type_convertion_1/main.k b/tests/grammar/comprehension/dict/type_convertion_1/main.k similarity index 100% rename from test/grammar/comprehension/dict/type_convertion_1/main.k rename to tests/grammar/comprehension/dict/type_convertion_1/main.k diff --git a/test/grammar/comprehension/dict/type_convertion_1/stdout.golden b/tests/grammar/comprehension/dict/type_convertion_1/stdout.golden similarity index 100% rename from test/grammar/comprehension/dict/type_convertion_1/stdout.golden rename to tests/grammar/comprehension/dict/type_convertion_1/stdout.golden diff --git a/test/grammar/comprehension/list/func_call/main.k b/tests/grammar/comprehension/list/func_call/main.k similarity index 100% rename from test/grammar/comprehension/list/func_call/main.k rename to tests/grammar/comprehension/list/func_call/main.k diff --git a/test/grammar/comprehension/list/func_call/stdout.golden b/tests/grammar/comprehension/list/func_call/stdout.golden similarity index 100% rename from test/grammar/comprehension/list/func_call/stdout.golden rename to tests/grammar/comprehension/list/func_call/stdout.golden diff --git a/test/grammar/comprehension/list/in_schema_expr/main.k b/tests/grammar/comprehension/list/in_schema_expr/main.k similarity index 100% rename from test/grammar/comprehension/list/in_schema_expr/main.k rename to tests/grammar/comprehension/list/in_schema_expr/main.k diff --git a/test/grammar/comprehension/list/in_schema_expr/stdout.golden b/tests/grammar/comprehension/list/in_schema_expr/stdout.golden similarity index 100% rename from test/grammar/comprehension/list/in_schema_expr/stdout.golden rename to tests/grammar/comprehension/list/in_schema_expr/stdout.golden diff --git a/test/grammar/comprehension/list/invalid_loop_var_fail_0/main.k b/tests/grammar/comprehension/list/invalid_loop_var_fail_0/main.k similarity index 100% rename from test/grammar/comprehension/list/invalid_loop_var_fail_0/main.k rename to tests/grammar/comprehension/list/invalid_loop_var_fail_0/main.k diff --git a/test/grammar/comprehension/list/invalid_loop_var_fail_0/stderr.golden b/tests/grammar/comprehension/list/invalid_loop_var_fail_0/stderr.golden similarity index 100% rename from test/grammar/comprehension/list/invalid_loop_var_fail_0/stderr.golden rename to tests/grammar/comprehension/list/invalid_loop_var_fail_0/stderr.golden diff --git a/test/grammar/comprehension/list/invalid_loop_var_fail_1/main.k b/tests/grammar/comprehension/list/invalid_loop_var_fail_1/main.k similarity index 100% rename from test/grammar/comprehension/list/invalid_loop_var_fail_1/main.k rename to tests/grammar/comprehension/list/invalid_loop_var_fail_1/main.k diff --git a/test/grammar/comprehension/list/invalid_loop_var_fail_1/stderr.golden b/tests/grammar/comprehension/list/invalid_loop_var_fail_1/stderr.golden similarity index 100% rename from test/grammar/comprehension/list/invalid_loop_var_fail_1/stderr.golden rename to tests/grammar/comprehension/list/invalid_loop_var_fail_1/stderr.golden diff --git a/test/grammar/comprehension/list/invalid_loop_var_fail_2/main.k b/tests/grammar/comprehension/list/invalid_loop_var_fail_2/main.k similarity index 100% rename from test/grammar/comprehension/list/invalid_loop_var_fail_2/main.k rename to tests/grammar/comprehension/list/invalid_loop_var_fail_2/main.k diff --git a/test/grammar/comprehension/list/invalid_loop_var_fail_2/stderr.golden b/tests/grammar/comprehension/list/invalid_loop_var_fail_2/stderr.golden similarity index 100% rename from test/grammar/comprehension/list/invalid_loop_var_fail_2/stderr.golden rename to tests/grammar/comprehension/list/invalid_loop_var_fail_2/stderr.golden diff --git a/test/grammar/comprehension/list/module_var_in_for_0/app.k b/tests/grammar/comprehension/list/module_var_in_for_0/app.k similarity index 100% rename from test/grammar/comprehension/list/module_var_in_for_0/app.k rename to tests/grammar/comprehension/list/module_var_in_for_0/app.k diff --git a/test/grammar/comprehension/list/module_var_in_for_0/main.k b/tests/grammar/comprehension/list/module_var_in_for_0/main.k similarity index 100% rename from test/grammar/comprehension/list/module_var_in_for_0/main.k rename to tests/grammar/comprehension/list/module_var_in_for_0/main.k diff --git a/test/grammar/comprehension/list/module_var_in_for_0/stdout.golden b/tests/grammar/comprehension/list/module_var_in_for_0/stdout.golden similarity index 100% rename from test/grammar/comprehension/list/module_var_in_for_0/stdout.golden rename to tests/grammar/comprehension/list/module_var_in_for_0/stdout.golden diff --git a/test/grammar/comprehension/list/multi_vars_0/main.k b/tests/grammar/comprehension/list/multi_vars_0/main.k similarity index 100% rename from test/grammar/comprehension/list/multi_vars_0/main.k rename to tests/grammar/comprehension/list/multi_vars_0/main.k diff --git a/test/grammar/comprehension/list/multi_vars_0/stdout.golden b/tests/grammar/comprehension/list/multi_vars_0/stdout.golden similarity index 100% rename from test/grammar/comprehension/list/multi_vars_0/stdout.golden rename to tests/grammar/comprehension/list/multi_vars_0/stdout.golden diff --git a/test/grammar/comprehension/list/multi_vars_1/main.k b/tests/grammar/comprehension/list/multi_vars_1/main.k similarity index 100% rename from test/grammar/comprehension/list/multi_vars_1/main.k rename to tests/grammar/comprehension/list/multi_vars_1/main.k diff --git a/test/grammar/comprehension/list/multi_vars_1/stdout.golden b/tests/grammar/comprehension/list/multi_vars_1/stdout.golden similarity index 100% rename from test/grammar/comprehension/list/multi_vars_1/stdout.golden rename to tests/grammar/comprehension/list/multi_vars_1/stdout.golden diff --git a/test/grammar/comprehension/list/multi_vars_2/main.k b/tests/grammar/comprehension/list/multi_vars_2/main.k similarity index 100% rename from test/grammar/comprehension/list/multi_vars_2/main.k rename to tests/grammar/comprehension/list/multi_vars_2/main.k diff --git a/test/grammar/comprehension/list/multi_vars_2/stdout.golden b/tests/grammar/comprehension/list/multi_vars_2/stdout.golden similarity index 100% rename from test/grammar/comprehension/list/multi_vars_2/stdout.golden rename to tests/grammar/comprehension/list/multi_vars_2/stdout.golden diff --git a/test/grammar/comprehension/list/nested/main.k b/tests/grammar/comprehension/list/nested/main.k similarity index 100% rename from test/grammar/comprehension/list/nested/main.k rename to tests/grammar/comprehension/list/nested/main.k diff --git a/test/grammar/comprehension/list/nested/stdout.golden b/tests/grammar/comprehension/list/nested/stdout.golden similarity index 100% rename from test/grammar/comprehension/list/nested/stdout.golden rename to tests/grammar/comprehension/list/nested/stdout.golden diff --git a/test/grammar/comprehension/list/normal/main.k b/tests/grammar/comprehension/list/normal/main.k similarity index 100% rename from test/grammar/comprehension/list/normal/main.k rename to tests/grammar/comprehension/list/normal/main.k diff --git a/test/grammar/comprehension/list/normal/stdout.golden b/tests/grammar/comprehension/list/normal/stdout.golden similarity index 100% rename from test/grammar/comprehension/list/normal/stdout.golden rename to tests/grammar/comprehension/list/normal/stdout.golden diff --git a/test/grammar/comprehension/list/to_dict_0/main.k b/tests/grammar/comprehension/list/to_dict_0/main.k similarity index 100% rename from test/grammar/comprehension/list/to_dict_0/main.k rename to tests/grammar/comprehension/list/to_dict_0/main.k diff --git a/test/grammar/comprehension/list/to_dict_0/stdout.golden b/tests/grammar/comprehension/list/to_dict_0/stdout.golden similarity index 100% rename from test/grammar/comprehension/list/to_dict_0/stdout.golden rename to tests/grammar/comprehension/list/to_dict_0/stdout.golden diff --git a/test/grammar/comprehension/list/to_dict_1/main.k b/tests/grammar/comprehension/list/to_dict_1/main.k similarity index 100% rename from test/grammar/comprehension/list/to_dict_1/main.k rename to tests/grammar/comprehension/list/to_dict_1/main.k diff --git a/test/grammar/comprehension/list/to_dict_1/stdout.golden b/tests/grammar/comprehension/list/to_dict_1/stdout.golden similarity index 100% rename from test/grammar/comprehension/list/to_dict_1/stdout.golden rename to tests/grammar/comprehension/list/to_dict_1/stdout.golden diff --git a/test/grammar/comprehension/list/type_convertion_0/main.k b/tests/grammar/comprehension/list/type_convertion_0/main.k similarity index 100% rename from test/grammar/comprehension/list/type_convertion_0/main.k rename to tests/grammar/comprehension/list/type_convertion_0/main.k diff --git a/test/grammar/comprehension/list/type_convertion_0/stdout.golden b/tests/grammar/comprehension/list/type_convertion_0/stdout.golden similarity index 100% rename from test/grammar/comprehension/list/type_convertion_0/stdout.golden rename to tests/grammar/comprehension/list/type_convertion_0/stdout.golden diff --git a/test/grammar/comprehension/list/type_convertion_1/main.k b/tests/grammar/comprehension/list/type_convertion_1/main.k similarity index 100% rename from test/grammar/comprehension/list/type_convertion_1/main.k rename to tests/grammar/comprehension/list/type_convertion_1/main.k diff --git a/test/grammar/comprehension/list/type_convertion_1/stdout.golden b/tests/grammar/comprehension/list/type_convertion_1/stdout.golden similarity index 100% rename from test/grammar/comprehension/list/type_convertion_1/stdout.golden rename to tests/grammar/comprehension/list/type_convertion_1/stdout.golden diff --git a/test/grammar/comprehension/str/func_call/main.k b/tests/grammar/comprehension/str/func_call/main.k similarity index 100% rename from test/grammar/comprehension/str/func_call/main.k rename to tests/grammar/comprehension/str/func_call/main.k diff --git a/test/grammar/comprehension/str/func_call/stdout.golden b/tests/grammar/comprehension/str/func_call/stdout.golden similarity index 100% rename from test/grammar/comprehension/str/func_call/stdout.golden rename to tests/grammar/comprehension/str/func_call/stdout.golden diff --git a/test/grammar/comprehension/str/in_schema_expr/main.k b/tests/grammar/comprehension/str/in_schema_expr/main.k similarity index 100% rename from test/grammar/comprehension/str/in_schema_expr/main.k rename to tests/grammar/comprehension/str/in_schema_expr/main.k diff --git a/test/grammar/comprehension/str/in_schema_expr/stdout.golden b/tests/grammar/comprehension/str/in_schema_expr/stdout.golden similarity index 100% rename from test/grammar/comprehension/str/in_schema_expr/stdout.golden rename to tests/grammar/comprehension/str/in_schema_expr/stdout.golden diff --git a/test/grammar/comprehension/str/invalid_loop_var_fail_0/main.k b/tests/grammar/comprehension/str/invalid_loop_var_fail_0/main.k similarity index 100% rename from test/grammar/comprehension/str/invalid_loop_var_fail_0/main.k rename to tests/grammar/comprehension/str/invalid_loop_var_fail_0/main.k diff --git a/test/grammar/comprehension/str/invalid_loop_var_fail_0/stderr.golden b/tests/grammar/comprehension/str/invalid_loop_var_fail_0/stderr.golden similarity index 100% rename from test/grammar/comprehension/str/invalid_loop_var_fail_0/stderr.golden rename to tests/grammar/comprehension/str/invalid_loop_var_fail_0/stderr.golden diff --git a/test/grammar/comprehension/str/invalid_loop_var_fail_1/main.k b/tests/grammar/comprehension/str/invalid_loop_var_fail_1/main.k similarity index 100% rename from test/grammar/comprehension/str/invalid_loop_var_fail_1/main.k rename to tests/grammar/comprehension/str/invalid_loop_var_fail_1/main.k diff --git a/test/grammar/comprehension/str/invalid_loop_var_fail_1/stderr.golden b/tests/grammar/comprehension/str/invalid_loop_var_fail_1/stderr.golden similarity index 100% rename from test/grammar/comprehension/str/invalid_loop_var_fail_1/stderr.golden rename to tests/grammar/comprehension/str/invalid_loop_var_fail_1/stderr.golden diff --git a/test/grammar/comprehension/str/invalid_loop_var_fail_2/main.k b/tests/grammar/comprehension/str/invalid_loop_var_fail_2/main.k similarity index 100% rename from test/grammar/comprehension/str/invalid_loop_var_fail_2/main.k rename to tests/grammar/comprehension/str/invalid_loop_var_fail_2/main.k diff --git a/test/grammar/comprehension/str/invalid_loop_var_fail_2/stderr.golden b/tests/grammar/comprehension/str/invalid_loop_var_fail_2/stderr.golden similarity index 100% rename from test/grammar/comprehension/str/invalid_loop_var_fail_2/stderr.golden rename to tests/grammar/comprehension/str/invalid_loop_var_fail_2/stderr.golden diff --git a/test/grammar/comprehension/str/nested/main.k b/tests/grammar/comprehension/str/nested/main.k similarity index 100% rename from test/grammar/comprehension/str/nested/main.k rename to tests/grammar/comprehension/str/nested/main.k diff --git a/test/grammar/comprehension/str/nested/stdout.golden b/tests/grammar/comprehension/str/nested/stdout.golden similarity index 100% rename from test/grammar/comprehension/str/nested/stdout.golden rename to tests/grammar/comprehension/str/nested/stdout.golden diff --git a/test/grammar/comprehension/str/normal/main.k b/tests/grammar/comprehension/str/normal/main.k similarity index 100% rename from test/grammar/comprehension/str/normal/main.k rename to tests/grammar/comprehension/str/normal/main.k diff --git a/test/grammar/comprehension/str/normal/stdout.golden b/tests/grammar/comprehension/str/normal/stdout.golden similarity index 100% rename from test/grammar/comprehension/str/normal/stdout.golden rename to tests/grammar/comprehension/str/normal/stdout.golden diff --git a/test/grammar/datatype/conversion/int2float_0/main.k b/tests/grammar/datatype/conversion/int2float_0/main.k similarity index 100% rename from test/grammar/datatype/conversion/int2float_0/main.k rename to tests/grammar/datatype/conversion/int2float_0/main.k diff --git a/test/grammar/datatype/conversion/int2float_0/stdout.golden b/tests/grammar/datatype/conversion/int2float_0/stdout.golden similarity index 100% rename from test/grammar/datatype/conversion/int2float_0/stdout.golden rename to tests/grammar/datatype/conversion/int2float_0/stdout.golden diff --git a/test/grammar/datatype/conversion/int2float_1/main.k b/tests/grammar/datatype/conversion/int2float_1/main.k similarity index 100% rename from test/grammar/datatype/conversion/int2float_1/main.k rename to tests/grammar/datatype/conversion/int2float_1/main.k diff --git a/test/grammar/datatype/conversion/int2float_1/stdout.golden b/tests/grammar/datatype/conversion/int2float_1/stdout.golden similarity index 100% rename from test/grammar/datatype/conversion/int2float_1/stdout.golden rename to tests/grammar/datatype/conversion/int2float_1/stdout.golden diff --git a/test/grammar/datatype/datetime/today/main.k b/tests/grammar/datatype/datetime/today/main.k similarity index 100% rename from test/grammar/datatype/datetime/today/main.k rename to tests/grammar/datatype/datetime/today/main.k diff --git a/test/grammar/datatype/datetime/today/stdout.golden b/tests/grammar/datatype/datetime/today/stdout.golden similarity index 100% rename from test/grammar/datatype/datetime/today/stdout.golden rename to tests/grammar/datatype/datetime/today/stdout.golden diff --git a/test/grammar/datatype/dict/empty/main.k b/tests/grammar/datatype/dict/empty/main.k similarity index 100% rename from test/grammar/datatype/dict/empty/main.k rename to tests/grammar/datatype/dict/empty/main.k diff --git a/test/grammar/datatype/dict/empty/stdout.golden b/tests/grammar/datatype/dict/empty/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/empty/stdout.golden rename to tests/grammar/datatype/dict/empty/stdout.golden diff --git a/test/grammar/datatype/dict/if_item_0/main.k b/tests/grammar/datatype/dict/if_item_0/main.k similarity index 100% rename from test/grammar/datatype/dict/if_item_0/main.k rename to tests/grammar/datatype/dict/if_item_0/main.k diff --git a/test/grammar/datatype/dict/if_item_0/stdout.golden b/tests/grammar/datatype/dict/if_item_0/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/if_item_0/stdout.golden rename to tests/grammar/datatype/dict/if_item_0/stdout.golden diff --git a/test/grammar/datatype/dict/if_item_1/main.k b/tests/grammar/datatype/dict/if_item_1/main.k similarity index 100% rename from test/grammar/datatype/dict/if_item_1/main.k rename to tests/grammar/datatype/dict/if_item_1/main.k diff --git a/test/grammar/datatype/dict/if_item_1/stdout.golden b/tests/grammar/datatype/dict/if_item_1/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/if_item_1/stdout.golden rename to tests/grammar/datatype/dict/if_item_1/stdout.golden diff --git a/test/grammar/datatype/dict/if_item_10/main.k b/tests/grammar/datatype/dict/if_item_10/main.k similarity index 100% rename from test/grammar/datatype/dict/if_item_10/main.k rename to tests/grammar/datatype/dict/if_item_10/main.k diff --git a/test/grammar/datatype/dict/if_item_10/stdout.golden b/tests/grammar/datatype/dict/if_item_10/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/if_item_10/stdout.golden rename to tests/grammar/datatype/dict/if_item_10/stdout.golden diff --git a/test/grammar/datatype/dict/if_item_11/main.k b/tests/grammar/datatype/dict/if_item_11/main.k similarity index 100% rename from test/grammar/datatype/dict/if_item_11/main.k rename to tests/grammar/datatype/dict/if_item_11/main.k diff --git a/test/grammar/datatype/dict/if_item_11/stdout.golden b/tests/grammar/datatype/dict/if_item_11/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/if_item_11/stdout.golden rename to tests/grammar/datatype/dict/if_item_11/stdout.golden diff --git a/test/grammar/datatype/dict/if_item_2/main.k b/tests/grammar/datatype/dict/if_item_2/main.k similarity index 100% rename from test/grammar/datatype/dict/if_item_2/main.k rename to tests/grammar/datatype/dict/if_item_2/main.k diff --git a/test/grammar/datatype/dict/if_item_2/stdout.golden b/tests/grammar/datatype/dict/if_item_2/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/if_item_2/stdout.golden rename to tests/grammar/datatype/dict/if_item_2/stdout.golden diff --git a/test/grammar/datatype/dict/if_item_3/main.k b/tests/grammar/datatype/dict/if_item_3/main.k similarity index 100% rename from test/grammar/datatype/dict/if_item_3/main.k rename to tests/grammar/datatype/dict/if_item_3/main.k diff --git a/test/grammar/datatype/dict/if_item_3/stdout.golden b/tests/grammar/datatype/dict/if_item_3/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/if_item_3/stdout.golden rename to tests/grammar/datatype/dict/if_item_3/stdout.golden diff --git a/test/grammar/datatype/dict/if_item_4/main.k b/tests/grammar/datatype/dict/if_item_4/main.k similarity index 100% rename from test/grammar/datatype/dict/if_item_4/main.k rename to tests/grammar/datatype/dict/if_item_4/main.k diff --git a/test/grammar/datatype/dict/if_item_4/stdout.golden b/tests/grammar/datatype/dict/if_item_4/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/if_item_4/stdout.golden rename to tests/grammar/datatype/dict/if_item_4/stdout.golden diff --git a/test/grammar/datatype/dict/if_item_5/main.k b/tests/grammar/datatype/dict/if_item_5/main.k similarity index 100% rename from test/grammar/datatype/dict/if_item_5/main.k rename to tests/grammar/datatype/dict/if_item_5/main.k diff --git a/test/grammar/datatype/dict/if_item_5/stdout.golden b/tests/grammar/datatype/dict/if_item_5/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/if_item_5/stdout.golden rename to tests/grammar/datatype/dict/if_item_5/stdout.golden diff --git a/test/grammar/datatype/dict/if_item_6/main.k b/tests/grammar/datatype/dict/if_item_6/main.k similarity index 100% rename from test/grammar/datatype/dict/if_item_6/main.k rename to tests/grammar/datatype/dict/if_item_6/main.k diff --git a/test/grammar/datatype/dict/if_item_6/stdout.golden b/tests/grammar/datatype/dict/if_item_6/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/if_item_6/stdout.golden rename to tests/grammar/datatype/dict/if_item_6/stdout.golden diff --git a/test/grammar/datatype/dict/if_item_7/main.k b/tests/grammar/datatype/dict/if_item_7/main.k similarity index 100% rename from test/grammar/datatype/dict/if_item_7/main.k rename to tests/grammar/datatype/dict/if_item_7/main.k diff --git a/test/grammar/datatype/dict/if_item_7/stdout.golden b/tests/grammar/datatype/dict/if_item_7/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/if_item_7/stdout.golden rename to tests/grammar/datatype/dict/if_item_7/stdout.golden diff --git a/test/grammar/datatype/dict/if_item_8/main.k b/tests/grammar/datatype/dict/if_item_8/main.k similarity index 100% rename from test/grammar/datatype/dict/if_item_8/main.k rename to tests/grammar/datatype/dict/if_item_8/main.k diff --git a/test/grammar/datatype/dict/if_item_8/stdout.golden b/tests/grammar/datatype/dict/if_item_8/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/if_item_8/stdout.golden rename to tests/grammar/datatype/dict/if_item_8/stdout.golden diff --git a/test/grammar/datatype/dict/if_item_9/main.k b/tests/grammar/datatype/dict/if_item_9/main.k similarity index 100% rename from test/grammar/datatype/dict/if_item_9/main.k rename to tests/grammar/datatype/dict/if_item_9/main.k diff --git a/test/grammar/datatype/dict/if_item_9/stdout.golden b/tests/grammar/datatype/dict/if_item_9/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/if_item_9/stdout.golden rename to tests/grammar/datatype/dict/if_item_9/stdout.golden diff --git a/test/grammar/datatype/dict/indexing_0/main.k b/tests/grammar/datatype/dict/indexing_0/main.k similarity index 100% rename from test/grammar/datatype/dict/indexing_0/main.k rename to tests/grammar/datatype/dict/indexing_0/main.k diff --git a/test/grammar/datatype/dict/indexing_0/stdout.golden b/tests/grammar/datatype/dict/indexing_0/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/indexing_0/stdout.golden rename to tests/grammar/datatype/dict/indexing_0/stdout.golden diff --git a/test/grammar/datatype/dict/indexing_1/main.k b/tests/grammar/datatype/dict/indexing_1/main.k similarity index 100% rename from test/grammar/datatype/dict/indexing_1/main.k rename to tests/grammar/datatype/dict/indexing_1/main.k diff --git a/test/grammar/datatype/dict/indexing_1/stdout.golden b/tests/grammar/datatype/dict/indexing_1/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/indexing_1/stdout.golden rename to tests/grammar/datatype/dict/indexing_1/stdout.golden diff --git a/test/grammar/datatype/dict/indexing_in_comprehension_0/main.k b/tests/grammar/datatype/dict/indexing_in_comprehension_0/main.k similarity index 100% rename from test/grammar/datatype/dict/indexing_in_comprehension_0/main.k rename to tests/grammar/datatype/dict/indexing_in_comprehension_0/main.k diff --git a/test/grammar/datatype/dict/indexing_in_comprehension_0/stdout.golden b/tests/grammar/datatype/dict/indexing_in_comprehension_0/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/indexing_in_comprehension_0/stdout.golden rename to tests/grammar/datatype/dict/indexing_in_comprehension_0/stdout.golden diff --git a/test/grammar/datatype/dict/indexing_in_comprehension_1/main.k b/tests/grammar/datatype/dict/indexing_in_comprehension_1/main.k similarity index 100% rename from test/grammar/datatype/dict/indexing_in_comprehension_1/main.k rename to tests/grammar/datatype/dict/indexing_in_comprehension_1/main.k diff --git a/test/grammar/datatype/dict/indexing_in_comprehension_1/stdout.golden b/tests/grammar/datatype/dict/indexing_in_comprehension_1/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/indexing_in_comprehension_1/stdout.golden rename to tests/grammar/datatype/dict/indexing_in_comprehension_1/stdout.golden diff --git a/test/grammar/datatype/dict/indexing_in_comprehension_2/main.k b/tests/grammar/datatype/dict/indexing_in_comprehension_2/main.k similarity index 100% rename from test/grammar/datatype/dict/indexing_in_comprehension_2/main.k rename to tests/grammar/datatype/dict/indexing_in_comprehension_2/main.k diff --git a/test/grammar/datatype/dict/indexing_in_comprehension_2/stdout.golden b/tests/grammar/datatype/dict/indexing_in_comprehension_2/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/indexing_in_comprehension_2/stdout.golden rename to tests/grammar/datatype/dict/indexing_in_comprehension_2/stdout.golden diff --git a/test/grammar/datatype/dict/indexing_in_comprehension_3/main.k b/tests/grammar/datatype/dict/indexing_in_comprehension_3/main.k similarity index 100% rename from test/grammar/datatype/dict/indexing_in_comprehension_3/main.k rename to tests/grammar/datatype/dict/indexing_in_comprehension_3/main.k diff --git a/test/grammar/datatype/dict/indexing_in_comprehension_3/stdout.golden b/tests/grammar/datatype/dict/indexing_in_comprehension_3/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/indexing_in_comprehension_3/stdout.golden rename to tests/grammar/datatype/dict/indexing_in_comprehension_3/stdout.golden diff --git a/test/grammar/datatype/dict/indexing_in_comprehension_fail_0/main.k b/tests/grammar/datatype/dict/indexing_in_comprehension_fail_0/main.k similarity index 100% rename from test/grammar/datatype/dict/indexing_in_comprehension_fail_0/main.k rename to tests/grammar/datatype/dict/indexing_in_comprehension_fail_0/main.k diff --git a/test/grammar/datatype/dict/indexing_in_comprehension_fail_0/stderr.golden b/tests/grammar/datatype/dict/indexing_in_comprehension_fail_0/stderr.golden similarity index 100% rename from test/grammar/datatype/dict/indexing_in_comprehension_fail_0/stderr.golden rename to tests/grammar/datatype/dict/indexing_in_comprehension_fail_0/stderr.golden diff --git a/test/grammar/datatype/dict/insert_0/main.k b/tests/grammar/datatype/dict/insert_0/main.k similarity index 100% rename from test/grammar/datatype/dict/insert_0/main.k rename to tests/grammar/datatype/dict/insert_0/main.k diff --git a/test/grammar/datatype/dict/insert_0/stdout.golden b/tests/grammar/datatype/dict/insert_0/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/insert_0/stdout.golden rename to tests/grammar/datatype/dict/insert_0/stdout.golden diff --git a/test/grammar/datatype/dict/insert_1/main.k b/tests/grammar/datatype/dict/insert_1/main.k similarity index 100% rename from test/grammar/datatype/dict/insert_1/main.k rename to tests/grammar/datatype/dict/insert_1/main.k diff --git a/test/grammar/datatype/dict/insert_1/stdout.golden b/tests/grammar/datatype/dict/insert_1/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/insert_1/stdout.golden rename to tests/grammar/datatype/dict/insert_1/stdout.golden diff --git a/test/grammar/datatype/dict/insert_2/main.k b/tests/grammar/datatype/dict/insert_2/main.k similarity index 100% rename from test/grammar/datatype/dict/insert_2/main.k rename to tests/grammar/datatype/dict/insert_2/main.k diff --git a/test/grammar/datatype/dict/insert_2/stdout.golden b/tests/grammar/datatype/dict/insert_2/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/insert_2/stdout.golden rename to tests/grammar/datatype/dict/insert_2/stdout.golden diff --git a/test/grammar/datatype/dict/merge_0/main.k b/tests/grammar/datatype/dict/merge_0/main.k similarity index 100% rename from test/grammar/datatype/dict/merge_0/main.k rename to tests/grammar/datatype/dict/merge_0/main.k diff --git a/test/grammar/datatype/dict/merge_0/stdout.golden b/tests/grammar/datatype/dict/merge_0/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/merge_0/stdout.golden rename to tests/grammar/datatype/dict/merge_0/stdout.golden diff --git a/test/grammar/datatype/dict/merge_1/main.k b/tests/grammar/datatype/dict/merge_1/main.k similarity index 100% rename from test/grammar/datatype/dict/merge_1/main.k rename to tests/grammar/datatype/dict/merge_1/main.k diff --git a/test/grammar/datatype/dict/merge_1/stdout.golden b/tests/grammar/datatype/dict/merge_1/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/merge_1/stdout.golden rename to tests/grammar/datatype/dict/merge_1/stdout.golden diff --git a/test/grammar/datatype/dict/merge_2/main.k b/tests/grammar/datatype/dict/merge_2/main.k similarity index 100% rename from test/grammar/datatype/dict/merge_2/main.k rename to tests/grammar/datatype/dict/merge_2/main.k diff --git a/test/grammar/datatype/dict/merge_2/stdout.golden b/tests/grammar/datatype/dict/merge_2/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/merge_2/stdout.golden rename to tests/grammar/datatype/dict/merge_2/stdout.golden diff --git a/test/grammar/datatype/dict/merge_3/main.k b/tests/grammar/datatype/dict/merge_3/main.k similarity index 100% rename from test/grammar/datatype/dict/merge_3/main.k rename to tests/grammar/datatype/dict/merge_3/main.k diff --git a/test/grammar/datatype/dict/merge_3/stdout.golden b/tests/grammar/datatype/dict/merge_3/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/merge_3/stdout.golden rename to tests/grammar/datatype/dict/merge_3/stdout.golden diff --git a/test/grammar/datatype/dict/merge_None_0/main.k b/tests/grammar/datatype/dict/merge_None_0/main.k similarity index 100% rename from test/grammar/datatype/dict/merge_None_0/main.k rename to tests/grammar/datatype/dict/merge_None_0/main.k diff --git a/test/grammar/datatype/dict/merge_None_0/stdout.golden b/tests/grammar/datatype/dict/merge_None_0/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/merge_None_0/stdout.golden rename to tests/grammar/datatype/dict/merge_None_0/stdout.golden diff --git a/test/grammar/datatype/dict/merge_None_1/main.k b/tests/grammar/datatype/dict/merge_None_1/main.k similarity index 100% rename from test/grammar/datatype/dict/merge_None_1/main.k rename to tests/grammar/datatype/dict/merge_None_1/main.k diff --git a/test/grammar/datatype/dict/merge_None_1/stdout.golden b/tests/grammar/datatype/dict/merge_None_1/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/merge_None_1/stdout.golden rename to tests/grammar/datatype/dict/merge_None_1/stdout.golden diff --git a/test/grammar/datatype/dict/merge_if_expr_0/main.k b/tests/grammar/datatype/dict/merge_if_expr_0/main.k similarity index 100% rename from test/grammar/datatype/dict/merge_if_expr_0/main.k rename to tests/grammar/datatype/dict/merge_if_expr_0/main.k diff --git a/test/grammar/datatype/dict/merge_if_expr_0/stdout.golden b/tests/grammar/datatype/dict/merge_if_expr_0/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/merge_if_expr_0/stdout.golden rename to tests/grammar/datatype/dict/merge_if_expr_0/stdout.golden diff --git a/test/grammar/datatype/dict/merge_in_comprehension_0/main.k b/tests/grammar/datatype/dict/merge_in_comprehension_0/main.k similarity index 100% rename from test/grammar/datatype/dict/merge_in_comprehension_0/main.k rename to tests/grammar/datatype/dict/merge_in_comprehension_0/main.k diff --git a/test/grammar/datatype/dict/merge_in_comprehension_0/stdout.golden b/tests/grammar/datatype/dict/merge_in_comprehension_0/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/merge_in_comprehension_0/stdout.golden rename to tests/grammar/datatype/dict/merge_in_comprehension_0/stdout.golden diff --git a/test/grammar/datatype/dict/merge_in_comprehension_1/main.k b/tests/grammar/datatype/dict/merge_in_comprehension_1/main.k similarity index 100% rename from test/grammar/datatype/dict/merge_in_comprehension_1/main.k rename to tests/grammar/datatype/dict/merge_in_comprehension_1/main.k diff --git a/test/grammar/datatype/dict/merge_in_comprehension_1/stdout.golden b/tests/grammar/datatype/dict/merge_in_comprehension_1/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/merge_in_comprehension_1/stdout.golden rename to tests/grammar/datatype/dict/merge_in_comprehension_1/stdout.golden diff --git a/test/grammar/datatype/dict/merge_indent/main.k b/tests/grammar/datatype/dict/merge_indent/main.k similarity index 100% rename from test/grammar/datatype/dict/merge_indent/main.k rename to tests/grammar/datatype/dict/merge_indent/main.k diff --git a/test/grammar/datatype/dict/merge_indent/stdout.golden b/tests/grammar/datatype/dict/merge_indent/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/merge_indent/stdout.golden rename to tests/grammar/datatype/dict/merge_indent/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_0/main.k b/tests/grammar/datatype/dict/mutual_ref_0/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_0/main.k rename to tests/grammar/datatype/dict/mutual_ref_0/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_0/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_0/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_0/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_0/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_1/main.k b/tests/grammar/datatype/dict/mutual_ref_1/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_1/main.k rename to tests/grammar/datatype/dict/mutual_ref_1/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_1/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_1/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_1/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_1/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_10/main.k b/tests/grammar/datatype/dict/mutual_ref_10/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_10/main.k rename to tests/grammar/datatype/dict/mutual_ref_10/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_10/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_10/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_10/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_10/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_11/main.k b/tests/grammar/datatype/dict/mutual_ref_11/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_11/main.k rename to tests/grammar/datatype/dict/mutual_ref_11/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_11/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_11/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_11/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_11/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_12/main.k b/tests/grammar/datatype/dict/mutual_ref_12/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_12/main.k rename to tests/grammar/datatype/dict/mutual_ref_12/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_12/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_12/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_12/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_12/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_13/main.k b/tests/grammar/datatype/dict/mutual_ref_13/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_13/main.k rename to tests/grammar/datatype/dict/mutual_ref_13/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_13/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_13/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_13/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_13/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_14/main.k b/tests/grammar/datatype/dict/mutual_ref_14/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_14/main.k rename to tests/grammar/datatype/dict/mutual_ref_14/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_14/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_14/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_14/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_14/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_15/main.k b/tests/grammar/datatype/dict/mutual_ref_15/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_15/main.k rename to tests/grammar/datatype/dict/mutual_ref_15/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_15/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_15/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_15/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_15/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_16/main.k b/tests/grammar/datatype/dict/mutual_ref_16/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_16/main.k rename to tests/grammar/datatype/dict/mutual_ref_16/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_16/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_16/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_16/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_16/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_2/main.k b/tests/grammar/datatype/dict/mutual_ref_2/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_2/main.k rename to tests/grammar/datatype/dict/mutual_ref_2/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_2/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_2/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_2/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_2/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_3/main.k b/tests/grammar/datatype/dict/mutual_ref_3/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_3/main.k rename to tests/grammar/datatype/dict/mutual_ref_3/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_3/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_3/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_3/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_3/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_4/main.k b/tests/grammar/datatype/dict/mutual_ref_4/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_4/main.k rename to tests/grammar/datatype/dict/mutual_ref_4/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_4/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_4/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_4/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_4/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_5/main.k b/tests/grammar/datatype/dict/mutual_ref_5/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_5/main.k rename to tests/grammar/datatype/dict/mutual_ref_5/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_5/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_5/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_5/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_5/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_6/main.k b/tests/grammar/datatype/dict/mutual_ref_6/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_6/main.k rename to tests/grammar/datatype/dict/mutual_ref_6/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_6/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_6/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_6/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_6/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_7/main.k b/tests/grammar/datatype/dict/mutual_ref_7/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_7/main.k rename to tests/grammar/datatype/dict/mutual_ref_7/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_7/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_7/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_7/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_7/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_8/main.k b/tests/grammar/datatype/dict/mutual_ref_8/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_8/main.k rename to tests/grammar/datatype/dict/mutual_ref_8/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_8/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_8/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_8/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_8/stdout.golden diff --git a/test/grammar/datatype/dict/mutual_ref_9/main.k b/tests/grammar/datatype/dict/mutual_ref_9/main.k similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_9/main.k rename to tests/grammar/datatype/dict/mutual_ref_9/main.k diff --git a/test/grammar/datatype/dict/mutual_ref_9/stdout.golden b/tests/grammar/datatype/dict/mutual_ref_9/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/mutual_ref_9/stdout.golden rename to tests/grammar/datatype/dict/mutual_ref_9/stdout.golden diff --git a/test/grammar/datatype/dict/override_0/main.k b/tests/grammar/datatype/dict/override_0/main.k similarity index 100% rename from test/grammar/datatype/dict/override_0/main.k rename to tests/grammar/datatype/dict/override_0/main.k diff --git a/test/grammar/datatype/dict/override_0/stdout.golden b/tests/grammar/datatype/dict/override_0/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/override_0/stdout.golden rename to tests/grammar/datatype/dict/override_0/stdout.golden diff --git a/test/grammar/datatype/dict/override_1/main.k b/tests/grammar/datatype/dict/override_1/main.k similarity index 100% rename from test/grammar/datatype/dict/override_1/main.k rename to tests/grammar/datatype/dict/override_1/main.k diff --git a/test/grammar/datatype/dict/override_1/stdout.golden b/tests/grammar/datatype/dict/override_1/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/override_1/stdout.golden rename to tests/grammar/datatype/dict/override_1/stdout.golden diff --git a/test/grammar/datatype/dict/select_0/main.k b/tests/grammar/datatype/dict/select_0/main.k similarity index 100% rename from test/grammar/datatype/dict/select_0/main.k rename to tests/grammar/datatype/dict/select_0/main.k diff --git a/test/grammar/datatype/dict/select_0/stdout.golden b/tests/grammar/datatype/dict/select_0/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/select_0/stdout.golden rename to tests/grammar/datatype/dict/select_0/stdout.golden diff --git a/test/grammar/datatype/dict/select_1/main.k b/tests/grammar/datatype/dict/select_1/main.k similarity index 100% rename from test/grammar/datatype/dict/select_1/main.k rename to tests/grammar/datatype/dict/select_1/main.k diff --git a/test/grammar/datatype/dict/select_1/stdout.golden b/tests/grammar/datatype/dict/select_1/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/select_1/stdout.golden rename to tests/grammar/datatype/dict/select_1/stdout.golden diff --git a/test/grammar/datatype/dict/string_call_in_comprehension/main.k b/tests/grammar/datatype/dict/string_call_in_comprehension/main.k similarity index 100% rename from test/grammar/datatype/dict/string_call_in_comprehension/main.k rename to tests/grammar/datatype/dict/string_call_in_comprehension/main.k diff --git a/test/grammar/datatype/dict/string_call_in_comprehension/stdout.golden b/tests/grammar/datatype/dict/string_call_in_comprehension/stdout.golden similarity index 100% rename from test/grammar/datatype/dict/string_call_in_comprehension/stdout.golden rename to tests/grammar/datatype/dict/string_call_in_comprehension/stdout.golden diff --git a/test/grammar/datatype/int/int_0/main.k b/tests/grammar/datatype/int/int_0/main.k similarity index 100% rename from test/grammar/datatype/int/int_0/main.k rename to tests/grammar/datatype/int/int_0/main.k diff --git a/test/grammar/datatype/int/int_0/stdout.golden b/tests/grammar/datatype/int/int_0/stdout.golden similarity index 100% rename from test/grammar/datatype/int/int_0/stdout.golden rename to tests/grammar/datatype/int/int_0/stdout.golden diff --git a/test/grammar/datatype/list/add_0/main.k b/tests/grammar/datatype/list/add_0/main.k similarity index 100% rename from test/grammar/datatype/list/add_0/main.k rename to tests/grammar/datatype/list/add_0/main.k diff --git a/test/grammar/datatype/list/add_0/stdout.golden b/tests/grammar/datatype/list/add_0/stdout.golden similarity index 100% rename from test/grammar/datatype/list/add_0/stdout.golden rename to tests/grammar/datatype/list/add_0/stdout.golden diff --git a/test/grammar/datatype/list/add_1/main.k b/tests/grammar/datatype/list/add_1/main.k similarity index 100% rename from test/grammar/datatype/list/add_1/main.k rename to tests/grammar/datatype/list/add_1/main.k diff --git a/test/grammar/datatype/list/add_1/stdout.golden b/tests/grammar/datatype/list/add_1/stdout.golden similarity index 100% rename from test/grammar/datatype/list/add_1/stdout.golden rename to tests/grammar/datatype/list/add_1/stdout.golden diff --git a/test/grammar/datatype/list/add_2/main.k b/tests/grammar/datatype/list/add_2/main.k similarity index 100% rename from test/grammar/datatype/list/add_2/main.k rename to tests/grammar/datatype/list/add_2/main.k diff --git a/test/grammar/datatype/list/add_2/stdout.golden b/tests/grammar/datatype/list/add_2/stdout.golden similarity index 100% rename from test/grammar/datatype/list/add_2/stdout.golden rename to tests/grammar/datatype/list/add_2/stdout.golden diff --git a/test/grammar/datatype/list/add_None_0/main.k b/tests/grammar/datatype/list/add_None_0/main.k similarity index 100% rename from test/grammar/datatype/list/add_None_0/main.k rename to tests/grammar/datatype/list/add_None_0/main.k diff --git a/test/grammar/datatype/list/add_None_0/stdout.golden b/tests/grammar/datatype/list/add_None_0/stdout.golden similarity index 100% rename from test/grammar/datatype/list/add_None_0/stdout.golden rename to tests/grammar/datatype/list/add_None_0/stdout.golden diff --git a/test/grammar/datatype/list/add_None_1/main.k b/tests/grammar/datatype/list/add_None_1/main.k similarity index 100% rename from test/grammar/datatype/list/add_None_1/main.k rename to tests/grammar/datatype/list/add_None_1/main.k diff --git a/test/grammar/datatype/list/add_None_1/stdout.golden b/tests/grammar/datatype/list/add_None_1/stdout.golden similarity index 100% rename from test/grammar/datatype/list/add_None_1/stdout.golden rename to tests/grammar/datatype/list/add_None_1/stdout.golden diff --git a/test/grammar/datatype/list/add_None_fail/main.k b/tests/grammar/datatype/list/add_None_fail/main.k similarity index 100% rename from test/grammar/datatype/list/add_None_fail/main.k rename to tests/grammar/datatype/list/add_None_fail/main.k diff --git a/test/grammar/datatype/list/add_None_fail/stderr.golden b/tests/grammar/datatype/list/add_None_fail/stderr.golden similarity index 100% rename from test/grammar/datatype/list/add_None_fail/stderr.golden rename to tests/grammar/datatype/list/add_None_fail/stderr.golden diff --git a/test/grammar/datatype/list/add_if_expr/main.k b/tests/grammar/datatype/list/add_if_expr/main.k similarity index 100% rename from test/grammar/datatype/list/add_if_expr/main.k rename to tests/grammar/datatype/list/add_if_expr/main.k diff --git a/test/grammar/datatype/list/add_if_expr/stdout.golden b/tests/grammar/datatype/list/add_if_expr/stdout.golden similarity index 100% rename from test/grammar/datatype/list/add_if_expr/stdout.golden rename to tests/grammar/datatype/list/add_if_expr/stdout.golden diff --git a/test/grammar/datatype/list/if_item_0/main.k b/tests/grammar/datatype/list/if_item_0/main.k similarity index 100% rename from test/grammar/datatype/list/if_item_0/main.k rename to tests/grammar/datatype/list/if_item_0/main.k diff --git a/test/grammar/datatype/list/if_item_0/stdout.golden b/tests/grammar/datatype/list/if_item_0/stdout.golden similarity index 100% rename from test/grammar/datatype/list/if_item_0/stdout.golden rename to tests/grammar/datatype/list/if_item_0/stdout.golden diff --git a/test/grammar/datatype/list/if_item_1/main.k b/tests/grammar/datatype/list/if_item_1/main.k similarity index 100% rename from test/grammar/datatype/list/if_item_1/main.k rename to tests/grammar/datatype/list/if_item_1/main.k diff --git a/test/grammar/datatype/list/if_item_1/stdout.golden b/tests/grammar/datatype/list/if_item_1/stdout.golden similarity index 100% rename from test/grammar/datatype/list/if_item_1/stdout.golden rename to tests/grammar/datatype/list/if_item_1/stdout.golden diff --git a/test/grammar/datatype/list/if_item_2/main.k b/tests/grammar/datatype/list/if_item_2/main.k similarity index 100% rename from test/grammar/datatype/list/if_item_2/main.k rename to tests/grammar/datatype/list/if_item_2/main.k diff --git a/test/grammar/datatype/list/if_item_2/stdout.golden b/tests/grammar/datatype/list/if_item_2/stdout.golden similarity index 100% rename from test/grammar/datatype/list/if_item_2/stdout.golden rename to tests/grammar/datatype/list/if_item_2/stdout.golden diff --git a/test/grammar/datatype/list/if_item_3/main.k b/tests/grammar/datatype/list/if_item_3/main.k similarity index 100% rename from test/grammar/datatype/list/if_item_3/main.k rename to tests/grammar/datatype/list/if_item_3/main.k diff --git a/test/grammar/datatype/list/if_item_3/stdout.golden b/tests/grammar/datatype/list/if_item_3/stdout.golden similarity index 100% rename from test/grammar/datatype/list/if_item_3/stdout.golden rename to tests/grammar/datatype/list/if_item_3/stdout.golden diff --git a/test/grammar/datatype/list/if_item_4/main.k b/tests/grammar/datatype/list/if_item_4/main.k similarity index 100% rename from test/grammar/datatype/list/if_item_4/main.k rename to tests/grammar/datatype/list/if_item_4/main.k diff --git a/test/grammar/datatype/list/if_item_4/stdout.golden b/tests/grammar/datatype/list/if_item_4/stdout.golden similarity index 100% rename from test/grammar/datatype/list/if_item_4/stdout.golden rename to tests/grammar/datatype/list/if_item_4/stdout.golden diff --git a/test/grammar/datatype/list/if_item_5/main.k b/tests/grammar/datatype/list/if_item_5/main.k similarity index 100% rename from test/grammar/datatype/list/if_item_5/main.k rename to tests/grammar/datatype/list/if_item_5/main.k diff --git a/test/grammar/datatype/list/if_item_5/stdout.golden b/tests/grammar/datatype/list/if_item_5/stdout.golden similarity index 100% rename from test/grammar/datatype/list/if_item_5/stdout.golden rename to tests/grammar/datatype/list/if_item_5/stdout.golden diff --git a/test/grammar/datatype/list/if_item_6/main.k b/tests/grammar/datatype/list/if_item_6/main.k similarity index 100% rename from test/grammar/datatype/list/if_item_6/main.k rename to tests/grammar/datatype/list/if_item_6/main.k diff --git a/test/grammar/datatype/list/if_item_6/stdout.golden b/tests/grammar/datatype/list/if_item_6/stdout.golden similarity index 100% rename from test/grammar/datatype/list/if_item_6/stdout.golden rename to tests/grammar/datatype/list/if_item_6/stdout.golden diff --git a/test/grammar/datatype/list/if_item_7/main.k b/tests/grammar/datatype/list/if_item_7/main.k similarity index 100% rename from test/grammar/datatype/list/if_item_7/main.k rename to tests/grammar/datatype/list/if_item_7/main.k diff --git a/test/grammar/datatype/list/if_item_7/stdout.golden b/tests/grammar/datatype/list/if_item_7/stdout.golden similarity index 100% rename from test/grammar/datatype/list/if_item_7/stdout.golden rename to tests/grammar/datatype/list/if_item_7/stdout.golden diff --git a/test/grammar/datatype/list/if_item_8/main.k b/tests/grammar/datatype/list/if_item_8/main.k similarity index 100% rename from test/grammar/datatype/list/if_item_8/main.k rename to tests/grammar/datatype/list/if_item_8/main.k diff --git a/test/grammar/datatype/list/if_item_8/stdout.golden b/tests/grammar/datatype/list/if_item_8/stdout.golden similarity index 100% rename from test/grammar/datatype/list/if_item_8/stdout.golden rename to tests/grammar/datatype/list/if_item_8/stdout.golden diff --git a/test/grammar/datatype/list/merge_dict/main.k b/tests/grammar/datatype/list/merge_dict/main.k similarity index 100% rename from test/grammar/datatype/list/merge_dict/main.k rename to tests/grammar/datatype/list/merge_dict/main.k diff --git a/test/grammar/datatype/list/merge_dict/stdout.golden b/tests/grammar/datatype/list/merge_dict/stdout.golden similarity index 100% rename from test/grammar/datatype/list/merge_dict/stdout.golden rename to tests/grammar/datatype/list/merge_dict/stdout.golden diff --git a/test/grammar/datatype/list/slice/main.k b/tests/grammar/datatype/list/slice/main.k similarity index 100% rename from test/grammar/datatype/list/slice/main.k rename to tests/grammar/datatype/list/slice/main.k diff --git a/test/grammar/datatype/list/slice/stdout.golden b/tests/grammar/datatype/list/slice/stdout.golden similarity index 100% rename from test/grammar/datatype/list/slice/stdout.golden rename to tests/grammar/datatype/list/slice/stdout.golden diff --git a/test/grammar/datatype/range_check_float/normal/main.k b/tests/grammar/datatype/range_check_float/normal/main.k similarity index 100% rename from test/grammar/datatype/range_check_float/normal/main.k rename to tests/grammar/datatype/range_check_float/normal/main.k diff --git a/test/grammar/datatype/range_check_float/normal/stdout.golden b/tests/grammar/datatype/range_check_float/normal/stdout.golden similarity index 100% rename from test/grammar/datatype/range_check_float/normal/stdout.golden rename to tests/grammar/datatype/range_check_float/normal/stdout.golden diff --git a/test/grammar/datatype/range_check_float/overflow/inf/main.k b/tests/grammar/datatype/range_check_float/overflow/inf/main.k similarity index 100% rename from test/grammar/datatype/range_check_float/overflow/inf/main.k rename to tests/grammar/datatype/range_check_float/overflow/inf/main.k diff --git a/test/grammar/datatype/range_check_float/overflow/inf/settings.yaml b/tests/grammar/datatype/range_check_float/overflow/inf/settings.yaml similarity index 100% rename from test/grammar/datatype/range_check_float/overflow/inf/settings.yaml rename to tests/grammar/datatype/range_check_float/overflow/inf/settings.yaml diff --git a/test/grammar/datatype/range_check_float/overflow/inf/stderr.golden b/tests/grammar/datatype/range_check_float/overflow/inf/stderr.golden similarity index 100% rename from test/grammar/datatype/range_check_float/overflow/inf/stderr.golden rename to tests/grammar/datatype/range_check_float/overflow/inf/stderr.golden diff --git a/test/grammar/datatype/range_check_float/overflow/number_0/main.k b/tests/grammar/datatype/range_check_float/overflow/number_0/main.k similarity index 100% rename from test/grammar/datatype/range_check_float/overflow/number_0/main.k rename to tests/grammar/datatype/range_check_float/overflow/number_0/main.k diff --git a/test/grammar/datatype/range_check_float/overflow/number_0/settings.yaml b/tests/grammar/datatype/range_check_float/overflow/number_0/settings.yaml similarity index 100% rename from test/grammar/datatype/range_check_float/overflow/number_0/settings.yaml rename to tests/grammar/datatype/range_check_float/overflow/number_0/settings.yaml diff --git a/tests/grammar/datatype/range_check_float/overflow/number_0/stderr.golden b/tests/grammar/datatype/range_check_float/overflow/number_0/stderr.golden new file mode 100644 index 000000000..ff0121b71 --- /dev/null +++ b/tests/grammar/datatype/range_check_float/overflow/number_0/stderr.golden @@ -0,0 +1,9 @@ +error[E3M38]: EvaluationError + --> ${CWD}/main.k:8:1 + | +8 | a = uplimit * (100 + epsilon) + | 3.4e+40: A 32-bit floating point number overflow + | +note: backtrace: + 0: kcl_main + at ${CWD}/main.k:8 \ No newline at end of file diff --git a/test/grammar/datatype/range_check_float/overflow/number_1/main.k b/tests/grammar/datatype/range_check_float/overflow/number_1/main.k similarity index 100% rename from test/grammar/datatype/range_check_float/overflow/number_1/main.k rename to tests/grammar/datatype/range_check_float/overflow/number_1/main.k diff --git a/test/grammar/datatype/range_check_float/overflow/number_1/settings.yaml b/tests/grammar/datatype/range_check_float/overflow/number_1/settings.yaml similarity index 100% rename from test/grammar/datatype/range_check_float/overflow/number_1/settings.yaml rename to tests/grammar/datatype/range_check_float/overflow/number_1/settings.yaml diff --git a/test/grammar/datatype/range_check_float/overflow/number_1/stdout.golden b/tests/grammar/datatype/range_check_float/overflow/number_1/stdout.golden similarity index 100% rename from test/grammar/datatype/range_check_float/overflow/number_1/stdout.golden rename to tests/grammar/datatype/range_check_float/overflow/number_1/stdout.golden diff --git a/test/grammar/datatype/range_check_float/underflow/number_0/_main.k b/tests/grammar/datatype/range_check_float/underflow/number_0/_main.k similarity index 100% rename from test/grammar/datatype/range_check_float/underflow/number_0/_main.k rename to tests/grammar/datatype/range_check_float/underflow/number_0/_main.k diff --git a/test/grammar/datatype/range_check_float/underflow/number_0/settings.yaml b/tests/grammar/datatype/range_check_float/underflow/number_0/settings.yaml similarity index 100% rename from test/grammar/datatype/range_check_float/underflow/number_0/settings.yaml rename to tests/grammar/datatype/range_check_float/underflow/number_0/settings.yaml diff --git a/test/grammar/datatype/range_check_float/underflow/number_0/stderr.golden b/tests/grammar/datatype/range_check_float/underflow/number_0/stderr.golden similarity index 100% rename from test/grammar/datatype/range_check_float/underflow/number_0/stderr.golden rename to tests/grammar/datatype/range_check_float/underflow/number_0/stderr.golden diff --git a/test/grammar/datatype/range_check_float/underflow/number_1/_main.k b/tests/grammar/datatype/range_check_float/underflow/number_1/_main.k similarity index 100% rename from test/grammar/datatype/range_check_float/underflow/number_1/_main.k rename to tests/grammar/datatype/range_check_float/underflow/number_1/_main.k diff --git a/test/grammar/datatype/range_check_float/underflow/number_1/settings.yaml b/tests/grammar/datatype/range_check_float/underflow/number_1/settings.yaml similarity index 100% rename from test/grammar/datatype/range_check_float/underflow/number_1/settings.yaml rename to tests/grammar/datatype/range_check_float/underflow/number_1/settings.yaml diff --git a/test/grammar/datatype/range_check_float/underflow/number_1/stdout.golden b/tests/grammar/datatype/range_check_float/underflow/number_1/stdout.golden similarity index 100% rename from test/grammar/datatype/range_check_float/underflow/number_1/stdout.golden rename to tests/grammar/datatype/range_check_float/underflow/number_1/stdout.golden diff --git a/test/grammar/datatype/range_check_int/augment_assign_fail_0/main.k b/tests/grammar/datatype/range_check_int/augment_assign_fail_0/main.k similarity index 100% rename from test/grammar/datatype/range_check_int/augment_assign_fail_0/main.k rename to tests/grammar/datatype/range_check_int/augment_assign_fail_0/main.k diff --git a/test/grammar/datatype/range_check_int/augment_assign_fail_0/settings.yaml b/tests/grammar/datatype/range_check_int/augment_assign_fail_0/settings.yaml similarity index 100% rename from test/grammar/datatype/range_check_int/augment_assign_fail_0/settings.yaml rename to tests/grammar/datatype/range_check_int/augment_assign_fail_0/settings.yaml diff --git a/tests/grammar/datatype/range_check_int/augment_assign_fail_0/stderr.golden b/tests/grammar/datatype/range_check_int/augment_assign_fail_0/stderr.golden new file mode 100644 index 000000000..aeb0c2380 --- /dev/null +++ b/tests/grammar/datatype/range_check_int/augment_assign_fail_0/stderr.golden @@ -0,0 +1,9 @@ +error[E3M38]: EvaluationError + --> ${CWD}/main.k:2:1 + | +2 | _a += 1 + | 2147483648: A 32 bit integer overflow + | +note: backtrace: + 0: kcl_main + at ${CWD}/main.k:2 \ No newline at end of file diff --git a/test/grammar/datatype/range_check_int/augment_assign_fail_1/main.k b/tests/grammar/datatype/range_check_int/augment_assign_fail_1/main.k similarity index 100% rename from test/grammar/datatype/range_check_int/augment_assign_fail_1/main.k rename to tests/grammar/datatype/range_check_int/augment_assign_fail_1/main.k diff --git a/test/grammar/datatype/range_check_int/augment_assign_fail_1/settings.yaml b/tests/grammar/datatype/range_check_int/augment_assign_fail_1/settings.yaml similarity index 100% rename from test/grammar/datatype/range_check_int/augment_assign_fail_1/settings.yaml rename to tests/grammar/datatype/range_check_int/augment_assign_fail_1/settings.yaml diff --git a/tests/grammar/datatype/range_check_int/augment_assign_fail_1/stderr.golden b/tests/grammar/datatype/range_check_int/augment_assign_fail_1/stderr.golden new file mode 100644 index 000000000..242ef4676 --- /dev/null +++ b/tests/grammar/datatype/range_check_int/augment_assign_fail_1/stderr.golden @@ -0,0 +1,9 @@ +error[E3M38]: EvaluationError + --> ${CWD}/main.k:2:1 + | +2 | _a += 1 + | 9223372036854775808: A 64 bit integer overflow + | +note: backtrace: + 0: kcl_main + at ${CWD}/main.k:2 \ No newline at end of file diff --git a/test/grammar/datatype/range_check_int/augment_assign_fail_2/main.k b/tests/grammar/datatype/range_check_int/augment_assign_fail_2/main.k similarity index 100% rename from test/grammar/datatype/range_check_int/augment_assign_fail_2/main.k rename to tests/grammar/datatype/range_check_int/augment_assign_fail_2/main.k diff --git a/test/grammar/datatype/range_check_int/augment_assign_fail_2/settings.yaml b/tests/grammar/datatype/range_check_int/augment_assign_fail_2/settings.yaml similarity index 100% rename from test/grammar/datatype/range_check_int/augment_assign_fail_2/settings.yaml rename to tests/grammar/datatype/range_check_int/augment_assign_fail_2/settings.yaml diff --git a/tests/grammar/datatype/range_check_int/augment_assign_fail_2/stderr.golden b/tests/grammar/datatype/range_check_int/augment_assign_fail_2/stderr.golden new file mode 100644 index 000000000..242ef4676 --- /dev/null +++ b/tests/grammar/datatype/range_check_int/augment_assign_fail_2/stderr.golden @@ -0,0 +1,9 @@ +error[E3M38]: EvaluationError + --> ${CWD}/main.k:2:1 + | +2 | _a += 1 + | 9223372036854775808: A 64 bit integer overflow + | +note: backtrace: + 0: kcl_main + at ${CWD}/main.k:2 \ No newline at end of file diff --git a/test/grammar/datatype/range_check_int/augment_assign_fail_3/main.k b/tests/grammar/datatype/range_check_int/augment_assign_fail_3/main.k similarity index 100% rename from test/grammar/datatype/range_check_int/augment_assign_fail_3/main.k rename to tests/grammar/datatype/range_check_int/augment_assign_fail_3/main.k diff --git a/test/grammar/datatype/range_check_int/augment_assign_fail_3/settings.yaml b/tests/grammar/datatype/range_check_int/augment_assign_fail_3/settings.yaml similarity index 100% rename from test/grammar/datatype/range_check_int/augment_assign_fail_3/settings.yaml rename to tests/grammar/datatype/range_check_int/augment_assign_fail_3/settings.yaml diff --git a/tests/grammar/datatype/range_check_int/augment_assign_fail_3/stderr.golden b/tests/grammar/datatype/range_check_int/augment_assign_fail_3/stderr.golden new file mode 100644 index 000000000..aeb0c2380 --- /dev/null +++ b/tests/grammar/datatype/range_check_int/augment_assign_fail_3/stderr.golden @@ -0,0 +1,9 @@ +error[E3M38]: EvaluationError + --> ${CWD}/main.k:2:1 + | +2 | _a += 1 + | 2147483648: A 32 bit integer overflow + | +note: backtrace: + 0: kcl_main + at ${CWD}/main.k:2 \ No newline at end of file diff --git a/test/grammar/datatype/range_check_int/augment_assign_fail_4/main.k b/tests/grammar/datatype/range_check_int/augment_assign_fail_4/main.k similarity index 100% rename from test/grammar/datatype/range_check_int/augment_assign_fail_4/main.k rename to tests/grammar/datatype/range_check_int/augment_assign_fail_4/main.k diff --git a/test/grammar/datatype/range_check_int/augment_assign_fail_4/stderr.golden b/tests/grammar/datatype/range_check_int/augment_assign_fail_4/stderr.golden similarity index 100% rename from test/grammar/datatype/range_check_int/augment_assign_fail_4/stderr.golden rename to tests/grammar/datatype/range_check_int/augment_assign_fail_4/stderr.golden diff --git a/test/grammar/datatype/range_check_int/dict/main.k b/tests/grammar/datatype/range_check_int/dict/main.k similarity index 100% rename from test/grammar/datatype/range_check_int/dict/main.k rename to tests/grammar/datatype/range_check_int/dict/main.k diff --git a/test/grammar/datatype/range_check_int/dict/stdout.golden b/tests/grammar/datatype/range_check_int/dict/stdout.golden similarity index 100% rename from test/grammar/datatype/range_check_int/dict/stdout.golden rename to tests/grammar/datatype/range_check_int/dict/stdout.golden diff --git a/test/grammar/datatype/range_check_int/list/main.k b/tests/grammar/datatype/range_check_int/list/main.k similarity index 100% rename from test/grammar/datatype/range_check_int/list/main.k rename to tests/grammar/datatype/range_check_int/list/main.k diff --git a/test/grammar/datatype/range_check_int/list/stdout.golden b/tests/grammar/datatype/range_check_int/list/stdout.golden similarity index 100% rename from test/grammar/datatype/range_check_int/list/stdout.golden rename to tests/grammar/datatype/range_check_int/list/stdout.golden diff --git a/test/grammar/datatype/range_check_int/normal_assign/main.k b/tests/grammar/datatype/range_check_int/normal_assign/main.k similarity index 100% rename from test/grammar/datatype/range_check_int/normal_assign/main.k rename to tests/grammar/datatype/range_check_int/normal_assign/main.k diff --git a/test/grammar/datatype/range_check_int/normal_assign/stdout.golden b/tests/grammar/datatype/range_check_int/normal_assign/stdout.golden similarity index 100% rename from test/grammar/datatype/range_check_int/normal_assign/stdout.golden rename to tests/grammar/datatype/range_check_int/normal_assign/stdout.golden diff --git a/test/grammar/datatype/range_check_int/normal_assign_fail_0/main.k b/tests/grammar/datatype/range_check_int/normal_assign_fail_0/main.k similarity index 100% rename from test/grammar/datatype/range_check_int/normal_assign_fail_0/main.k rename to tests/grammar/datatype/range_check_int/normal_assign_fail_0/main.k diff --git a/test/grammar/datatype/range_check_int/normal_assign_fail_0/settings.yaml b/tests/grammar/datatype/range_check_int/normal_assign_fail_0/settings.yaml similarity index 100% rename from test/grammar/datatype/range_check_int/normal_assign_fail_0/settings.yaml rename to tests/grammar/datatype/range_check_int/normal_assign_fail_0/settings.yaml diff --git a/test/grammar/datatype/range_check_int/normal_assign_fail_0/stderr.golden b/tests/grammar/datatype/range_check_int/normal_assign_fail_0/stderr.golden similarity index 100% rename from test/grammar/datatype/range_check_int/normal_assign_fail_0/stderr.golden rename to tests/grammar/datatype/range_check_int/normal_assign_fail_0/stderr.golden diff --git a/test/grammar/datatype/range_check_int/oneliner/main.k b/tests/grammar/datatype/range_check_int/oneliner/main.k similarity index 100% rename from test/grammar/datatype/range_check_int/oneliner/main.k rename to tests/grammar/datatype/range_check_int/oneliner/main.k diff --git a/test/grammar/datatype/range_check_int/oneliner/settings.yaml b/tests/grammar/datatype/range_check_int/oneliner/settings.yaml similarity index 100% rename from test/grammar/datatype/range_check_int/oneliner/settings.yaml rename to tests/grammar/datatype/range_check_int/oneliner/settings.yaml diff --git a/test/grammar/datatype/range_check_int/oneliner/stdout.golden b/tests/grammar/datatype/range_check_int/oneliner/stdout.golden similarity index 100% rename from test/grammar/datatype/range_check_int/oneliner/stdout.golden rename to tests/grammar/datatype/range_check_int/oneliner/stdout.golden diff --git a/test/grammar/datatype/str/count_0/main.k b/tests/grammar/datatype/str/count_0/main.k similarity index 100% rename from test/grammar/datatype/str/count_0/main.k rename to tests/grammar/datatype/str/count_0/main.k diff --git a/test/grammar/datatype/str/count_0/stdout.golden b/tests/grammar/datatype/str/count_0/stdout.golden similarity index 100% rename from test/grammar/datatype/str/count_0/stdout.golden rename to tests/grammar/datatype/str/count_0/stdout.golden diff --git a/test/grammar/datatype/str/index_0/main.k b/tests/grammar/datatype/str/index_0/main.k similarity index 100% rename from test/grammar/datatype/str/index_0/main.k rename to tests/grammar/datatype/str/index_0/main.k diff --git a/test/grammar/datatype/str/index_0/stdout.golden b/tests/grammar/datatype/str/index_0/stdout.golden similarity index 100% rename from test/grammar/datatype/str/index_0/stdout.golden rename to tests/grammar/datatype/str/index_0/stdout.golden diff --git a/test/grammar/datatype/str/long_str_0/main.k b/tests/grammar/datatype/str/long_str_0/main.k similarity index 100% rename from test/grammar/datatype/str/long_str_0/main.k rename to tests/grammar/datatype/str/long_str_0/main.k diff --git a/test/grammar/datatype/str/long_str_0/stdout.golden b/tests/grammar/datatype/str/long_str_0/stdout.golden similarity index 100% rename from test/grammar/datatype/str/long_str_0/stdout.golden rename to tests/grammar/datatype/str/long_str_0/stdout.golden diff --git a/test/grammar/datatype/str/octet/main.k b/tests/grammar/datatype/str/octet/main.k similarity index 100% rename from test/grammar/datatype/str/octet/main.k rename to tests/grammar/datatype/str/octet/main.k diff --git a/test/grammar/datatype/str/octet/stdout.golden b/tests/grammar/datatype/str/octet/stdout.golden similarity index 100% rename from test/grammar/datatype/str/octet/stdout.golden rename to tests/grammar/datatype/str/octet/stdout.golden diff --git a/test/grammar/datatype/str/slice_0/main.k b/tests/grammar/datatype/str/slice_0/main.k similarity index 100% rename from test/grammar/datatype/str/slice_0/main.k rename to tests/grammar/datatype/str/slice_0/main.k diff --git a/test/grammar/datatype/str/slice_0/stdout.golden b/tests/grammar/datatype/str/slice_0/stdout.golden similarity index 100% rename from test/grammar/datatype/str/slice_0/stdout.golden rename to tests/grammar/datatype/str/slice_0/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/complex_0/main.k b/tests/grammar/datatype/str_interpolation/complex_0/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/complex_0/main.k rename to tests/grammar/datatype/str_interpolation/complex_0/main.k diff --git a/test/grammar/datatype/str_interpolation/complex_0/stdout.golden b/tests/grammar/datatype/str_interpolation/complex_0/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/complex_0/stdout.golden rename to tests/grammar/datatype/str_interpolation/complex_0/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/complex_1/main.k b/tests/grammar/datatype/str_interpolation/complex_1/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/complex_1/main.k rename to tests/grammar/datatype/str_interpolation/complex_1/main.k diff --git a/test/grammar/datatype/str_interpolation/complex_1/stdout.golden b/tests/grammar/datatype/str_interpolation/complex_1/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/complex_1/stdout.golden rename to tests/grammar/datatype/str_interpolation/complex_1/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/complex_2/kcl.mod b/tests/grammar/datatype/str_interpolation/complex_2/kcl.mod similarity index 100% rename from test/grammar/datatype/str_interpolation/complex_2/kcl.mod rename to tests/grammar/datatype/str_interpolation/complex_2/kcl.mod diff --git a/test/grammar/datatype/str_interpolation/complex_2/main.k b/tests/grammar/datatype/str_interpolation/complex_2/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/complex_2/main.k rename to tests/grammar/datatype/str_interpolation/complex_2/main.k diff --git a/test/grammar/datatype/str_interpolation/complex_2/pkg/pkg.k b/tests/grammar/datatype/str_interpolation/complex_2/pkg/pkg.k similarity index 100% rename from test/grammar/datatype/str_interpolation/complex_2/pkg/pkg.k rename to tests/grammar/datatype/str_interpolation/complex_2/pkg/pkg.k diff --git a/test/grammar/datatype/str_interpolation/complex_2/stdout.golden b/tests/grammar/datatype/str_interpolation/complex_2/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/complex_2/stdout.golden rename to tests/grammar/datatype/str_interpolation/complex_2/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/complex_3/kcl.mod b/tests/grammar/datatype/str_interpolation/complex_3/kcl.mod similarity index 100% rename from test/grammar/datatype/str_interpolation/complex_3/kcl.mod rename to tests/grammar/datatype/str_interpolation/complex_3/kcl.mod diff --git a/test/grammar/datatype/str_interpolation/complex_3/main.k b/tests/grammar/datatype/str_interpolation/complex_3/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/complex_3/main.k rename to tests/grammar/datatype/str_interpolation/complex_3/main.k diff --git a/test/grammar/datatype/str_interpolation/complex_3/pkg/pkg.k b/tests/grammar/datatype/str_interpolation/complex_3/pkg/pkg.k similarity index 100% rename from test/grammar/datatype/str_interpolation/complex_3/pkg/pkg.k rename to tests/grammar/datatype/str_interpolation/complex_3/pkg/pkg.k diff --git a/test/grammar/datatype/str_interpolation/complex_3/stdout.golden b/tests/grammar/datatype/str_interpolation/complex_3/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/complex_3/stdout.golden rename to tests/grammar/datatype/str_interpolation/complex_3/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/dollar_escape_0/main.k b/tests/grammar/datatype/str_interpolation/dollar_escape_0/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/dollar_escape_0/main.k rename to tests/grammar/datatype/str_interpolation/dollar_escape_0/main.k diff --git a/test/grammar/datatype/str_interpolation/dollar_escape_0/stdout.golden b/tests/grammar/datatype/str_interpolation/dollar_escape_0/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/dollar_escape_0/stdout.golden rename to tests/grammar/datatype/str_interpolation/dollar_escape_0/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/index/main.k b/tests/grammar/datatype/str_interpolation/index/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/index/main.k rename to tests/grammar/datatype/str_interpolation/index/main.k diff --git a/test/grammar/datatype/str_interpolation/index/stdout.golden b/tests/grammar/datatype/str_interpolation/index/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/index/stdout.golden rename to tests/grammar/datatype/str_interpolation/index/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/invalid_format_spec_fail_0/main.k b/tests/grammar/datatype/str_interpolation/invalid_format_spec_fail_0/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/invalid_format_spec_fail_0/main.k rename to tests/grammar/datatype/str_interpolation/invalid_format_spec_fail_0/main.k diff --git a/test/grammar/datatype/str_interpolation/invalid_format_spec_fail_0/stderr.golden b/tests/grammar/datatype/str_interpolation/invalid_format_spec_fail_0/stderr.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/invalid_format_spec_fail_0/stderr.golden rename to tests/grammar/datatype/str_interpolation/invalid_format_spec_fail_0/stderr.golden diff --git a/test/grammar/datatype/str_interpolation/invalid_format_spec_fail_1/main.k b/tests/grammar/datatype/str_interpolation/invalid_format_spec_fail_1/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/invalid_format_spec_fail_1/main.k rename to tests/grammar/datatype/str_interpolation/invalid_format_spec_fail_1/main.k diff --git a/test/grammar/datatype/str_interpolation/invalid_format_spec_fail_1/stderr.golden b/tests/grammar/datatype/str_interpolation/invalid_format_spec_fail_1/stderr.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/invalid_format_spec_fail_1/stderr.golden rename to tests/grammar/datatype/str_interpolation/invalid_format_spec_fail_1/stderr.golden diff --git a/test/grammar/datatype/str_interpolation/invalid_format_value_fail_0/main.k b/tests/grammar/datatype/str_interpolation/invalid_format_value_fail_0/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/invalid_format_value_fail_0/main.k rename to tests/grammar/datatype/str_interpolation/invalid_format_value_fail_0/main.k diff --git a/test/grammar/datatype/str_interpolation/invalid_format_value_fail_0/stderr.golden b/tests/grammar/datatype/str_interpolation/invalid_format_value_fail_0/stderr.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/invalid_format_value_fail_0/stderr.golden rename to tests/grammar/datatype/str_interpolation/invalid_format_value_fail_0/stderr.golden diff --git a/test/grammar/datatype/str_interpolation/select/main.k b/tests/grammar/datatype/str_interpolation/select/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/select/main.k rename to tests/grammar/datatype/str_interpolation/select/main.k diff --git a/test/grammar/datatype/str_interpolation/select/stdout.golden b/tests/grammar/datatype/str_interpolation/select/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/select/stdout.golden rename to tests/grammar/datatype/str_interpolation/select/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/simple_0/main.k b/tests/grammar/datatype/str_interpolation/simple_0/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_0/main.k rename to tests/grammar/datatype/str_interpolation/simple_0/main.k diff --git a/test/grammar/datatype/str_interpolation/simple_0/stdout.golden b/tests/grammar/datatype/str_interpolation/simple_0/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_0/stdout.golden rename to tests/grammar/datatype/str_interpolation/simple_0/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/simple_1/main.k b/tests/grammar/datatype/str_interpolation/simple_1/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_1/main.k rename to tests/grammar/datatype/str_interpolation/simple_1/main.k diff --git a/test/grammar/datatype/str_interpolation/simple_1/stdout.golden b/tests/grammar/datatype/str_interpolation/simple_1/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_1/stdout.golden rename to tests/grammar/datatype/str_interpolation/simple_1/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/simple_2/main.k b/tests/grammar/datatype/str_interpolation/simple_2/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_2/main.k rename to tests/grammar/datatype/str_interpolation/simple_2/main.k diff --git a/test/grammar/datatype/str_interpolation/simple_2/stdout.golden b/tests/grammar/datatype/str_interpolation/simple_2/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_2/stdout.golden rename to tests/grammar/datatype/str_interpolation/simple_2/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/simple_3/main.k b/tests/grammar/datatype/str_interpolation/simple_3/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_3/main.k rename to tests/grammar/datatype/str_interpolation/simple_3/main.k diff --git a/test/grammar/datatype/str_interpolation/simple_3/stdout.golden b/tests/grammar/datatype/str_interpolation/simple_3/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_3/stdout.golden rename to tests/grammar/datatype/str_interpolation/simple_3/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/simple_4/main.k b/tests/grammar/datatype/str_interpolation/simple_4/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_4/main.k rename to tests/grammar/datatype/str_interpolation/simple_4/main.k diff --git a/test/grammar/datatype/str_interpolation/simple_4/stdout.golden b/tests/grammar/datatype/str_interpolation/simple_4/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_4/stdout.golden rename to tests/grammar/datatype/str_interpolation/simple_4/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/simple_json_spec_0/main.k b/tests/grammar/datatype/str_interpolation/simple_json_spec_0/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_json_spec_0/main.k rename to tests/grammar/datatype/str_interpolation/simple_json_spec_0/main.k diff --git a/test/grammar/datatype/str_interpolation/simple_json_spec_0/stdout.golden b/tests/grammar/datatype/str_interpolation/simple_json_spec_0/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_json_spec_0/stdout.golden rename to tests/grammar/datatype/str_interpolation/simple_json_spec_0/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/simple_json_spec_1/main.k b/tests/grammar/datatype/str_interpolation/simple_json_spec_1/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_json_spec_1/main.k rename to tests/grammar/datatype/str_interpolation/simple_json_spec_1/main.k diff --git a/test/grammar/datatype/str_interpolation/simple_json_spec_1/stdout.golden b/tests/grammar/datatype/str_interpolation/simple_json_spec_1/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_json_spec_1/stdout.golden rename to tests/grammar/datatype/str_interpolation/simple_json_spec_1/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/simple_yaml_spec_0/main.k b/tests/grammar/datatype/str_interpolation/simple_yaml_spec_0/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_yaml_spec_0/main.k rename to tests/grammar/datatype/str_interpolation/simple_yaml_spec_0/main.k diff --git a/test/grammar/datatype/str_interpolation/simple_yaml_spec_0/stdout.golden b/tests/grammar/datatype/str_interpolation/simple_yaml_spec_0/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_yaml_spec_0/stdout.golden rename to tests/grammar/datatype/str_interpolation/simple_yaml_spec_0/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/simple_yaml_spec_1/_main.k b/tests/grammar/datatype/str_interpolation/simple_yaml_spec_1/_main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_yaml_spec_1/_main.k rename to tests/grammar/datatype/str_interpolation/simple_yaml_spec_1/_main.k diff --git a/test/grammar/datatype/str_interpolation/simple_yaml_spec_1/stdout.golden b/tests/grammar/datatype/str_interpolation/simple_yaml_spec_1/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/simple_yaml_spec_1/stdout.golden rename to tests/grammar/datatype/str_interpolation/simple_yaml_spec_1/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/string_with_raw_prefix_0/main.k b/tests/grammar/datatype/str_interpolation/string_with_raw_prefix_0/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/string_with_raw_prefix_0/main.k rename to tests/grammar/datatype/str_interpolation/string_with_raw_prefix_0/main.k diff --git a/test/grammar/datatype/str_interpolation/string_with_raw_prefix_0/stdout.golden b/tests/grammar/datatype/str_interpolation/string_with_raw_prefix_0/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/string_with_raw_prefix_0/stdout.golden rename to tests/grammar/datatype/str_interpolation/string_with_raw_prefix_0/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/var_after_string_interpolation/main.k b/tests/grammar/datatype/str_interpolation/var_after_string_interpolation/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/var_after_string_interpolation/main.k rename to tests/grammar/datatype/str_interpolation/var_after_string_interpolation/main.k diff --git a/test/grammar/datatype/str_interpolation/var_after_string_interpolation/stdout.golden b/tests/grammar/datatype/str_interpolation/var_after_string_interpolation/stdout.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/var_after_string_interpolation/stdout.golden rename to tests/grammar/datatype/str_interpolation/var_after_string_interpolation/stdout.golden diff --git a/test/grammar/datatype/str_interpolation/var_not_define_fail_0/main.k b/tests/grammar/datatype/str_interpolation/var_not_define_fail_0/main.k similarity index 100% rename from test/grammar/datatype/str_interpolation/var_not_define_fail_0/main.k rename to tests/grammar/datatype/str_interpolation/var_not_define_fail_0/main.k diff --git a/test/grammar/datatype/str_interpolation/var_not_define_fail_0/stderr.golden b/tests/grammar/datatype/str_interpolation/var_not_define_fail_0/stderr.golden similarity index 100% rename from test/grammar/datatype/str_interpolation/var_not_define_fail_0/stderr.golden rename to tests/grammar/datatype/str_interpolation/var_not_define_fail_0/stderr.golden diff --git a/test/grammar/datatype/subscript/subscript_0/main.k b/tests/grammar/datatype/subscript/subscript_0/main.k similarity index 100% rename from test/grammar/datatype/subscript/subscript_0/main.k rename to tests/grammar/datatype/subscript/subscript_0/main.k diff --git a/test/grammar/datatype/subscript/subscript_0/stdout.golden b/tests/grammar/datatype/subscript/subscript_0/stdout.golden similarity index 100% rename from test/grammar/datatype/subscript/subscript_0/stdout.golden rename to tests/grammar/datatype/subscript/subscript_0/stdout.golden diff --git a/test/grammar/datatype/subscript/subscript_1/main.k b/tests/grammar/datatype/subscript/subscript_1/main.k similarity index 100% rename from test/grammar/datatype/subscript/subscript_1/main.k rename to tests/grammar/datatype/subscript/subscript_1/main.k diff --git a/test/grammar/datatype/subscript/subscript_1/stdout.golden b/tests/grammar/datatype/subscript/subscript_1/stdout.golden similarity index 100% rename from test/grammar/datatype/subscript/subscript_1/stdout.golden rename to tests/grammar/datatype/subscript/subscript_1/stdout.golden diff --git a/test/grammar/datatype/subscript/subscript_2/main.k b/tests/grammar/datatype/subscript/subscript_2/main.k similarity index 100% rename from test/grammar/datatype/subscript/subscript_2/main.k rename to tests/grammar/datatype/subscript/subscript_2/main.k diff --git a/test/grammar/datatype/subscript/subscript_2/stdout.golden b/tests/grammar/datatype/subscript/subscript_2/stdout.golden similarity index 100% rename from test/grammar/datatype/subscript/subscript_2/stdout.golden rename to tests/grammar/datatype/subscript/subscript_2/stdout.golden diff --git a/test/grammar/datatype/subscript/subscript_3/main.k b/tests/grammar/datatype/subscript/subscript_3/main.k similarity index 100% rename from test/grammar/datatype/subscript/subscript_3/main.k rename to tests/grammar/datatype/subscript/subscript_3/main.k diff --git a/test/grammar/datatype/subscript/subscript_3/stdout.golden b/tests/grammar/datatype/subscript/subscript_3/stdout.golden similarity index 100% rename from test/grammar/datatype/subscript/subscript_3/stdout.golden rename to tests/grammar/datatype/subscript/subscript_3/stdout.golden diff --git a/test/grammar/datatype/undefined/builtin/main.k b/tests/grammar/datatype/undefined/builtin/main.k similarity index 100% rename from test/grammar/datatype/undefined/builtin/main.k rename to tests/grammar/datatype/undefined/builtin/main.k diff --git a/test/grammar/datatype/undefined/builtin/stdout.golden b/tests/grammar/datatype/undefined/builtin/stdout.golden similarity index 100% rename from test/grammar/datatype/undefined/builtin/stdout.golden rename to tests/grammar/datatype/undefined/builtin/stdout.golden diff --git a/test/grammar/datatype/undefined/condition_0/main.k b/tests/grammar/datatype/undefined/condition_0/main.k similarity index 100% rename from test/grammar/datatype/undefined/condition_0/main.k rename to tests/grammar/datatype/undefined/condition_0/main.k diff --git a/test/grammar/datatype/undefined/condition_0/stdout.golden b/tests/grammar/datatype/undefined/condition_0/stdout.golden similarity index 100% rename from test/grammar/datatype/undefined/condition_0/stdout.golden rename to tests/grammar/datatype/undefined/condition_0/stdout.golden diff --git a/test/grammar/datatype/undefined/condition_1/main.k b/tests/grammar/datatype/undefined/condition_1/main.k similarity index 100% rename from test/grammar/datatype/undefined/condition_1/main.k rename to tests/grammar/datatype/undefined/condition_1/main.k diff --git a/test/grammar/datatype/undefined/condition_1/stdout.golden b/tests/grammar/datatype/undefined/condition_1/stdout.golden similarity index 100% rename from test/grammar/datatype/undefined/condition_1/stdout.golden rename to tests/grammar/datatype/undefined/condition_1/stdout.golden diff --git a/test/grammar/datatype/undefined/dict/main.k b/tests/grammar/datatype/undefined/dict/main.k similarity index 100% rename from test/grammar/datatype/undefined/dict/main.k rename to tests/grammar/datatype/undefined/dict/main.k diff --git a/test/grammar/datatype/undefined/dict/stdout.golden b/tests/grammar/datatype/undefined/dict/stdout.golden similarity index 100% rename from test/grammar/datatype/undefined/dict/stdout.golden rename to tests/grammar/datatype/undefined/dict/stdout.golden diff --git a/test/grammar/datatype/undefined/fail_0/main.k b/tests/grammar/datatype/undefined/fail_0/main.k similarity index 100% rename from test/grammar/datatype/undefined/fail_0/main.k rename to tests/grammar/datatype/undefined/fail_0/main.k diff --git a/test/grammar/datatype/undefined/fail_0/stderr.golden b/tests/grammar/datatype/undefined/fail_0/stderr.golden similarity index 100% rename from test/grammar/datatype/undefined/fail_0/stderr.golden rename to tests/grammar/datatype/undefined/fail_0/stderr.golden diff --git a/test/grammar/datatype/undefined/fail_1/_main.k b/tests/grammar/datatype/undefined/fail_1/_main.k similarity index 100% rename from test/grammar/datatype/undefined/fail_1/_main.k rename to tests/grammar/datatype/undefined/fail_1/_main.k diff --git a/test/grammar/datatype/undefined/fail_1/stderr.golden b/tests/grammar/datatype/undefined/fail_1/stderr.golden similarity index 100% rename from test/grammar/datatype/undefined/fail_1/stderr.golden rename to tests/grammar/datatype/undefined/fail_1/stderr.golden diff --git a/test/grammar/datatype/undefined/schema_0/main.k b/tests/grammar/datatype/undefined/schema_0/main.k similarity index 100% rename from test/grammar/datatype/undefined/schema_0/main.k rename to tests/grammar/datatype/undefined/schema_0/main.k diff --git a/test/grammar/datatype/undefined/schema_0/stdout.golden b/tests/grammar/datatype/undefined/schema_0/stdout.golden similarity index 100% rename from test/grammar/datatype/undefined/schema_0/stdout.golden rename to tests/grammar/datatype/undefined/schema_0/stdout.golden diff --git a/test/grammar/datatype/undefined/schema_1/main.k b/tests/grammar/datatype/undefined/schema_1/main.k similarity index 100% rename from test/grammar/datatype/undefined/schema_1/main.k rename to tests/grammar/datatype/undefined/schema_1/main.k diff --git a/test/grammar/datatype/undefined/schema_1/stdout.golden b/tests/grammar/datatype/undefined/schema_1/stdout.golden similarity index 100% rename from test/grammar/datatype/undefined/schema_1/stdout.golden rename to tests/grammar/datatype/undefined/schema_1/stdout.golden diff --git a/test/grammar/datatype/undefined/simple_0/main.k b/tests/grammar/datatype/undefined/simple_0/main.k similarity index 100% rename from test/grammar/datatype/undefined/simple_0/main.k rename to tests/grammar/datatype/undefined/simple_0/main.k diff --git a/test/grammar/datatype/undefined/simple_0/stdout.golden b/tests/grammar/datatype/undefined/simple_0/stdout.golden similarity index 100% rename from test/grammar/datatype/undefined/simple_0/stdout.golden rename to tests/grammar/datatype/undefined/simple_0/stdout.golden diff --git a/test/grammar/datatype/undefined/simple_1/main.k b/tests/grammar/datatype/undefined/simple_1/main.k similarity index 100% rename from test/grammar/datatype/undefined/simple_1/main.k rename to tests/grammar/datatype/undefined/simple_1/main.k diff --git a/test/grammar/datatype/undefined/simple_1/stdout.golden b/tests/grammar/datatype/undefined/simple_1/stdout.golden similarity index 100% rename from test/grammar/datatype/undefined/simple_1/stdout.golden rename to tests/grammar/datatype/undefined/simple_1/stdout.golden diff --git a/test/grammar/datatype/undefined/simple_2/main.k b/tests/grammar/datatype/undefined/simple_2/main.k similarity index 100% rename from test/grammar/datatype/undefined/simple_2/main.k rename to tests/grammar/datatype/undefined/simple_2/main.k diff --git a/test/grammar/datatype/undefined/simple_2/stdout.golden b/tests/grammar/datatype/undefined/simple_2/stdout.golden similarity index 100% rename from test/grammar/datatype/undefined/simple_2/stdout.golden rename to tests/grammar/datatype/undefined/simple_2/stdout.golden diff --git a/test/grammar/datatype/undefined/unpack/main.k b/tests/grammar/datatype/undefined/unpack/main.k similarity index 100% rename from test/grammar/datatype/undefined/unpack/main.k rename to tests/grammar/datatype/undefined/unpack/main.k diff --git a/test/grammar/datatype/undefined/unpack/stdout.golden b/tests/grammar/datatype/undefined/unpack/stdout.golden similarity index 100% rename from test/grammar/datatype/undefined/unpack/stdout.golden rename to tests/grammar/datatype/undefined/unpack/stdout.golden diff --git a/test/grammar/datatype/units/invalid_units_fail_0/main.k b/tests/grammar/datatype/units/invalid_units_fail_0/main.k similarity index 100% rename from test/grammar/datatype/units/invalid_units_fail_0/main.k rename to tests/grammar/datatype/units/invalid_units_fail_0/main.k diff --git a/test/grammar/datatype/units/invalid_units_fail_0/stderr.golden b/tests/grammar/datatype/units/invalid_units_fail_0/stderr.golden similarity index 100% rename from test/grammar/datatype/units/invalid_units_fail_0/stderr.golden rename to tests/grammar/datatype/units/invalid_units_fail_0/stderr.golden diff --git a/test/grammar/datatype/units/invalid_units_fail_1/main.k b/tests/grammar/datatype/units/invalid_units_fail_1/main.k similarity index 100% rename from test/grammar/datatype/units/invalid_units_fail_1/main.k rename to tests/grammar/datatype/units/invalid_units_fail_1/main.k diff --git a/test/grammar/datatype/units/invalid_units_fail_1/stderr.golden b/tests/grammar/datatype/units/invalid_units_fail_1/stderr.golden similarity index 100% rename from test/grammar/datatype/units/invalid_units_fail_1/stderr.golden rename to tests/grammar/datatype/units/invalid_units_fail_1/stderr.golden diff --git a/test/grammar/datatype/units/invalid_units_fail_2/main.k b/tests/grammar/datatype/units/invalid_units_fail_2/main.k similarity index 100% rename from test/grammar/datatype/units/invalid_units_fail_2/main.k rename to tests/grammar/datatype/units/invalid_units_fail_2/main.k diff --git a/test/grammar/datatype/units/invalid_units_fail_2/stderr.golden b/tests/grammar/datatype/units/invalid_units_fail_2/stderr.golden similarity index 100% rename from test/grammar/datatype/units/invalid_units_fail_2/stderr.golden rename to tests/grammar/datatype/units/invalid_units_fail_2/stderr.golden diff --git a/test/grammar/datatype/units/range_check_fail_0/main.k b/tests/grammar/datatype/units/range_check_fail_0/main.k similarity index 100% rename from test/grammar/datatype/units/range_check_fail_0/main.k rename to tests/grammar/datatype/units/range_check_fail_0/main.k diff --git a/test/grammar/datatype/units/range_check_fail_0/settings.yaml b/tests/grammar/datatype/units/range_check_fail_0/settings.yaml similarity index 100% rename from test/grammar/datatype/units/range_check_fail_0/settings.yaml rename to tests/grammar/datatype/units/range_check_fail_0/settings.yaml diff --git a/test/grammar/datatype/units/range_check_fail_0/stderr.golden b/tests/grammar/datatype/units/range_check_fail_0/stderr.golden similarity index 100% rename from test/grammar/datatype/units/range_check_fail_0/stderr.golden rename to tests/grammar/datatype/units/range_check_fail_0/stderr.golden diff --git a/test/grammar/datatype/units/range_check_fail_1/main.k b/tests/grammar/datatype/units/range_check_fail_1/main.k similarity index 100% rename from test/grammar/datatype/units/range_check_fail_1/main.k rename to tests/grammar/datatype/units/range_check_fail_1/main.k diff --git a/test/grammar/datatype/units/range_check_fail_1/settings.yaml b/tests/grammar/datatype/units/range_check_fail_1/settings.yaml similarity index 100% rename from test/grammar/datatype/units/range_check_fail_1/settings.yaml rename to tests/grammar/datatype/units/range_check_fail_1/settings.yaml diff --git a/test/grammar/datatype/units/range_check_fail_1/stderr.golden b/tests/grammar/datatype/units/range_check_fail_1/stderr.golden similarity index 100% rename from test/grammar/datatype/units/range_check_fail_1/stderr.golden rename to tests/grammar/datatype/units/range_check_fail_1/stderr.golden diff --git a/test/grammar/datatype/units/simple_0/main.k b/tests/grammar/datatype/units/simple_0/main.k similarity index 100% rename from test/grammar/datatype/units/simple_0/main.k rename to tests/grammar/datatype/units/simple_0/main.k diff --git a/test/grammar/datatype/units/simple_0/stdout.golden b/tests/grammar/datatype/units/simple_0/stdout.golden similarity index 100% rename from test/grammar/datatype/units/simple_0/stdout.golden rename to tests/grammar/datatype/units/simple_0/stdout.golden diff --git a/test/grammar/datatype/units/simple_1/main.k b/tests/grammar/datatype/units/simple_1/main.k similarity index 100% rename from test/grammar/datatype/units/simple_1/main.k rename to tests/grammar/datatype/units/simple_1/main.k diff --git a/test/grammar/datatype/units/simple_1/stdout.golden b/tests/grammar/datatype/units/simple_1/stdout.golden similarity index 100% rename from test/grammar/datatype/units/simple_1/stdout.golden rename to tests/grammar/datatype/units/simple_1/stdout.golden diff --git a/test/grammar/datatype/units/simple_2/main.k b/tests/grammar/datatype/units/simple_2/main.k similarity index 100% rename from test/grammar/datatype/units/simple_2/main.k rename to tests/grammar/datatype/units/simple_2/main.k diff --git a/test/grammar/datatype/units/simple_2/stdout.golden b/tests/grammar/datatype/units/simple_2/stdout.golden similarity index 100% rename from test/grammar/datatype/units/simple_2/stdout.golden rename to tests/grammar/datatype/units/simple_2/stdout.golden diff --git a/test/grammar/datatype/units/simple_3/main.k b/tests/grammar/datatype/units/simple_3/main.k similarity index 100% rename from test/grammar/datatype/units/simple_3/main.k rename to tests/grammar/datatype/units/simple_3/main.k diff --git a/test/grammar/datatype/units/simple_3/stdout.golden b/tests/grammar/datatype/units/simple_3/stdout.golden similarity index 100% rename from test/grammar/datatype/units/simple_3/stdout.golden rename to tests/grammar/datatype/units/simple_3/stdout.golden diff --git a/test/grammar/datatype/units/simple_4/main.k b/tests/grammar/datatype/units/simple_4/main.k similarity index 100% rename from test/grammar/datatype/units/simple_4/main.k rename to tests/grammar/datatype/units/simple_4/main.k diff --git a/test/grammar/datatype/units/simple_4/stdout.golden b/tests/grammar/datatype/units/simple_4/stdout.golden similarity index 100% rename from test/grammar/datatype/units/simple_4/stdout.golden rename to tests/grammar/datatype/units/simple_4/stdout.golden diff --git a/test/grammar/datatype/units/simple_5/main.k b/tests/grammar/datatype/units/simple_5/main.k similarity index 100% rename from test/grammar/datatype/units/simple_5/main.k rename to tests/grammar/datatype/units/simple_5/main.k diff --git a/test/grammar/datatype/units/simple_5/stdout.golden b/tests/grammar/datatype/units/simple_5/stdout.golden similarity index 100% rename from test/grammar/datatype/units/simple_5/stdout.golden rename to tests/grammar/datatype/units/simple_5/stdout.golden diff --git a/test/grammar/expr/braket_expr/main.k b/tests/grammar/expr/braket_expr/main.k similarity index 100% rename from test/grammar/expr/braket_expr/main.k rename to tests/grammar/expr/braket_expr/main.k diff --git a/test/grammar/expr/braket_expr/stdout.golden b/tests/grammar/expr/braket_expr/stdout.golden similarity index 100% rename from test/grammar/expr/braket_expr/stdout.golden rename to tests/grammar/expr/braket_expr/stdout.golden diff --git a/test/grammar/expr/identifier_prefix/fail_0/main.k b/tests/grammar/expr/identifier_prefix/fail_0/main.k similarity index 100% rename from test/grammar/expr/identifier_prefix/fail_0/main.k rename to tests/grammar/expr/identifier_prefix/fail_0/main.k diff --git a/test/grammar/expr/identifier_prefix/fail_0/stderr.golden b/tests/grammar/expr/identifier_prefix/fail_0/stderr.golden similarity index 100% rename from test/grammar/expr/identifier_prefix/fail_0/stderr.golden rename to tests/grammar/expr/identifier_prefix/fail_0/stderr.golden diff --git a/test/grammar/expr/identifier_prefix/fail_1/main.k b/tests/grammar/expr/identifier_prefix/fail_1/main.k similarity index 100% rename from test/grammar/expr/identifier_prefix/fail_1/main.k rename to tests/grammar/expr/identifier_prefix/fail_1/main.k diff --git a/test/grammar/expr/identifier_prefix/fail_1/stderr.golden b/tests/grammar/expr/identifier_prefix/fail_1/stderr.golden similarity index 100% rename from test/grammar/expr/identifier_prefix/fail_1/stderr.golden rename to tests/grammar/expr/identifier_prefix/fail_1/stderr.golden diff --git a/test/grammar/expr/identifier_prefix/if_0/main.k b/tests/grammar/expr/identifier_prefix/if_0/main.k similarity index 100% rename from test/grammar/expr/identifier_prefix/if_0/main.k rename to tests/grammar/expr/identifier_prefix/if_0/main.k diff --git a/test/grammar/expr/identifier_prefix/if_0/stdout.golden b/tests/grammar/expr/identifier_prefix/if_0/stdout.golden similarity index 100% rename from test/grammar/expr/identifier_prefix/if_0/stdout.golden rename to tests/grammar/expr/identifier_prefix/if_0/stdout.golden diff --git a/test/grammar/expr/identifier_prefix/if_1/main.k b/tests/grammar/expr/identifier_prefix/if_1/main.k similarity index 100% rename from test/grammar/expr/identifier_prefix/if_1/main.k rename to tests/grammar/expr/identifier_prefix/if_1/main.k diff --git a/test/grammar/expr/identifier_prefix/if_1/stdout.golden b/tests/grammar/expr/identifier_prefix/if_1/stdout.golden similarity index 100% rename from test/grammar/expr/identifier_prefix/if_1/stdout.golden rename to tests/grammar/expr/identifier_prefix/if_1/stdout.golden diff --git a/test/grammar/expr/identifier_prefix/if_2/main.k b/tests/grammar/expr/identifier_prefix/if_2/main.k similarity index 100% rename from test/grammar/expr/identifier_prefix/if_2/main.k rename to tests/grammar/expr/identifier_prefix/if_2/main.k diff --git a/test/grammar/expr/identifier_prefix/if_2/stdout.golden b/tests/grammar/expr/identifier_prefix/if_2/stdout.golden similarity index 100% rename from test/grammar/expr/identifier_prefix/if_2/stdout.golden rename to tests/grammar/expr/identifier_prefix/if_2/stdout.golden diff --git a/test/grammar/expr/identifier_prefix/test_0/main.k b/tests/grammar/expr/identifier_prefix/test_0/main.k similarity index 100% rename from test/grammar/expr/identifier_prefix/test_0/main.k rename to tests/grammar/expr/identifier_prefix/test_0/main.k diff --git a/test/grammar/expr/identifier_prefix/test_0/stdout.golden b/tests/grammar/expr/identifier_prefix/test_0/stdout.golden similarity index 100% rename from test/grammar/expr/identifier_prefix/test_0/stdout.golden rename to tests/grammar/expr/identifier_prefix/test_0/stdout.golden diff --git a/test/grammar/expr/identifier_prefix/test_1/main.k b/tests/grammar/expr/identifier_prefix/test_1/main.k similarity index 100% rename from test/grammar/expr/identifier_prefix/test_1/main.k rename to tests/grammar/expr/identifier_prefix/test_1/main.k diff --git a/test/grammar/expr/identifier_prefix/test_1/stdout.golden b/tests/grammar/expr/identifier_prefix/test_1/stdout.golden similarity index 100% rename from test/grammar/expr/identifier_prefix/test_1/stdout.golden rename to tests/grammar/expr/identifier_prefix/test_1/stdout.golden diff --git a/test/grammar/expr/identifier_prefix/test_2/main.k b/tests/grammar/expr/identifier_prefix/test_2/main.k similarity index 100% rename from test/grammar/expr/identifier_prefix/test_2/main.k rename to tests/grammar/expr/identifier_prefix/test_2/main.k diff --git a/test/grammar/expr/identifier_prefix/test_2/stdout.golden b/tests/grammar/expr/identifier_prefix/test_2/stdout.golden similarity index 100% rename from test/grammar/expr/identifier_prefix/test_2/stdout.golden rename to tests/grammar/expr/identifier_prefix/test_2/stdout.golden diff --git a/test/grammar/expr/identifier_prefix/test_3/main.k b/tests/grammar/expr/identifier_prefix/test_3/main.k similarity index 100% rename from test/grammar/expr/identifier_prefix/test_3/main.k rename to tests/grammar/expr/identifier_prefix/test_3/main.k diff --git a/test/grammar/expr/identifier_prefix/test_3/stdout.golden b/tests/grammar/expr/identifier_prefix/test_3/stdout.golden similarity index 100% rename from test/grammar/expr/identifier_prefix/test_3/stdout.golden rename to tests/grammar/expr/identifier_prefix/test_3/stdout.golden diff --git a/test/grammar/expr/identifier_prefix/test_4/main.k b/tests/grammar/expr/identifier_prefix/test_4/main.k similarity index 100% rename from test/grammar/expr/identifier_prefix/test_4/main.k rename to tests/grammar/expr/identifier_prefix/test_4/main.k diff --git a/test/grammar/expr/identifier_prefix/test_4/stdout.golden b/tests/grammar/expr/identifier_prefix/test_4/stdout.golden similarity index 100% rename from test/grammar/expr/identifier_prefix/test_4/stdout.golden rename to tests/grammar/expr/identifier_prefix/test_4/stdout.golden diff --git a/test/grammar/expr/logic_expr/test_0/main.k b/tests/grammar/expr/logic_expr/test_0/main.k similarity index 100% rename from test/grammar/expr/logic_expr/test_0/main.k rename to tests/grammar/expr/logic_expr/test_0/main.k diff --git a/test/grammar/expr/logic_expr/test_0/stdout.golden b/tests/grammar/expr/logic_expr/test_0/stdout.golden similarity index 100% rename from test/grammar/expr/logic_expr/test_0/stdout.golden rename to tests/grammar/expr/logic_expr/test_0/stdout.golden diff --git a/test/grammar/expr/logic_expr/test_1/main.k b/tests/grammar/expr/logic_expr/test_1/main.k similarity index 100% rename from test/grammar/expr/logic_expr/test_1/main.k rename to tests/grammar/expr/logic_expr/test_1/main.k diff --git a/test/grammar/expr/logic_expr/test_1/stdout.golden b/tests/grammar/expr/logic_expr/test_1/stdout.golden similarity index 100% rename from test/grammar/expr/logic_expr/test_1/stdout.golden rename to tests/grammar/expr/logic_expr/test_1/stdout.golden diff --git a/test/grammar/expr/logic_expr/test_2/main.k b/tests/grammar/expr/logic_expr/test_2/main.k similarity index 100% rename from test/grammar/expr/logic_expr/test_2/main.k rename to tests/grammar/expr/logic_expr/test_2/main.k diff --git a/test/grammar/expr/logic_expr/test_2/stdout.golden b/tests/grammar/expr/logic_expr/test_2/stdout.golden similarity index 100% rename from test/grammar/expr/logic_expr/test_2/stdout.golden rename to tests/grammar/expr/logic_expr/test_2/stdout.golden diff --git a/test/grammar/expr/paren_expr/test_0/main.k b/tests/grammar/expr/paren_expr/test_0/main.k similarity index 100% rename from test/grammar/expr/paren_expr/test_0/main.k rename to tests/grammar/expr/paren_expr/test_0/main.k diff --git a/test/grammar/expr/paren_expr/test_0/stdout.golden b/tests/grammar/expr/paren_expr/test_0/stdout.golden similarity index 100% rename from test/grammar/expr/paren_expr/test_0/stdout.golden rename to tests/grammar/expr/paren_expr/test_0/stdout.golden diff --git a/test/grammar/expr/paren_expr/test_1/main.k b/tests/grammar/expr/paren_expr/test_1/main.k similarity index 100% rename from test/grammar/expr/paren_expr/test_1/main.k rename to tests/grammar/expr/paren_expr/test_1/main.k diff --git a/test/grammar/expr/paren_expr/test_1/stdout.golden b/tests/grammar/expr/paren_expr/test_1/stdout.golden similarity index 100% rename from test/grammar/expr/paren_expr/test_1/stdout.golden rename to tests/grammar/expr/paren_expr/test_1/stdout.golden diff --git a/test/grammar/expr/paren_expr/test_2/main.k b/tests/grammar/expr/paren_expr/test_2/main.k similarity index 100% rename from test/grammar/expr/paren_expr/test_2/main.k rename to tests/grammar/expr/paren_expr/test_2/main.k diff --git a/test/grammar/expr/paren_expr/test_2/stdout.golden b/tests/grammar/expr/paren_expr/test_2/stdout.golden similarity index 100% rename from test/grammar/expr/paren_expr/test_2/stdout.golden rename to tests/grammar/expr/paren_expr/test_2/stdout.golden diff --git a/test/grammar/expr/paren_expr/test_3/main.k b/tests/grammar/expr/paren_expr/test_3/main.k similarity index 100% rename from test/grammar/expr/paren_expr/test_3/main.k rename to tests/grammar/expr/paren_expr/test_3/main.k diff --git a/test/grammar/expr/paren_expr/test_3/stdout.golden b/tests/grammar/expr/paren_expr/test_3/stdout.golden similarity index 100% rename from test/grammar/expr/paren_expr/test_3/stdout.golden rename to tests/grammar/expr/paren_expr/test_3/stdout.golden diff --git a/test/grammar/expr/select_expr/in_for_0/main.k b/tests/grammar/expr/select_expr/in_for_0/main.k similarity index 100% rename from test/grammar/expr/select_expr/in_for_0/main.k rename to tests/grammar/expr/select_expr/in_for_0/main.k diff --git a/test/grammar/expr/select_expr/in_for_0/stdout.golden b/tests/grammar/expr/select_expr/in_for_0/stdout.golden similarity index 100% rename from test/grammar/expr/select_expr/in_for_0/stdout.golden rename to tests/grammar/expr/select_expr/in_for_0/stdout.golden diff --git a/test/grammar/expr/select_expr/in_for_1/main.k b/tests/grammar/expr/select_expr/in_for_1/main.k similarity index 100% rename from test/grammar/expr/select_expr/in_for_1/main.k rename to tests/grammar/expr/select_expr/in_for_1/main.k diff --git a/test/grammar/expr/select_expr/in_for_1/stdout.golden b/tests/grammar/expr/select_expr/in_for_1/stdout.golden similarity index 100% rename from test/grammar/expr/select_expr/in_for_1/stdout.golden rename to tests/grammar/expr/select_expr/in_for_1/stdout.golden diff --git a/test/grammar/expr/select_expr/optional/complex_0/main.k b/tests/grammar/expr/select_expr/optional/complex_0/main.k similarity index 100% rename from test/grammar/expr/select_expr/optional/complex_0/main.k rename to tests/grammar/expr/select_expr/optional/complex_0/main.k diff --git a/test/grammar/expr/select_expr/optional/complex_0/stdout.golden b/tests/grammar/expr/select_expr/optional/complex_0/stdout.golden similarity index 100% rename from test/grammar/expr/select_expr/optional/complex_0/stdout.golden rename to tests/grammar/expr/select_expr/optional/complex_0/stdout.golden diff --git a/test/grammar/expr/select_expr/optional/complex_1/main.k b/tests/grammar/expr/select_expr/optional/complex_1/main.k similarity index 100% rename from test/grammar/expr/select_expr/optional/complex_1/main.k rename to tests/grammar/expr/select_expr/optional/complex_1/main.k diff --git a/test/grammar/expr/select_expr/optional/complex_1/stdout.golden b/tests/grammar/expr/select_expr/optional/complex_1/stdout.golden similarity index 100% rename from test/grammar/expr/select_expr/optional/complex_1/stdout.golden rename to tests/grammar/expr/select_expr/optional/complex_1/stdout.golden diff --git a/test/grammar/expr/select_expr/optional/simple_0/main.k b/tests/grammar/expr/select_expr/optional/simple_0/main.k similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_0/main.k rename to tests/grammar/expr/select_expr/optional/simple_0/main.k diff --git a/test/grammar/expr/select_expr/optional/simple_0/stdout.golden b/tests/grammar/expr/select_expr/optional/simple_0/stdout.golden similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_0/stdout.golden rename to tests/grammar/expr/select_expr/optional/simple_0/stdout.golden diff --git a/test/grammar/expr/select_expr/optional/simple_1/main.k b/tests/grammar/expr/select_expr/optional/simple_1/main.k similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_1/main.k rename to tests/grammar/expr/select_expr/optional/simple_1/main.k diff --git a/test/grammar/expr/select_expr/optional/simple_1/stdout.golden b/tests/grammar/expr/select_expr/optional/simple_1/stdout.golden similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_1/stdout.golden rename to tests/grammar/expr/select_expr/optional/simple_1/stdout.golden diff --git a/test/grammar/expr/select_expr/optional/simple_2/main.k b/tests/grammar/expr/select_expr/optional/simple_2/main.k similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_2/main.k rename to tests/grammar/expr/select_expr/optional/simple_2/main.k diff --git a/test/grammar/expr/select_expr/optional/simple_2/stdout.golden b/tests/grammar/expr/select_expr/optional/simple_2/stdout.golden similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_2/stdout.golden rename to tests/grammar/expr/select_expr/optional/simple_2/stdout.golden diff --git a/test/grammar/expr/select_expr/optional/simple_3/main.k b/tests/grammar/expr/select_expr/optional/simple_3/main.k similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_3/main.k rename to tests/grammar/expr/select_expr/optional/simple_3/main.k diff --git a/test/grammar/expr/select_expr/optional/simple_3/stdout.golden b/tests/grammar/expr/select_expr/optional/simple_3/stdout.golden similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_3/stdout.golden rename to tests/grammar/expr/select_expr/optional/simple_3/stdout.golden diff --git a/test/grammar/expr/select_expr/optional/simple_4/main.k b/tests/grammar/expr/select_expr/optional/simple_4/main.k similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_4/main.k rename to tests/grammar/expr/select_expr/optional/simple_4/main.k diff --git a/test/grammar/expr/select_expr/optional/simple_4/stdout.golden b/tests/grammar/expr/select_expr/optional/simple_4/stdout.golden similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_4/stdout.golden rename to tests/grammar/expr/select_expr/optional/simple_4/stdout.golden diff --git a/test/grammar/expr/select_expr/optional/simple_5/main.k b/tests/grammar/expr/select_expr/optional/simple_5/main.k similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_5/main.k rename to tests/grammar/expr/select_expr/optional/simple_5/main.k diff --git a/test/grammar/expr/select_expr/optional/simple_5/stdout.golden b/tests/grammar/expr/select_expr/optional/simple_5/stdout.golden similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_5/stdout.golden rename to tests/grammar/expr/select_expr/optional/simple_5/stdout.golden diff --git a/test/grammar/expr/select_expr/optional/simple_6/main.k b/tests/grammar/expr/select_expr/optional/simple_6/main.k similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_6/main.k rename to tests/grammar/expr/select_expr/optional/simple_6/main.k diff --git a/test/grammar/expr/select_expr/optional/simple_6/stdout.golden b/tests/grammar/expr/select_expr/optional/simple_6/stdout.golden similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_6/stdout.golden rename to tests/grammar/expr/select_expr/optional/simple_6/stdout.golden diff --git a/test/grammar/expr/select_expr/optional/simple_7/main.k b/tests/grammar/expr/select_expr/optional/simple_7/main.k similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_7/main.k rename to tests/grammar/expr/select_expr/optional/simple_7/main.k diff --git a/test/grammar/expr/select_expr/optional/simple_7/stdout.golden b/tests/grammar/expr/select_expr/optional/simple_7/stdout.golden similarity index 100% rename from test/grammar/expr/select_expr/optional/simple_7/stdout.golden rename to tests/grammar/expr/select_expr/optional/simple_7/stdout.golden diff --git a/test/grammar/expr/sub_expr/in_schema_0/main.k b/tests/grammar/expr/sub_expr/in_schema_0/main.k similarity index 100% rename from test/grammar/expr/sub_expr/in_schema_0/main.k rename to tests/grammar/expr/sub_expr/in_schema_0/main.k diff --git a/test/grammar/expr/sub_expr/in_schema_0/stdout.golden b/tests/grammar/expr/sub_expr/in_schema_0/stdout.golden similarity index 100% rename from test/grammar/expr/sub_expr/in_schema_0/stdout.golden rename to tests/grammar/expr/sub_expr/in_schema_0/stdout.golden diff --git a/test/grammar/expr/sub_expr/in_schema_1/main.k b/tests/grammar/expr/sub_expr/in_schema_1/main.k similarity index 100% rename from test/grammar/expr/sub_expr/in_schema_1/main.k rename to tests/grammar/expr/sub_expr/in_schema_1/main.k diff --git a/test/grammar/expr/sub_expr/in_schema_1/stdout.golden b/tests/grammar/expr/sub_expr/in_schema_1/stdout.golden similarity index 100% rename from test/grammar/expr/sub_expr/in_schema_1/stdout.golden rename to tests/grammar/expr/sub_expr/in_schema_1/stdout.golden diff --git a/test/grammar/expr/sub_expr/in_schema_2/main.k b/tests/grammar/expr/sub_expr/in_schema_2/main.k similarity index 100% rename from test/grammar/expr/sub_expr/in_schema_2/main.k rename to tests/grammar/expr/sub_expr/in_schema_2/main.k diff --git a/test/grammar/expr/sub_expr/in_schema_2/stdout.golden b/tests/grammar/expr/sub_expr/in_schema_2/stdout.golden similarity index 100% rename from test/grammar/expr/sub_expr/in_schema_2/stdout.golden rename to tests/grammar/expr/sub_expr/in_schema_2/stdout.golden diff --git a/test/grammar/expr/sub_expr/test_0/main.k b/tests/grammar/expr/sub_expr/test_0/main.k similarity index 100% rename from test/grammar/expr/sub_expr/test_0/main.k rename to tests/grammar/expr/sub_expr/test_0/main.k diff --git a/test/grammar/expr/sub_expr/test_0/stdout.golden b/tests/grammar/expr/sub_expr/test_0/stdout.golden similarity index 100% rename from test/grammar/expr/sub_expr/test_0/stdout.golden rename to tests/grammar/expr/sub_expr/test_0/stdout.golden diff --git a/test/grammar/expr/sub_expr/test_1/main.k b/tests/grammar/expr/sub_expr/test_1/main.k similarity index 100% rename from test/grammar/expr/sub_expr/test_1/main.k rename to tests/grammar/expr/sub_expr/test_1/main.k diff --git a/test/grammar/expr/sub_expr/test_1/stdout.golden b/tests/grammar/expr/sub_expr/test_1/stdout.golden similarity index 100% rename from test/grammar/expr/sub_expr/test_1/stdout.golden rename to tests/grammar/expr/sub_expr/test_1/stdout.golden diff --git a/test/grammar/if/if_expr/test_0/main.k b/tests/grammar/if/if_expr/test_0/main.k similarity index 100% rename from test/grammar/if/if_expr/test_0/main.k rename to tests/grammar/if/if_expr/test_0/main.k diff --git a/test/grammar/if/if_expr/test_0/stdout.golden b/tests/grammar/if/if_expr/test_0/stdout.golden similarity index 100% rename from test/grammar/if/if_expr/test_0/stdout.golden rename to tests/grammar/if/if_expr/test_0/stdout.golden diff --git a/test/grammar/if/if_expr/test_1/main.k b/tests/grammar/if/if_expr/test_1/main.k similarity index 100% rename from test/grammar/if/if_expr/test_1/main.k rename to tests/grammar/if/if_expr/test_1/main.k diff --git a/test/grammar/if/if_expr/test_1/stdout.golden b/tests/grammar/if/if_expr/test_1/stdout.golden similarity index 100% rename from test/grammar/if/if_expr/test_1/stdout.golden rename to tests/grammar/if/if_expr/test_1/stdout.golden diff --git a/test/grammar/if/if_expr/test_2/main.k b/tests/grammar/if/if_expr/test_2/main.k similarity index 100% rename from test/grammar/if/if_expr/test_2/main.k rename to tests/grammar/if/if_expr/test_2/main.k diff --git a/test/grammar/if/if_expr/test_2/stdout.golden b/tests/grammar/if/if_expr/test_2/stdout.golden similarity index 100% rename from test/grammar/if/if_expr/test_2/stdout.golden rename to tests/grammar/if/if_expr/test_2/stdout.golden diff --git a/test/grammar/if/if_stmt/test_0/main.k b/tests/grammar/if/if_stmt/test_0/main.k similarity index 100% rename from test/grammar/if/if_stmt/test_0/main.k rename to tests/grammar/if/if_stmt/test_0/main.k diff --git a/test/grammar/if/if_stmt/test_0/stdout.golden b/tests/grammar/if/if_stmt/test_0/stdout.golden similarity index 100% rename from test/grammar/if/if_stmt/test_0/stdout.golden rename to tests/grammar/if/if_stmt/test_0/stdout.golden diff --git a/test/grammar/if/if_stmt/test_1/main.k b/tests/grammar/if/if_stmt/test_1/main.k similarity index 100% rename from test/grammar/if/if_stmt/test_1/main.k rename to tests/grammar/if/if_stmt/test_1/main.k diff --git a/test/grammar/if/if_stmt/test_1/stdout.golden b/tests/grammar/if/if_stmt/test_1/stdout.golden similarity index 100% rename from test/grammar/if/if_stmt/test_1/stdout.golden rename to tests/grammar/if/if_stmt/test_1/stdout.golden diff --git a/test/grammar/if/if_stmt/test_2/main.k b/tests/grammar/if/if_stmt/test_2/main.k similarity index 100% rename from test/grammar/if/if_stmt/test_2/main.k rename to tests/grammar/if/if_stmt/test_2/main.k diff --git a/test/grammar/if/if_stmt/test_2/stdout.golden b/tests/grammar/if/if_stmt/test_2/stdout.golden similarity index 100% rename from test/grammar/if/if_stmt/test_2/stdout.golden rename to tests/grammar/if/if_stmt/test_2/stdout.golden diff --git a/test/grammar/if/if_stmt/test_3/main.k b/tests/grammar/if/if_stmt/test_3/main.k similarity index 100% rename from test/grammar/if/if_stmt/test_3/main.k rename to tests/grammar/if/if_stmt/test_3/main.k diff --git a/test/grammar/if/if_stmt/test_3/stdout.golden b/tests/grammar/if/if_stmt/test_3/stdout.golden similarity index 100% rename from test/grammar/if/if_stmt/test_3/stdout.golden rename to tests/grammar/if/if_stmt/test_3/stdout.golden diff --git a/test/grammar/if/if_stmt/test_4/main.k b/tests/grammar/if/if_stmt/test_4/main.k similarity index 100% rename from test/grammar/if/if_stmt/test_4/main.k rename to tests/grammar/if/if_stmt/test_4/main.k diff --git a/test/grammar/if/if_stmt/test_4/stdout.golden b/tests/grammar/if/if_stmt/test_4/stdout.golden similarity index 100% rename from test/grammar/if/if_stmt/test_4/stdout.golden rename to tests/grammar/if/if_stmt/test_4/stdout.golden diff --git a/test/grammar/if/if_stmt/test_5/main.k b/tests/grammar/if/if_stmt/test_5/main.k similarity index 100% rename from test/grammar/if/if_stmt/test_5/main.k rename to tests/grammar/if/if_stmt/test_5/main.k diff --git a/test/grammar/if/if_stmt/test_5/stdout.golden b/tests/grammar/if/if_stmt/test_5/stdout.golden similarity index 100% rename from test/grammar/if/if_stmt/test_5/stdout.golden rename to tests/grammar/if/if_stmt/test_5/stdout.golden diff --git a/test/grammar/import/builtin/main.k b/tests/grammar/import/builtin/main.k similarity index 100% rename from test/grammar/import/builtin/main.k rename to tests/grammar/import/builtin/main.k diff --git a/test/grammar/import/builtin/stdout.golden b/tests/grammar/import/builtin/stdout.golden similarity index 100% rename from test/grammar/import/builtin/stdout.golden rename to tests/grammar/import/builtin/stdout.golden diff --git a/test/grammar/import/builtin_import_as/main.k b/tests/grammar/import/builtin_import_as/main.k similarity index 100% rename from test/grammar/import/builtin_import_as/main.k rename to tests/grammar/import/builtin_import_as/main.k diff --git a/test/grammar/import/builtin_import_as/stdout.golden b/tests/grammar/import/builtin_import_as/stdout.golden similarity index 100% rename from test/grammar/import/builtin_import_as/stdout.golden rename to tests/grammar/import/builtin_import_as/stdout.golden diff --git a/test/grammar/import/empty_file_import/kcl.mod b/tests/grammar/import/empty_file_import/kcl.mod similarity index 100% rename from test/grammar/import/empty_file_import/kcl.mod rename to tests/grammar/import/empty_file_import/kcl.mod diff --git a/test/grammar/import/empty_file_import/main.k b/tests/grammar/import/empty_file_import/main.k similarity index 100% rename from test/grammar/import/empty_file_import/main.k rename to tests/grammar/import/empty_file_import/main.k diff --git a/test/grammar/import/empty_file_import/pkg/empty.k b/tests/grammar/import/empty_file_import/pkg/empty.k similarity index 100% rename from test/grammar/import/empty_file_import/pkg/empty.k rename to tests/grammar/import/empty_file_import/pkg/empty.k diff --git a/test/grammar/import/empty_file_import/stdout.golden b/tests/grammar/import/empty_file_import/stdout.golden similarity index 100% rename from test/grammar/import/empty_file_import/stdout.golden rename to tests/grammar/import/empty_file_import/stdout.golden diff --git a/test/grammar/import/import_abs_fail_0/app-main/main.k b/tests/grammar/import/import_abs_fail_0/app-main/main.k similarity index 100% rename from test/grammar/import/import_abs_fail_0/app-main/main.k rename to tests/grammar/import/import_abs_fail_0/app-main/main.k diff --git a/test/grammar/import/import_abs_fail_0/app-main/some1/pkg1/pkg1.k b/tests/grammar/import/import_abs_fail_0/app-main/some1/pkg1/pkg1.k similarity index 100% rename from test/grammar/import/import_abs_fail_0/app-main/some1/pkg1/pkg1.k rename to tests/grammar/import/import_abs_fail_0/app-main/some1/pkg1/pkg1.k diff --git a/test/grammar/import/import_abs_fail_0/app-main/stderr.golden b/tests/grammar/import/import_abs_fail_0/app-main/stderr.golden similarity index 100% rename from test/grammar/import/import_abs_fail_0/app-main/stderr.golden rename to tests/grammar/import/import_abs_fail_0/app-main/stderr.golden diff --git a/test/grammar/import/import_abs_fail_0/kcl.mod b/tests/grammar/import/import_abs_fail_0/kcl.mod similarity index 100% rename from test/grammar/import/import_abs_fail_0/kcl.mod rename to tests/grammar/import/import_abs_fail_0/kcl.mod diff --git a/test/grammar/import/import_abs_fail_0/some0/pkg1/pkg1.k b/tests/grammar/import/import_abs_fail_0/some0/pkg1/pkg1.k similarity index 100% rename from test/grammar/import/import_abs_fail_0/some0/pkg1/pkg1.k rename to tests/grammar/import/import_abs_fail_0/some0/pkg1/pkg1.k diff --git a/test/grammar/import/import_abs_fail_0/some1/pkg1/pkg1.k b/tests/grammar/import/import_abs_fail_0/some1/pkg1/pkg1.k similarity index 100% rename from test/grammar/import/import_abs_fail_0/some1/pkg1/pkg1.k rename to tests/grammar/import/import_abs_fail_0/some1/pkg1/pkg1.k diff --git a/test/grammar/import/import_abs_fail_1/app-main/main.k b/tests/grammar/import/import_abs_fail_1/app-main/main.k similarity index 100% rename from test/grammar/import/import_abs_fail_1/app-main/main.k rename to tests/grammar/import/import_abs_fail_1/app-main/main.k diff --git a/test/grammar/import/import_abs_fail_1/app-main/some1/pkg1/pkg1.k b/tests/grammar/import/import_abs_fail_1/app-main/some1/pkg1/pkg1.k similarity index 100% rename from test/grammar/import/import_abs_fail_1/app-main/some1/pkg1/pkg1.k rename to tests/grammar/import/import_abs_fail_1/app-main/some1/pkg1/pkg1.k diff --git a/test/grammar/import/import_abs_fail_1/app-main/stderr.golden b/tests/grammar/import/import_abs_fail_1/app-main/stderr.golden similarity index 100% rename from test/grammar/import/import_abs_fail_1/app-main/stderr.golden rename to tests/grammar/import/import_abs_fail_1/app-main/stderr.golden diff --git a/test/grammar/import/import_abs_fail_1/kcl.mod b/tests/grammar/import/import_abs_fail_1/kcl.mod similarity index 100% rename from test/grammar/import/import_abs_fail_1/kcl.mod rename to tests/grammar/import/import_abs_fail_1/kcl.mod diff --git a/test/grammar/import/import_abs_fail_1/some0/pkg1/pkg1.k b/tests/grammar/import/import_abs_fail_1/some0/pkg1/pkg1.k similarity index 100% rename from test/grammar/import/import_abs_fail_1/some0/pkg1/pkg1.k rename to tests/grammar/import/import_abs_fail_1/some0/pkg1/pkg1.k diff --git a/test/grammar/import/import_abs_fail_1/some1/pkg1/pkg1.k b/tests/grammar/import/import_abs_fail_1/some1/pkg1/pkg1.k similarity index 100% rename from test/grammar/import/import_abs_fail_1/some1/pkg1/pkg1.k rename to tests/grammar/import/import_abs_fail_1/some1/pkg1/pkg1.k diff --git a/test/grammar/import/import_abs_path/app-main/main.k b/tests/grammar/import/import_abs_path/app-main/main.k similarity index 100% rename from test/grammar/import/import_abs_path/app-main/main.k rename to tests/grammar/import/import_abs_path/app-main/main.k diff --git a/test/grammar/import/import_abs_path/app-main/some1/pkg1/pkg1.k b/tests/grammar/import/import_abs_path/app-main/some1/pkg1/pkg1.k similarity index 100% rename from test/grammar/import/import_abs_path/app-main/some1/pkg1/pkg1.k rename to tests/grammar/import/import_abs_path/app-main/some1/pkg1/pkg1.k diff --git a/test/grammar/import/import_abs_path/app-main/stdout.golden b/tests/grammar/import/import_abs_path/app-main/stdout.golden similarity index 100% rename from test/grammar/import/import_abs_path/app-main/stdout.golden rename to tests/grammar/import/import_abs_path/app-main/stdout.golden diff --git a/test/grammar/import/import_abs_path/kcl.mod b/tests/grammar/import/import_abs_path/kcl.mod similarity index 100% rename from test/grammar/import/import_abs_path/kcl.mod rename to tests/grammar/import/import_abs_path/kcl.mod diff --git a/test/grammar/import/import_abs_path/some0/pkg1/pkg1.k b/tests/grammar/import/import_abs_path/some0/pkg1/pkg1.k similarity index 100% rename from test/grammar/import/import_abs_path/some0/pkg1/pkg1.k rename to tests/grammar/import/import_abs_path/some0/pkg1/pkg1.k diff --git a/test/grammar/import/import_abs_path/some1/pkg1/pkg1.k b/tests/grammar/import/import_abs_path/some1/pkg1/pkg1.k similarity index 100% rename from test/grammar/import/import_abs_path/some1/pkg1/pkg1.k rename to tests/grammar/import/import_abs_path/some1/pkg1/pkg1.k diff --git a/test/grammar/import/import_as_diff_alias/kcl.mod b/tests/grammar/import/import_as_diff_alias/kcl.mod similarity index 100% rename from test/grammar/import/import_as_diff_alias/kcl.mod rename to tests/grammar/import/import_as_diff_alias/kcl.mod diff --git a/test/grammar/import/import_as_diff_alias/main.k b/tests/grammar/import/import_as_diff_alias/main.k similarity index 100% rename from test/grammar/import/import_as_diff_alias/main.k rename to tests/grammar/import/import_as_diff_alias/main.k diff --git a/test/grammar/import/import_as_diff_alias/name_pkg/v1/name.k b/tests/grammar/import/import_as_diff_alias/name_pkg/v1/name.k similarity index 100% rename from test/grammar/import/import_as_diff_alias/name_pkg/v1/name.k rename to tests/grammar/import/import_as_diff_alias/name_pkg/v1/name.k diff --git a/test/grammar/import/import_as_diff_alias/person_pkg/v1/person.k b/tests/grammar/import/import_as_diff_alias/person_pkg/v1/person.k similarity index 100% rename from test/grammar/import/import_as_diff_alias/person_pkg/v1/person.k rename to tests/grammar/import/import_as_diff_alias/person_pkg/v1/person.k diff --git a/test/grammar/import/import_as_diff_alias/stdout.golden b/tests/grammar/import/import_as_diff_alias/stdout.golden similarity index 100% rename from test/grammar/import/import_as_diff_alias/stdout.golden rename to tests/grammar/import/import_as_diff_alias/stdout.golden diff --git a/test/grammar/import/import_complex/kcl.mod b/tests/grammar/import/import_complex/kcl.mod similarity index 100% rename from test/grammar/import/import_complex/kcl.mod rename to tests/grammar/import/import_complex/kcl.mod diff --git a/test/grammar/import/import_complex/main.k b/tests/grammar/import/import_complex/main.k similarity index 100% rename from test/grammar/import/import_complex/main.k rename to tests/grammar/import/import_complex/main.k diff --git a/test/grammar/import/import_complex/pkg/a.k b/tests/grammar/import/import_complex/pkg/a.k similarity index 100% rename from test/grammar/import/import_complex/pkg/a.k rename to tests/grammar/import/import_complex/pkg/a.k diff --git a/test/grammar/import/import_complex/pkg/c.k b/tests/grammar/import/import_complex/pkg/c.k similarity index 100% rename from test/grammar/import/import_complex/pkg/c.k rename to tests/grammar/import/import_complex/pkg/c.k diff --git a/test/grammar/import/import_complex/pkg/d.k b/tests/grammar/import/import_complex/pkg/d.k similarity index 100% rename from test/grammar/import/import_complex/pkg/d.k rename to tests/grammar/import/import_complex/pkg/d.k diff --git a/test/grammar/import/import_complex/pkg2/b.k b/tests/grammar/import/import_complex/pkg2/b.k similarity index 100% rename from test/grammar/import/import_complex/pkg2/b.k rename to tests/grammar/import/import_complex/pkg2/b.k diff --git a/test/grammar/import/import_complex/stdout.golden b/tests/grammar/import/import_complex/stdout.golden similarity index 100% rename from test/grammar/import/import_complex/stdout.golden rename to tests/grammar/import/import_complex/stdout.golden diff --git a/test/grammar/import/import_file/kcl.mod b/tests/grammar/import/import_file/kcl.mod similarity index 100% rename from test/grammar/import/import_file/kcl.mod rename to tests/grammar/import/import_file/kcl.mod diff --git a/test/grammar/import/import_file/main.k b/tests/grammar/import/import_file/main.k similarity index 100% rename from test/grammar/import/import_file/main.k rename to tests/grammar/import/import_file/main.k diff --git a/test/grammar/import/import_file/module.k b/tests/grammar/import/import_file/module.k similarity index 100% rename from test/grammar/import/import_file/module.k rename to tests/grammar/import/import_file/module.k diff --git a/test/grammar/import/import_file/stdout.golden b/tests/grammar/import/import_file/stdout.golden similarity index 100% rename from test/grammar/import/import_file/stdout.golden rename to tests/grammar/import/import_file/stdout.golden diff --git a/test/grammar/import/import_main_file_fail_0/kcl.mod b/tests/grammar/import/import_main_file_fail_0/kcl.mod similarity index 100% rename from test/grammar/import/import_main_file_fail_0/kcl.mod rename to tests/grammar/import/import_main_file_fail_0/kcl.mod diff --git a/test/grammar/import/import_main_file_fail_0/main.k b/tests/grammar/import/import_main_file_fail_0/main.k similarity index 100% rename from test/grammar/import/import_main_file_fail_0/main.k rename to tests/grammar/import/import_main_file_fail_0/main.k diff --git a/test/grammar/import/import_main_file_fail_0/module.k b/tests/grammar/import/import_main_file_fail_0/module.k similarity index 100% rename from test/grammar/import/import_main_file_fail_0/module.k rename to tests/grammar/import/import_main_file_fail_0/module.k diff --git a/test/grammar/import/import_main_file_fail_0/stderr.golden b/tests/grammar/import/import_main_file_fail_0/stderr.golden similarity index 100% rename from test/grammar/import/import_main_file_fail_0/stderr.golden rename to tests/grammar/import/import_main_file_fail_0/stderr.golden diff --git a/test/grammar/import/import_main_file_fail_1/main.k b/tests/grammar/import/import_main_file_fail_1/main.k similarity index 100% rename from test/grammar/import/import_main_file_fail_1/main.k rename to tests/grammar/import/import_main_file_fail_1/main.k diff --git a/test/grammar/import/import_main_file_fail_1/stderr.golden b/tests/grammar/import/import_main_file_fail_1/stderr.golden similarity index 100% rename from test/grammar/import/import_main_file_fail_1/stderr.golden rename to tests/grammar/import/import_main_file_fail_1/stderr.golden diff --git a/test/grammar/import/import_name_same_with_schema_attr/main.k b/tests/grammar/import/import_name_same_with_schema_attr/main.k similarity index 100% rename from test/grammar/import/import_name_same_with_schema_attr/main.k rename to tests/grammar/import/import_name_same_with_schema_attr/main.k diff --git a/test/grammar/import/import_name_same_with_schema_attr/stdout.golden b/tests/grammar/import/import_name_same_with_schema_attr/stdout.golden similarity index 100% rename from test/grammar/import/import_name_same_with_schema_attr/stdout.golden rename to tests/grammar/import/import_name_same_with_schema_attr/stdout.golden diff --git a/test/grammar/import/import_package/kcl.mod b/tests/grammar/import/import_package/kcl.mod similarity index 100% rename from test/grammar/import/import_package/kcl.mod rename to tests/grammar/import/import_package/kcl.mod diff --git a/test/grammar/import/import_package/main.k b/tests/grammar/import/import_package/main.k similarity index 100% rename from test/grammar/import/import_package/main.k rename to tests/grammar/import/import_package/main.k diff --git a/test/grammar/import/import_package/mymodule/a.k b/tests/grammar/import/import_package/mymodule/a.k similarity index 100% rename from test/grammar/import/import_package/mymodule/a.k rename to tests/grammar/import/import_package/mymodule/a.k diff --git a/test/grammar/import/import_package/mymodule/b.k b/tests/grammar/import/import_package/mymodule/b.k similarity index 100% rename from test/grammar/import/import_package/mymodule/b.k rename to tests/grammar/import/import_package/mymodule/b.k diff --git a/test/grammar/import/import_package/stdout.golden b/tests/grammar/import/import_package/stdout.golden similarity index 100% rename from test/grammar/import/import_package/stdout.golden rename to tests/grammar/import/import_package/stdout.golden diff --git a/test/grammar/import/import_package_as/kcl.mod b/tests/grammar/import/import_package_as/kcl.mod similarity index 100% rename from test/grammar/import/import_package_as/kcl.mod rename to tests/grammar/import/import_package_as/kcl.mod diff --git a/test/grammar/import/import_package_as/main.k b/tests/grammar/import/import_package_as/main.k similarity index 100% rename from test/grammar/import/import_package_as/main.k rename to tests/grammar/import/import_package_as/main.k diff --git a/test/grammar/import/import_package_as/mymodule/a.k b/tests/grammar/import/import_package_as/mymodule/a.k similarity index 100% rename from test/grammar/import/import_package_as/mymodule/a.k rename to tests/grammar/import/import_package_as/mymodule/a.k diff --git a/test/grammar/import/import_package_as/mymodule/b.k b/tests/grammar/import/import_package_as/mymodule/b.k similarity index 100% rename from test/grammar/import/import_package_as/mymodule/b.k rename to tests/grammar/import/import_package_as/mymodule/b.k diff --git a/test/grammar/import/import_package_as/stdout.golden b/tests/grammar/import/import_package_as/stdout.golden similarity index 100% rename from test/grammar/import/import_package_as/stdout.golden rename to tests/grammar/import/import_package_as/stdout.golden diff --git a/test/grammar/import/import_package_module_0/kcl.mod b/tests/grammar/import/import_package_module_0/kcl.mod similarity index 100% rename from test/grammar/import/import_package_module_0/kcl.mod rename to tests/grammar/import/import_package_module_0/kcl.mod diff --git a/test/grammar/import/import_package_module_0/main.k b/tests/grammar/import/import_package_module_0/main.k similarity index 100% rename from test/grammar/import/import_package_module_0/main.k rename to tests/grammar/import/import_package_module_0/main.k diff --git a/test/grammar/import/import_package_module_0/pkg_b/a.k b/tests/grammar/import/import_package_module_0/pkg_b/a.k similarity index 100% rename from test/grammar/import/import_package_module_0/pkg_b/a.k rename to tests/grammar/import/import_package_module_0/pkg_b/a.k diff --git a/test/grammar/import/import_package_module_0/pkg_b/pkg_c/a.k b/tests/grammar/import/import_package_module_0/pkg_b/pkg_c/a.k similarity index 100% rename from test/grammar/import/import_package_module_0/pkg_b/pkg_c/a.k rename to tests/grammar/import/import_package_module_0/pkg_b/pkg_c/a.k diff --git a/test/grammar/import/import_package_module_0/pkg_b/pkg_c/b.k b/tests/grammar/import/import_package_module_0/pkg_b/pkg_c/b.k similarity index 100% rename from test/grammar/import/import_package_module_0/pkg_b/pkg_c/b.k rename to tests/grammar/import/import_package_module_0/pkg_b/pkg_c/b.k diff --git a/test/grammar/import/import_package_module_0/stdout.golden b/tests/grammar/import/import_package_module_0/stdout.golden similarity index 100% rename from test/grammar/import/import_package_module_0/stdout.golden rename to tests/grammar/import/import_package_module_0/stdout.golden diff --git a/test/grammar/import/import_package_module_1/kcl.mod b/tests/grammar/import/import_package_module_1/kcl.mod similarity index 100% rename from test/grammar/import/import_package_module_1/kcl.mod rename to tests/grammar/import/import_package_module_1/kcl.mod diff --git a/test/grammar/import/import_package_module_1/main.k b/tests/grammar/import/import_package_module_1/main.k similarity index 100% rename from test/grammar/import/import_package_module_1/main.k rename to tests/grammar/import/import_package_module_1/main.k diff --git a/test/grammar/import/import_package_module_1/pkg/moduleA.k b/tests/grammar/import/import_package_module_1/pkg/moduleA.k similarity index 100% rename from test/grammar/import/import_package_module_1/pkg/moduleA.k rename to tests/grammar/import/import_package_module_1/pkg/moduleA.k diff --git a/test/grammar/import/import_package_module_1/pkg/pkg2/moduleA.k b/tests/grammar/import/import_package_module_1/pkg/pkg2/moduleA.k similarity index 100% rename from test/grammar/import/import_package_module_1/pkg/pkg2/moduleA.k rename to tests/grammar/import/import_package_module_1/pkg/pkg2/moduleA.k diff --git a/test/grammar/import/import_package_module_1/pkg/pkg2/moduleB.k b/tests/grammar/import/import_package_module_1/pkg/pkg2/moduleB.k similarity index 100% rename from test/grammar/import/import_package_module_1/pkg/pkg2/moduleB.k rename to tests/grammar/import/import_package_module_1/pkg/pkg2/moduleB.k diff --git a/test/grammar/import/import_package_module_1/stdout.golden b/tests/grammar/import/import_package_module_1/stdout.golden similarity index 100% rename from test/grammar/import/import_package_module_1/stdout.golden rename to tests/grammar/import/import_package_module_1/stdout.golden diff --git a/test/grammar/import/import_package_module_2/kcl.mod b/tests/grammar/import/import_package_module_2/kcl.mod similarity index 100% rename from test/grammar/import/import_package_module_2/kcl.mod rename to tests/grammar/import/import_package_module_2/kcl.mod diff --git a/test/grammar/import/import_package_module_2/main.k b/tests/grammar/import/import_package_module_2/main.k similarity index 100% rename from test/grammar/import/import_package_module_2/main.k rename to tests/grammar/import/import_package_module_2/main.k diff --git a/test/grammar/import/import_package_module_2/pkg/pkg1.k b/tests/grammar/import/import_package_module_2/pkg/pkg1.k similarity index 100% rename from test/grammar/import/import_package_module_2/pkg/pkg1.k rename to tests/grammar/import/import_package_module_2/pkg/pkg1.k diff --git a/test/grammar/import/import_package_module_2/pkg/pkg2.k b/tests/grammar/import/import_package_module_2/pkg/pkg2.k similarity index 100% rename from test/grammar/import/import_package_module_2/pkg/pkg2.k rename to tests/grammar/import/import_package_module_2/pkg/pkg2.k diff --git a/test/grammar/import/import_package_module_2/stdout.golden b/tests/grammar/import/import_package_module_2/stdout.golden similarity index 100% rename from test/grammar/import/import_package_module_2/stdout.golden rename to tests/grammar/import/import_package_module_2/stdout.golden diff --git a/test/grammar/import/import_regular_module/kcl.mod b/tests/grammar/import/import_regular_module/kcl.mod similarity index 100% rename from test/grammar/import/import_regular_module/kcl.mod rename to tests/grammar/import/import_regular_module/kcl.mod diff --git a/test/grammar/import/import_regular_module/main.k b/tests/grammar/import/import_regular_module/main.k similarity index 100% rename from test/grammar/import/import_regular_module/main.k rename to tests/grammar/import/import_regular_module/main.k diff --git a/test/grammar/import/import_regular_module/mymodule.k b/tests/grammar/import/import_regular_module/mymodule.k similarity index 100% rename from test/grammar/import/import_regular_module/mymodule.k rename to tests/grammar/import/import_regular_module/mymodule.k diff --git a/test/grammar/import/import_regular_module/stdout.golden b/tests/grammar/import/import_regular_module/stdout.golden similarity index 100% rename from test/grammar/import/import_regular_module/stdout.golden rename to tests/grammar/import/import_regular_module/stdout.golden diff --git a/test/grammar/import/import_regular_module_as/kcl.mod b/tests/grammar/import/import_regular_module_as/kcl.mod similarity index 100% rename from test/grammar/import/import_regular_module_as/kcl.mod rename to tests/grammar/import/import_regular_module_as/kcl.mod diff --git a/test/grammar/import/import_regular_module_as/main.k b/tests/grammar/import/import_regular_module_as/main.k similarity index 100% rename from test/grammar/import/import_regular_module_as/main.k rename to tests/grammar/import/import_regular_module_as/main.k diff --git a/test/grammar/import/import_regular_module_as/mymodule.k b/tests/grammar/import/import_regular_module_as/mymodule.k similarity index 100% rename from test/grammar/import/import_regular_module_as/mymodule.k rename to tests/grammar/import/import_regular_module_as/mymodule.k diff --git a/test/grammar/import/import_regular_module_as/stdout.golden b/tests/grammar/import/import_regular_module_as/stdout.golden similarity index 100% rename from test/grammar/import/import_regular_module_as/stdout.golden rename to tests/grammar/import/import_regular_module_as/stdout.golden diff --git a/test/grammar/import/import_relative_path_with_multi_input_files/base/main.k b/tests/grammar/import/import_relative_path_with_multi_input_files/base/main.k similarity index 100% rename from test/grammar/import/import_relative_path_with_multi_input_files/base/main.k rename to tests/grammar/import/import_relative_path_with_multi_input_files/base/main.k diff --git a/test/grammar/import/import_relative_path_with_multi_input_files/base/settings.yaml b/tests/grammar/import/import_relative_path_with_multi_input_files/base/settings.yaml similarity index 100% rename from test/grammar/import/import_relative_path_with_multi_input_files/base/settings.yaml rename to tests/grammar/import/import_relative_path_with_multi_input_files/base/settings.yaml diff --git a/test/grammar/import/import_relative_path_with_multi_input_files/base/stdout.golden b/tests/grammar/import/import_relative_path_with_multi_input_files/base/stdout.golden similarity index 100% rename from test/grammar/import/import_relative_path_with_multi_input_files/base/stdout.golden rename to tests/grammar/import/import_relative_path_with_multi_input_files/base/stdout.golden diff --git a/test/grammar/import/import_relative_path_with_multi_input_files/kcl.mod b/tests/grammar/import/import_relative_path_with_multi_input_files/kcl.mod similarity index 100% rename from test/grammar/import/import_relative_path_with_multi_input_files/kcl.mod rename to tests/grammar/import/import_relative_path_with_multi_input_files/kcl.mod diff --git a/test/grammar/import/import_relative_path_with_multi_input_files/prod/pkg/pkg.k b/tests/grammar/import/import_relative_path_with_multi_input_files/prod/pkg/pkg.k similarity index 100% rename from test/grammar/import/import_relative_path_with_multi_input_files/prod/pkg/pkg.k rename to tests/grammar/import/import_relative_path_with_multi_input_files/prod/pkg/pkg.k diff --git a/test/grammar/import/import_relative_path_with_multi_input_files/prod/prod.k b/tests/grammar/import/import_relative_path_with_multi_input_files/prod/prod.k similarity index 100% rename from test/grammar/import/import_relative_path_with_multi_input_files/prod/prod.k rename to tests/grammar/import/import_relative_path_with_multi_input_files/prod/prod.k diff --git a/test/grammar/import/import_same_as_name_0/kcl.mod b/tests/grammar/import/import_same_as_name_0/kcl.mod similarity index 100% rename from test/grammar/import/import_same_as_name_0/kcl.mod rename to tests/grammar/import/import_same_as_name_0/kcl.mod diff --git a/test/grammar/import/import_same_as_name_0/main.k b/tests/grammar/import/import_same_as_name_0/main.k similarity index 100% rename from test/grammar/import/import_same_as_name_0/main.k rename to tests/grammar/import/import_same_as_name_0/main.k diff --git a/test/grammar/import/import_same_as_name_0/pkg/core/v1/deploy.k b/tests/grammar/import/import_same_as_name_0/pkg/core/v1/deploy.k similarity index 100% rename from test/grammar/import/import_same_as_name_0/pkg/core/v1/deploy.k rename to tests/grammar/import/import_same_as_name_0/pkg/core/v1/deploy.k diff --git a/test/grammar/import/import_same_as_name_0/pkg/data.k b/tests/grammar/import/import_same_as_name_0/pkg/data.k similarity index 100% rename from test/grammar/import/import_same_as_name_0/pkg/data.k rename to tests/grammar/import/import_same_as_name_0/pkg/data.k diff --git a/test/grammar/import/import_same_as_name_0/pkg/mixin/v1/mixin.k b/tests/grammar/import/import_same_as_name_0/pkg/mixin/v1/mixin.k similarity index 100% rename from test/grammar/import/import_same_as_name_0/pkg/mixin/v1/mixin.k rename to tests/grammar/import/import_same_as_name_0/pkg/mixin/v1/mixin.k diff --git a/test/grammar/import/import_same_as_name_0/pkg/temp.k b/tests/grammar/import/import_same_as_name_0/pkg/temp.k similarity index 100% rename from test/grammar/import/import_same_as_name_0/pkg/temp.k rename to tests/grammar/import/import_same_as_name_0/pkg/temp.k diff --git a/test/grammar/import/import_same_as_name_0/stdout.golden b/tests/grammar/import/import_same_as_name_0/stdout.golden similarity index 100% rename from test/grammar/import/import_same_as_name_0/stdout.golden rename to tests/grammar/import/import_same_as_name_0/stdout.golden diff --git a/test/grammar/import/import_submodule/app-main/main.k b/tests/grammar/import/import_submodule/app-main/main.k similarity index 100% rename from test/grammar/import/import_submodule/app-main/main.k rename to tests/grammar/import/import_submodule/app-main/main.k diff --git a/test/grammar/import/import_submodule/app-main/stdout.golden b/tests/grammar/import/import_submodule/app-main/stdout.golden similarity index 100% rename from test/grammar/import/import_submodule/app-main/stdout.golden rename to tests/grammar/import/import_submodule/app-main/stdout.golden diff --git a/test/grammar/import/import_submodule/kcl.mod b/tests/grammar/import/import_submodule/kcl.mod similarity index 100% rename from test/grammar/import/import_submodule/kcl.mod rename to tests/grammar/import/import_submodule/kcl.mod diff --git a/test/grammar/import/import_submodule/mydir/mydir2/mymodule.k b/tests/grammar/import/import_submodule/mydir/mydir2/mymodule.k similarity index 100% rename from test/grammar/import/import_submodule/mydir/mydir2/mymodule.k rename to tests/grammar/import/import_submodule/mydir/mydir2/mymodule.k diff --git a/test/grammar/import/import_submodule_as/app-main/main.k b/tests/grammar/import/import_submodule_as/app-main/main.k similarity index 100% rename from test/grammar/import/import_submodule_as/app-main/main.k rename to tests/grammar/import/import_submodule_as/app-main/main.k diff --git a/test/grammar/import/import_submodule_as/app-main/stdout.golden b/tests/grammar/import/import_submodule_as/app-main/stdout.golden similarity index 100% rename from test/grammar/import/import_submodule_as/app-main/stdout.golden rename to tests/grammar/import/import_submodule_as/app-main/stdout.golden diff --git a/test/grammar/import/import_submodule_as/kcl.mod b/tests/grammar/import/import_submodule_as/kcl.mod similarity index 100% rename from test/grammar/import/import_submodule_as/kcl.mod rename to tests/grammar/import/import_submodule_as/kcl.mod diff --git a/test/grammar/import/import_submodule_as/mydir/mydir2/mymodule.k b/tests/grammar/import/import_submodule_as/mydir/mydir2/mymodule.k similarity index 100% rename from test/grammar/import/import_submodule_as/mydir/mydir2/mymodule.k rename to tests/grammar/import/import_submodule_as/mydir/mydir2/mymodule.k diff --git a/test/grammar/import/import_syntax_error_0/app-main/main.k b/tests/grammar/import/import_syntax_error_0/app-main/main.k similarity index 100% rename from test/grammar/import/import_syntax_error_0/app-main/main.k rename to tests/grammar/import/import_syntax_error_0/app-main/main.k diff --git a/test/grammar/import/import_syntax_error_0/app-main/some1/pkg1/pkg1.k b/tests/grammar/import/import_syntax_error_0/app-main/some1/pkg1/pkg1.k similarity index 100% rename from test/grammar/import/import_syntax_error_0/app-main/some1/pkg1/pkg1.k rename to tests/grammar/import/import_syntax_error_0/app-main/some1/pkg1/pkg1.k diff --git a/test/grammar/import/import_syntax_error_0/app-main/stderr.golden b/tests/grammar/import/import_syntax_error_0/app-main/stderr.golden similarity index 100% rename from test/grammar/import/import_syntax_error_0/app-main/stderr.golden rename to tests/grammar/import/import_syntax_error_0/app-main/stderr.golden diff --git a/test/grammar/import/import_syntax_error_0/kcl.mod b/tests/grammar/import/import_syntax_error_0/kcl.mod similarity index 100% rename from test/grammar/import/import_syntax_error_0/kcl.mod rename to tests/grammar/import/import_syntax_error_0/kcl.mod diff --git a/test/grammar/import/import_syntax_error_0/some0/pkg1/pkg1.k b/tests/grammar/import/import_syntax_error_0/some0/pkg1/pkg1.k similarity index 100% rename from test/grammar/import/import_syntax_error_0/some0/pkg1/pkg1.k rename to tests/grammar/import/import_syntax_error_0/some0/pkg1/pkg1.k diff --git a/test/grammar/import/import_syntax_error_0/some1/pkg1/pkg1.k b/tests/grammar/import/import_syntax_error_0/some1/pkg1/pkg1.k similarity index 100% rename from test/grammar/import/import_syntax_error_0/some1/pkg1/pkg1.k rename to tests/grammar/import/import_syntax_error_0/some1/pkg1/pkg1.k diff --git a/test/grammar/import/import_with_complex_types_0/kcl.mod b/tests/grammar/import/import_with_complex_types_0/kcl.mod similarity index 100% rename from test/grammar/import/import_with_complex_types_0/kcl.mod rename to tests/grammar/import/import_with_complex_types_0/kcl.mod diff --git a/test/grammar/import/import_with_complex_types_0/main.k b/tests/grammar/import/import_with_complex_types_0/main.k similarity index 100% rename from test/grammar/import/import_with_complex_types_0/main.k rename to tests/grammar/import/import_with_complex_types_0/main.k diff --git a/test/grammar/import/import_with_complex_types_0/types/host.k b/tests/grammar/import/import_with_complex_types_0/types/host.k similarity index 100% rename from test/grammar/import/import_with_complex_types_0/types/host.k rename to tests/grammar/import/import_with_complex_types_0/types/host.k diff --git a/test/grammar/import/import_with_complex_types_1/kcl.mod b/tests/grammar/import/import_with_complex_types_1/kcl.mod similarity index 100% rename from test/grammar/import/import_with_complex_types_1/kcl.mod rename to tests/grammar/import/import_with_complex_types_1/kcl.mod diff --git a/test/grammar/import/import_with_complex_types_1/main.k b/tests/grammar/import/import_with_complex_types_1/main.k similarity index 100% rename from test/grammar/import/import_with_complex_types_1/main.k rename to tests/grammar/import/import_with_complex_types_1/main.k diff --git a/test/grammar/import/import_with_complex_types_1/types/host.k b/tests/grammar/import/import_with_complex_types_1/types/host.k similarity index 100% rename from test/grammar/import/import_with_complex_types_1/types/host.k rename to tests/grammar/import/import_with_complex_types_1/types/host.k diff --git a/test/grammar/import/module/no_module_attr_fail_0/kcl.mod b/tests/grammar/import/module/no_module_attr_fail_0/kcl.mod similarity index 100% rename from test/grammar/import/module/no_module_attr_fail_0/kcl.mod rename to tests/grammar/import/module/no_module_attr_fail_0/kcl.mod diff --git a/test/grammar/import/module/no_module_attr_fail_0/main.k b/tests/grammar/import/module/no_module_attr_fail_0/main.k similarity index 100% rename from test/grammar/import/module/no_module_attr_fail_0/main.k rename to tests/grammar/import/module/no_module_attr_fail_0/main.k diff --git a/test/grammar/import/module/no_module_attr_fail_0/pkg/a.k b/tests/grammar/import/module/no_module_attr_fail_0/pkg/a.k similarity index 100% rename from test/grammar/import/module/no_module_attr_fail_0/pkg/a.k rename to tests/grammar/import/module/no_module_attr_fail_0/pkg/a.k diff --git a/test/grammar/import/module/no_module_attr_fail_0/stderr.golden b/tests/grammar/import/module/no_module_attr_fail_0/stderr.golden similarity index 100% rename from test/grammar/import/module/no_module_attr_fail_0/stderr.golden rename to tests/grammar/import/module/no_module_attr_fail_0/stderr.golden diff --git a/test/grammar/import/module/no_module_attr_fail_1/kcl.mod b/tests/grammar/import/module/no_module_attr_fail_1/kcl.mod similarity index 100% rename from test/grammar/import/module/no_module_attr_fail_1/kcl.mod rename to tests/grammar/import/module/no_module_attr_fail_1/kcl.mod diff --git a/test/grammar/import/module/no_module_attr_fail_1/main.k b/tests/grammar/import/module/no_module_attr_fail_1/main.k similarity index 100% rename from test/grammar/import/module/no_module_attr_fail_1/main.k rename to tests/grammar/import/module/no_module_attr_fail_1/main.k diff --git a/test/grammar/import/module/no_module_attr_fail_1/pkg/a.k b/tests/grammar/import/module/no_module_attr_fail_1/pkg/a.k similarity index 100% rename from test/grammar/import/module/no_module_attr_fail_1/pkg/a.k rename to tests/grammar/import/module/no_module_attr_fail_1/pkg/a.k diff --git a/test/grammar/import/module/no_module_attr_fail_1/stderr.golden b/tests/grammar/import/module/no_module_attr_fail_1/stderr.golden similarity index 100% rename from test/grammar/import/module/no_module_attr_fail_1/stderr.golden rename to tests/grammar/import/module/no_module_attr_fail_1/stderr.golden diff --git a/test/grammar/import/module/no_module_attr_fail_2/main.k b/tests/grammar/import/module/no_module_attr_fail_2/main.k similarity index 100% rename from test/grammar/import/module/no_module_attr_fail_2/main.k rename to tests/grammar/import/module/no_module_attr_fail_2/main.k diff --git a/test/grammar/import/module/no_module_attr_fail_2/stderr.golden b/tests/grammar/import/module/no_module_attr_fail_2/stderr.golden similarity index 100% rename from test/grammar/import/module/no_module_attr_fail_2/stderr.golden rename to tests/grammar/import/module/no_module_attr_fail_2/stderr.golden diff --git a/test/grammar/import/module/no_module_attr_fail_3/main.k b/tests/grammar/import/module/no_module_attr_fail_3/main.k similarity index 100% rename from test/grammar/import/module/no_module_attr_fail_3/main.k rename to tests/grammar/import/module/no_module_attr_fail_3/main.k diff --git a/test/grammar/import/module/no_module_attr_fail_3/stderr.golden b/tests/grammar/import/module/no_module_attr_fail_3/stderr.golden similarity index 100% rename from test/grammar/import/module/no_module_attr_fail_3/stderr.golden rename to tests/grammar/import/module/no_module_attr_fail_3/stderr.golden diff --git a/test/grammar/import/no_kcl_mod_file/main.k b/tests/grammar/import/no_kcl_mod_file/main.k similarity index 100% rename from test/grammar/import/no_kcl_mod_file/main.k rename to tests/grammar/import/no_kcl_mod_file/main.k diff --git a/test/grammar/import/no_kcl_mod_file/pkg1/pkg.k b/tests/grammar/import/no_kcl_mod_file/pkg1/pkg.k similarity index 100% rename from test/grammar/import/no_kcl_mod_file/pkg1/pkg.k rename to tests/grammar/import/no_kcl_mod_file/pkg1/pkg.k diff --git a/test/grammar/import/no_kcl_mod_file/pkg2.k b/tests/grammar/import/no_kcl_mod_file/pkg2.k similarity index 100% rename from test/grammar/import/no_kcl_mod_file/pkg2.k rename to tests/grammar/import/no_kcl_mod_file/pkg2.k diff --git a/test/grammar/import/no_kcl_mod_file/stdout.golden b/tests/grammar/import/no_kcl_mod_file/stdout.golden similarity index 100% rename from test/grammar/import/no_kcl_mod_file/stdout.golden rename to tests/grammar/import/no_kcl_mod_file/stdout.golden diff --git a/test/grammar/import/pkg_inplace_modify_fail_0/kcl.mod b/tests/grammar/import/pkg_inplace_modify_fail_0/kcl.mod similarity index 100% rename from test/grammar/import/pkg_inplace_modify_fail_0/kcl.mod rename to tests/grammar/import/pkg_inplace_modify_fail_0/kcl.mod diff --git a/test/grammar/import/pkg_inplace_modify_fail_0/main.k b/tests/grammar/import/pkg_inplace_modify_fail_0/main.k similarity index 100% rename from test/grammar/import/pkg_inplace_modify_fail_0/main.k rename to tests/grammar/import/pkg_inplace_modify_fail_0/main.k diff --git a/test/grammar/import/pkg_inplace_modify_fail_0/pkg/pkg.k b/tests/grammar/import/pkg_inplace_modify_fail_0/pkg/pkg.k similarity index 100% rename from test/grammar/import/pkg_inplace_modify_fail_0/pkg/pkg.k rename to tests/grammar/import/pkg_inplace_modify_fail_0/pkg/pkg.k diff --git a/test/grammar/import/pkg_inplace_modify_fail_0/stderr.golden b/tests/grammar/import/pkg_inplace_modify_fail_0/stderr.golden similarity index 100% rename from test/grammar/import/pkg_inplace_modify_fail_0/stderr.golden rename to tests/grammar/import/pkg_inplace_modify_fail_0/stderr.golden diff --git a/test/grammar/import/pkg_inplace_modify_fail_1/main.k b/tests/grammar/import/pkg_inplace_modify_fail_1/main.k similarity index 100% rename from test/grammar/import/pkg_inplace_modify_fail_1/main.k rename to tests/grammar/import/pkg_inplace_modify_fail_1/main.k diff --git a/test/grammar/import/pkg_inplace_modify_fail_1/pkg/pkg.k b/tests/grammar/import/pkg_inplace_modify_fail_1/pkg/pkg.k similarity index 100% rename from test/grammar/import/pkg_inplace_modify_fail_1/pkg/pkg.k rename to tests/grammar/import/pkg_inplace_modify_fail_1/pkg/pkg.k diff --git a/test/grammar/import/pkg_inplace_modify_fail_1/stderr.golden b/tests/grammar/import/pkg_inplace_modify_fail_1/stderr.golden similarity index 100% rename from test/grammar/import/pkg_inplace_modify_fail_1/stderr.golden rename to tests/grammar/import/pkg_inplace_modify_fail_1/stderr.golden diff --git a/test/grammar/import/pkg_inplace_modify_fail_2/main.k b/tests/grammar/import/pkg_inplace_modify_fail_2/main.k similarity index 100% rename from test/grammar/import/pkg_inplace_modify_fail_2/main.k rename to tests/grammar/import/pkg_inplace_modify_fail_2/main.k diff --git a/test/grammar/import/pkg_inplace_modify_fail_2/pkg/pkg.k b/tests/grammar/import/pkg_inplace_modify_fail_2/pkg/pkg.k similarity index 100% rename from test/grammar/import/pkg_inplace_modify_fail_2/pkg/pkg.k rename to tests/grammar/import/pkg_inplace_modify_fail_2/pkg/pkg.k diff --git a/test/grammar/import/pkg_inplace_modify_fail_2/stderr.golden b/tests/grammar/import/pkg_inplace_modify_fail_2/stderr.golden similarity index 100% rename from test/grammar/import/pkg_inplace_modify_fail_2/stderr.golden rename to tests/grammar/import/pkg_inplace_modify_fail_2/stderr.golden diff --git a/test/grammar/import/relative_import/main.k b/tests/grammar/import/relative_import/main.k similarity index 100% rename from test/grammar/import/relative_import/main.k rename to tests/grammar/import/relative_import/main.k diff --git a/test/grammar/import/relative_import/mydir/mydir2/mymodule2.k b/tests/grammar/import/relative_import/mydir/mydir2/mymodule2.k similarity index 100% rename from test/grammar/import/relative_import/mydir/mydir2/mymodule2.k rename to tests/grammar/import/relative_import/mydir/mydir2/mymodule2.k diff --git a/test/grammar/import/relative_import/mydir/mymodule.k b/tests/grammar/import/relative_import/mydir/mymodule.k similarity index 100% rename from test/grammar/import/relative_import/mydir/mymodule.k rename to tests/grammar/import/relative_import/mydir/mymodule.k diff --git a/test/grammar/import/relative_import/stdout.golden b/tests/grammar/import/relative_import/stdout.golden similarity index 100% rename from test/grammar/import/relative_import/stdout.golden rename to tests/grammar/import/relative_import/stdout.golden diff --git a/test/grammar/import/relative_import_as/main.k b/tests/grammar/import/relative_import_as/main.k similarity index 100% rename from test/grammar/import/relative_import_as/main.k rename to tests/grammar/import/relative_import_as/main.k diff --git a/test/grammar/import/relative_import_as/mydir/mydir2/mymodule2.k b/tests/grammar/import/relative_import_as/mydir/mydir2/mymodule2.k similarity index 100% rename from test/grammar/import/relative_import_as/mydir/mydir2/mymodule2.k rename to tests/grammar/import/relative_import_as/mydir/mydir2/mymodule2.k diff --git a/test/grammar/import/relative_import_as/mydir/mymodule.k b/tests/grammar/import/relative_import_as/mydir/mymodule.k similarity index 100% rename from test/grammar/import/relative_import_as/mydir/mymodule.k rename to tests/grammar/import/relative_import_as/mydir/mymodule.k diff --git a/test/grammar/import/relative_import_as/stdout.golden b/tests/grammar/import/relative_import_as/stdout.golden similarity index 100% rename from test/grammar/import/relative_import_as/stdout.golden rename to tests/grammar/import/relative_import_as/stdout.golden diff --git a/test/grammar/lambda/arg_type/main.k b/tests/grammar/lambda/arg_type/main.k similarity index 100% rename from test/grammar/lambda/arg_type/main.k rename to tests/grammar/lambda/arg_type/main.k diff --git a/test/grammar/lambda/arg_type/stdout.golden b/tests/grammar/lambda/arg_type/stdout.golden similarity index 100% rename from test/grammar/lambda/arg_type/stdout.golden rename to tests/grammar/lambda/arg_type/stdout.golden diff --git a/test/grammar/lambda/arg_type/sub.k b/tests/grammar/lambda/arg_type/sub.k similarity index 100% rename from test/grammar/lambda/arg_type/sub.k rename to tests/grammar/lambda/arg_type/sub.k diff --git a/test/grammar/lambda/arg_type_annotation/main.k b/tests/grammar/lambda/arg_type_annotation/main.k similarity index 100% rename from test/grammar/lambda/arg_type_annotation/main.k rename to tests/grammar/lambda/arg_type_annotation/main.k diff --git a/test/grammar/lambda/arg_type_annotation/stdout.golden b/tests/grammar/lambda/arg_type_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/arg_type_annotation/stdout.golden rename to tests/grammar/lambda/arg_type_annotation/stdout.golden diff --git a/test/grammar/lambda/arg_type_annotation/sub.k b/tests/grammar/lambda/arg_type_annotation/sub.k similarity index 100% rename from test/grammar/lambda/arg_type_annotation/sub.k rename to tests/grammar/lambda/arg_type_annotation/sub.k diff --git a/test/grammar/lambda/closure_0/main.k b/tests/grammar/lambda/closure_0/main.k similarity index 100% rename from test/grammar/lambda/closure_0/main.k rename to tests/grammar/lambda/closure_0/main.k diff --git a/test/grammar/lambda/closure_0/stdout.golden b/tests/grammar/lambda/closure_0/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_0/stdout.golden rename to tests/grammar/lambda/closure_0/stdout.golden diff --git a/test/grammar/lambda/closure_0_annotation/main.k b/tests/grammar/lambda/closure_0_annotation/main.k similarity index 100% rename from test/grammar/lambda/closure_0_annotation/main.k rename to tests/grammar/lambda/closure_0_annotation/main.k diff --git a/test/grammar/lambda/closure_0_annotation/stdout.golden b/tests/grammar/lambda/closure_0_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_0_annotation/stdout.golden rename to tests/grammar/lambda/closure_0_annotation/stdout.golden diff --git a/test/grammar/lambda/closure_1/main.k b/tests/grammar/lambda/closure_1/main.k similarity index 100% rename from test/grammar/lambda/closure_1/main.k rename to tests/grammar/lambda/closure_1/main.k diff --git a/test/grammar/lambda/closure_1/stdout.golden b/tests/grammar/lambda/closure_1/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_1/stdout.golden rename to tests/grammar/lambda/closure_1/stdout.golden diff --git a/test/grammar/lambda/closure_10/main.k b/tests/grammar/lambda/closure_10/main.k similarity index 100% rename from test/grammar/lambda/closure_10/main.k rename to tests/grammar/lambda/closure_10/main.k diff --git a/test/grammar/lambda/closure_10/stdout.golden b/tests/grammar/lambda/closure_10/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_10/stdout.golden rename to tests/grammar/lambda/closure_10/stdout.golden diff --git a/test/grammar/lambda/closure_11/main.k b/tests/grammar/lambda/closure_11/main.k similarity index 100% rename from test/grammar/lambda/closure_11/main.k rename to tests/grammar/lambda/closure_11/main.k diff --git a/test/grammar/lambda/closure_11/stdout.golden b/tests/grammar/lambda/closure_11/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_11/stdout.golden rename to tests/grammar/lambda/closure_11/stdout.golden diff --git a/test/grammar/lambda/closure_1_annotation/main.k b/tests/grammar/lambda/closure_1_annotation/main.k similarity index 100% rename from test/grammar/lambda/closure_1_annotation/main.k rename to tests/grammar/lambda/closure_1_annotation/main.k diff --git a/test/grammar/lambda/closure_1_annotation/stdout.golden b/tests/grammar/lambda/closure_1_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_1_annotation/stdout.golden rename to tests/grammar/lambda/closure_1_annotation/stdout.golden diff --git a/test/grammar/lambda/closure_2/main.k b/tests/grammar/lambda/closure_2/main.k similarity index 100% rename from test/grammar/lambda/closure_2/main.k rename to tests/grammar/lambda/closure_2/main.k diff --git a/test/grammar/lambda/closure_2/stdout.golden b/tests/grammar/lambda/closure_2/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_2/stdout.golden rename to tests/grammar/lambda/closure_2/stdout.golden diff --git a/test/grammar/lambda/closure_2_annotation/main.k b/tests/grammar/lambda/closure_2_annotation/main.k similarity index 100% rename from test/grammar/lambda/closure_2_annotation/main.k rename to tests/grammar/lambda/closure_2_annotation/main.k diff --git a/test/grammar/lambda/closure_2_annotation/stdout.golden b/tests/grammar/lambda/closure_2_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_2_annotation/stdout.golden rename to tests/grammar/lambda/closure_2_annotation/stdout.golden diff --git a/test/grammar/lambda/closure_3/main.k b/tests/grammar/lambda/closure_3/main.k similarity index 100% rename from test/grammar/lambda/closure_3/main.k rename to tests/grammar/lambda/closure_3/main.k diff --git a/test/grammar/lambda/closure_3/stdout.golden b/tests/grammar/lambda/closure_3/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_3/stdout.golden rename to tests/grammar/lambda/closure_3/stdout.golden diff --git a/test/grammar/lambda/closure_4/main.k b/tests/grammar/lambda/closure_4/main.k similarity index 100% rename from test/grammar/lambda/closure_4/main.k rename to tests/grammar/lambda/closure_4/main.k diff --git a/test/grammar/lambda/closure_4/stdout.golden b/tests/grammar/lambda/closure_4/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_4/stdout.golden rename to tests/grammar/lambda/closure_4/stdout.golden diff --git a/test/grammar/lambda/closure_4_annotation/main.k b/tests/grammar/lambda/closure_4_annotation/main.k similarity index 100% rename from test/grammar/lambda/closure_4_annotation/main.k rename to tests/grammar/lambda/closure_4_annotation/main.k diff --git a/test/grammar/lambda/closure_4_annotation/stdout.golden b/tests/grammar/lambda/closure_4_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_4_annotation/stdout.golden rename to tests/grammar/lambda/closure_4_annotation/stdout.golden diff --git a/test/grammar/lambda/closure_5/main.k b/tests/grammar/lambda/closure_5/main.k similarity index 100% rename from test/grammar/lambda/closure_5/main.k rename to tests/grammar/lambda/closure_5/main.k diff --git a/test/grammar/lambda/closure_5/stdout.golden b/tests/grammar/lambda/closure_5/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_5/stdout.golden rename to tests/grammar/lambda/closure_5/stdout.golden diff --git a/test/grammar/lambda/closure_5_annotation/main.k b/tests/grammar/lambda/closure_5_annotation/main.k similarity index 100% rename from test/grammar/lambda/closure_5_annotation/main.k rename to tests/grammar/lambda/closure_5_annotation/main.k diff --git a/test/grammar/lambda/closure_5_annotation/stdout.golden b/tests/grammar/lambda/closure_5_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_5_annotation/stdout.golden rename to tests/grammar/lambda/closure_5_annotation/stdout.golden diff --git a/test/grammar/lambda/closure_6/main.k b/tests/grammar/lambda/closure_6/main.k similarity index 100% rename from test/grammar/lambda/closure_6/main.k rename to tests/grammar/lambda/closure_6/main.k diff --git a/test/grammar/lambda/closure_6/stdout.golden b/tests/grammar/lambda/closure_6/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_6/stdout.golden rename to tests/grammar/lambda/closure_6/stdout.golden diff --git a/test/grammar/lambda/closure_7/main.k b/tests/grammar/lambda/closure_7/main.k similarity index 100% rename from test/grammar/lambda/closure_7/main.k rename to tests/grammar/lambda/closure_7/main.k diff --git a/test/grammar/lambda/closure_7/stdout.golden b/tests/grammar/lambda/closure_7/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_7/stdout.golden rename to tests/grammar/lambda/closure_7/stdout.golden diff --git a/test/grammar/lambda/closure_8/main.k b/tests/grammar/lambda/closure_8/main.k similarity index 100% rename from test/grammar/lambda/closure_8/main.k rename to tests/grammar/lambda/closure_8/main.k diff --git a/test/grammar/lambda/closure_8/stdout.golden b/tests/grammar/lambda/closure_8/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_8/stdout.golden rename to tests/grammar/lambda/closure_8/stdout.golden diff --git a/test/grammar/lambda/closure_9/main.k b/tests/grammar/lambda/closure_9/main.k similarity index 100% rename from test/grammar/lambda/closure_9/main.k rename to tests/grammar/lambda/closure_9/main.k diff --git a/test/grammar/lambda/closure_9/stdout.golden b/tests/grammar/lambda/closure_9/stdout.golden similarity index 100% rename from test/grammar/lambda/closure_9/stdout.golden rename to tests/grammar/lambda/closure_9/stdout.golden diff --git a/test/grammar/lambda/in_diff_pkg/kcl.mod b/tests/grammar/lambda/in_diff_pkg/kcl.mod similarity index 100% rename from test/grammar/lambda/in_diff_pkg/kcl.mod rename to tests/grammar/lambda/in_diff_pkg/kcl.mod diff --git a/test/grammar/lambda/in_diff_pkg/main.k b/tests/grammar/lambda/in_diff_pkg/main.k similarity index 100% rename from test/grammar/lambda/in_diff_pkg/main.k rename to tests/grammar/lambda/in_diff_pkg/main.k diff --git a/test/grammar/lambda/in_diff_pkg/pkg/pkg.k b/tests/grammar/lambda/in_diff_pkg/pkg/pkg.k similarity index 100% rename from test/grammar/lambda/in_diff_pkg/pkg/pkg.k rename to tests/grammar/lambda/in_diff_pkg/pkg/pkg.k diff --git a/test/grammar/lambda/in_diff_pkg/stdout.golden b/tests/grammar/lambda/in_diff_pkg/stdout.golden similarity index 100% rename from test/grammar/lambda/in_diff_pkg/stdout.golden rename to tests/grammar/lambda/in_diff_pkg/stdout.golden diff --git a/test/grammar/lambda/in_diff_pkg_annotation/kcl.mod b/tests/grammar/lambda/in_diff_pkg_annotation/kcl.mod similarity index 100% rename from test/grammar/lambda/in_diff_pkg_annotation/kcl.mod rename to tests/grammar/lambda/in_diff_pkg_annotation/kcl.mod diff --git a/test/grammar/lambda/in_diff_pkg_annotation/main.k b/tests/grammar/lambda/in_diff_pkg_annotation/main.k similarity index 100% rename from test/grammar/lambda/in_diff_pkg_annotation/main.k rename to tests/grammar/lambda/in_diff_pkg_annotation/main.k diff --git a/test/grammar/lambda/in_diff_pkg_annotation/pkg/pkg.k b/tests/grammar/lambda/in_diff_pkg_annotation/pkg/pkg.k similarity index 100% rename from test/grammar/lambda/in_diff_pkg_annotation/pkg/pkg.k rename to tests/grammar/lambda/in_diff_pkg_annotation/pkg/pkg.k diff --git a/test/grammar/lambda/in_diff_pkg_annotation/stdout.golden b/tests/grammar/lambda/in_diff_pkg_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/in_diff_pkg_annotation/stdout.golden rename to tests/grammar/lambda/in_diff_pkg_annotation/stdout.golden diff --git a/test/grammar/lambda/in_for_0/main.k b/tests/grammar/lambda/in_for_0/main.k similarity index 100% rename from test/grammar/lambda/in_for_0/main.k rename to tests/grammar/lambda/in_for_0/main.k diff --git a/test/grammar/lambda/in_for_0/stdout.golden b/tests/grammar/lambda/in_for_0/stdout.golden similarity index 100% rename from test/grammar/lambda/in_for_0/stdout.golden rename to tests/grammar/lambda/in_for_0/stdout.golden diff --git a/test/grammar/lambda/in_for_0_annotation/main.k b/tests/grammar/lambda/in_for_0_annotation/main.k similarity index 100% rename from test/grammar/lambda/in_for_0_annotation/main.k rename to tests/grammar/lambda/in_for_0_annotation/main.k diff --git a/test/grammar/lambda/in_for_0_annotation/stdout.golden b/tests/grammar/lambda/in_for_0_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/in_for_0_annotation/stdout.golden rename to tests/grammar/lambda/in_for_0_annotation/stdout.golden diff --git a/test/grammar/lambda/in_for_1/main.k b/tests/grammar/lambda/in_for_1/main.k similarity index 100% rename from test/grammar/lambda/in_for_1/main.k rename to tests/grammar/lambda/in_for_1/main.k diff --git a/test/grammar/lambda/in_for_1/stdout.golden b/tests/grammar/lambda/in_for_1/stdout.golden similarity index 100% rename from test/grammar/lambda/in_for_1/stdout.golden rename to tests/grammar/lambda/in_for_1/stdout.golden diff --git a/test/grammar/lambda/in_for_1_annotation/main.k b/tests/grammar/lambda/in_for_1_annotation/main.k similarity index 100% rename from test/grammar/lambda/in_for_1_annotation/main.k rename to tests/grammar/lambda/in_for_1_annotation/main.k diff --git a/test/grammar/lambda/in_for_1_annotation/stdout.golden b/tests/grammar/lambda/in_for_1_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/in_for_1_annotation/stdout.golden rename to tests/grammar/lambda/in_for_1_annotation/stdout.golden diff --git a/test/grammar/lambda/in_for_2/main.k b/tests/grammar/lambda/in_for_2/main.k similarity index 100% rename from test/grammar/lambda/in_for_2/main.k rename to tests/grammar/lambda/in_for_2/main.k diff --git a/test/grammar/lambda/in_for_2/stdout.golden b/tests/grammar/lambda/in_for_2/stdout.golden similarity index 100% rename from test/grammar/lambda/in_for_2/stdout.golden rename to tests/grammar/lambda/in_for_2/stdout.golden diff --git a/test/grammar/lambda/in_for_2_annotation/main.k b/tests/grammar/lambda/in_for_2_annotation/main.k similarity index 100% rename from test/grammar/lambda/in_for_2_annotation/main.k rename to tests/grammar/lambda/in_for_2_annotation/main.k diff --git a/test/grammar/lambda/in_for_2_annotation/stdout.golden b/tests/grammar/lambda/in_for_2_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/in_for_2_annotation/stdout.golden rename to tests/grammar/lambda/in_for_2_annotation/stdout.golden diff --git a/test/grammar/lambda/in_for_3/main.k b/tests/grammar/lambda/in_for_3/main.k similarity index 100% rename from test/grammar/lambda/in_for_3/main.k rename to tests/grammar/lambda/in_for_3/main.k diff --git a/test/grammar/lambda/in_for_3/stdout.golden b/tests/grammar/lambda/in_for_3/stdout.golden similarity index 100% rename from test/grammar/lambda/in_for_3/stdout.golden rename to tests/grammar/lambda/in_for_3/stdout.golden diff --git a/test/grammar/lambda/in_pkg_0/kcl.mod b/tests/grammar/lambda/in_pkg_0/kcl.mod similarity index 100% rename from test/grammar/lambda/in_pkg_0/kcl.mod rename to tests/grammar/lambda/in_pkg_0/kcl.mod diff --git a/test/grammar/lambda/in_pkg_0/main.k b/tests/grammar/lambda/in_pkg_0/main.k similarity index 100% rename from test/grammar/lambda/in_pkg_0/main.k rename to tests/grammar/lambda/in_pkg_0/main.k diff --git a/test/grammar/lambda/in_pkg_0/pkg/pkg.k b/tests/grammar/lambda/in_pkg_0/pkg/pkg.k similarity index 100% rename from test/grammar/lambda/in_pkg_0/pkg/pkg.k rename to tests/grammar/lambda/in_pkg_0/pkg/pkg.k diff --git a/test/grammar/lambda/in_pkg_0/stdout.golden b/tests/grammar/lambda/in_pkg_0/stdout.golden similarity index 100% rename from test/grammar/lambda/in_pkg_0/stdout.golden rename to tests/grammar/lambda/in_pkg_0/stdout.golden diff --git a/test/grammar/lambda/in_pkg_0_annotation/kcl.mod b/tests/grammar/lambda/in_pkg_0_annotation/kcl.mod similarity index 100% rename from test/grammar/lambda/in_pkg_0_annotation/kcl.mod rename to tests/grammar/lambda/in_pkg_0_annotation/kcl.mod diff --git a/test/grammar/lambda/in_pkg_0_annotation/main.k b/tests/grammar/lambda/in_pkg_0_annotation/main.k similarity index 100% rename from test/grammar/lambda/in_pkg_0_annotation/main.k rename to tests/grammar/lambda/in_pkg_0_annotation/main.k diff --git a/test/grammar/lambda/in_pkg_0_annotation/pkg/pkg.k b/tests/grammar/lambda/in_pkg_0_annotation/pkg/pkg.k similarity index 100% rename from test/grammar/lambda/in_pkg_0_annotation/pkg/pkg.k rename to tests/grammar/lambda/in_pkg_0_annotation/pkg/pkg.k diff --git a/test/grammar/lambda/in_pkg_0_annotation/stdout.golden b/tests/grammar/lambda/in_pkg_0_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/in_pkg_0_annotation/stdout.golden rename to tests/grammar/lambda/in_pkg_0_annotation/stdout.golden diff --git a/test/grammar/lambda/in_pkg_1/kcl.mod b/tests/grammar/lambda/in_pkg_1/kcl.mod similarity index 100% rename from test/grammar/lambda/in_pkg_1/kcl.mod rename to tests/grammar/lambda/in_pkg_1/kcl.mod diff --git a/test/grammar/lambda/in_pkg_1/main.k b/tests/grammar/lambda/in_pkg_1/main.k similarity index 100% rename from test/grammar/lambda/in_pkg_1/main.k rename to tests/grammar/lambda/in_pkg_1/main.k diff --git a/test/grammar/lambda/in_pkg_1/pkg/pkg.k b/tests/grammar/lambda/in_pkg_1/pkg/pkg.k similarity index 100% rename from test/grammar/lambda/in_pkg_1/pkg/pkg.k rename to tests/grammar/lambda/in_pkg_1/pkg/pkg.k diff --git a/test/grammar/lambda/in_pkg_1/stdout.golden b/tests/grammar/lambda/in_pkg_1/stdout.golden similarity index 100% rename from test/grammar/lambda/in_pkg_1/stdout.golden rename to tests/grammar/lambda/in_pkg_1/stdout.golden diff --git a/test/grammar/lambda/in_pkg_1_annotation/kcl.mod b/tests/grammar/lambda/in_pkg_1_annotation/kcl.mod similarity index 100% rename from test/grammar/lambda/in_pkg_1_annotation/kcl.mod rename to tests/grammar/lambda/in_pkg_1_annotation/kcl.mod diff --git a/test/grammar/lambda/in_pkg_1_annotation/main.k b/tests/grammar/lambda/in_pkg_1_annotation/main.k similarity index 100% rename from test/grammar/lambda/in_pkg_1_annotation/main.k rename to tests/grammar/lambda/in_pkg_1_annotation/main.k diff --git a/test/grammar/lambda/in_pkg_1_annotation/pkg/pkg.k b/tests/grammar/lambda/in_pkg_1_annotation/pkg/pkg.k similarity index 100% rename from test/grammar/lambda/in_pkg_1_annotation/pkg/pkg.k rename to tests/grammar/lambda/in_pkg_1_annotation/pkg/pkg.k diff --git a/test/grammar/lambda/in_pkg_1_annotation/stdout.golden b/tests/grammar/lambda/in_pkg_1_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/in_pkg_1_annotation/stdout.golden rename to tests/grammar/lambda/in_pkg_1_annotation/stdout.golden diff --git a/test/grammar/lambda/in_schema_0/main.k b/tests/grammar/lambda/in_schema_0/main.k similarity index 100% rename from test/grammar/lambda/in_schema_0/main.k rename to tests/grammar/lambda/in_schema_0/main.k diff --git a/test/grammar/lambda/in_schema_0/stdout.golden b/tests/grammar/lambda/in_schema_0/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_0/stdout.golden rename to tests/grammar/lambda/in_schema_0/stdout.golden diff --git a/test/grammar/lambda/in_schema_0_annotation/main.k b/tests/grammar/lambda/in_schema_0_annotation/main.k similarity index 100% rename from test/grammar/lambda/in_schema_0_annotation/main.k rename to tests/grammar/lambda/in_schema_0_annotation/main.k diff --git a/test/grammar/lambda/in_schema_0_annotation/stdout.golden b/tests/grammar/lambda/in_schema_0_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_0_annotation/stdout.golden rename to tests/grammar/lambda/in_schema_0_annotation/stdout.golden diff --git a/test/grammar/lambda/in_schema_1/main.k b/tests/grammar/lambda/in_schema_1/main.k similarity index 100% rename from test/grammar/lambda/in_schema_1/main.k rename to tests/grammar/lambda/in_schema_1/main.k diff --git a/test/grammar/lambda/in_schema_1/stdout.golden b/tests/grammar/lambda/in_schema_1/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_1/stdout.golden rename to tests/grammar/lambda/in_schema_1/stdout.golden diff --git a/test/grammar/lambda/in_schema_10/main.k b/tests/grammar/lambda/in_schema_10/main.k similarity index 100% rename from test/grammar/lambda/in_schema_10/main.k rename to tests/grammar/lambda/in_schema_10/main.k diff --git a/test/grammar/lambda/in_schema_10/stdout.golden b/tests/grammar/lambda/in_schema_10/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_10/stdout.golden rename to tests/grammar/lambda/in_schema_10/stdout.golden diff --git a/test/grammar/lambda/in_schema_11/main.k b/tests/grammar/lambda/in_schema_11/main.k similarity index 100% rename from test/grammar/lambda/in_schema_11/main.k rename to tests/grammar/lambda/in_schema_11/main.k diff --git a/test/grammar/lambda/in_schema_11/stdout.golden b/tests/grammar/lambda/in_schema_11/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_11/stdout.golden rename to tests/grammar/lambda/in_schema_11/stdout.golden diff --git a/test/grammar/lambda/in_schema_1_annotation/main.k b/tests/grammar/lambda/in_schema_1_annotation/main.k similarity index 100% rename from test/grammar/lambda/in_schema_1_annotation/main.k rename to tests/grammar/lambda/in_schema_1_annotation/main.k diff --git a/test/grammar/lambda/in_schema_1_annotation/stdout.golden b/tests/grammar/lambda/in_schema_1_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_1_annotation/stdout.golden rename to tests/grammar/lambda/in_schema_1_annotation/stdout.golden diff --git a/test/grammar/lambda/in_schema_2/main.k b/tests/grammar/lambda/in_schema_2/main.k similarity index 100% rename from test/grammar/lambda/in_schema_2/main.k rename to tests/grammar/lambda/in_schema_2/main.k diff --git a/test/grammar/lambda/in_schema_2/stdout.golden b/tests/grammar/lambda/in_schema_2/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_2/stdout.golden rename to tests/grammar/lambda/in_schema_2/stdout.golden diff --git a/test/grammar/lambda/in_schema_2_annotation/main.k b/tests/grammar/lambda/in_schema_2_annotation/main.k similarity index 100% rename from test/grammar/lambda/in_schema_2_annotation/main.k rename to tests/grammar/lambda/in_schema_2_annotation/main.k diff --git a/test/grammar/lambda/in_schema_2_annotation/stdout.golden b/tests/grammar/lambda/in_schema_2_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_2_annotation/stdout.golden rename to tests/grammar/lambda/in_schema_2_annotation/stdout.golden diff --git a/test/grammar/lambda/in_schema_3/main.k b/tests/grammar/lambda/in_schema_3/main.k similarity index 100% rename from test/grammar/lambda/in_schema_3/main.k rename to tests/grammar/lambda/in_schema_3/main.k diff --git a/test/grammar/lambda/in_schema_3/stdout.golden b/tests/grammar/lambda/in_schema_3/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_3/stdout.golden rename to tests/grammar/lambda/in_schema_3/stdout.golden diff --git a/test/grammar/lambda/in_schema_4/main.k b/tests/grammar/lambda/in_schema_4/main.k similarity index 100% rename from test/grammar/lambda/in_schema_4/main.k rename to tests/grammar/lambda/in_schema_4/main.k diff --git a/test/grammar/lambda/in_schema_4/stdout.golden b/tests/grammar/lambda/in_schema_4/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_4/stdout.golden rename to tests/grammar/lambda/in_schema_4/stdout.golden diff --git a/test/grammar/lambda/in_schema_5/main.k b/tests/grammar/lambda/in_schema_5/main.k similarity index 100% rename from test/grammar/lambda/in_schema_5/main.k rename to tests/grammar/lambda/in_schema_5/main.k diff --git a/test/grammar/lambda/in_schema_5/stdout.golden b/tests/grammar/lambda/in_schema_5/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_5/stdout.golden rename to tests/grammar/lambda/in_schema_5/stdout.golden diff --git a/test/grammar/lambda/in_schema_6/main.k b/tests/grammar/lambda/in_schema_6/main.k similarity index 100% rename from test/grammar/lambda/in_schema_6/main.k rename to tests/grammar/lambda/in_schema_6/main.k diff --git a/test/grammar/lambda/in_schema_6/stdout.golden b/tests/grammar/lambda/in_schema_6/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_6/stdout.golden rename to tests/grammar/lambda/in_schema_6/stdout.golden diff --git a/test/grammar/lambda/in_schema_7/main.k b/tests/grammar/lambda/in_schema_7/main.k similarity index 100% rename from test/grammar/lambda/in_schema_7/main.k rename to tests/grammar/lambda/in_schema_7/main.k diff --git a/test/grammar/lambda/in_schema_7/stdout.golden b/tests/grammar/lambda/in_schema_7/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_7/stdout.golden rename to tests/grammar/lambda/in_schema_7/stdout.golden diff --git a/test/grammar/lambda/in_schema_8/main.k b/tests/grammar/lambda/in_schema_8/main.k similarity index 100% rename from test/grammar/lambda/in_schema_8/main.k rename to tests/grammar/lambda/in_schema_8/main.k diff --git a/test/grammar/lambda/in_schema_8/stdout.golden b/tests/grammar/lambda/in_schema_8/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_8/stdout.golden rename to tests/grammar/lambda/in_schema_8/stdout.golden diff --git a/test/grammar/lambda/in_schema_9/main.k b/tests/grammar/lambda/in_schema_9/main.k similarity index 100% rename from test/grammar/lambda/in_schema_9/main.k rename to tests/grammar/lambda/in_schema_9/main.k diff --git a/test/grammar/lambda/in_schema_9/stdout.golden b/tests/grammar/lambda/in_schema_9/stdout.golden similarity index 100% rename from test/grammar/lambda/in_schema_9/stdout.golden rename to tests/grammar/lambda/in_schema_9/stdout.golden diff --git a/test/grammar/lambda/top_level_0/main.k b/tests/grammar/lambda/top_level_0/main.k similarity index 100% rename from test/grammar/lambda/top_level_0/main.k rename to tests/grammar/lambda/top_level_0/main.k diff --git a/test/grammar/lambda/top_level_0/stdout.golden b/tests/grammar/lambda/top_level_0/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_0/stdout.golden rename to tests/grammar/lambda/top_level_0/stdout.golden diff --git a/test/grammar/lambda/top_level_0_annotation/main.k b/tests/grammar/lambda/top_level_0_annotation/main.k similarity index 100% rename from test/grammar/lambda/top_level_0_annotation/main.k rename to tests/grammar/lambda/top_level_0_annotation/main.k diff --git a/test/grammar/lambda/top_level_0_annotation/stdout.golden b/tests/grammar/lambda/top_level_0_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_0_annotation/stdout.golden rename to tests/grammar/lambda/top_level_0_annotation/stdout.golden diff --git a/test/grammar/lambda/top_level_1/main.k b/tests/grammar/lambda/top_level_1/main.k similarity index 100% rename from test/grammar/lambda/top_level_1/main.k rename to tests/grammar/lambda/top_level_1/main.k diff --git a/test/grammar/lambda/top_level_1/stdout.golden b/tests/grammar/lambda/top_level_1/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_1/stdout.golden rename to tests/grammar/lambda/top_level_1/stdout.golden diff --git a/test/grammar/lambda/top_level_10/main.k b/tests/grammar/lambda/top_level_10/main.k similarity index 100% rename from test/grammar/lambda/top_level_10/main.k rename to tests/grammar/lambda/top_level_10/main.k diff --git a/test/grammar/lambda/top_level_10/stdout.golden b/tests/grammar/lambda/top_level_10/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_10/stdout.golden rename to tests/grammar/lambda/top_level_10/stdout.golden diff --git a/test/grammar/lambda/top_level_11/main.k b/tests/grammar/lambda/top_level_11/main.k similarity index 100% rename from test/grammar/lambda/top_level_11/main.k rename to tests/grammar/lambda/top_level_11/main.k diff --git a/test/grammar/lambda/top_level_11/stdout.golden b/tests/grammar/lambda/top_level_11/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_11/stdout.golden rename to tests/grammar/lambda/top_level_11/stdout.golden diff --git a/test/grammar/lambda/top_level_1_annotation/main.k b/tests/grammar/lambda/top_level_1_annotation/main.k similarity index 100% rename from test/grammar/lambda/top_level_1_annotation/main.k rename to tests/grammar/lambda/top_level_1_annotation/main.k diff --git a/test/grammar/lambda/top_level_1_annotation/stdout.golden b/tests/grammar/lambda/top_level_1_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_1_annotation/stdout.golden rename to tests/grammar/lambda/top_level_1_annotation/stdout.golden diff --git a/test/grammar/lambda/top_level_2/main.k b/tests/grammar/lambda/top_level_2/main.k similarity index 100% rename from test/grammar/lambda/top_level_2/main.k rename to tests/grammar/lambda/top_level_2/main.k diff --git a/test/grammar/lambda/top_level_2/stdout.golden b/tests/grammar/lambda/top_level_2/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_2/stdout.golden rename to tests/grammar/lambda/top_level_2/stdout.golden diff --git a/test/grammar/lambda/top_level_2_annotation/main.k b/tests/grammar/lambda/top_level_2_annotation/main.k similarity index 100% rename from test/grammar/lambda/top_level_2_annotation/main.k rename to tests/grammar/lambda/top_level_2_annotation/main.k diff --git a/test/grammar/lambda/top_level_2_annotation/stdout.golden b/tests/grammar/lambda/top_level_2_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_2_annotation/stdout.golden rename to tests/grammar/lambda/top_level_2_annotation/stdout.golden diff --git a/test/grammar/lambda/top_level_3/main.k b/tests/grammar/lambda/top_level_3/main.k similarity index 100% rename from test/grammar/lambda/top_level_3/main.k rename to tests/grammar/lambda/top_level_3/main.k diff --git a/test/grammar/lambda/top_level_3/stdout.golden b/tests/grammar/lambda/top_level_3/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_3/stdout.golden rename to tests/grammar/lambda/top_level_3/stdout.golden diff --git a/test/grammar/lambda/top_level_4/main.k b/tests/grammar/lambda/top_level_4/main.k similarity index 100% rename from test/grammar/lambda/top_level_4/main.k rename to tests/grammar/lambda/top_level_4/main.k diff --git a/test/grammar/lambda/top_level_4/stdout.golden b/tests/grammar/lambda/top_level_4/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_4/stdout.golden rename to tests/grammar/lambda/top_level_4/stdout.golden diff --git a/test/grammar/lambda/top_level_4_annotation/main.k b/tests/grammar/lambda/top_level_4_annotation/main.k similarity index 100% rename from test/grammar/lambda/top_level_4_annotation/main.k rename to tests/grammar/lambda/top_level_4_annotation/main.k diff --git a/test/grammar/lambda/top_level_4_annotation/stdout.golden b/tests/grammar/lambda/top_level_4_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_4_annotation/stdout.golden rename to tests/grammar/lambda/top_level_4_annotation/stdout.golden diff --git a/test/grammar/lambda/top_level_5/main.k b/tests/grammar/lambda/top_level_5/main.k similarity index 100% rename from test/grammar/lambda/top_level_5/main.k rename to tests/grammar/lambda/top_level_5/main.k diff --git a/test/grammar/lambda/top_level_5/stdout.golden b/tests/grammar/lambda/top_level_5/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_5/stdout.golden rename to tests/grammar/lambda/top_level_5/stdout.golden diff --git a/test/grammar/lambda/top_level_5_annotation/main.k b/tests/grammar/lambda/top_level_5_annotation/main.k similarity index 100% rename from test/grammar/lambda/top_level_5_annotation/main.k rename to tests/grammar/lambda/top_level_5_annotation/main.k diff --git a/test/grammar/lambda/top_level_5_annotation/stdout.golden b/tests/grammar/lambda/top_level_5_annotation/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_5_annotation/stdout.golden rename to tests/grammar/lambda/top_level_5_annotation/stdout.golden diff --git a/test/grammar/lambda/top_level_6/main.k b/tests/grammar/lambda/top_level_6/main.k similarity index 100% rename from test/grammar/lambda/top_level_6/main.k rename to tests/grammar/lambda/top_level_6/main.k diff --git a/test/grammar/lambda/top_level_6/stdout.golden b/tests/grammar/lambda/top_level_6/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_6/stdout.golden rename to tests/grammar/lambda/top_level_6/stdout.golden diff --git a/test/grammar/lambda/top_level_7/main.k b/tests/grammar/lambda/top_level_7/main.k similarity index 100% rename from test/grammar/lambda/top_level_7/main.k rename to tests/grammar/lambda/top_level_7/main.k diff --git a/test/grammar/lambda/top_level_7/stdout.golden b/tests/grammar/lambda/top_level_7/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_7/stdout.golden rename to tests/grammar/lambda/top_level_7/stdout.golden diff --git a/test/grammar/lambda/top_level_8/main.k b/tests/grammar/lambda/top_level_8/main.k similarity index 100% rename from test/grammar/lambda/top_level_8/main.k rename to tests/grammar/lambda/top_level_8/main.k diff --git a/test/grammar/lambda/top_level_8/stdout.golden b/tests/grammar/lambda/top_level_8/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_8/stdout.golden rename to tests/grammar/lambda/top_level_8/stdout.golden diff --git a/test/grammar/lambda/top_level_9/main.k b/tests/grammar/lambda/top_level_9/main.k similarity index 100% rename from test/grammar/lambda/top_level_9/main.k rename to tests/grammar/lambda/top_level_9/main.k diff --git a/test/grammar/lambda/top_level_9/stdout.golden b/tests/grammar/lambda/top_level_9/stdout.golden similarity index 100% rename from test/grammar/lambda/top_level_9/stdout.golden rename to tests/grammar/lambda/top_level_9/stdout.golden diff --git a/test/grammar/lambda/type_annotation/schema/invalid_0/main.k b/tests/grammar/lambda/type_annotation/schema/invalid_0/main.k similarity index 100% rename from test/grammar/lambda/type_annotation/schema/invalid_0/main.k rename to tests/grammar/lambda/type_annotation/schema/invalid_0/main.k diff --git a/test/grammar/lambda/type_annotation/schema/invalid_0/stderr.golden b/tests/grammar/lambda/type_annotation/schema/invalid_0/stderr.golden similarity index 100% rename from test/grammar/lambda/type_annotation/schema/invalid_0/stderr.golden rename to tests/grammar/lambda/type_annotation/schema/invalid_0/stderr.golden diff --git a/test/grammar/lambda/type_annotation/schema/invalid_1/main.k b/tests/grammar/lambda/type_annotation/schema/invalid_1/main.k similarity index 100% rename from test/grammar/lambda/type_annotation/schema/invalid_1/main.k rename to tests/grammar/lambda/type_annotation/schema/invalid_1/main.k diff --git a/test/grammar/lambda/type_annotation/schema/invalid_1/stderr.golden b/tests/grammar/lambda/type_annotation/schema/invalid_1/stderr.golden similarity index 100% rename from test/grammar/lambda/type_annotation/schema/invalid_1/stderr.golden rename to tests/grammar/lambda/type_annotation/schema/invalid_1/stderr.golden diff --git a/test/grammar/misc/disable_none/main.k b/tests/grammar/misc/disable_none/main.k similarity index 100% rename from test/grammar/misc/disable_none/main.k rename to tests/grammar/misc/disable_none/main.k diff --git a/test/grammar/misc/disable_none/settings.yaml b/tests/grammar/misc/disable_none/settings.yaml similarity index 100% rename from test/grammar/misc/disable_none/settings.yaml rename to tests/grammar/misc/disable_none/settings.yaml diff --git a/test/grammar/misc/disable_none/stdout.golden b/tests/grammar/misc/disable_none/stdout.golden similarity index 100% rename from test/grammar/misc/disable_none/stdout.golden rename to tests/grammar/misc/disable_none/stdout.golden diff --git a/test/grammar/misc/dump_order/main.k b/tests/grammar/misc/dump_order/main.k similarity index 100% rename from test/grammar/misc/dump_order/main.k rename to tests/grammar/misc/dump_order/main.k diff --git a/test/grammar/misc/dump_order/stdout.golden b/tests/grammar/misc/dump_order/stdout.golden similarity index 100% rename from test/grammar/misc/dump_order/stdout.golden rename to tests/grammar/misc/dump_order/stdout.golden diff --git a/test/grammar/misc/emit_empty/empty_dict_0/main.k b/tests/grammar/misc/emit_empty/empty_dict_0/main.k similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_0/main.k rename to tests/grammar/misc/emit_empty/empty_dict_0/main.k diff --git a/test/grammar/misc/emit_empty/empty_dict_0/settings.yaml b/tests/grammar/misc/emit_empty/empty_dict_0/settings.yaml similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_0/settings.yaml rename to tests/grammar/misc/emit_empty/empty_dict_0/settings.yaml diff --git a/test/grammar/misc/emit_empty/empty_dict_0/stdout.golden b/tests/grammar/misc/emit_empty/empty_dict_0/stdout.golden similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_0/stdout.golden rename to tests/grammar/misc/emit_empty/empty_dict_0/stdout.golden diff --git a/test/grammar/misc/emit_empty/empty_dict_1/main.k b/tests/grammar/misc/emit_empty/empty_dict_1/main.k similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_1/main.k rename to tests/grammar/misc/emit_empty/empty_dict_1/main.k diff --git a/test/grammar/misc/emit_empty/empty_dict_1/stdout.golden b/tests/grammar/misc/emit_empty/empty_dict_1/stdout.golden similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_1/stdout.golden rename to tests/grammar/misc/emit_empty/empty_dict_1/stdout.golden diff --git a/test/grammar/misc/emit_empty/empty_dict_2/main.k b/tests/grammar/misc/emit_empty/empty_dict_2/main.k similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_2/main.k rename to tests/grammar/misc/emit_empty/empty_dict_2/main.k diff --git a/test/grammar/misc/emit_empty/empty_dict_2/settings.yaml b/tests/grammar/misc/emit_empty/empty_dict_2/settings.yaml similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_2/settings.yaml rename to tests/grammar/misc/emit_empty/empty_dict_2/settings.yaml diff --git a/test/grammar/misc/emit_empty/empty_dict_2/stdout.golden b/tests/grammar/misc/emit_empty/empty_dict_2/stdout.golden similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_2/stdout.golden rename to tests/grammar/misc/emit_empty/empty_dict_2/stdout.golden diff --git a/test/grammar/misc/emit_empty/empty_dict_3/apicore/empty_dir_volume_source.k b/tests/grammar/misc/emit_empty/empty_dict_3/apicore/empty_dir_volume_source.k similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_3/apicore/empty_dir_volume_source.k rename to tests/grammar/misc/emit_empty/empty_dict_3/apicore/empty_dir_volume_source.k diff --git a/test/grammar/misc/emit_empty/empty_dict_3/apicore/pod_spec.k b/tests/grammar/misc/emit_empty/empty_dict_3/apicore/pod_spec.k similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_3/apicore/pod_spec.k rename to tests/grammar/misc/emit_empty/empty_dict_3/apicore/pod_spec.k diff --git a/test/grammar/misc/emit_empty/empty_dict_3/apicore/pod_template_spec.k b/tests/grammar/misc/emit_empty/empty_dict_3/apicore/pod_template_spec.k similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_3/apicore/pod_template_spec.k rename to tests/grammar/misc/emit_empty/empty_dict_3/apicore/pod_template_spec.k diff --git a/test/grammar/misc/emit_empty/empty_dict_3/apicore/volume.k b/tests/grammar/misc/emit_empty/empty_dict_3/apicore/volume.k similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_3/apicore/volume.k rename to tests/grammar/misc/emit_empty/empty_dict_3/apicore/volume.k diff --git a/test/grammar/misc/emit_empty/empty_dict_3/apimachinery/object_meta.k b/tests/grammar/misc/emit_empty/empty_dict_3/apimachinery/object_meta.k similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_3/apimachinery/object_meta.k rename to tests/grammar/misc/emit_empty/empty_dict_3/apimachinery/object_meta.k diff --git a/test/grammar/misc/emit_empty/empty_dict_3/apps/deployment.k b/tests/grammar/misc/emit_empty/empty_dict_3/apps/deployment.k similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_3/apps/deployment.k rename to tests/grammar/misc/emit_empty/empty_dict_3/apps/deployment.k diff --git a/test/grammar/misc/emit_empty/empty_dict_3/apps/deployment_spec.k b/tests/grammar/misc/emit_empty/empty_dict_3/apps/deployment_spec.k similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_3/apps/deployment_spec.k rename to tests/grammar/misc/emit_empty/empty_dict_3/apps/deployment_spec.k diff --git a/test/grammar/misc/emit_empty/empty_dict_3/kcl.mod b/tests/grammar/misc/emit_empty/empty_dict_3/kcl.mod similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_3/kcl.mod rename to tests/grammar/misc/emit_empty/empty_dict_3/kcl.mod diff --git a/test/grammar/misc/emit_empty/empty_dict_3/main.k b/tests/grammar/misc/emit_empty/empty_dict_3/main.k similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_3/main.k rename to tests/grammar/misc/emit_empty/empty_dict_3/main.k diff --git a/test/grammar/misc/emit_empty/empty_dict_3/models/server.k b/tests/grammar/misc/emit_empty/empty_dict_3/models/server.k similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_3/models/server.k rename to tests/grammar/misc/emit_empty/empty_dict_3/models/server.k diff --git a/test/grammar/misc/emit_empty/empty_dict_3/settings.yaml b/tests/grammar/misc/emit_empty/empty_dict_3/settings.yaml similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_3/settings.yaml rename to tests/grammar/misc/emit_empty/empty_dict_3/settings.yaml diff --git a/test/grammar/misc/emit_empty/empty_dict_3/stdout.golden b/tests/grammar/misc/emit_empty/empty_dict_3/stdout.golden similarity index 100% rename from test/grammar/misc/emit_empty/empty_dict_3/stdout.golden rename to tests/grammar/misc/emit_empty/empty_dict_3/stdout.golden diff --git a/test/grammar/misc/empty_file/main.k b/tests/grammar/misc/empty_file/main.k similarity index 100% rename from test/grammar/misc/empty_file/main.k rename to tests/grammar/misc/empty_file/main.k diff --git a/test/grammar/misc/empty_file/stdout.golden b/tests/grammar/misc/empty_file/stdout.golden similarity index 100% rename from test/grammar/misc/empty_file/stdout.golden rename to tests/grammar/misc/empty_file/stdout.golden diff --git a/test/grammar/misc/empty_plan/main.k b/tests/grammar/misc/empty_plan/main.k similarity index 100% rename from test/grammar/misc/empty_plan/main.k rename to tests/grammar/misc/empty_plan/main.k diff --git a/test/grammar/misc/empty_plan/stdout.golden b/tests/grammar/misc/empty_plan/stdout.golden similarity index 100% rename from test/grammar/misc/empty_plan/stdout.golden rename to tests/grammar/misc/empty_plan/stdout.golden diff --git a/test/grammar/misc/no_line_terminator/main.k b/tests/grammar/misc/no_line_terminator/main.k similarity index 100% rename from test/grammar/misc/no_line_terminator/main.k rename to tests/grammar/misc/no_line_terminator/main.k diff --git a/test/grammar/misc/no_line_terminator/stdout.golden b/tests/grammar/misc/no_line_terminator/stdout.golden similarity index 100% rename from test/grammar/misc/no_line_terminator/stdout.golden rename to tests/grammar/misc/no_line_terminator/stdout.golden diff --git a/test/grammar/misc/only_line_continuation/test_0/main.k b/tests/grammar/misc/only_line_continuation/test_0/main.k similarity index 100% rename from test/grammar/misc/only_line_continuation/test_0/main.k rename to tests/grammar/misc/only_line_continuation/test_0/main.k diff --git a/test/grammar/misc/only_line_continuation/test_0/stdout.golden b/tests/grammar/misc/only_line_continuation/test_0/stdout.golden similarity index 100% rename from test/grammar/misc/only_line_continuation/test_0/stdout.golden rename to tests/grammar/misc/only_line_continuation/test_0/stdout.golden diff --git a/test/grammar/misc/only_line_continuation/test_1/main.k b/tests/grammar/misc/only_line_continuation/test_1/main.k similarity index 100% rename from test/grammar/misc/only_line_continuation/test_1/main.k rename to tests/grammar/misc/only_line_continuation/test_1/main.k diff --git a/test/grammar/misc/only_line_continuation/test_1/stdout.golden b/tests/grammar/misc/only_line_continuation/test_1/stdout.golden similarity index 100% rename from test/grammar/misc/only_line_continuation/test_1/stdout.golden rename to tests/grammar/misc/only_line_continuation/test_1/stdout.golden diff --git a/test/grammar/misc/only_line_continuation/test_2/main.k b/tests/grammar/misc/only_line_continuation/test_2/main.k similarity index 100% rename from test/grammar/misc/only_line_continuation/test_2/main.k rename to tests/grammar/misc/only_line_continuation/test_2/main.k diff --git a/test/grammar/misc/only_line_continuation/test_2/stdout.golden b/tests/grammar/misc/only_line_continuation/test_2/stdout.golden similarity index 100% rename from test/grammar/misc/only_line_continuation/test_2/stdout.golden rename to tests/grammar/misc/only_line_continuation/test_2/stdout.golden diff --git a/test/grammar/misc/profile/main.k b/tests/grammar/misc/profile/main.k similarity index 100% rename from test/grammar/misc/profile/main.k rename to tests/grammar/misc/profile/main.k diff --git a/test/grammar/misc/profile/settings.yaml b/tests/grammar/misc/profile/settings.yaml similarity index 100% rename from test/grammar/misc/profile/settings.yaml rename to tests/grammar/misc/profile/settings.yaml diff --git a/test/grammar/multi_file_compilation/complex/complex_0/main.k b/tests/grammar/multi_file_compilation/complex/complex_0/main.k similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_0/main.k rename to tests/grammar/multi_file_compilation/complex/complex_0/main.k diff --git a/test/grammar/multi_file_compilation/complex/complex_0/pkg.k b/tests/grammar/multi_file_compilation/complex/complex_0/pkg.k similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_0/pkg.k rename to tests/grammar/multi_file_compilation/complex/complex_0/pkg.k diff --git a/test/grammar/multi_file_compilation/complex/complex_0/settings.yaml b/tests/grammar/multi_file_compilation/complex/complex_0/settings.yaml similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_0/settings.yaml rename to tests/grammar/multi_file_compilation/complex/complex_0/settings.yaml diff --git a/test/grammar/multi_file_compilation/complex/complex_0/stdout.golden b/tests/grammar/multi_file_compilation/complex/complex_0/stdout.golden similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_0/stdout.golden rename to tests/grammar/multi_file_compilation/complex/complex_0/stdout.golden diff --git a/test/grammar/multi_file_compilation/complex/complex_1/kcl.mod b/tests/grammar/multi_file_compilation/complex/complex_1/kcl.mod similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_1/kcl.mod rename to tests/grammar/multi_file_compilation/complex/complex_1/kcl.mod diff --git a/test/grammar/multi_file_compilation/complex/complex_1/main.k b/tests/grammar/multi_file_compilation/complex/complex_1/main.k similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_1/main.k rename to tests/grammar/multi_file_compilation/complex/complex_1/main.k diff --git a/test/grammar/multi_file_compilation/complex/complex_1/pkg/pkg.k b/tests/grammar/multi_file_compilation/complex/complex_1/pkg/pkg.k similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_1/pkg/pkg.k rename to tests/grammar/multi_file_compilation/complex/complex_1/pkg/pkg.k diff --git a/test/grammar/multi_file_compilation/complex/complex_1/settings.yaml b/tests/grammar/multi_file_compilation/complex/complex_1/settings.yaml similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_1/settings.yaml rename to tests/grammar/multi_file_compilation/complex/complex_1/settings.yaml diff --git a/test/grammar/multi_file_compilation/complex/complex_1/stdout.golden b/tests/grammar/multi_file_compilation/complex/complex_1/stdout.golden similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_1/stdout.golden rename to tests/grammar/multi_file_compilation/complex/complex_1/stdout.golden diff --git a/test/grammar/multi_file_compilation/complex/complex_2/kcl.mod b/tests/grammar/multi_file_compilation/complex/complex_2/kcl.mod similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_2/kcl.mod rename to tests/grammar/multi_file_compilation/complex/complex_2/kcl.mod diff --git a/test/grammar/multi_file_compilation/complex/complex_2/main.k b/tests/grammar/multi_file_compilation/complex/complex_2/main.k similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_2/main.k rename to tests/grammar/multi_file_compilation/complex/complex_2/main.k diff --git a/test/grammar/multi_file_compilation/complex/complex_2/pkg.k b/tests/grammar/multi_file_compilation/complex/complex_2/pkg.k similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_2/pkg.k rename to tests/grammar/multi_file_compilation/complex/complex_2/pkg.k diff --git a/test/grammar/multi_file_compilation/complex/complex_2/settings.yaml b/tests/grammar/multi_file_compilation/complex/complex_2/settings.yaml similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_2/settings.yaml rename to tests/grammar/multi_file_compilation/complex/complex_2/settings.yaml diff --git a/test/grammar/multi_file_compilation/complex/complex_2/stdout.golden b/tests/grammar/multi_file_compilation/complex/complex_2/stdout.golden similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_2/stdout.golden rename to tests/grammar/multi_file_compilation/complex/complex_2/stdout.golden diff --git a/test/grammar/multi_file_compilation/complex/complex_3/kcl.mod b/tests/grammar/multi_file_compilation/complex/complex_3/kcl.mod similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_3/kcl.mod rename to tests/grammar/multi_file_compilation/complex/complex_3/kcl.mod diff --git a/test/grammar/multi_file_compilation/complex/complex_3/main.k b/tests/grammar/multi_file_compilation/complex/complex_3/main.k similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_3/main.k rename to tests/grammar/multi_file_compilation/complex/complex_3/main.k diff --git a/test/grammar/multi_file_compilation/complex/complex_3/pkg/pkg.k b/tests/grammar/multi_file_compilation/complex/complex_3/pkg/pkg.k similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_3/pkg/pkg.k rename to tests/grammar/multi_file_compilation/complex/complex_3/pkg/pkg.k diff --git a/test/grammar/multi_file_compilation/complex/complex_3/settings.yaml b/tests/grammar/multi_file_compilation/complex/complex_3/settings.yaml similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_3/settings.yaml rename to tests/grammar/multi_file_compilation/complex/complex_3/settings.yaml diff --git a/test/grammar/multi_file_compilation/complex/complex_3/stdout.golden b/tests/grammar/multi_file_compilation/complex/complex_3/stdout.golden similarity index 100% rename from test/grammar/multi_file_compilation/complex/complex_3/stdout.golden rename to tests/grammar/multi_file_compilation/complex/complex_3/stdout.golden diff --git a/test/grammar/multi_file_compilation/instances/instances_0/main.k b/tests/grammar/multi_file_compilation/instances/instances_0/main.k similarity index 100% rename from test/grammar/multi_file_compilation/instances/instances_0/main.k rename to tests/grammar/multi_file_compilation/instances/instances_0/main.k diff --git a/test/grammar/multi_file_compilation/instances/instances_0/pkg.k b/tests/grammar/multi_file_compilation/instances/instances_0/pkg.k similarity index 100% rename from test/grammar/multi_file_compilation/instances/instances_0/pkg.k rename to tests/grammar/multi_file_compilation/instances/instances_0/pkg.k diff --git a/test/grammar/multi_file_compilation/instances/instances_0/settings.yaml b/tests/grammar/multi_file_compilation/instances/instances_0/settings.yaml similarity index 100% rename from test/grammar/multi_file_compilation/instances/instances_0/settings.yaml rename to tests/grammar/multi_file_compilation/instances/instances_0/settings.yaml diff --git a/test/grammar/multi_file_compilation/instances/instances_0/stdout.golden b/tests/grammar/multi_file_compilation/instances/instances_0/stdout.golden similarity index 100% rename from test/grammar/multi_file_compilation/instances/instances_0/stdout.golden rename to tests/grammar/multi_file_compilation/instances/instances_0/stdout.golden diff --git a/test/grammar/multi_file_compilation/instances/instances_1/main.k b/tests/grammar/multi_file_compilation/instances/instances_1/main.k similarity index 100% rename from test/grammar/multi_file_compilation/instances/instances_1/main.k rename to tests/grammar/multi_file_compilation/instances/instances_1/main.k diff --git a/test/grammar/multi_file_compilation/instances/instances_1/pkg.k b/tests/grammar/multi_file_compilation/instances/instances_1/pkg.k similarity index 100% rename from test/grammar/multi_file_compilation/instances/instances_1/pkg.k rename to tests/grammar/multi_file_compilation/instances/instances_1/pkg.k diff --git a/test/grammar/multi_file_compilation/instances/instances_1/settings.yaml b/tests/grammar/multi_file_compilation/instances/instances_1/settings.yaml similarity index 100% rename from test/grammar/multi_file_compilation/instances/instances_1/settings.yaml rename to tests/grammar/multi_file_compilation/instances/instances_1/settings.yaml diff --git a/test/grammar/multi_file_compilation/instances/instances_1/stdout.golden b/tests/grammar/multi_file_compilation/instances/instances_1/stdout.golden similarity index 100% rename from test/grammar/multi_file_compilation/instances/instances_1/stdout.golden rename to tests/grammar/multi_file_compilation/instances/instances_1/stdout.golden diff --git a/test/grammar/multi_file_compilation/invalid/invalid_0/main.k b/tests/grammar/multi_file_compilation/invalid/invalid_0/main.k similarity index 100% rename from test/grammar/multi_file_compilation/invalid/invalid_0/main.k rename to tests/grammar/multi_file_compilation/invalid/invalid_0/main.k diff --git a/test/grammar/multi_file_compilation/invalid/invalid_0/pkg.k b/tests/grammar/multi_file_compilation/invalid/invalid_0/pkg.k similarity index 100% rename from test/grammar/multi_file_compilation/invalid/invalid_0/pkg.k rename to tests/grammar/multi_file_compilation/invalid/invalid_0/pkg.k diff --git a/test/grammar/multi_file_compilation/invalid/invalid_0/settings.yaml b/tests/grammar/multi_file_compilation/invalid/invalid_0/settings.yaml similarity index 100% rename from test/grammar/multi_file_compilation/invalid/invalid_0/settings.yaml rename to tests/grammar/multi_file_compilation/invalid/invalid_0/settings.yaml diff --git a/test/grammar/multi_file_compilation/invalid/invalid_0/stderr.golden b/tests/grammar/multi_file_compilation/invalid/invalid_0/stderr.golden similarity index 100% rename from test/grammar/multi_file_compilation/invalid/invalid_0/stderr.golden rename to tests/grammar/multi_file_compilation/invalid/invalid_0/stderr.golden diff --git a/test/grammar/multi_file_compilation/invalid/invalid_1/main.k b/tests/grammar/multi_file_compilation/invalid/invalid_1/main.k similarity index 100% rename from test/grammar/multi_file_compilation/invalid/invalid_1/main.k rename to tests/grammar/multi_file_compilation/invalid/invalid_1/main.k diff --git a/test/grammar/multi_file_compilation/invalid/invalid_1/pkg.k b/tests/grammar/multi_file_compilation/invalid/invalid_1/pkg.k similarity index 100% rename from test/grammar/multi_file_compilation/invalid/invalid_1/pkg.k rename to tests/grammar/multi_file_compilation/invalid/invalid_1/pkg.k diff --git a/test/grammar/multi_file_compilation/invalid/invalid_1/settings.yaml b/tests/grammar/multi_file_compilation/invalid/invalid_1/settings.yaml similarity index 100% rename from test/grammar/multi_file_compilation/invalid/invalid_1/settings.yaml rename to tests/grammar/multi_file_compilation/invalid/invalid_1/settings.yaml diff --git a/test/grammar/multi_file_compilation/invalid/invalid_1/stderr.golden b/tests/grammar/multi_file_compilation/invalid/invalid_1/stderr.golden similarity index 100% rename from test/grammar/multi_file_compilation/invalid/invalid_1/stderr.golden rename to tests/grammar/multi_file_compilation/invalid/invalid_1/stderr.golden diff --git a/test/grammar/multi_file_compilation/invalid/invalid_2/main.k b/tests/grammar/multi_file_compilation/invalid/invalid_2/main.k similarity index 100% rename from test/grammar/multi_file_compilation/invalid/invalid_2/main.k rename to tests/grammar/multi_file_compilation/invalid/invalid_2/main.k diff --git a/test/grammar/multi_file_compilation/invalid/invalid_2/pkg1.k b/tests/grammar/multi_file_compilation/invalid/invalid_2/pkg1.k similarity index 100% rename from test/grammar/multi_file_compilation/invalid/invalid_2/pkg1.k rename to tests/grammar/multi_file_compilation/invalid/invalid_2/pkg1.k diff --git a/test/grammar/multi_file_compilation/invalid/invalid_2/pkg2.k b/tests/grammar/multi_file_compilation/invalid/invalid_2/pkg2.k similarity index 100% rename from test/grammar/multi_file_compilation/invalid/invalid_2/pkg2.k rename to tests/grammar/multi_file_compilation/invalid/invalid_2/pkg2.k diff --git a/test/grammar/multi_file_compilation/invalid/invalid_2/settings.yaml b/tests/grammar/multi_file_compilation/invalid/invalid_2/settings.yaml similarity index 100% rename from test/grammar/multi_file_compilation/invalid/invalid_2/settings.yaml rename to tests/grammar/multi_file_compilation/invalid/invalid_2/settings.yaml diff --git a/test/grammar/multi_file_compilation/invalid/invalid_2/stderr.golden b/tests/grammar/multi_file_compilation/invalid/invalid_2/stderr.golden similarity index 100% rename from test/grammar/multi_file_compilation/invalid/invalid_2/stderr.golden rename to tests/grammar/multi_file_compilation/invalid/invalid_2/stderr.golden diff --git a/test/grammar/multi_file_compilation/simple/simple_0/main.k b/tests/grammar/multi_file_compilation/simple/simple_0/main.k similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_0/main.k rename to tests/grammar/multi_file_compilation/simple/simple_0/main.k diff --git a/test/grammar/multi_file_compilation/simple/simple_0/pkg.k b/tests/grammar/multi_file_compilation/simple/simple_0/pkg.k similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_0/pkg.k rename to tests/grammar/multi_file_compilation/simple/simple_0/pkg.k diff --git a/test/grammar/multi_file_compilation/simple/simple_0/settings.yaml b/tests/grammar/multi_file_compilation/simple/simple_0/settings.yaml similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_0/settings.yaml rename to tests/grammar/multi_file_compilation/simple/simple_0/settings.yaml diff --git a/test/grammar/multi_file_compilation/simple/simple_0/stdout.golden b/tests/grammar/multi_file_compilation/simple/simple_0/stdout.golden similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_0/stdout.golden rename to tests/grammar/multi_file_compilation/simple/simple_0/stdout.golden diff --git a/test/grammar/multi_file_compilation/simple/simple_1/main.k b/tests/grammar/multi_file_compilation/simple/simple_1/main.k similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_1/main.k rename to tests/grammar/multi_file_compilation/simple/simple_1/main.k diff --git a/test/grammar/multi_file_compilation/simple/simple_1/pkg.k b/tests/grammar/multi_file_compilation/simple/simple_1/pkg.k similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_1/pkg.k rename to tests/grammar/multi_file_compilation/simple/simple_1/pkg.k diff --git a/test/grammar/multi_file_compilation/simple/simple_1/settings.yaml b/tests/grammar/multi_file_compilation/simple/simple_1/settings.yaml similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_1/settings.yaml rename to tests/grammar/multi_file_compilation/simple/simple_1/settings.yaml diff --git a/test/grammar/multi_file_compilation/simple/simple_1/stdout.golden b/tests/grammar/multi_file_compilation/simple/simple_1/stdout.golden similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_1/stdout.golden rename to tests/grammar/multi_file_compilation/simple/simple_1/stdout.golden diff --git a/test/grammar/multi_file_compilation/simple/simple_2/main.k b/tests/grammar/multi_file_compilation/simple/simple_2/main.k similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_2/main.k rename to tests/grammar/multi_file_compilation/simple/simple_2/main.k diff --git a/test/grammar/multi_file_compilation/simple/simple_2/pkg.k b/tests/grammar/multi_file_compilation/simple/simple_2/pkg.k similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_2/pkg.k rename to tests/grammar/multi_file_compilation/simple/simple_2/pkg.k diff --git a/test/grammar/multi_file_compilation/simple/simple_2/settings.yaml b/tests/grammar/multi_file_compilation/simple/simple_2/settings.yaml similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_2/settings.yaml rename to tests/grammar/multi_file_compilation/simple/simple_2/settings.yaml diff --git a/test/grammar/multi_file_compilation/simple/simple_2/stdout.golden b/tests/grammar/multi_file_compilation/simple/simple_2/stdout.golden similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_2/stdout.golden rename to tests/grammar/multi_file_compilation/simple/simple_2/stdout.golden diff --git a/test/grammar/multi_file_compilation/simple/simple_3/main.k b/tests/grammar/multi_file_compilation/simple/simple_3/main.k similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_3/main.k rename to tests/grammar/multi_file_compilation/simple/simple_3/main.k diff --git a/test/grammar/multi_file_compilation/simple/simple_3/pkg1.k b/tests/grammar/multi_file_compilation/simple/simple_3/pkg1.k similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_3/pkg1.k rename to tests/grammar/multi_file_compilation/simple/simple_3/pkg1.k diff --git a/test/grammar/multi_file_compilation/simple/simple_3/pkg2.k b/tests/grammar/multi_file_compilation/simple/simple_3/pkg2.k similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_3/pkg2.k rename to tests/grammar/multi_file_compilation/simple/simple_3/pkg2.k diff --git a/test/grammar/multi_file_compilation/simple/simple_3/settings.yaml b/tests/grammar/multi_file_compilation/simple/simple_3/settings.yaml similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_3/settings.yaml rename to tests/grammar/multi_file_compilation/simple/simple_3/settings.yaml diff --git a/test/grammar/multi_file_compilation/simple/simple_3/stdout.golden b/tests/grammar/multi_file_compilation/simple/simple_3/stdout.golden similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_3/stdout.golden rename to tests/grammar/multi_file_compilation/simple/simple_3/stdout.golden diff --git a/test/grammar/multi_file_compilation/simple/simple_4/kcl.mod b/tests/grammar/multi_file_compilation/simple/simple_4/kcl.mod similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_4/kcl.mod rename to tests/grammar/multi_file_compilation/simple/simple_4/kcl.mod diff --git a/test/grammar/multi_file_compilation/simple/simple_4/main.k b/tests/grammar/multi_file_compilation/simple/simple_4/main.k similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_4/main.k rename to tests/grammar/multi_file_compilation/simple/simple_4/main.k diff --git a/test/grammar/multi_file_compilation/simple/simple_4/pkg/pkg.k b/tests/grammar/multi_file_compilation/simple/simple_4/pkg/pkg.k similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_4/pkg/pkg.k rename to tests/grammar/multi_file_compilation/simple/simple_4/pkg/pkg.k diff --git a/test/grammar/multi_file_compilation/simple/simple_4/pkg1.k b/tests/grammar/multi_file_compilation/simple/simple_4/pkg1.k similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_4/pkg1.k rename to tests/grammar/multi_file_compilation/simple/simple_4/pkg1.k diff --git a/test/grammar/multi_file_compilation/simple/simple_4/settings.yaml b/tests/grammar/multi_file_compilation/simple/simple_4/settings.yaml similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_4/settings.yaml rename to tests/grammar/multi_file_compilation/simple/simple_4/settings.yaml diff --git a/test/grammar/multi_file_compilation/simple/simple_4/stdout.golden b/tests/grammar/multi_file_compilation/simple/simple_4/stdout.golden similarity index 100% rename from test/grammar/multi_file_compilation/simple/simple_4/stdout.golden rename to tests/grammar/multi_file_compilation/simple/simple_4/stdout.golden diff --git a/test/grammar/nest_var/nest_var_0/main.k b/tests/grammar/nest_var/nest_var_0/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_0/main.k rename to tests/grammar/nest_var/nest_var_0/main.k diff --git a/test/grammar/nest_var/nest_var_0/stdout.golden b/tests/grammar/nest_var/nest_var_0/stdout.golden similarity index 100% rename from test/grammar/nest_var/nest_var_0/stdout.golden rename to tests/grammar/nest_var/nest_var_0/stdout.golden diff --git a/test/grammar/nest_var/nest_var_1/main.k b/tests/grammar/nest_var/nest_var_1/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_1/main.k rename to tests/grammar/nest_var/nest_var_1/main.k diff --git a/test/grammar/nest_var/nest_var_1/stdout.golden b/tests/grammar/nest_var/nest_var_1/stdout.golden similarity index 100% rename from test/grammar/nest_var/nest_var_1/stdout.golden rename to tests/grammar/nest_var/nest_var_1/stdout.golden diff --git a/test/grammar/nest_var/nest_var_10/main.k b/tests/grammar/nest_var/nest_var_10/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_10/main.k rename to tests/grammar/nest_var/nest_var_10/main.k diff --git a/test/grammar/nest_var/nest_var_10/stdout.golden b/tests/grammar/nest_var/nest_var_10/stdout.golden similarity index 100% rename from test/grammar/nest_var/nest_var_10/stdout.golden rename to tests/grammar/nest_var/nest_var_10/stdout.golden diff --git a/test/grammar/nest_var/nest_var_11/main.k b/tests/grammar/nest_var/nest_var_11/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_11/main.k rename to tests/grammar/nest_var/nest_var_11/main.k diff --git a/test/grammar/nest_var/nest_var_11/stdout.golden b/tests/grammar/nest_var/nest_var_11/stdout.golden similarity index 100% rename from test/grammar/nest_var/nest_var_11/stdout.golden rename to tests/grammar/nest_var/nest_var_11/stdout.golden diff --git a/test/grammar/nest_var/nest_var_12/main.k b/tests/grammar/nest_var/nest_var_12/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_12/main.k rename to tests/grammar/nest_var/nest_var_12/main.k diff --git a/test/grammar/nest_var/nest_var_12/stdout.golden b/tests/grammar/nest_var/nest_var_12/stdout.golden similarity index 100% rename from test/grammar/nest_var/nest_var_12/stdout.golden rename to tests/grammar/nest_var/nest_var_12/stdout.golden diff --git a/test/grammar/nest_var/nest_var_13/main.k b/tests/grammar/nest_var/nest_var_13/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_13/main.k rename to tests/grammar/nest_var/nest_var_13/main.k diff --git a/test/grammar/nest_var/nest_var_13/stdout.golden b/tests/grammar/nest_var/nest_var_13/stdout.golden similarity index 100% rename from test/grammar/nest_var/nest_var_13/stdout.golden rename to tests/grammar/nest_var/nest_var_13/stdout.golden diff --git a/test/grammar/nest_var/nest_var_2/main.k b/tests/grammar/nest_var/nest_var_2/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_2/main.k rename to tests/grammar/nest_var/nest_var_2/main.k diff --git a/test/grammar/nest_var/nest_var_2/stdout.golden b/tests/grammar/nest_var/nest_var_2/stdout.golden similarity index 100% rename from test/grammar/nest_var/nest_var_2/stdout.golden rename to tests/grammar/nest_var/nest_var_2/stdout.golden diff --git a/test/grammar/nest_var/nest_var_3/main.k b/tests/grammar/nest_var/nest_var_3/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_3/main.k rename to tests/grammar/nest_var/nest_var_3/main.k diff --git a/test/grammar/nest_var/nest_var_3/stdout.golden b/tests/grammar/nest_var/nest_var_3/stdout.golden similarity index 100% rename from test/grammar/nest_var/nest_var_3/stdout.golden rename to tests/grammar/nest_var/nest_var_3/stdout.golden diff --git a/test/grammar/nest_var/nest_var_4/main.k b/tests/grammar/nest_var/nest_var_4/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_4/main.k rename to tests/grammar/nest_var/nest_var_4/main.k diff --git a/test/grammar/nest_var/nest_var_4/stdout.golden b/tests/grammar/nest_var/nest_var_4/stdout.golden similarity index 100% rename from test/grammar/nest_var/nest_var_4/stdout.golden rename to tests/grammar/nest_var/nest_var_4/stdout.golden diff --git a/test/grammar/nest_var/nest_var_5/main.k b/tests/grammar/nest_var/nest_var_5/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_5/main.k rename to tests/grammar/nest_var/nest_var_5/main.k diff --git a/test/grammar/nest_var/nest_var_5/stdout.golden b/tests/grammar/nest_var/nest_var_5/stdout.golden similarity index 100% rename from test/grammar/nest_var/nest_var_5/stdout.golden rename to tests/grammar/nest_var/nest_var_5/stdout.golden diff --git a/test/grammar/nest_var/nest_var_6/main.k b/tests/grammar/nest_var/nest_var_6/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_6/main.k rename to tests/grammar/nest_var/nest_var_6/main.k diff --git a/test/grammar/nest_var/nest_var_6/stdout.golden b/tests/grammar/nest_var/nest_var_6/stdout.golden similarity index 100% rename from test/grammar/nest_var/nest_var_6/stdout.golden rename to tests/grammar/nest_var/nest_var_6/stdout.golden diff --git a/test/grammar/nest_var/nest_var_7/main.k b/tests/grammar/nest_var/nest_var_7/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_7/main.k rename to tests/grammar/nest_var/nest_var_7/main.k diff --git a/test/grammar/nest_var/nest_var_7/stdout.golden b/tests/grammar/nest_var/nest_var_7/stdout.golden similarity index 100% rename from test/grammar/nest_var/nest_var_7/stdout.golden rename to tests/grammar/nest_var/nest_var_7/stdout.golden diff --git a/test/grammar/nest_var/nest_var_8/main.k b/tests/grammar/nest_var/nest_var_8/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_8/main.k rename to tests/grammar/nest_var/nest_var_8/main.k diff --git a/test/grammar/nest_var/nest_var_8/stdout.golden b/tests/grammar/nest_var/nest_var_8/stdout.golden similarity index 100% rename from test/grammar/nest_var/nest_var_8/stdout.golden rename to tests/grammar/nest_var/nest_var_8/stdout.golden diff --git a/test/grammar/nest_var/nest_var_9/main.k b/tests/grammar/nest_var/nest_var_9/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_9/main.k rename to tests/grammar/nest_var/nest_var_9/main.k diff --git a/test/grammar/nest_var/nest_var_9/stdout.golden b/tests/grammar/nest_var/nest_var_9/stdout.golden similarity index 100% rename from test/grammar/nest_var/nest_var_9/stdout.golden rename to tests/grammar/nest_var/nest_var_9/stdout.golden diff --git a/test/grammar/nest_var/nest_var_fail_0/main.k b/tests/grammar/nest_var/nest_var_fail_0/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_fail_0/main.k rename to tests/grammar/nest_var/nest_var_fail_0/main.k diff --git a/test/grammar/nest_var/nest_var_fail_0/stderr.golden b/tests/grammar/nest_var/nest_var_fail_0/stderr.golden similarity index 100% rename from test/grammar/nest_var/nest_var_fail_0/stderr.golden rename to tests/grammar/nest_var/nest_var_fail_0/stderr.golden diff --git a/test/grammar/nest_var/nest_var_fail_1/main.k b/tests/grammar/nest_var/nest_var_fail_1/main.k similarity index 100% rename from test/grammar/nest_var/nest_var_fail_1/main.k rename to tests/grammar/nest_var/nest_var_fail_1/main.k diff --git a/test/grammar/nest_var/nest_var_fail_1/stderr.golden b/tests/grammar/nest_var/nest_var_fail_1/stderr.golden similarity index 100% rename from test/grammar/nest_var/nest_var_fail_1/stderr.golden rename to tests/grammar/nest_var/nest_var_fail_1/stderr.golden diff --git a/test/grammar/option/complex_type_option/main.k b/tests/grammar/option/complex_type_option/main.k similarity index 100% rename from test/grammar/option/complex_type_option/main.k rename to tests/grammar/option/complex_type_option/main.k diff --git a/test/grammar/option/complex_type_option/settings.yaml b/tests/grammar/option/complex_type_option/settings.yaml similarity index 100% rename from test/grammar/option/complex_type_option/settings.yaml rename to tests/grammar/option/complex_type_option/settings.yaml diff --git a/test/grammar/option/complex_type_option/stdout.golden b/tests/grammar/option/complex_type_option/stdout.golden similarity index 100% rename from test/grammar/option/complex_type_option/stdout.golden rename to tests/grammar/option/complex_type_option/stdout.golden diff --git a/test/grammar/option/complex_type_option_1/main.k b/tests/grammar/option/complex_type_option_1/main.k similarity index 100% rename from test/grammar/option/complex_type_option_1/main.k rename to tests/grammar/option/complex_type_option_1/main.k diff --git a/test/grammar/option/complex_type_option_1/settings.yaml b/tests/grammar/option/complex_type_option_1/settings.yaml similarity index 100% rename from test/grammar/option/complex_type_option_1/settings.yaml rename to tests/grammar/option/complex_type_option_1/settings.yaml diff --git a/test/grammar/option/complex_type_option_1/stdout.golden b/tests/grammar/option/complex_type_option_1/stdout.golden similarity index 100% rename from test/grammar/option/complex_type_option_1/stdout.golden rename to tests/grammar/option/complex_type_option_1/stdout.golden diff --git a/test/grammar/option/file_empty_options/main.k b/tests/grammar/option/file_empty_options/main.k similarity index 100% rename from test/grammar/option/file_empty_options/main.k rename to tests/grammar/option/file_empty_options/main.k diff --git a/test/grammar/option/file_empty_options/settings.yaml b/tests/grammar/option/file_empty_options/settings.yaml similarity index 100% rename from test/grammar/option/file_empty_options/settings.yaml rename to tests/grammar/option/file_empty_options/settings.yaml diff --git a/test/grammar/option/file_empty_options/stdout.golden b/tests/grammar/option/file_empty_options/stdout.golden similarity index 100% rename from test/grammar/option/file_empty_options/stdout.golden rename to tests/grammar/option/file_empty_options/stdout.golden diff --git a/test/grammar/option/file_empty_options/temp.yaml b/tests/grammar/option/file_empty_options/temp.yaml similarity index 100% rename from test/grammar/option/file_empty_options/temp.yaml rename to tests/grammar/option/file_empty_options/temp.yaml diff --git a/test/grammar/option/file_options/_main.k b/tests/grammar/option/file_options/_main.k similarity index 100% rename from test/grammar/option/file_options/_main.k rename to tests/grammar/option/file_options/_main.k diff --git a/test/grammar/option/file_options/settings.yaml b/tests/grammar/option/file_options/settings.yaml similarity index 100% rename from test/grammar/option/file_options/settings.yaml rename to tests/grammar/option/file_options/settings.yaml diff --git a/test/grammar/option/file_options/stdout.golden b/tests/grammar/option/file_options/stdout.golden similarity index 100% rename from test/grammar/option/file_options/stdout.golden rename to tests/grammar/option/file_options/stdout.golden diff --git a/test/grammar/option/file_options/temp.yaml b/tests/grammar/option/file_options/temp.yaml similarity index 100% rename from test/grammar/option/file_options/temp.yaml rename to tests/grammar/option/file_options/temp.yaml diff --git a/test/grammar/option/file_options_fail_0/main.k b/tests/grammar/option/file_options_fail_0/main.k similarity index 100% rename from test/grammar/option/file_options_fail_0/main.k rename to tests/grammar/option/file_options_fail_0/main.k diff --git a/test/grammar/option/file_options_fail_0/settings.yaml b/tests/grammar/option/file_options_fail_0/settings.yaml similarity index 100% rename from test/grammar/option/file_options_fail_0/settings.yaml rename to tests/grammar/option/file_options_fail_0/settings.yaml diff --git a/test/grammar/option/file_options_fail_0/stderr.golden b/tests/grammar/option/file_options_fail_0/stderr.golden similarity index 100% rename from test/grammar/option/file_options_fail_0/stderr.golden rename to tests/grammar/option/file_options_fail_0/stderr.golden diff --git a/test/grammar/option/file_options_fail_0/temp.yaml b/tests/grammar/option/file_options_fail_0/temp.yaml similarity index 100% rename from test/grammar/option/file_options_fail_0/temp.yaml rename to tests/grammar/option/file_options_fail_0/temp.yaml diff --git a/test/grammar/option/file_options_fail_1/main.k b/tests/grammar/option/file_options_fail_1/main.k similarity index 100% rename from test/grammar/option/file_options_fail_1/main.k rename to tests/grammar/option/file_options_fail_1/main.k diff --git a/test/grammar/option/file_options_fail_1/settings.yaml b/tests/grammar/option/file_options_fail_1/settings.yaml similarity index 100% rename from test/grammar/option/file_options_fail_1/settings.yaml rename to tests/grammar/option/file_options_fail_1/settings.yaml diff --git a/test/grammar/option/file_options_fail_1/stderr.golden b/tests/grammar/option/file_options_fail_1/stderr.golden similarity index 100% rename from test/grammar/option/file_options_fail_1/stderr.golden rename to tests/grammar/option/file_options_fail_1/stderr.golden diff --git a/test/grammar/option/file_options_fail_1/temp.yaml b/tests/grammar/option/file_options_fail_1/temp.yaml similarity index 100% rename from test/grammar/option/file_options_fail_1/temp.yaml rename to tests/grammar/option/file_options_fail_1/temp.yaml diff --git a/test/grammar/option/file_options_fail_2/main.k b/tests/grammar/option/file_options_fail_2/main.k similarity index 100% rename from test/grammar/option/file_options_fail_2/main.k rename to tests/grammar/option/file_options_fail_2/main.k diff --git a/test/grammar/option/file_options_fail_2/settings.yaml b/tests/grammar/option/file_options_fail_2/settings.yaml similarity index 100% rename from test/grammar/option/file_options_fail_2/settings.yaml rename to tests/grammar/option/file_options_fail_2/settings.yaml diff --git a/test/grammar/option/file_options_fail_2/stderr.golden b/tests/grammar/option/file_options_fail_2/stderr.golden similarity index 100% rename from test/grammar/option/file_options_fail_2/stderr.golden rename to tests/grammar/option/file_options_fail_2/stderr.golden diff --git a/test/grammar/option/file_options_fail_2/temp.yaml b/tests/grammar/option/file_options_fail_2/temp.yaml similarity index 100% rename from test/grammar/option/file_options_fail_2/temp.yaml rename to tests/grammar/option/file_options_fail_2/temp.yaml diff --git a/test/grammar/option/file_options_fail_3/main.k b/tests/grammar/option/file_options_fail_3/main.k similarity index 100% rename from test/grammar/option/file_options_fail_3/main.k rename to tests/grammar/option/file_options_fail_3/main.k diff --git a/test/grammar/option/file_options_fail_3/settings.yaml b/tests/grammar/option/file_options_fail_3/settings.yaml similarity index 100% rename from test/grammar/option/file_options_fail_3/settings.yaml rename to tests/grammar/option/file_options_fail_3/settings.yaml diff --git a/test/grammar/option/file_options_fail_3/stderr.golden b/tests/grammar/option/file_options_fail_3/stderr.golden similarity index 100% rename from test/grammar/option/file_options_fail_3/stderr.golden rename to tests/grammar/option/file_options_fail_3/stderr.golden diff --git a/test/grammar/option/file_options_fail_3/temp.yaml b/tests/grammar/option/file_options_fail_3/temp.yaml similarity index 100% rename from test/grammar/option/file_options_fail_3/temp.yaml rename to tests/grammar/option/file_options_fail_3/temp.yaml diff --git a/test/grammar/option/file_options_fail_4/main.k b/tests/grammar/option/file_options_fail_4/main.k similarity index 100% rename from test/grammar/option/file_options_fail_4/main.k rename to tests/grammar/option/file_options_fail_4/main.k diff --git a/test/grammar/option/file_options_fail_4/settings.yaml b/tests/grammar/option/file_options_fail_4/settings.yaml similarity index 100% rename from test/grammar/option/file_options_fail_4/settings.yaml rename to tests/grammar/option/file_options_fail_4/settings.yaml diff --git a/test/grammar/option/file_options_fail_4/stderr.golden b/tests/grammar/option/file_options_fail_4/stderr.golden similarity index 100% rename from test/grammar/option/file_options_fail_4/stderr.golden rename to tests/grammar/option/file_options_fail_4/stderr.golden diff --git a/test/grammar/option/file_options_fail_4/temp.yaml b/tests/grammar/option/file_options_fail_4/temp.yaml similarity index 100% rename from test/grammar/option/file_options_fail_4/temp.yaml rename to tests/grammar/option/file_options_fail_4/temp.yaml diff --git a/test/grammar/option/invalid_option_fail_0/main.k b/tests/grammar/option/invalid_option_fail_0/main.k similarity index 100% rename from test/grammar/option/invalid_option_fail_0/main.k rename to tests/grammar/option/invalid_option_fail_0/main.k diff --git a/test/grammar/option/invalid_option_fail_0/settings.yaml b/tests/grammar/option/invalid_option_fail_0/settings.yaml similarity index 100% rename from test/grammar/option/invalid_option_fail_0/settings.yaml rename to tests/grammar/option/invalid_option_fail_0/settings.yaml diff --git a/test/grammar/option/invalid_option_fail_0/stderr.golden b/tests/grammar/option/invalid_option_fail_0/stderr.golden similarity index 100% rename from test/grammar/option/invalid_option_fail_0/stderr.golden rename to tests/grammar/option/invalid_option_fail_0/stderr.golden diff --git a/test/grammar/option/invalid_option_fail_1/main.k b/tests/grammar/option/invalid_option_fail_1/main.k similarity index 100% rename from test/grammar/option/invalid_option_fail_1/main.k rename to tests/grammar/option/invalid_option_fail_1/main.k diff --git a/test/grammar/option/invalid_option_fail_1/settings.yaml b/tests/grammar/option/invalid_option_fail_1/settings.yaml similarity index 100% rename from test/grammar/option/invalid_option_fail_1/settings.yaml rename to tests/grammar/option/invalid_option_fail_1/settings.yaml diff --git a/test/grammar/option/invalid_option_fail_1/stderr.golden b/tests/grammar/option/invalid_option_fail_1/stderr.golden similarity index 100% rename from test/grammar/option/invalid_option_fail_1/stderr.golden rename to tests/grammar/option/invalid_option_fail_1/stderr.golden diff --git a/test/grammar/option/invalid_option_fail_2/main.k b/tests/grammar/option/invalid_option_fail_2/main.k similarity index 100% rename from test/grammar/option/invalid_option_fail_2/main.k rename to tests/grammar/option/invalid_option_fail_2/main.k diff --git a/test/grammar/option/invalid_option_fail_2/settings.yaml b/tests/grammar/option/invalid_option_fail_2/settings.yaml similarity index 100% rename from test/grammar/option/invalid_option_fail_2/settings.yaml rename to tests/grammar/option/invalid_option_fail_2/settings.yaml diff --git a/test/grammar/option/invalid_option_fail_2/stderr.golden b/tests/grammar/option/invalid_option_fail_2/stderr.golden similarity index 100% rename from test/grammar/option/invalid_option_fail_2/stderr.golden rename to tests/grammar/option/invalid_option_fail_2/stderr.golden diff --git a/test/grammar/option/multiple_options/main.k b/tests/grammar/option/multiple_options/main.k similarity index 100% rename from test/grammar/option/multiple_options/main.k rename to tests/grammar/option/multiple_options/main.k diff --git a/test/grammar/option/multiple_options/settings.yaml b/tests/grammar/option/multiple_options/settings.yaml similarity index 100% rename from test/grammar/option/multiple_options/settings.yaml rename to tests/grammar/option/multiple_options/settings.yaml diff --git a/test/grammar/option/multiple_options/stdout.golden b/tests/grammar/option/multiple_options/stdout.golden similarity index 100% rename from test/grammar/option/multiple_options/stdout.golden rename to tests/grammar/option/multiple_options/stdout.golden diff --git a/test/grammar/option/no_option/main.k b/tests/grammar/option/no_option/main.k similarity index 100% rename from test/grammar/option/no_option/main.k rename to tests/grammar/option/no_option/main.k diff --git a/test/grammar/option/no_option/settings.yaml b/tests/grammar/option/no_option/settings.yaml similarity index 100% rename from test/grammar/option/no_option/settings.yaml rename to tests/grammar/option/no_option/settings.yaml diff --git a/test/grammar/option/no_option/stdout.golden b/tests/grammar/option/no_option/stdout.golden similarity index 100% rename from test/grammar/option/no_option/stdout.golden rename to tests/grammar/option/no_option/stdout.golden diff --git a/test/grammar/option/option_help_fail_0/main.k b/tests/grammar/option/option_help_fail_0/main.k similarity index 100% rename from test/grammar/option/option_help_fail_0/main.k rename to tests/grammar/option/option_help_fail_0/main.k diff --git a/test/grammar/option/option_help_fail_0/settings.yaml b/tests/grammar/option/option_help_fail_0/settings.yaml similarity index 100% rename from test/grammar/option/option_help_fail_0/settings.yaml rename to tests/grammar/option/option_help_fail_0/settings.yaml diff --git a/test/grammar/option/option_help_fail_0/stderr.golden b/tests/grammar/option/option_help_fail_0/stderr.golden similarity index 100% rename from test/grammar/option/option_help_fail_0/stderr.golden rename to tests/grammar/option/option_help_fail_0/stderr.golden diff --git a/test/grammar/option/option_help_in_schema/_main.k b/tests/grammar/option/option_help_in_schema/_main.k similarity index 100% rename from test/grammar/option/option_help_in_schema/_main.k rename to tests/grammar/option/option_help_in_schema/_main.k diff --git a/test/grammar/option/option_help_in_schema/settings.yaml b/tests/grammar/option/option_help_in_schema/settings.yaml similarity index 100% rename from test/grammar/option/option_help_in_schema/settings.yaml rename to tests/grammar/option/option_help_in_schema/settings.yaml diff --git a/test/grammar/option/option_help_in_schema/stdout.golden b/tests/grammar/option/option_help_in_schema/stdout.golden similarity index 100% rename from test/grammar/option/option_help_in_schema/stdout.golden rename to tests/grammar/option/option_help_in_schema/stdout.golden diff --git a/test/grammar/option/option_help_type_0/_main.k b/tests/grammar/option/option_help_type_0/_main.k similarity index 100% rename from test/grammar/option/option_help_type_0/_main.k rename to tests/grammar/option/option_help_type_0/_main.k diff --git a/test/grammar/option/option_help_type_0/settings.yaml b/tests/grammar/option/option_help_type_0/settings.yaml similarity index 100% rename from test/grammar/option/option_help_type_0/settings.yaml rename to tests/grammar/option/option_help_type_0/settings.yaml diff --git a/test/grammar/option/option_help_type_0/stdout.golden b/tests/grammar/option/option_help_type_0/stdout.golden similarity index 100% rename from test/grammar/option/option_help_type_0/stdout.golden rename to tests/grammar/option/option_help_type_0/stdout.golden diff --git a/test/grammar/option/option_help_type_fail_0/main.k b/tests/grammar/option/option_help_type_fail_0/main.k similarity index 100% rename from test/grammar/option/option_help_type_fail_0/main.k rename to tests/grammar/option/option_help_type_fail_0/main.k diff --git a/test/grammar/option/option_help_type_fail_0/settings.yaml b/tests/grammar/option/option_help_type_fail_0/settings.yaml similarity index 100% rename from test/grammar/option/option_help_type_fail_0/settings.yaml rename to tests/grammar/option/option_help_type_fail_0/settings.yaml diff --git a/test/grammar/option/option_help_type_fail_0/stderr.golden b/tests/grammar/option/option_help_type_fail_0/stderr.golden similarity index 100% rename from test/grammar/option/option_help_type_fail_0/stderr.golden rename to tests/grammar/option/option_help_type_fail_0/stderr.golden diff --git a/test/grammar/option/option_same_key/main.k b/tests/grammar/option/option_same_key/main.k similarity index 100% rename from test/grammar/option/option_same_key/main.k rename to tests/grammar/option/option_same_key/main.k diff --git a/test/grammar/option/option_same_key/settings.yaml b/tests/grammar/option/option_same_key/settings.yaml similarity index 100% rename from test/grammar/option/option_same_key/settings.yaml rename to tests/grammar/option/option_same_key/settings.yaml diff --git a/test/grammar/option/option_same_key/stdout.golden b/tests/grammar/option/option_same_key/stdout.golden similarity index 100% rename from test/grammar/option/option_same_key/stdout.golden rename to tests/grammar/option/option_same_key/stdout.golden diff --git a/test/grammar/option/simple_0/main.k b/tests/grammar/option/simple_0/main.k similarity index 100% rename from test/grammar/option/simple_0/main.k rename to tests/grammar/option/simple_0/main.k diff --git a/test/grammar/option/simple_0/settings.yaml b/tests/grammar/option/simple_0/settings.yaml similarity index 100% rename from test/grammar/option/simple_0/settings.yaml rename to tests/grammar/option/simple_0/settings.yaml diff --git a/test/grammar/option/simple_0/stdout.golden b/tests/grammar/option/simple_0/stdout.golden similarity index 100% rename from test/grammar/option/simple_0/stdout.golden rename to tests/grammar/option/simple_0/stdout.golden diff --git a/test/grammar/option/simple_1/main.k b/tests/grammar/option/simple_1/main.k similarity index 100% rename from test/grammar/option/simple_1/main.k rename to tests/grammar/option/simple_1/main.k diff --git a/test/grammar/option/simple_1/settings.yaml b/tests/grammar/option/simple_1/settings.yaml similarity index 100% rename from test/grammar/option/simple_1/settings.yaml rename to tests/grammar/option/simple_1/settings.yaml diff --git a/test/grammar/option/simple_1/stdout.golden b/tests/grammar/option/simple_1/stdout.golden similarity index 100% rename from test/grammar/option/simple_1/stdout.golden rename to tests/grammar/option/simple_1/stdout.golden diff --git a/test/grammar/option/simple_2/main.k b/tests/grammar/option/simple_2/main.k similarity index 100% rename from test/grammar/option/simple_2/main.k rename to tests/grammar/option/simple_2/main.k diff --git a/test/grammar/option/simple_2/settings.yaml b/tests/grammar/option/simple_2/settings.yaml similarity index 100% rename from test/grammar/option/simple_2/settings.yaml rename to tests/grammar/option/simple_2/settings.yaml diff --git a/test/grammar/option/simple_2/stdout.golden b/tests/grammar/option/simple_2/stdout.golden similarity index 100% rename from test/grammar/option/simple_2/stdout.golden rename to tests/grammar/option/simple_2/stdout.golden diff --git a/test/grammar/option/single_option/main.k b/tests/grammar/option/single_option/main.k similarity index 100% rename from test/grammar/option/single_option/main.k rename to tests/grammar/option/single_option/main.k diff --git a/test/grammar/option/single_option/settings.yaml b/tests/grammar/option/single_option/settings.yaml similarity index 100% rename from test/grammar/option/single_option/settings.yaml rename to tests/grammar/option/single_option/settings.yaml diff --git a/test/grammar/option/single_option/stdout.golden b/tests/grammar/option/single_option/stdout.golden similarity index 100% rename from test/grammar/option/single_option/stdout.golden rename to tests/grammar/option/single_option/stdout.golden diff --git a/test/grammar/option/type_convert_0/main.k b/tests/grammar/option/type_convert_0/main.k similarity index 100% rename from test/grammar/option/type_convert_0/main.k rename to tests/grammar/option/type_convert_0/main.k diff --git a/test/grammar/option/type_convert_0/settings.yaml b/tests/grammar/option/type_convert_0/settings.yaml similarity index 100% rename from test/grammar/option/type_convert_0/settings.yaml rename to tests/grammar/option/type_convert_0/settings.yaml diff --git a/test/grammar/option/type_convert_0/stdout.golden b/tests/grammar/option/type_convert_0/stdout.golden similarity index 100% rename from test/grammar/option/type_convert_0/stdout.golden rename to tests/grammar/option/type_convert_0/stdout.golden diff --git a/test/grammar/option/type_convert_1/main.k b/tests/grammar/option/type_convert_1/main.k similarity index 100% rename from test/grammar/option/type_convert_1/main.k rename to tests/grammar/option/type_convert_1/main.k diff --git a/test/grammar/option/type_convert_1/stdout.golden b/tests/grammar/option/type_convert_1/stdout.golden similarity index 100% rename from test/grammar/option/type_convert_1/stdout.golden rename to tests/grammar/option/type_convert_1/stdout.golden diff --git a/test/grammar/option/type_convert_2/main.k b/tests/grammar/option/type_convert_2/main.k similarity index 100% rename from test/grammar/option/type_convert_2/main.k rename to tests/grammar/option/type_convert_2/main.k diff --git a/test/grammar/option/type_convert_2/settings.yaml b/tests/grammar/option/type_convert_2/settings.yaml similarity index 100% rename from test/grammar/option/type_convert_2/settings.yaml rename to tests/grammar/option/type_convert_2/settings.yaml diff --git a/test/grammar/option/type_convert_2/stdout.golden b/tests/grammar/option/type_convert_2/stdout.golden similarity index 100% rename from test/grammar/option/type_convert_2/stdout.golden rename to tests/grammar/option/type_convert_2/stdout.golden diff --git a/test/grammar/option/type_convert_fail_0/main.k b/tests/grammar/option/type_convert_fail_0/main.k similarity index 100% rename from test/grammar/option/type_convert_fail_0/main.k rename to tests/grammar/option/type_convert_fail_0/main.k diff --git a/test/grammar/option/type_convert_fail_0/settings.yaml b/tests/grammar/option/type_convert_fail_0/settings.yaml similarity index 100% rename from test/grammar/option/type_convert_fail_0/settings.yaml rename to tests/grammar/option/type_convert_fail_0/settings.yaml diff --git a/test/grammar/option/type_convert_fail_0/stderr.golden b/tests/grammar/option/type_convert_fail_0/stderr.golden similarity index 100% rename from test/grammar/option/type_convert_fail_0/stderr.golden rename to tests/grammar/option/type_convert_fail_0/stderr.golden diff --git a/test/grammar/option/type_convert_fail_1/main.k b/tests/grammar/option/type_convert_fail_1/main.k similarity index 100% rename from test/grammar/option/type_convert_fail_1/main.k rename to tests/grammar/option/type_convert_fail_1/main.k diff --git a/test/grammar/option/type_convert_fail_1/stderr.golden b/tests/grammar/option/type_convert_fail_1/stderr.golden similarity index 100% rename from test/grammar/option/type_convert_fail_1/stderr.golden rename to tests/grammar/option/type_convert_fail_1/stderr.golden diff --git a/test/grammar/option/type_convert_fail_2/main.k b/tests/grammar/option/type_convert_fail_2/main.k similarity index 100% rename from test/grammar/option/type_convert_fail_2/main.k rename to tests/grammar/option/type_convert_fail_2/main.k diff --git a/test/grammar/option/type_convert_fail_2/stderr.golden b/tests/grammar/option/type_convert_fail_2/stderr.golden similarity index 100% rename from test/grammar/option/type_convert_fail_2/stderr.golden rename to tests/grammar/option/type_convert_fail_2/stderr.golden diff --git a/test/grammar/override/combination/_main.k b/tests/grammar/override/combination/_main.k similarity index 100% rename from test/grammar/override/combination/_main.k rename to tests/grammar/override/combination/_main.k diff --git a/test/grammar/override/combination/settings.yaml b/tests/grammar/override/combination/settings.yaml similarity index 100% rename from test/grammar/override/combination/settings.yaml rename to tests/grammar/override/combination/settings.yaml diff --git a/test/grammar/override/combination/stdout.golden b/tests/grammar/override/combination/stdout.golden similarity index 100% rename from test/grammar/override/combination/stdout.golden rename to tests/grammar/override/combination/stdout.golden diff --git a/test/grammar/override/delete_0/_main.k b/tests/grammar/override/delete_0/_main.k similarity index 100% rename from test/grammar/override/delete_0/_main.k rename to tests/grammar/override/delete_0/_main.k diff --git a/test/grammar/override/delete_0/settings.yaml b/tests/grammar/override/delete_0/settings.yaml similarity index 100% rename from test/grammar/override/delete_0/settings.yaml rename to tests/grammar/override/delete_0/settings.yaml diff --git a/test/grammar/override/delete_0/stdout.golden b/tests/grammar/override/delete_0/stdout.golden similarity index 100% rename from test/grammar/override/delete_0/stdout.golden rename to tests/grammar/override/delete_0/stdout.golden diff --git a/test/grammar/override/delete_1/_main.k b/tests/grammar/override/delete_1/_main.k similarity index 100% rename from test/grammar/override/delete_1/_main.k rename to tests/grammar/override/delete_1/_main.k diff --git a/test/grammar/override/delete_1/settings.yaml b/tests/grammar/override/delete_1/settings.yaml similarity index 100% rename from test/grammar/override/delete_1/settings.yaml rename to tests/grammar/override/delete_1/settings.yaml diff --git a/test/grammar/override/delete_1/stdout.golden b/tests/grammar/override/delete_1/stdout.golden similarity index 100% rename from test/grammar/override/delete_1/stdout.golden rename to tests/grammar/override/delete_1/stdout.golden diff --git a/test/grammar/override/dict/_main.k b/tests/grammar/override/dict/_main.k similarity index 100% rename from test/grammar/override/dict/_main.k rename to tests/grammar/override/dict/_main.k diff --git a/test/grammar/override/dict/settings.yaml b/tests/grammar/override/dict/settings.yaml similarity index 100% rename from test/grammar/override/dict/settings.yaml rename to tests/grammar/override/dict/settings.yaml diff --git a/test/grammar/override/dict/stdout.golden b/tests/grammar/override/dict/stdout.golden similarity index 100% rename from test/grammar/override/dict/stdout.golden rename to tests/grammar/override/dict/stdout.golden diff --git a/test/grammar/override/fail/type_fail/_main.k b/tests/grammar/override/fail/type_fail/_main.k similarity index 100% rename from test/grammar/override/fail/type_fail/_main.k rename to tests/grammar/override/fail/type_fail/_main.k diff --git a/test/grammar/override/fail/type_fail/settings.yaml b/tests/grammar/override/fail/type_fail/settings.yaml similarity index 100% rename from test/grammar/override/fail/type_fail/settings.yaml rename to tests/grammar/override/fail/type_fail/settings.yaml diff --git a/test/grammar/override/fail/type_fail/stderr.golden b/tests/grammar/override/fail/type_fail/stderr.golden similarity index 100% rename from test/grammar/override/fail/type_fail/stderr.golden rename to tests/grammar/override/fail/type_fail/stderr.golden diff --git a/test/grammar/override/import_package/_main.k b/tests/grammar/override/import_package/_main.k similarity index 100% rename from test/grammar/override/import_package/_main.k rename to tests/grammar/override/import_package/_main.k diff --git a/test/grammar/override/import_package/kcl.mod b/tests/grammar/override/import_package/kcl.mod similarity index 100% rename from test/grammar/override/import_package/kcl.mod rename to tests/grammar/override/import_package/kcl.mod diff --git a/test/grammar/override/import_package/mymodule/a.k b/tests/grammar/override/import_package/mymodule/a.k similarity index 100% rename from test/grammar/override/import_package/mymodule/a.k rename to tests/grammar/override/import_package/mymodule/a.k diff --git a/test/grammar/override/import_package/mymodule/b.k b/tests/grammar/override/import_package/mymodule/b.k similarity index 100% rename from test/grammar/override/import_package/mymodule/b.k rename to tests/grammar/override/import_package/mymodule/b.k diff --git a/test/grammar/override/import_package/settings.yaml b/tests/grammar/override/import_package/settings.yaml similarity index 100% rename from test/grammar/override/import_package/settings.yaml rename to tests/grammar/override/import_package/settings.yaml diff --git a/test/grammar/override/import_package/stdout.golden b/tests/grammar/override/import_package/stdout.golden similarity index 100% rename from test/grammar/override/import_package/stdout.golden rename to tests/grammar/override/import_package/stdout.golden diff --git a/test/grammar/override/inherit/_main.k b/tests/grammar/override/inherit/_main.k similarity index 100% rename from test/grammar/override/inherit/_main.k rename to tests/grammar/override/inherit/_main.k diff --git a/test/grammar/override/inherit/settings.yaml b/tests/grammar/override/inherit/settings.yaml similarity index 100% rename from test/grammar/override/inherit/settings.yaml rename to tests/grammar/override/inherit/settings.yaml diff --git a/test/grammar/override/inherit/stdout.golden b/tests/grammar/override/inherit/stdout.golden similarity index 100% rename from test/grammar/override/inherit/stdout.golden rename to tests/grammar/override/inherit/stdout.golden diff --git a/test/grammar/override/kcl.mod b/tests/grammar/override/kcl.mod similarity index 100% rename from test/grammar/override/kcl.mod rename to tests/grammar/override/kcl.mod diff --git a/test/grammar/override/mod_root/_main.k b/tests/grammar/override/mod_root/_main.k similarity index 100% rename from test/grammar/override/mod_root/_main.k rename to tests/grammar/override/mod_root/_main.k diff --git a/test/grammar/override/mod_root/kcl.mod b/tests/grammar/override/mod_root/kcl.mod similarity index 100% rename from test/grammar/override/mod_root/kcl.mod rename to tests/grammar/override/mod_root/kcl.mod diff --git a/test/grammar/override/mod_root/settings.yaml b/tests/grammar/override/mod_root/settings.yaml similarity index 100% rename from test/grammar/override/mod_root/settings.yaml rename to tests/grammar/override/mod_root/settings.yaml diff --git a/test/grammar/override/mod_root/stdout.golden b/tests/grammar/override/mod_root/stdout.golden similarity index 100% rename from test/grammar/override/mod_root/stdout.golden rename to tests/grammar/override/mod_root/stdout.golden diff --git a/test/grammar/override/more_assign/more_assign_0/_main.k b/tests/grammar/override/more_assign/more_assign_0/_main.k similarity index 100% rename from test/grammar/override/more_assign/more_assign_0/_main.k rename to tests/grammar/override/more_assign/more_assign_0/_main.k diff --git a/test/grammar/override/more_assign/more_assign_0/kcl.mod b/tests/grammar/override/more_assign/more_assign_0/kcl.mod similarity index 100% rename from test/grammar/override/more_assign/more_assign_0/kcl.mod rename to tests/grammar/override/more_assign/more_assign_0/kcl.mod diff --git a/test/grammar/override/more_assign/more_assign_0/settings.yaml b/tests/grammar/override/more_assign/more_assign_0/settings.yaml similarity index 100% rename from test/grammar/override/more_assign/more_assign_0/settings.yaml rename to tests/grammar/override/more_assign/more_assign_0/settings.yaml diff --git a/test/grammar/override/more_assign/more_assign_0/stdout.golden b/tests/grammar/override/more_assign/more_assign_0/stdout.golden similarity index 100% rename from test/grammar/override/more_assign/more_assign_0/stdout.golden rename to tests/grammar/override/more_assign/more_assign_0/stdout.golden diff --git a/test/grammar/override/more_assign/more_assign_1/_main.k b/tests/grammar/override/more_assign/more_assign_1/_main.k similarity index 100% rename from test/grammar/override/more_assign/more_assign_1/_main.k rename to tests/grammar/override/more_assign/more_assign_1/_main.k diff --git a/test/grammar/override/more_assign/more_assign_1/kcl.mod b/tests/grammar/override/more_assign/more_assign_1/kcl.mod similarity index 100% rename from test/grammar/override/more_assign/more_assign_1/kcl.mod rename to tests/grammar/override/more_assign/more_assign_1/kcl.mod diff --git a/test/grammar/override/more_assign/more_assign_1/settings.yaml b/tests/grammar/override/more_assign/more_assign_1/settings.yaml similarity index 100% rename from test/grammar/override/more_assign/more_assign_1/settings.yaml rename to tests/grammar/override/more_assign/more_assign_1/settings.yaml diff --git a/test/grammar/override/more_assign/more_assign_1/stdout.golden b/tests/grammar/override/more_assign/more_assign_1/stdout.golden similarity index 100% rename from test/grammar/override/more_assign/more_assign_1/stdout.golden rename to tests/grammar/override/more_assign/more_assign_1/stdout.golden diff --git a/test/grammar/override/nested0/kcl.mod b/tests/grammar/override/nested0/kcl.mod similarity index 100% rename from test/grammar/override/nested0/kcl.mod rename to tests/grammar/override/nested0/kcl.mod diff --git a/test/grammar/override/nested0/nested1/simple/_main.k b/tests/grammar/override/nested0/nested1/simple/_main.k similarity index 100% rename from test/grammar/override/nested0/nested1/simple/_main.k rename to tests/grammar/override/nested0/nested1/simple/_main.k diff --git a/test/grammar/override/nested0/nested1/simple/settings.yaml b/tests/grammar/override/nested0/nested1/simple/settings.yaml similarity index 100% rename from test/grammar/override/nested0/nested1/simple/settings.yaml rename to tests/grammar/override/nested0/nested1/simple/settings.yaml diff --git a/test/grammar/override/nested0/nested1/simple/stdout.golden b/tests/grammar/override/nested0/nested1/simple/stdout.golden similarity index 100% rename from test/grammar/override/nested0/nested1/simple/stdout.golden rename to tests/grammar/override/nested0/nested1/simple/stdout.golden diff --git a/test/grammar/override/pkg/_main.k b/tests/grammar/override/pkg/_main.k similarity index 100% rename from test/grammar/override/pkg/_main.k rename to tests/grammar/override/pkg/_main.k diff --git a/test/grammar/override/pkg/internal_pkg/main.k b/tests/grammar/override/pkg/internal_pkg/main.k similarity index 100% rename from test/grammar/override/pkg/internal_pkg/main.k rename to tests/grammar/override/pkg/internal_pkg/main.k diff --git a/test/grammar/override/pkg/kcl.mod b/tests/grammar/override/pkg/kcl.mod similarity index 100% rename from test/grammar/override/pkg/kcl.mod rename to tests/grammar/override/pkg/kcl.mod diff --git a/test/grammar/override/pkg/settings.yaml b/tests/grammar/override/pkg/settings.yaml similarity index 100% rename from test/grammar/override/pkg/settings.yaml rename to tests/grammar/override/pkg/settings.yaml diff --git a/test/grammar/override/pkg/stdout.golden b/tests/grammar/override/pkg/stdout.golden similarity index 100% rename from test/grammar/override/pkg/stdout.golden rename to tests/grammar/override/pkg/stdout.golden diff --git a/test/grammar/override/simple_0/_main.k b/tests/grammar/override/simple_0/_main.k similarity index 100% rename from test/grammar/override/simple_0/_main.k rename to tests/grammar/override/simple_0/_main.k diff --git a/test/grammar/override/simple_0/settings.yaml b/tests/grammar/override/simple_0/settings.yaml similarity index 100% rename from test/grammar/override/simple_0/settings.yaml rename to tests/grammar/override/simple_0/settings.yaml diff --git a/test/grammar/override/simple_0/stdout.golden b/tests/grammar/override/simple_0/stdout.golden similarity index 100% rename from test/grammar/override/simple_0/stdout.golden rename to tests/grammar/override/simple_0/stdout.golden diff --git a/test/grammar/override/simple_1/_main.k b/tests/grammar/override/simple_1/_main.k similarity index 100% rename from test/grammar/override/simple_1/_main.k rename to tests/grammar/override/simple_1/_main.k diff --git a/test/grammar/override/simple_1/settings.yaml b/tests/grammar/override/simple_1/settings.yaml similarity index 100% rename from test/grammar/override/simple_1/settings.yaml rename to tests/grammar/override/simple_1/settings.yaml diff --git a/test/grammar/override/simple_1/stdout.golden b/tests/grammar/override/simple_1/stdout.golden similarity index 100% rename from test/grammar/override/simple_1/stdout.golden rename to tests/grammar/override/simple_1/stdout.golden diff --git a/test/grammar/override/simple_2/_main.k b/tests/grammar/override/simple_2/_main.k similarity index 100% rename from test/grammar/override/simple_2/_main.k rename to tests/grammar/override/simple_2/_main.k diff --git a/test/grammar/override/simple_2/settings.yaml b/tests/grammar/override/simple_2/settings.yaml similarity index 100% rename from test/grammar/override/simple_2/settings.yaml rename to tests/grammar/override/simple_2/settings.yaml diff --git a/test/grammar/override/simple_2/stdout.golden b/tests/grammar/override/simple_2/stdout.golden similarity index 100% rename from test/grammar/override/simple_2/stdout.golden rename to tests/grammar/override/simple_2/stdout.golden diff --git a/test/grammar/override/type_dict/_main.k b/tests/grammar/override/type_dict/_main.k similarity index 100% rename from test/grammar/override/type_dict/_main.k rename to tests/grammar/override/type_dict/_main.k diff --git a/test/grammar/override/type_dict/settings.yaml b/tests/grammar/override/type_dict/settings.yaml similarity index 100% rename from test/grammar/override/type_dict/settings.yaml rename to tests/grammar/override/type_dict/settings.yaml diff --git a/test/grammar/override/type_dict/stdout.golden b/tests/grammar/override/type_dict/stdout.golden similarity index 100% rename from test/grammar/override/type_dict/stdout.golden rename to tests/grammar/override/type_dict/stdout.golden diff --git a/test/grammar/path_selector/all_elements/_main.k b/tests/grammar/path_selector/all_elements/_main.k similarity index 100% rename from test/grammar/path_selector/all_elements/_main.k rename to tests/grammar/path_selector/all_elements/_main.k diff --git a/test/grammar/path_selector/all_elements/kcl.mod b/tests/grammar/path_selector/all_elements/kcl.mod similarity index 100% rename from test/grammar/path_selector/all_elements/kcl.mod rename to tests/grammar/path_selector/all_elements/kcl.mod diff --git a/test/grammar/path_selector/all_elements/settings.yaml b/tests/grammar/path_selector/all_elements/settings.yaml similarity index 100% rename from test/grammar/path_selector/all_elements/settings.yaml rename to tests/grammar/path_selector/all_elements/settings.yaml diff --git a/test/grammar/path_selector/all_elements/stdout.golden b/tests/grammar/path_selector/all_elements/stdout.golden similarity index 100% rename from test/grammar/path_selector/all_elements/stdout.golden rename to tests/grammar/path_selector/all_elements/stdout.golden diff --git a/test/grammar/path_selector/combination/main.k b/tests/grammar/path_selector/combination/main.k similarity index 100% rename from test/grammar/path_selector/combination/main.k rename to tests/grammar/path_selector/combination/main.k diff --git a/test/grammar/path_selector/combination/settings.yaml b/tests/grammar/path_selector/combination/settings.yaml similarity index 100% rename from test/grammar/path_selector/combination/settings.yaml rename to tests/grammar/path_selector/combination/settings.yaml diff --git a/test/grammar/path_selector/combination/stdout.golden b/tests/grammar/path_selector/combination/stdout.golden similarity index 100% rename from test/grammar/path_selector/combination/stdout.golden rename to tests/grammar/path_selector/combination/stdout.golden diff --git a/test/grammar/path_selector/dict/main.k b/tests/grammar/path_selector/dict/main.k similarity index 100% rename from test/grammar/path_selector/dict/main.k rename to tests/grammar/path_selector/dict/main.k diff --git a/test/grammar/path_selector/dict/settings.yaml b/tests/grammar/path_selector/dict/settings.yaml similarity index 100% rename from test/grammar/path_selector/dict/settings.yaml rename to tests/grammar/path_selector/dict/settings.yaml diff --git a/test/grammar/path_selector/dict/stdout.golden b/tests/grammar/path_selector/dict/stdout.golden similarity index 100% rename from test/grammar/path_selector/dict/stdout.golden rename to tests/grammar/path_selector/dict/stdout.golden diff --git a/test/grammar/path_selector/import_package/kcl.mod b/tests/grammar/path_selector/import_package/kcl.mod similarity index 100% rename from test/grammar/path_selector/import_package/kcl.mod rename to tests/grammar/path_selector/import_package/kcl.mod diff --git a/test/grammar/path_selector/import_package/main.k b/tests/grammar/path_selector/import_package/main.k similarity index 100% rename from test/grammar/path_selector/import_package/main.k rename to tests/grammar/path_selector/import_package/main.k diff --git a/test/grammar/path_selector/import_package/mymodule/a.k b/tests/grammar/path_selector/import_package/mymodule/a.k similarity index 100% rename from test/grammar/path_selector/import_package/mymodule/a.k rename to tests/grammar/path_selector/import_package/mymodule/a.k diff --git a/test/grammar/path_selector/import_package/mymodule/b.k b/tests/grammar/path_selector/import_package/mymodule/b.k similarity index 100% rename from test/grammar/path_selector/import_package/mymodule/b.k rename to tests/grammar/path_selector/import_package/mymodule/b.k diff --git a/test/grammar/path_selector/import_package/settings.yaml b/tests/grammar/path_selector/import_package/settings.yaml similarity index 100% rename from test/grammar/path_selector/import_package/settings.yaml rename to tests/grammar/path_selector/import_package/settings.yaml diff --git a/test/grammar/path_selector/import_package/stdout.golden b/tests/grammar/path_selector/import_package/stdout.golden similarity index 100% rename from test/grammar/path_selector/import_package/stdout.golden rename to tests/grammar/path_selector/import_package/stdout.golden diff --git a/test/grammar/path_selector/index/_main.k b/tests/grammar/path_selector/index/_main.k similarity index 100% rename from test/grammar/path_selector/index/_main.k rename to tests/grammar/path_selector/index/_main.k diff --git a/test/grammar/path_selector/index/kcl.mod b/tests/grammar/path_selector/index/kcl.mod similarity index 100% rename from test/grammar/path_selector/index/kcl.mod rename to tests/grammar/path_selector/index/kcl.mod diff --git a/test/grammar/path_selector/index/settings.yaml b/tests/grammar/path_selector/index/settings.yaml similarity index 100% rename from test/grammar/path_selector/index/settings.yaml rename to tests/grammar/path_selector/index/settings.yaml diff --git a/test/grammar/path_selector/index/stdout.golden b/tests/grammar/path_selector/index/stdout.golden similarity index 100% rename from test/grammar/path_selector/index/stdout.golden rename to tests/grammar/path_selector/index/stdout.golden diff --git a/test/grammar/path_selector/inherit/main.k b/tests/grammar/path_selector/inherit/main.k similarity index 100% rename from test/grammar/path_selector/inherit/main.k rename to tests/grammar/path_selector/inherit/main.k diff --git a/test/grammar/path_selector/inherit/settings.yaml b/tests/grammar/path_selector/inherit/settings.yaml similarity index 100% rename from test/grammar/path_selector/inherit/settings.yaml rename to tests/grammar/path_selector/inherit/settings.yaml diff --git a/test/grammar/path_selector/inherit/stdout.golden b/tests/grammar/path_selector/inherit/stdout.golden similarity index 100% rename from test/grammar/path_selector/inherit/stdout.golden rename to tests/grammar/path_selector/inherit/stdout.golden diff --git a/test/grammar/path_selector/invalid/invalid_0/kcl.mod b/tests/grammar/path_selector/invalid/invalid_0/kcl.mod similarity index 100% rename from test/grammar/path_selector/invalid/invalid_0/kcl.mod rename to tests/grammar/path_selector/invalid/invalid_0/kcl.mod diff --git a/test/grammar/path_selector/invalid/invalid_0/main.k b/tests/grammar/path_selector/invalid/invalid_0/main.k similarity index 100% rename from test/grammar/path_selector/invalid/invalid_0/main.k rename to tests/grammar/path_selector/invalid/invalid_0/main.k diff --git a/test/grammar/path_selector/invalid/invalid_0/settings.yaml b/tests/grammar/path_selector/invalid/invalid_0/settings.yaml similarity index 100% rename from test/grammar/path_selector/invalid/invalid_0/settings.yaml rename to tests/grammar/path_selector/invalid/invalid_0/settings.yaml diff --git a/test/grammar/path_selector/invalid/invalid_0/stderr.golden b/tests/grammar/path_selector/invalid/invalid_0/stderr.golden similarity index 100% rename from test/grammar/path_selector/invalid/invalid_0/stderr.golden rename to tests/grammar/path_selector/invalid/invalid_0/stderr.golden diff --git a/test/grammar/path_selector/invalid/invalid_1/_main.k b/tests/grammar/path_selector/invalid/invalid_1/_main.k similarity index 100% rename from test/grammar/path_selector/invalid/invalid_1/_main.k rename to tests/grammar/path_selector/invalid/invalid_1/_main.k diff --git a/test/grammar/path_selector/invalid/invalid_1/kcl.mod b/tests/grammar/path_selector/invalid/invalid_1/kcl.mod similarity index 100% rename from test/grammar/path_selector/invalid/invalid_1/kcl.mod rename to tests/grammar/path_selector/invalid/invalid_1/kcl.mod diff --git a/test/grammar/path_selector/invalid/invalid_1/settings.yaml b/tests/grammar/path_selector/invalid/invalid_1/settings.yaml similarity index 100% rename from test/grammar/path_selector/invalid/invalid_1/settings.yaml rename to tests/grammar/path_selector/invalid/invalid_1/settings.yaml diff --git a/test/grammar/path_selector/invalid/invalid_1/stderr.golden b/tests/grammar/path_selector/invalid/invalid_1/stderr.golden similarity index 100% rename from test/grammar/path_selector/invalid/invalid_1/stderr.golden rename to tests/grammar/path_selector/invalid/invalid_1/stderr.golden diff --git a/test/grammar/path_selector/invalid/invalid_2/_main.k b/tests/grammar/path_selector/invalid/invalid_2/_main.k similarity index 100% rename from test/grammar/path_selector/invalid/invalid_2/_main.k rename to tests/grammar/path_selector/invalid/invalid_2/_main.k diff --git a/test/grammar/path_selector/invalid/invalid_2/kcl.mod b/tests/grammar/path_selector/invalid/invalid_2/kcl.mod similarity index 100% rename from test/grammar/path_selector/invalid/invalid_2/kcl.mod rename to tests/grammar/path_selector/invalid/invalid_2/kcl.mod diff --git a/test/grammar/path_selector/invalid/invalid_2/settings.yaml b/tests/grammar/path_selector/invalid/invalid_2/settings.yaml similarity index 100% rename from test/grammar/path_selector/invalid/invalid_2/settings.yaml rename to tests/grammar/path_selector/invalid/invalid_2/settings.yaml diff --git a/test/grammar/path_selector/invalid/invalid_2/stderr.golden b/tests/grammar/path_selector/invalid/invalid_2/stderr.golden similarity index 100% rename from test/grammar/path_selector/invalid/invalid_2/stderr.golden rename to tests/grammar/path_selector/invalid/invalid_2/stderr.golden diff --git a/test/grammar/path_selector/kcl.mod b/tests/grammar/path_selector/kcl.mod similarity index 100% rename from test/grammar/path_selector/kcl.mod rename to tests/grammar/path_selector/kcl.mod diff --git a/test/grammar/path_selector/list_content/kcl.mod b/tests/grammar/path_selector/list_content/kcl.mod similarity index 100% rename from test/grammar/path_selector/list_content/kcl.mod rename to tests/grammar/path_selector/list_content/kcl.mod diff --git a/test/grammar/path_selector/list_content/main.k b/tests/grammar/path_selector/list_content/main.k similarity index 100% rename from test/grammar/path_selector/list_content/main.k rename to tests/grammar/path_selector/list_content/main.k diff --git a/test/grammar/path_selector/list_content/settings.yaml b/tests/grammar/path_selector/list_content/settings.yaml similarity index 100% rename from test/grammar/path_selector/list_content/settings.yaml rename to tests/grammar/path_selector/list_content/settings.yaml diff --git a/test/grammar/path_selector/list_content/stdout.golden b/tests/grammar/path_selector/list_content/stdout.golden similarity index 100% rename from test/grammar/path_selector/list_content/stdout.golden rename to tests/grammar/path_selector/list_content/stdout.golden diff --git a/test/grammar/path_selector/mutiple_keys/_main.k b/tests/grammar/path_selector/mutiple_keys/_main.k similarity index 100% rename from test/grammar/path_selector/mutiple_keys/_main.k rename to tests/grammar/path_selector/mutiple_keys/_main.k diff --git a/test/grammar/path_selector/mutiple_keys/kcl.mod b/tests/grammar/path_selector/mutiple_keys/kcl.mod similarity index 100% rename from test/grammar/path_selector/mutiple_keys/kcl.mod rename to tests/grammar/path_selector/mutiple_keys/kcl.mod diff --git a/test/grammar/path_selector/mutiple_keys/settings.yaml b/tests/grammar/path_selector/mutiple_keys/settings.yaml similarity index 100% rename from test/grammar/path_selector/mutiple_keys/settings.yaml rename to tests/grammar/path_selector/mutiple_keys/settings.yaml diff --git a/test/grammar/path_selector/mutiple_keys/stdout.golden b/tests/grammar/path_selector/mutiple_keys/stdout.golden similarity index 100% rename from test/grammar/path_selector/mutiple_keys/stdout.golden rename to tests/grammar/path_selector/mutiple_keys/stdout.golden diff --git a/test/grammar/path_selector/simple/main.k b/tests/grammar/path_selector/simple/main.k similarity index 100% rename from test/grammar/path_selector/simple/main.k rename to tests/grammar/path_selector/simple/main.k diff --git a/test/grammar/path_selector/simple/settings.yaml b/tests/grammar/path_selector/simple/settings.yaml similarity index 100% rename from test/grammar/path_selector/simple/settings.yaml rename to tests/grammar/path_selector/simple/settings.yaml diff --git a/test/grammar/path_selector/simple/stdout.golden b/tests/grammar/path_selector/simple/stdout.golden similarity index 100% rename from test/grammar/path_selector/simple/stdout.golden rename to tests/grammar/path_selector/simple/stdout.golden diff --git a/test/grammar/path_selector/type_dict/main.k b/tests/grammar/path_selector/type_dict/main.k similarity index 100% rename from test/grammar/path_selector/type_dict/main.k rename to tests/grammar/path_selector/type_dict/main.k diff --git a/test/grammar/path_selector/type_dict/settings.yaml b/tests/grammar/path_selector/type_dict/settings.yaml similarity index 100% rename from test/grammar/path_selector/type_dict/settings.yaml rename to tests/grammar/path_selector/type_dict/settings.yaml diff --git a/test/grammar/path_selector/type_dict/stdout.golden b/tests/grammar/path_selector/type_dict/stdout.golden similarity index 100% rename from test/grammar/path_selector/type_dict/stdout.golden rename to tests/grammar/path_selector/type_dict/stdout.golden diff --git a/test/grammar/plugin/fail_0/main.k b/tests/grammar/plugin/fail_0/main.k similarity index 100% rename from test/grammar/plugin/fail_0/main.k rename to tests/grammar/plugin/fail_0/main.k diff --git a/test/grammar/plugin/fail_0/stderr.golden b/tests/grammar/plugin/fail_0/stderr.golden similarity index 100% rename from test/grammar/plugin/fail_0/stderr.golden rename to tests/grammar/plugin/fail_0/stderr.golden diff --git a/test/grammar/plugin/fail_1/main.k b/tests/grammar/plugin/fail_1/main.k similarity index 100% rename from test/grammar/plugin/fail_1/main.k rename to tests/grammar/plugin/fail_1/main.k diff --git a/test/grammar/plugin/fail_1/stderr.golden b/tests/grammar/plugin/fail_1/stderr.golden similarity index 100% rename from test/grammar/plugin/fail_1/stderr.golden rename to tests/grammar/plugin/fail_1/stderr.golden diff --git a/test/grammar/plugin/hello/_main.k b/tests/grammar/plugin/hello/_main.k similarity index 100% rename from test/grammar/plugin/hello/_main.k rename to tests/grammar/plugin/hello/_main.k diff --git a/test/grammar/plugin/hello/stdout.golden b/tests/grammar/plugin/hello/stdout.golden similarity index 100% rename from test/grammar/plugin/hello/stdout.golden rename to tests/grammar/plugin/hello/stdout.golden diff --git a/test/grammar/quant/all/multi_cons_invalid_0/main.k b/tests/grammar/quant/all/multi_cons_invalid_0/main.k similarity index 100% rename from test/grammar/quant/all/multi_cons_invalid_0/main.k rename to tests/grammar/quant/all/multi_cons_invalid_0/main.k diff --git a/test/grammar/quant/all/multi_cons_invalid_0/stderr.golden b/tests/grammar/quant/all/multi_cons_invalid_0/stderr.golden similarity index 100% rename from test/grammar/quant/all/multi_cons_invalid_0/stderr.golden rename to tests/grammar/quant/all/multi_cons_invalid_0/stderr.golden diff --git a/test/grammar/quant/all/multi_cons_invalid_1/main.k b/tests/grammar/quant/all/multi_cons_invalid_1/main.k similarity index 100% rename from test/grammar/quant/all/multi_cons_invalid_1/main.k rename to tests/grammar/quant/all/multi_cons_invalid_1/main.k diff --git a/test/grammar/quant/all/multi_cons_invalid_1/stderr.golden b/tests/grammar/quant/all/multi_cons_invalid_1/stderr.golden similarity index 100% rename from test/grammar/quant/all/multi_cons_invalid_1/stderr.golden rename to tests/grammar/quant/all/multi_cons_invalid_1/stderr.golden diff --git a/test/grammar/quant/all/multi_cons_invalid_2/main.k b/tests/grammar/quant/all/multi_cons_invalid_2/main.k similarity index 100% rename from test/grammar/quant/all/multi_cons_invalid_2/main.k rename to tests/grammar/quant/all/multi_cons_invalid_2/main.k diff --git a/test/grammar/quant/all/multi_cons_invalid_2/stderr.golden b/tests/grammar/quant/all/multi_cons_invalid_2/stderr.golden similarity index 100% rename from test/grammar/quant/all/multi_cons_invalid_2/stderr.golden rename to tests/grammar/quant/all/multi_cons_invalid_2/stderr.golden diff --git a/test/grammar/quant/all/multi_cons_invalid_3/main.k b/tests/grammar/quant/all/multi_cons_invalid_3/main.k similarity index 100% rename from test/grammar/quant/all/multi_cons_invalid_3/main.k rename to tests/grammar/quant/all/multi_cons_invalid_3/main.k diff --git a/test/grammar/quant/all/multi_cons_invalid_3/stderr.golden b/tests/grammar/quant/all/multi_cons_invalid_3/stderr.golden similarity index 100% rename from test/grammar/quant/all/multi_cons_invalid_3/stderr.golden rename to tests/grammar/quant/all/multi_cons_invalid_3/stderr.golden diff --git a/test/grammar/quant/all/multi_cons_invalid_4/main.k b/tests/grammar/quant/all/multi_cons_invalid_4/main.k similarity index 100% rename from test/grammar/quant/all/multi_cons_invalid_4/main.k rename to tests/grammar/quant/all/multi_cons_invalid_4/main.k diff --git a/test/grammar/quant/all/multi_cons_invalid_4/stderr.golden b/tests/grammar/quant/all/multi_cons_invalid_4/stderr.golden similarity index 100% rename from test/grammar/quant/all/multi_cons_invalid_4/stderr.golden rename to tests/grammar/quant/all/multi_cons_invalid_4/stderr.golden diff --git a/test/grammar/quant/all/multi_cons_valid_0/main.k b/tests/grammar/quant/all/multi_cons_valid_0/main.k similarity index 100% rename from test/grammar/quant/all/multi_cons_valid_0/main.k rename to tests/grammar/quant/all/multi_cons_valid_0/main.k diff --git a/test/grammar/quant/all/multi_cons_valid_0/stdout.golden b/tests/grammar/quant/all/multi_cons_valid_0/stdout.golden similarity index 100% rename from test/grammar/quant/all/multi_cons_valid_0/stdout.golden rename to tests/grammar/quant/all/multi_cons_valid_0/stdout.golden diff --git a/test/grammar/quant/all/multi_cons_valid_1/main.k b/tests/grammar/quant/all/multi_cons_valid_1/main.k similarity index 100% rename from test/grammar/quant/all/multi_cons_valid_1/main.k rename to tests/grammar/quant/all/multi_cons_valid_1/main.k diff --git a/test/grammar/quant/all/multi_cons_valid_1/stdout.golden b/tests/grammar/quant/all/multi_cons_valid_1/stdout.golden similarity index 100% rename from test/grammar/quant/all/multi_cons_valid_1/stdout.golden rename to tests/grammar/quant/all/multi_cons_valid_1/stdout.golden diff --git a/test/grammar/quant/all/multi_cons_valid_2/main.k b/tests/grammar/quant/all/multi_cons_valid_2/main.k similarity index 100% rename from test/grammar/quant/all/multi_cons_valid_2/main.k rename to tests/grammar/quant/all/multi_cons_valid_2/main.k diff --git a/test/grammar/quant/all/multi_cons_valid_2/stdout.golden b/tests/grammar/quant/all/multi_cons_valid_2/stdout.golden similarity index 100% rename from test/grammar/quant/all/multi_cons_valid_2/stdout.golden rename to tests/grammar/quant/all/multi_cons_valid_2/stdout.golden diff --git a/test/grammar/quant/all/multi_cons_valid_3/main.k b/tests/grammar/quant/all/multi_cons_valid_3/main.k similarity index 100% rename from test/grammar/quant/all/multi_cons_valid_3/main.k rename to tests/grammar/quant/all/multi_cons_valid_3/main.k diff --git a/test/grammar/quant/all/multi_cons_valid_3/stdout.golden b/tests/grammar/quant/all/multi_cons_valid_3/stdout.golden similarity index 100% rename from test/grammar/quant/all/multi_cons_valid_3/stdout.golden rename to tests/grammar/quant/all/multi_cons_valid_3/stdout.golden diff --git a/test/grammar/quant/all/multi_cons_valid_4/main.k b/tests/grammar/quant/all/multi_cons_valid_4/main.k similarity index 100% rename from test/grammar/quant/all/multi_cons_valid_4/main.k rename to tests/grammar/quant/all/multi_cons_valid_4/main.k diff --git a/test/grammar/quant/all/multi_cons_valid_4/stdout.golden b/tests/grammar/quant/all/multi_cons_valid_4/stdout.golden similarity index 100% rename from test/grammar/quant/all/multi_cons_valid_4/stdout.golden rename to tests/grammar/quant/all/multi_cons_valid_4/stdout.golden diff --git a/test/grammar/quant/all/simple_invalid_0/main.k b/tests/grammar/quant/all/simple_invalid_0/main.k similarity index 100% rename from test/grammar/quant/all/simple_invalid_0/main.k rename to tests/grammar/quant/all/simple_invalid_0/main.k diff --git a/test/grammar/quant/all/simple_invalid_0/stderr.golden b/tests/grammar/quant/all/simple_invalid_0/stderr.golden similarity index 100% rename from test/grammar/quant/all/simple_invalid_0/stderr.golden rename to tests/grammar/quant/all/simple_invalid_0/stderr.golden diff --git a/test/grammar/quant/all/simple_valid_0/main.k b/tests/grammar/quant/all/simple_valid_0/main.k similarity index 100% rename from test/grammar/quant/all/simple_valid_0/main.k rename to tests/grammar/quant/all/simple_valid_0/main.k diff --git a/test/grammar/quant/all/simple_valid_0/stdout.golden b/tests/grammar/quant/all/simple_valid_0/stdout.golden similarity index 100% rename from test/grammar/quant/all/simple_valid_0/stdout.golden rename to tests/grammar/quant/all/simple_valid_0/stdout.golden diff --git a/test/grammar/quant/all/simple_valid_1/main.k b/tests/grammar/quant/all/simple_valid_1/main.k similarity index 100% rename from test/grammar/quant/all/simple_valid_1/main.k rename to tests/grammar/quant/all/simple_valid_1/main.k diff --git a/test/grammar/quant/all/simple_valid_1/stdout.golden b/tests/grammar/quant/all/simple_valid_1/stdout.golden similarity index 100% rename from test/grammar/quant/all/simple_valid_1/stdout.golden rename to tests/grammar/quant/all/simple_valid_1/stdout.golden diff --git a/test/grammar/quant/all/simple_valid_2/main.k b/tests/grammar/quant/all/simple_valid_2/main.k similarity index 100% rename from test/grammar/quant/all/simple_valid_2/main.k rename to tests/grammar/quant/all/simple_valid_2/main.k diff --git a/test/grammar/quant/all/simple_valid_2/stdout.golden b/tests/grammar/quant/all/simple_valid_2/stdout.golden similarity index 100% rename from test/grammar/quant/all/simple_valid_2/stdout.golden rename to tests/grammar/quant/all/simple_valid_2/stdout.golden diff --git a/test/grammar/quant/all/simple_valid_3/main.k b/tests/grammar/quant/all/simple_valid_3/main.k similarity index 100% rename from test/grammar/quant/all/simple_valid_3/main.k rename to tests/grammar/quant/all/simple_valid_3/main.k diff --git a/test/grammar/quant/all/simple_valid_3/stdout.golden b/tests/grammar/quant/all/simple_valid_3/stdout.golden similarity index 100% rename from test/grammar/quant/all/simple_valid_3/stdout.golden rename to tests/grammar/quant/all/simple_valid_3/stdout.golden diff --git a/test/grammar/quant/all/simple_valid_4/main.k b/tests/grammar/quant/all/simple_valid_4/main.k similarity index 100% rename from test/grammar/quant/all/simple_valid_4/main.k rename to tests/grammar/quant/all/simple_valid_4/main.k diff --git a/test/grammar/quant/all/simple_valid_4/stdout.golden b/tests/grammar/quant/all/simple_valid_4/stdout.golden similarity index 100% rename from test/grammar/quant/all/simple_valid_4/stdout.golden rename to tests/grammar/quant/all/simple_valid_4/stdout.golden diff --git a/test/grammar/quant/any/multi_cons_invalid_0/main.k b/tests/grammar/quant/any/multi_cons_invalid_0/main.k similarity index 100% rename from test/grammar/quant/any/multi_cons_invalid_0/main.k rename to tests/grammar/quant/any/multi_cons_invalid_0/main.k diff --git a/test/grammar/quant/any/multi_cons_invalid_0/stderr.golden b/tests/grammar/quant/any/multi_cons_invalid_0/stderr.golden similarity index 100% rename from test/grammar/quant/any/multi_cons_invalid_0/stderr.golden rename to tests/grammar/quant/any/multi_cons_invalid_0/stderr.golden diff --git a/test/grammar/quant/any/multi_cons_invalid_1/main.k b/tests/grammar/quant/any/multi_cons_invalid_1/main.k similarity index 100% rename from test/grammar/quant/any/multi_cons_invalid_1/main.k rename to tests/grammar/quant/any/multi_cons_invalid_1/main.k diff --git a/test/grammar/quant/any/multi_cons_invalid_1/stderr.golden b/tests/grammar/quant/any/multi_cons_invalid_1/stderr.golden similarity index 100% rename from test/grammar/quant/any/multi_cons_invalid_1/stderr.golden rename to tests/grammar/quant/any/multi_cons_invalid_1/stderr.golden diff --git a/test/grammar/quant/any/multi_cons_invalid_2/main.k b/tests/grammar/quant/any/multi_cons_invalid_2/main.k similarity index 100% rename from test/grammar/quant/any/multi_cons_invalid_2/main.k rename to tests/grammar/quant/any/multi_cons_invalid_2/main.k diff --git a/test/grammar/quant/any/multi_cons_invalid_2/stderr.golden b/tests/grammar/quant/any/multi_cons_invalid_2/stderr.golden similarity index 100% rename from test/grammar/quant/any/multi_cons_invalid_2/stderr.golden rename to tests/grammar/quant/any/multi_cons_invalid_2/stderr.golden diff --git a/test/grammar/quant/any/multi_cons_invalid_3/main.k b/tests/grammar/quant/any/multi_cons_invalid_3/main.k similarity index 100% rename from test/grammar/quant/any/multi_cons_invalid_3/main.k rename to tests/grammar/quant/any/multi_cons_invalid_3/main.k diff --git a/test/grammar/quant/any/multi_cons_invalid_3/stderr.golden b/tests/grammar/quant/any/multi_cons_invalid_3/stderr.golden similarity index 100% rename from test/grammar/quant/any/multi_cons_invalid_3/stderr.golden rename to tests/grammar/quant/any/multi_cons_invalid_3/stderr.golden diff --git a/test/grammar/quant/any/multi_cons_invalid_4/main.k b/tests/grammar/quant/any/multi_cons_invalid_4/main.k similarity index 100% rename from test/grammar/quant/any/multi_cons_invalid_4/main.k rename to tests/grammar/quant/any/multi_cons_invalid_4/main.k diff --git a/test/grammar/quant/any/multi_cons_invalid_4/stderr.golden b/tests/grammar/quant/any/multi_cons_invalid_4/stderr.golden similarity index 100% rename from test/grammar/quant/any/multi_cons_invalid_4/stderr.golden rename to tests/grammar/quant/any/multi_cons_invalid_4/stderr.golden diff --git a/test/grammar/quant/any/multi_cons_valid_0/main.k b/tests/grammar/quant/any/multi_cons_valid_0/main.k similarity index 100% rename from test/grammar/quant/any/multi_cons_valid_0/main.k rename to tests/grammar/quant/any/multi_cons_valid_0/main.k diff --git a/test/grammar/quant/any/multi_cons_valid_0/stdout.golden b/tests/grammar/quant/any/multi_cons_valid_0/stdout.golden similarity index 100% rename from test/grammar/quant/any/multi_cons_valid_0/stdout.golden rename to tests/grammar/quant/any/multi_cons_valid_0/stdout.golden diff --git a/test/grammar/quant/any/multi_cons_valid_1/main.k b/tests/grammar/quant/any/multi_cons_valid_1/main.k similarity index 100% rename from test/grammar/quant/any/multi_cons_valid_1/main.k rename to tests/grammar/quant/any/multi_cons_valid_1/main.k diff --git a/test/grammar/quant/any/multi_cons_valid_1/stdout.golden b/tests/grammar/quant/any/multi_cons_valid_1/stdout.golden similarity index 100% rename from test/grammar/quant/any/multi_cons_valid_1/stdout.golden rename to tests/grammar/quant/any/multi_cons_valid_1/stdout.golden diff --git a/test/grammar/quant/any/multi_cons_valid_2/main.k b/tests/grammar/quant/any/multi_cons_valid_2/main.k similarity index 100% rename from test/grammar/quant/any/multi_cons_valid_2/main.k rename to tests/grammar/quant/any/multi_cons_valid_2/main.k diff --git a/test/grammar/quant/any/multi_cons_valid_2/stdout.golden b/tests/grammar/quant/any/multi_cons_valid_2/stdout.golden similarity index 100% rename from test/grammar/quant/any/multi_cons_valid_2/stdout.golden rename to tests/grammar/quant/any/multi_cons_valid_2/stdout.golden diff --git a/test/grammar/quant/any/multi_cons_valid_3/main.k b/tests/grammar/quant/any/multi_cons_valid_3/main.k similarity index 100% rename from test/grammar/quant/any/multi_cons_valid_3/main.k rename to tests/grammar/quant/any/multi_cons_valid_3/main.k diff --git a/test/grammar/quant/any/multi_cons_valid_3/stdout.golden b/tests/grammar/quant/any/multi_cons_valid_3/stdout.golden similarity index 100% rename from test/grammar/quant/any/multi_cons_valid_3/stdout.golden rename to tests/grammar/quant/any/multi_cons_valid_3/stdout.golden diff --git a/test/grammar/quant/any/multi_cons_valid_4/main.k b/tests/grammar/quant/any/multi_cons_valid_4/main.k similarity index 100% rename from test/grammar/quant/any/multi_cons_valid_4/main.k rename to tests/grammar/quant/any/multi_cons_valid_4/main.k diff --git a/test/grammar/quant/any/multi_cons_valid_4/stdout.golden b/tests/grammar/quant/any/multi_cons_valid_4/stdout.golden similarity index 100% rename from test/grammar/quant/any/multi_cons_valid_4/stdout.golden rename to tests/grammar/quant/any/multi_cons_valid_4/stdout.golden diff --git a/test/grammar/quant/any/simple_invalid_0/main.k b/tests/grammar/quant/any/simple_invalid_0/main.k similarity index 100% rename from test/grammar/quant/any/simple_invalid_0/main.k rename to tests/grammar/quant/any/simple_invalid_0/main.k diff --git a/test/grammar/quant/any/simple_invalid_0/stderr.golden b/tests/grammar/quant/any/simple_invalid_0/stderr.golden similarity index 100% rename from test/grammar/quant/any/simple_invalid_0/stderr.golden rename to tests/grammar/quant/any/simple_invalid_0/stderr.golden diff --git a/test/grammar/quant/any/simple_valid_0/main.k b/tests/grammar/quant/any/simple_valid_0/main.k similarity index 100% rename from test/grammar/quant/any/simple_valid_0/main.k rename to tests/grammar/quant/any/simple_valid_0/main.k diff --git a/test/grammar/quant/any/simple_valid_0/stdout.golden b/tests/grammar/quant/any/simple_valid_0/stdout.golden similarity index 100% rename from test/grammar/quant/any/simple_valid_0/stdout.golden rename to tests/grammar/quant/any/simple_valid_0/stdout.golden diff --git a/test/grammar/quant/any/simple_valid_1/main.k b/tests/grammar/quant/any/simple_valid_1/main.k similarity index 100% rename from test/grammar/quant/any/simple_valid_1/main.k rename to tests/grammar/quant/any/simple_valid_1/main.k diff --git a/test/grammar/quant/any/simple_valid_1/stdout.golden b/tests/grammar/quant/any/simple_valid_1/stdout.golden similarity index 100% rename from test/grammar/quant/any/simple_valid_1/stdout.golden rename to tests/grammar/quant/any/simple_valid_1/stdout.golden diff --git a/test/grammar/quant/filter/simple_dict_0/main.k b/tests/grammar/quant/filter/simple_dict_0/main.k similarity index 100% rename from test/grammar/quant/filter/simple_dict_0/main.k rename to tests/grammar/quant/filter/simple_dict_0/main.k diff --git a/test/grammar/quant/filter/simple_dict_0/stdout.golden b/tests/grammar/quant/filter/simple_dict_0/stdout.golden similarity index 100% rename from test/grammar/quant/filter/simple_dict_0/stdout.golden rename to tests/grammar/quant/filter/simple_dict_0/stdout.golden diff --git a/test/grammar/quant/filter/simple_dict_1/main.k b/tests/grammar/quant/filter/simple_dict_1/main.k similarity index 100% rename from test/grammar/quant/filter/simple_dict_1/main.k rename to tests/grammar/quant/filter/simple_dict_1/main.k diff --git a/test/grammar/quant/filter/simple_dict_1/stdout.golden b/tests/grammar/quant/filter/simple_dict_1/stdout.golden similarity index 100% rename from test/grammar/quant/filter/simple_dict_1/stdout.golden rename to tests/grammar/quant/filter/simple_dict_1/stdout.golden diff --git a/test/grammar/quant/filter/simple_list_0/main.k b/tests/grammar/quant/filter/simple_list_0/main.k similarity index 100% rename from test/grammar/quant/filter/simple_list_0/main.k rename to tests/grammar/quant/filter/simple_list_0/main.k diff --git a/test/grammar/quant/filter/simple_list_0/stdout.golden b/tests/grammar/quant/filter/simple_list_0/stdout.golden similarity index 100% rename from test/grammar/quant/filter/simple_list_0/stdout.golden rename to tests/grammar/quant/filter/simple_list_0/stdout.golden diff --git a/test/grammar/quant/filter/simple_list_1/main.k b/tests/grammar/quant/filter/simple_list_1/main.k similarity index 100% rename from test/grammar/quant/filter/simple_list_1/main.k rename to tests/grammar/quant/filter/simple_list_1/main.k diff --git a/test/grammar/quant/filter/simple_list_1/stdout.golden b/tests/grammar/quant/filter/simple_list_1/stdout.golden similarity index 100% rename from test/grammar/quant/filter/simple_list_1/stdout.golden rename to tests/grammar/quant/filter/simple_list_1/stdout.golden diff --git a/test/grammar/quant/filter/simple_list_2/main.k b/tests/grammar/quant/filter/simple_list_2/main.k similarity index 100% rename from test/grammar/quant/filter/simple_list_2/main.k rename to tests/grammar/quant/filter/simple_list_2/main.k diff --git a/test/grammar/quant/filter/simple_list_2/stdout.golden b/tests/grammar/quant/filter/simple_list_2/stdout.golden similarity index 100% rename from test/grammar/quant/filter/simple_list_2/stdout.golden rename to tests/grammar/quant/filter/simple_list_2/stdout.golden diff --git a/test/grammar/quant/map/simple_dict_0/main.k b/tests/grammar/quant/map/simple_dict_0/main.k similarity index 100% rename from test/grammar/quant/map/simple_dict_0/main.k rename to tests/grammar/quant/map/simple_dict_0/main.k diff --git a/test/grammar/quant/map/simple_dict_0/stdout.golden b/tests/grammar/quant/map/simple_dict_0/stdout.golden similarity index 100% rename from test/grammar/quant/map/simple_dict_0/stdout.golden rename to tests/grammar/quant/map/simple_dict_0/stdout.golden diff --git a/test/grammar/quant/map/simple_list_0/main.k b/tests/grammar/quant/map/simple_list_0/main.k similarity index 100% rename from test/grammar/quant/map/simple_list_0/main.k rename to tests/grammar/quant/map/simple_list_0/main.k diff --git a/test/grammar/quant/map/simple_list_0/stdout.golden b/tests/grammar/quant/map/simple_list_0/stdout.golden similarity index 100% rename from test/grammar/quant/map/simple_list_0/stdout.golden rename to tests/grammar/quant/map/simple_list_0/stdout.golden diff --git a/test/grammar/quant/map/simple_list_1/main.k b/tests/grammar/quant/map/simple_list_1/main.k similarity index 100% rename from test/grammar/quant/map/simple_list_1/main.k rename to tests/grammar/quant/map/simple_list_1/main.k diff --git a/test/grammar/quant/map/simple_list_1/stdout.golden b/tests/grammar/quant/map/simple_list_1/stdout.golden similarity index 100% rename from test/grammar/quant/map/simple_list_1/stdout.golden rename to tests/grammar/quant/map/simple_list_1/stdout.golden diff --git a/test/grammar/quant/map/simple_str_0/main.k b/tests/grammar/quant/map/simple_str_0/main.k similarity index 100% rename from test/grammar/quant/map/simple_str_0/main.k rename to tests/grammar/quant/map/simple_str_0/main.k diff --git a/test/grammar/quant/map/simple_str_0/stdout.golden b/tests/grammar/quant/map/simple_str_0/stdout.golden similarity index 100% rename from test/grammar/quant/map/simple_str_0/stdout.golden rename to tests/grammar/quant/map/simple_str_0/stdout.golden diff --git a/test/grammar/scalar/config/multi_config_inst_0/main.k b/tests/grammar/scalar/config/multi_config_inst_0/main.k similarity index 100% rename from test/grammar/scalar/config/multi_config_inst_0/main.k rename to tests/grammar/scalar/config/multi_config_inst_0/main.k diff --git a/test/grammar/scalar/config/multi_config_inst_0/stdout.golden b/tests/grammar/scalar/config/multi_config_inst_0/stdout.golden similarity index 100% rename from test/grammar/scalar/config/multi_config_inst_0/stdout.golden rename to tests/grammar/scalar/config/multi_config_inst_0/stdout.golden diff --git a/test/grammar/scalar/config/single_config_inst_0/main.k b/tests/grammar/scalar/config/single_config_inst_0/main.k similarity index 100% rename from test/grammar/scalar/config/single_config_inst_0/main.k rename to tests/grammar/scalar/config/single_config_inst_0/main.k diff --git a/test/grammar/scalar/config/single_config_inst_0/stdout.golden b/tests/grammar/scalar/config/single_config_inst_0/stdout.golden similarity index 100% rename from test/grammar/scalar/config/single_config_inst_0/stdout.golden rename to tests/grammar/scalar/config/single_config_inst_0/stdout.golden diff --git a/test/grammar/scalar/hidden_var/main.k b/tests/grammar/scalar/hidden_var/main.k similarity index 100% rename from test/grammar/scalar/hidden_var/main.k rename to tests/grammar/scalar/hidden_var/main.k diff --git a/test/grammar/scalar/hidden_var/stdout.golden b/tests/grammar/scalar/hidden_var/stdout.golden similarity index 100% rename from test/grammar/scalar/hidden_var/stdout.golden rename to tests/grammar/scalar/hidden_var/stdout.golden diff --git a/test/grammar/scalar/invalid/conflict_0/main.k b/tests/grammar/scalar/invalid/conflict_0/main.k similarity index 100% rename from test/grammar/scalar/invalid/conflict_0/main.k rename to tests/grammar/scalar/invalid/conflict_0/main.k diff --git a/test/grammar/scalar/invalid/conflict_0/stderr.golden b/tests/grammar/scalar/invalid/conflict_0/stderr.golden similarity index 100% rename from test/grammar/scalar/invalid/conflict_0/stderr.golden rename to tests/grammar/scalar/invalid/conflict_0/stderr.golden diff --git a/test/grammar/scalar/invalid/conflict_1/main.k b/tests/grammar/scalar/invalid/conflict_1/main.k similarity index 100% rename from test/grammar/scalar/invalid/conflict_1/main.k rename to tests/grammar/scalar/invalid/conflict_1/main.k diff --git a/test/grammar/scalar/invalid/conflict_1/stderr.golden b/tests/grammar/scalar/invalid/conflict_1/stderr.golden similarity index 100% rename from test/grammar/scalar/invalid/conflict_1/stderr.golden rename to tests/grammar/scalar/invalid/conflict_1/stderr.golden diff --git a/test/grammar/scalar/number/number_0/main.k b/tests/grammar/scalar/number/number_0/main.k similarity index 100% rename from test/grammar/scalar/number/number_0/main.k rename to tests/grammar/scalar/number/number_0/main.k diff --git a/test/grammar/scalar/number/number_0/stdout.golden b/tests/grammar/scalar/number/number_0/stdout.golden similarity index 100% rename from test/grammar/scalar/number/number_0/stdout.golden rename to tests/grammar/scalar/number/number_0/stdout.golden diff --git a/test/grammar/scalar/schema/multi_schema_inst_0/main.k b/tests/grammar/scalar/schema/multi_schema_inst_0/main.k similarity index 100% rename from test/grammar/scalar/schema/multi_schema_inst_0/main.k rename to tests/grammar/scalar/schema/multi_schema_inst_0/main.k diff --git a/test/grammar/scalar/schema/multi_schema_inst_0/stdout.golden b/tests/grammar/scalar/schema/multi_schema_inst_0/stdout.golden similarity index 100% rename from test/grammar/scalar/schema/multi_schema_inst_0/stdout.golden rename to tests/grammar/scalar/schema/multi_schema_inst_0/stdout.golden diff --git a/test/grammar/scalar/schema/single_schema_inst_0/main.k b/tests/grammar/scalar/schema/single_schema_inst_0/main.k similarity index 100% rename from test/grammar/scalar/schema/single_schema_inst_0/main.k rename to tests/grammar/scalar/schema/single_schema_inst_0/main.k diff --git a/test/grammar/scalar/schema/single_schema_inst_0/stdout.golden b/tests/grammar/scalar/schema/single_schema_inst_0/stdout.golden similarity index 100% rename from test/grammar/scalar/schema/single_schema_inst_0/stdout.golden rename to tests/grammar/scalar/schema/single_schema_inst_0/stdout.golden diff --git a/test/grammar/scalar/string/string_0/main.k b/tests/grammar/scalar/string/string_0/main.k similarity index 100% rename from test/grammar/scalar/string/string_0/main.k rename to tests/grammar/scalar/string/string_0/main.k diff --git a/test/grammar/scalar/string/string_0/stdout.golden b/tests/grammar/scalar/string/string_0/stdout.golden similarity index 100% rename from test/grammar/scalar/string/string_0/stdout.golden rename to tests/grammar/scalar/string/string_0/stdout.golden diff --git a/test/grammar/schema/assign_stmt/assign_stmt_0/main.k b/tests/grammar/schema/assign_stmt/assign_stmt_0/main.k similarity index 100% rename from test/grammar/schema/assign_stmt/assign_stmt_0/main.k rename to tests/grammar/schema/assign_stmt/assign_stmt_0/main.k diff --git a/test/grammar/schema/assign_stmt/assign_stmt_0/stdout.golden b/tests/grammar/schema/assign_stmt/assign_stmt_0/stdout.golden similarity index 100% rename from test/grammar/schema/assign_stmt/assign_stmt_0/stdout.golden rename to tests/grammar/schema/assign_stmt/assign_stmt_0/stdout.golden diff --git a/test/grammar/schema/assign_stmt/assign_stmt_1/main.k b/tests/grammar/schema/assign_stmt/assign_stmt_1/main.k similarity index 100% rename from test/grammar/schema/assign_stmt/assign_stmt_1/main.k rename to tests/grammar/schema/assign_stmt/assign_stmt_1/main.k diff --git a/test/grammar/schema/assign_stmt/assign_stmt_1/stdout.golden b/tests/grammar/schema/assign_stmt/assign_stmt_1/stdout.golden similarity index 100% rename from test/grammar/schema/assign_stmt/assign_stmt_1/stdout.golden rename to tests/grammar/schema/assign_stmt/assign_stmt_1/stdout.golden diff --git a/test/grammar/schema/assign_stmt/assign_stmt_2/main.k b/tests/grammar/schema/assign_stmt/assign_stmt_2/main.k similarity index 100% rename from test/grammar/schema/assign_stmt/assign_stmt_2/main.k rename to tests/grammar/schema/assign_stmt/assign_stmt_2/main.k diff --git a/test/grammar/schema/assign_stmt/assign_stmt_2/stdout.golden b/tests/grammar/schema/assign_stmt/assign_stmt_2/stdout.golden similarity index 100% rename from test/grammar/schema/assign_stmt/assign_stmt_2/stdout.golden rename to tests/grammar/schema/assign_stmt/assign_stmt_2/stdout.golden diff --git a/test/grammar/schema/assign_stmt/assign_stmt_3/main.k b/tests/grammar/schema/assign_stmt/assign_stmt_3/main.k similarity index 100% rename from test/grammar/schema/assign_stmt/assign_stmt_3/main.k rename to tests/grammar/schema/assign_stmt/assign_stmt_3/main.k diff --git a/test/grammar/schema/assign_stmt/assign_stmt_3/stdout.golden b/tests/grammar/schema/assign_stmt/assign_stmt_3/stdout.golden similarity index 100% rename from test/grammar/schema/assign_stmt/assign_stmt_3/stdout.golden rename to tests/grammar/schema/assign_stmt/assign_stmt_3/stdout.golden diff --git a/test/grammar/schema/assign_stmt/assign_stmt_4/main.k b/tests/grammar/schema/assign_stmt/assign_stmt_4/main.k similarity index 100% rename from test/grammar/schema/assign_stmt/assign_stmt_4/main.k rename to tests/grammar/schema/assign_stmt/assign_stmt_4/main.k diff --git a/test/grammar/schema/assign_stmt/assign_stmt_4/stdout.golden b/tests/grammar/schema/assign_stmt/assign_stmt_4/stdout.golden similarity index 100% rename from test/grammar/schema/assign_stmt/assign_stmt_4/stdout.golden rename to tests/grammar/schema/assign_stmt/assign_stmt_4/stdout.golden diff --git a/test/grammar/schema/assign_stmt/assign_stmt_5/main.k b/tests/grammar/schema/assign_stmt/assign_stmt_5/main.k similarity index 100% rename from test/grammar/schema/assign_stmt/assign_stmt_5/main.k rename to tests/grammar/schema/assign_stmt/assign_stmt_5/main.k diff --git a/test/grammar/schema/assign_stmt/assign_stmt_5/stdout.golden b/tests/grammar/schema/assign_stmt/assign_stmt_5/stdout.golden similarity index 100% rename from test/grammar/schema/assign_stmt/assign_stmt_5/stdout.golden rename to tests/grammar/schema/assign_stmt/assign_stmt_5/stdout.golden diff --git a/test/grammar/schema/assign_stmt/assign_stmt_6/main.k b/tests/grammar/schema/assign_stmt/assign_stmt_6/main.k similarity index 100% rename from test/grammar/schema/assign_stmt/assign_stmt_6/main.k rename to tests/grammar/schema/assign_stmt/assign_stmt_6/main.k diff --git a/test/grammar/schema/assign_stmt/assign_stmt_6/stdout.golden b/tests/grammar/schema/assign_stmt/assign_stmt_6/stdout.golden similarity index 100% rename from test/grammar/schema/assign_stmt/assign_stmt_6/stdout.golden rename to tests/grammar/schema/assign_stmt/assign_stmt_6/stdout.golden diff --git a/test/grammar/schema/assign_stmt/fail_0/main.k b/tests/grammar/schema/assign_stmt/fail_0/main.k similarity index 100% rename from test/grammar/schema/assign_stmt/fail_0/main.k rename to tests/grammar/schema/assign_stmt/fail_0/main.k diff --git a/test/grammar/schema/assign_stmt/fail_0/stderr.golden b/tests/grammar/schema/assign_stmt/fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/assign_stmt/fail_0/stderr.golden rename to tests/grammar/schema/assign_stmt/fail_0/stderr.golden diff --git a/test/grammar/schema/back_ref/back_ref_0/main.k b/tests/grammar/schema/back_ref/back_ref_0/main.k similarity index 100% rename from test/grammar/schema/back_ref/back_ref_0/main.k rename to tests/grammar/schema/back_ref/back_ref_0/main.k diff --git a/test/grammar/schema/back_ref/back_ref_0/stdout.golden b/tests/grammar/schema/back_ref/back_ref_0/stdout.golden similarity index 100% rename from test/grammar/schema/back_ref/back_ref_0/stdout.golden rename to tests/grammar/schema/back_ref/back_ref_0/stdout.golden diff --git a/test/grammar/schema/back_ref/back_ref_1/main.k b/tests/grammar/schema/back_ref/back_ref_1/main.k similarity index 100% rename from test/grammar/schema/back_ref/back_ref_1/main.k rename to tests/grammar/schema/back_ref/back_ref_1/main.k diff --git a/test/grammar/schema/back_ref/back_ref_1/stdout.golden b/tests/grammar/schema/back_ref/back_ref_1/stdout.golden similarity index 100% rename from test/grammar/schema/back_ref/back_ref_1/stdout.golden rename to tests/grammar/schema/back_ref/back_ref_1/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_0/main.k b/tests/grammar/schema/check_block/check_block_0/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_0/main.k rename to tests/grammar/schema/check_block/check_block_0/main.k diff --git a/test/grammar/schema/check_block/check_block_0/stdout.golden b/tests/grammar/schema/check_block/check_block_0/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_0/stdout.golden rename to tests/grammar/schema/check_block/check_block_0/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_1/main.k b/tests/grammar/schema/check_block/check_block_1/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_1/main.k rename to tests/grammar/schema/check_block/check_block_1/main.k diff --git a/test/grammar/schema/check_block/check_block_1/stdout.golden b/tests/grammar/schema/check_block/check_block_1/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_1/stdout.golden rename to tests/grammar/schema/check_block/check_block_1/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_10/main.k b/tests/grammar/schema/check_block/check_block_10/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_10/main.k rename to tests/grammar/schema/check_block/check_block_10/main.k diff --git a/test/grammar/schema/check_block/check_block_10/stdout.golden b/tests/grammar/schema/check_block/check_block_10/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_10/stdout.golden rename to tests/grammar/schema/check_block/check_block_10/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_11/main.k b/tests/grammar/schema/check_block/check_block_11/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_11/main.k rename to tests/grammar/schema/check_block/check_block_11/main.k diff --git a/test/grammar/schema/check_block/check_block_11/stdout.golden b/tests/grammar/schema/check_block/check_block_11/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_11/stdout.golden rename to tests/grammar/schema/check_block/check_block_11/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_12/main.k b/tests/grammar/schema/check_block/check_block_12/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_12/main.k rename to tests/grammar/schema/check_block/check_block_12/main.k diff --git a/test/grammar/schema/check_block/check_block_12/stdout.golden b/tests/grammar/schema/check_block/check_block_12/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_12/stdout.golden rename to tests/grammar/schema/check_block/check_block_12/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_13/main.k b/tests/grammar/schema/check_block/check_block_13/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_13/main.k rename to tests/grammar/schema/check_block/check_block_13/main.k diff --git a/test/grammar/schema/check_block/check_block_13/stdout.golden b/tests/grammar/schema/check_block/check_block_13/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_13/stdout.golden rename to tests/grammar/schema/check_block/check_block_13/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_14/main.k b/tests/grammar/schema/check_block/check_block_14/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_14/main.k rename to tests/grammar/schema/check_block/check_block_14/main.k diff --git a/test/grammar/schema/check_block/check_block_14/stdout.golden b/tests/grammar/schema/check_block/check_block_14/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_14/stdout.golden rename to tests/grammar/schema/check_block/check_block_14/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_2/main.k b/tests/grammar/schema/check_block/check_block_2/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_2/main.k rename to tests/grammar/schema/check_block/check_block_2/main.k diff --git a/test/grammar/schema/check_block/check_block_2/stdout.golden b/tests/grammar/schema/check_block/check_block_2/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_2/stdout.golden rename to tests/grammar/schema/check_block/check_block_2/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_3/main.k b/tests/grammar/schema/check_block/check_block_3/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_3/main.k rename to tests/grammar/schema/check_block/check_block_3/main.k diff --git a/test/grammar/schema/check_block/check_block_3/stdout.golden b/tests/grammar/schema/check_block/check_block_3/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_3/stdout.golden rename to tests/grammar/schema/check_block/check_block_3/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_4/main.k b/tests/grammar/schema/check_block/check_block_4/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_4/main.k rename to tests/grammar/schema/check_block/check_block_4/main.k diff --git a/test/grammar/schema/check_block/check_block_4/stdout.golden b/tests/grammar/schema/check_block/check_block_4/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_4/stdout.golden rename to tests/grammar/schema/check_block/check_block_4/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_5/main.k b/tests/grammar/schema/check_block/check_block_5/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_5/main.k rename to tests/grammar/schema/check_block/check_block_5/main.k diff --git a/test/grammar/schema/check_block/check_block_5/stdout.golden b/tests/grammar/schema/check_block/check_block_5/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_5/stdout.golden rename to tests/grammar/schema/check_block/check_block_5/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_6/main.k b/tests/grammar/schema/check_block/check_block_6/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_6/main.k rename to tests/grammar/schema/check_block/check_block_6/main.k diff --git a/test/grammar/schema/check_block/check_block_6/stdout.golden b/tests/grammar/schema/check_block/check_block_6/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_6/stdout.golden rename to tests/grammar/schema/check_block/check_block_6/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_7/main.k b/tests/grammar/schema/check_block/check_block_7/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_7/main.k rename to tests/grammar/schema/check_block/check_block_7/main.k diff --git a/test/grammar/schema/check_block/check_block_7/stdout.golden b/tests/grammar/schema/check_block/check_block_7/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_7/stdout.golden rename to tests/grammar/schema/check_block/check_block_7/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_8/main.k b/tests/grammar/schema/check_block/check_block_8/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_8/main.k rename to tests/grammar/schema/check_block/check_block_8/main.k diff --git a/test/grammar/schema/check_block/check_block_8/stdout.golden b/tests/grammar/schema/check_block/check_block_8/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_8/stdout.golden rename to tests/grammar/schema/check_block/check_block_8/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_9/main.k b/tests/grammar/schema/check_block/check_block_9/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_9/main.k rename to tests/grammar/schema/check_block/check_block_9/main.k diff --git a/test/grammar/schema/check_block/check_block_9/stdout.golden b/tests/grammar/schema/check_block/check_block_9/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_9/stdout.golden rename to tests/grammar/schema/check_block/check_block_9/stdout.golden diff --git a/test/grammar/schema/check_block/check_block_fail_0/main.k b/tests/grammar/schema/check_block/check_block_fail_0/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_0/main.k rename to tests/grammar/schema/check_block/check_block_fail_0/main.k diff --git a/test/grammar/schema/check_block/check_block_fail_0/stderr.golden b/tests/grammar/schema/check_block/check_block_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_0/stderr.golden rename to tests/grammar/schema/check_block/check_block_fail_0/stderr.golden diff --git a/test/grammar/schema/check_block/check_block_fail_1/main.k b/tests/grammar/schema/check_block/check_block_fail_1/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_1/main.k rename to tests/grammar/schema/check_block/check_block_fail_1/main.k diff --git a/test/grammar/schema/check_block/check_block_fail_1/stderr.golden b/tests/grammar/schema/check_block/check_block_fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_1/stderr.golden rename to tests/grammar/schema/check_block/check_block_fail_1/stderr.golden diff --git a/test/grammar/schema/check_block/check_block_fail_10/main.k b/tests/grammar/schema/check_block/check_block_fail_10/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_10/main.k rename to tests/grammar/schema/check_block/check_block_fail_10/main.k diff --git a/test/grammar/schema/check_block/check_block_fail_10/stderr.golden b/tests/grammar/schema/check_block/check_block_fail_10/stderr.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_10/stderr.golden rename to tests/grammar/schema/check_block/check_block_fail_10/stderr.golden diff --git a/test/grammar/schema/check_block/check_block_fail_11/kcl.mod b/tests/grammar/schema/check_block/check_block_fail_11/kcl.mod similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_11/kcl.mod rename to tests/grammar/schema/check_block/check_block_fail_11/kcl.mod diff --git a/test/grammar/schema/check_block/check_block_fail_11/main.k b/tests/grammar/schema/check_block/check_block_fail_11/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_11/main.k rename to tests/grammar/schema/check_block/check_block_fail_11/main.k diff --git a/test/grammar/schema/check_block/check_block_fail_11/pkg/person.k b/tests/grammar/schema/check_block/check_block_fail_11/pkg/person.k similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_11/pkg/person.k rename to tests/grammar/schema/check_block/check_block_fail_11/pkg/person.k diff --git a/test/grammar/schema/check_block/check_block_fail_11/stderr.golden b/tests/grammar/schema/check_block/check_block_fail_11/stderr.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_11/stderr.golden rename to tests/grammar/schema/check_block/check_block_fail_11/stderr.golden diff --git a/test/grammar/schema/check_block/check_block_fail_2/main.k b/tests/grammar/schema/check_block/check_block_fail_2/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_2/main.k rename to tests/grammar/schema/check_block/check_block_fail_2/main.k diff --git a/test/grammar/schema/check_block/check_block_fail_2/stderr.golden b/tests/grammar/schema/check_block/check_block_fail_2/stderr.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_2/stderr.golden rename to tests/grammar/schema/check_block/check_block_fail_2/stderr.golden diff --git a/test/grammar/schema/check_block/check_block_fail_3/main.k b/tests/grammar/schema/check_block/check_block_fail_3/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_3/main.k rename to tests/grammar/schema/check_block/check_block_fail_3/main.k diff --git a/test/grammar/schema/check_block/check_block_fail_3/stderr.golden b/tests/grammar/schema/check_block/check_block_fail_3/stderr.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_3/stderr.golden rename to tests/grammar/schema/check_block/check_block_fail_3/stderr.golden diff --git a/test/grammar/schema/check_block/check_block_fail_4/main.k b/tests/grammar/schema/check_block/check_block_fail_4/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_4/main.k rename to tests/grammar/schema/check_block/check_block_fail_4/main.k diff --git a/test/grammar/schema/check_block/check_block_fail_4/stderr.golden b/tests/grammar/schema/check_block/check_block_fail_4/stderr.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_4/stderr.golden rename to tests/grammar/schema/check_block/check_block_fail_4/stderr.golden diff --git a/test/grammar/schema/check_block/check_block_fail_5/main.k b/tests/grammar/schema/check_block/check_block_fail_5/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_5/main.k rename to tests/grammar/schema/check_block/check_block_fail_5/main.k diff --git a/test/grammar/schema/check_block/check_block_fail_5/stderr.golden b/tests/grammar/schema/check_block/check_block_fail_5/stderr.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_5/stderr.golden rename to tests/grammar/schema/check_block/check_block_fail_5/stderr.golden diff --git a/test/grammar/schema/check_block/check_block_fail_6/main.k b/tests/grammar/schema/check_block/check_block_fail_6/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_6/main.k rename to tests/grammar/schema/check_block/check_block_fail_6/main.k diff --git a/test/grammar/schema/check_block/check_block_fail_6/stderr.golden b/tests/grammar/schema/check_block/check_block_fail_6/stderr.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_6/stderr.golden rename to tests/grammar/schema/check_block/check_block_fail_6/stderr.golden diff --git a/test/grammar/schema/check_block/check_block_fail_7/main.k b/tests/grammar/schema/check_block/check_block_fail_7/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_7/main.k rename to tests/grammar/schema/check_block/check_block_fail_7/main.k diff --git a/test/grammar/schema/check_block/check_block_fail_7/stderr.golden b/tests/grammar/schema/check_block/check_block_fail_7/stderr.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_7/stderr.golden rename to tests/grammar/schema/check_block/check_block_fail_7/stderr.golden diff --git a/test/grammar/schema/check_block/check_block_fail_8/main.k b/tests/grammar/schema/check_block/check_block_fail_8/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_8/main.k rename to tests/grammar/schema/check_block/check_block_fail_8/main.k diff --git a/test/grammar/schema/check_block/check_block_fail_8/stderr.golden b/tests/grammar/schema/check_block/check_block_fail_8/stderr.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_8/stderr.golden rename to tests/grammar/schema/check_block/check_block_fail_8/stderr.golden diff --git a/test/grammar/schema/check_block/check_block_fail_9/main.k b/tests/grammar/schema/check_block/check_block_fail_9/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_9/main.k rename to tests/grammar/schema/check_block/check_block_fail_9/main.k diff --git a/test/grammar/schema/check_block/check_block_fail_9/stderr.golden b/tests/grammar/schema/check_block/check_block_fail_9/stderr.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_fail_9/stderr.golden rename to tests/grammar/schema/check_block/check_block_fail_9/stderr.golden diff --git a/test/grammar/schema/check_block/check_block_with_init/main.k b/tests/grammar/schema/check_block/check_block_with_init/main.k similarity index 100% rename from test/grammar/schema/check_block/check_block_with_init/main.k rename to tests/grammar/schema/check_block/check_block_with_init/main.k diff --git a/test/grammar/schema/check_block/check_block_with_init/stdout.golden b/tests/grammar/schema/check_block/check_block_with_init/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_block_with_init/stdout.golden rename to tests/grammar/schema/check_block/check_block_with_init/stdout.golden diff --git a/test/grammar/schema/check_block/check_iteratively_list_0/main.k b/tests/grammar/schema/check_block/check_iteratively_list_0/main.k similarity index 100% rename from test/grammar/schema/check_block/check_iteratively_list_0/main.k rename to tests/grammar/schema/check_block/check_iteratively_list_0/main.k diff --git a/test/grammar/schema/check_block/check_iteratively_list_0/stdout.golden b/tests/grammar/schema/check_block/check_iteratively_list_0/stdout.golden similarity index 100% rename from test/grammar/schema/check_block/check_iteratively_list_0/stdout.golden rename to tests/grammar/schema/check_block/check_iteratively_list_0/stdout.golden diff --git a/test/grammar/schema/complex/init_check_order_0/main.k b/tests/grammar/schema/complex/init_check_order_0/main.k similarity index 100% rename from test/grammar/schema/complex/init_check_order_0/main.k rename to tests/grammar/schema/complex/init_check_order_0/main.k diff --git a/test/grammar/schema/complex/init_check_order_0/stdout.golden b/tests/grammar/schema/complex/init_check_order_0/stdout.golden similarity index 100% rename from test/grammar/schema/complex/init_check_order_0/stdout.golden rename to tests/grammar/schema/complex/init_check_order_0/stdout.golden diff --git a/test/grammar/schema/complex/init_check_order_1/main.k b/tests/grammar/schema/complex/init_check_order_1/main.k similarity index 100% rename from test/grammar/schema/complex/init_check_order_1/main.k rename to tests/grammar/schema/complex/init_check_order_1/main.k diff --git a/test/grammar/schema/complex/init_check_order_1/stdout.golden b/tests/grammar/schema/complex/init_check_order_1/stdout.golden similarity index 100% rename from test/grammar/schema/complex/init_check_order_1/stdout.golden rename to tests/grammar/schema/complex/init_check_order_1/stdout.golden diff --git a/test/grammar/schema/config_op/delete/delete_0/main.k b/tests/grammar/schema/config_op/delete/delete_0/main.k similarity index 100% rename from test/grammar/schema/config_op/delete/delete_0/main.k rename to tests/grammar/schema/config_op/delete/delete_0/main.k diff --git a/test/grammar/schema/config_op/delete/delete_0/stdout.golden b/tests/grammar/schema/config_op/delete/delete_0/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/delete/delete_0/stdout.golden rename to tests/grammar/schema/config_op/delete/delete_0/stdout.golden diff --git a/test/grammar/schema/config_op/insert/insert_0/main.k b/tests/grammar/schema/config_op/insert/insert_0/main.k similarity index 100% rename from test/grammar/schema/config_op/insert/insert_0/main.k rename to tests/grammar/schema/config_op/insert/insert_0/main.k diff --git a/test/grammar/schema/config_op/insert/insert_0/stdout.golden b/tests/grammar/schema/config_op/insert/insert_0/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/insert/insert_0/stdout.golden rename to tests/grammar/schema/config_op/insert/insert_0/stdout.golden diff --git a/test/grammar/schema/config_op/insert/insert_1/main.k b/tests/grammar/schema/config_op/insert/insert_1/main.k similarity index 100% rename from test/grammar/schema/config_op/insert/insert_1/main.k rename to tests/grammar/schema/config_op/insert/insert_1/main.k diff --git a/test/grammar/schema/config_op/insert/insert_1/stdout.golden b/tests/grammar/schema/config_op/insert/insert_1/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/insert/insert_1/stdout.golden rename to tests/grammar/schema/config_op/insert/insert_1/stdout.golden diff --git a/test/grammar/schema/config_op/insert/insert_2/main.k b/tests/grammar/schema/config_op/insert/insert_2/main.k similarity index 100% rename from test/grammar/schema/config_op/insert/insert_2/main.k rename to tests/grammar/schema/config_op/insert/insert_2/main.k diff --git a/test/grammar/schema/config_op/insert/insert_2/stdout.golden b/tests/grammar/schema/config_op/insert/insert_2/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/insert/insert_2/stdout.golden rename to tests/grammar/schema/config_op/insert/insert_2/stdout.golden diff --git a/test/grammar/schema/config_op/insert/insert_3/main.k b/tests/grammar/schema/config_op/insert/insert_3/main.k similarity index 100% rename from test/grammar/schema/config_op/insert/insert_3/main.k rename to tests/grammar/schema/config_op/insert/insert_3/main.k diff --git a/test/grammar/schema/config_op/insert/insert_3/stdout.golden b/tests/grammar/schema/config_op/insert/insert_3/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/insert/insert_3/stdout.golden rename to tests/grammar/schema/config_op/insert/insert_3/stdout.golden diff --git a/test/grammar/schema/config_op/insert/insert_4/main.k b/tests/grammar/schema/config_op/insert/insert_4/main.k similarity index 100% rename from test/grammar/schema/config_op/insert/insert_4/main.k rename to tests/grammar/schema/config_op/insert/insert_4/main.k diff --git a/test/grammar/schema/config_op/insert/insert_4/stdout.golden b/tests/grammar/schema/config_op/insert/insert_4/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/insert/insert_4/stdout.golden rename to tests/grammar/schema/config_op/insert/insert_4/stdout.golden diff --git a/test/grammar/schema/config_op/insert/insert_5/main.k b/tests/grammar/schema/config_op/insert/insert_5/main.k similarity index 100% rename from test/grammar/schema/config_op/insert/insert_5/main.k rename to tests/grammar/schema/config_op/insert/insert_5/main.k diff --git a/test/grammar/schema/config_op/insert/insert_5/stdout.golden b/tests/grammar/schema/config_op/insert/insert_5/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/insert/insert_5/stdout.golden rename to tests/grammar/schema/config_op/insert/insert_5/stdout.golden diff --git a/test/grammar/schema/config_op/insert/insert_6/main.k b/tests/grammar/schema/config_op/insert/insert_6/main.k similarity index 100% rename from test/grammar/schema/config_op/insert/insert_6/main.k rename to tests/grammar/schema/config_op/insert/insert_6/main.k diff --git a/test/grammar/schema/config_op/insert/insert_6/stdout.golden b/tests/grammar/schema/config_op/insert/insert_6/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/insert/insert_6/stdout.golden rename to tests/grammar/schema/config_op/insert/insert_6/stdout.golden diff --git a/test/grammar/schema/config_op/override/override_0/main.k b/tests/grammar/schema/config_op/override/override_0/main.k similarity index 100% rename from test/grammar/schema/config_op/override/override_0/main.k rename to tests/grammar/schema/config_op/override/override_0/main.k diff --git a/test/grammar/schema/config_op/override/override_0/stdout.golden b/tests/grammar/schema/config_op/override/override_0/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/override/override_0/stdout.golden rename to tests/grammar/schema/config_op/override/override_0/stdout.golden diff --git a/test/grammar/schema/config_op/override/override_1/main.k b/tests/grammar/schema/config_op/override/override_1/main.k similarity index 100% rename from test/grammar/schema/config_op/override/override_1/main.k rename to tests/grammar/schema/config_op/override/override_1/main.k diff --git a/test/grammar/schema/config_op/override/override_1/stdout.golden b/tests/grammar/schema/config_op/override/override_1/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/override/override_1/stdout.golden rename to tests/grammar/schema/config_op/override/override_1/stdout.golden diff --git a/test/grammar/schema/config_op/override/override_2/main.k b/tests/grammar/schema/config_op/override/override_2/main.k similarity index 100% rename from test/grammar/schema/config_op/override/override_2/main.k rename to tests/grammar/schema/config_op/override/override_2/main.k diff --git a/test/grammar/schema/config_op/override/override_2/stdout.golden b/tests/grammar/schema/config_op/override/override_2/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/override/override_2/stdout.golden rename to tests/grammar/schema/config_op/override/override_2/stdout.golden diff --git a/test/grammar/schema/config_op/override/override_3/main.k b/tests/grammar/schema/config_op/override/override_3/main.k similarity index 100% rename from test/grammar/schema/config_op/override/override_3/main.k rename to tests/grammar/schema/config_op/override/override_3/main.k diff --git a/test/grammar/schema/config_op/override/override_3/stdout.golden b/tests/grammar/schema/config_op/override/override_3/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/override/override_3/stdout.golden rename to tests/grammar/schema/config_op/override/override_3/stdout.golden diff --git a/test/grammar/schema/config_op/override/override_4/main.k b/tests/grammar/schema/config_op/override/override_4/main.k similarity index 100% rename from test/grammar/schema/config_op/override/override_4/main.k rename to tests/grammar/schema/config_op/override/override_4/main.k diff --git a/test/grammar/schema/config_op/override/override_4/stdout.golden b/tests/grammar/schema/config_op/override/override_4/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/override/override_4/stdout.golden rename to tests/grammar/schema/config_op/override/override_4/stdout.golden diff --git a/test/grammar/schema/config_op/union/union_0/main.k b/tests/grammar/schema/config_op/union/union_0/main.k similarity index 100% rename from test/grammar/schema/config_op/union/union_0/main.k rename to tests/grammar/schema/config_op/union/union_0/main.k diff --git a/test/grammar/schema/config_op/union/union_0/stdout.golden b/tests/grammar/schema/config_op/union/union_0/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/union/union_0/stdout.golden rename to tests/grammar/schema/config_op/union/union_0/stdout.golden diff --git a/test/grammar/schema/config_op/union/union_1/main.k b/tests/grammar/schema/config_op/union/union_1/main.k similarity index 100% rename from test/grammar/schema/config_op/union/union_1/main.k rename to tests/grammar/schema/config_op/union/union_1/main.k diff --git a/test/grammar/schema/config_op/union/union_1/stdout.golden b/tests/grammar/schema/config_op/union/union_1/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/union/union_1/stdout.golden rename to tests/grammar/schema/config_op/union/union_1/stdout.golden diff --git a/test/grammar/schema/config_op/union/union_2/main.k b/tests/grammar/schema/config_op/union/union_2/main.k similarity index 100% rename from test/grammar/schema/config_op/union/union_2/main.k rename to tests/grammar/schema/config_op/union/union_2/main.k diff --git a/test/grammar/schema/config_op/union/union_2/stdout.golden b/tests/grammar/schema/config_op/union/union_2/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/union/union_2/stdout.golden rename to tests/grammar/schema/config_op/union/union_2/stdout.golden diff --git a/test/grammar/schema/config_op/union/union_3/main.k b/tests/grammar/schema/config_op/union/union_3/main.k similarity index 100% rename from test/grammar/schema/config_op/union/union_3/main.k rename to tests/grammar/schema/config_op/union/union_3/main.k diff --git a/test/grammar/schema/config_op/union/union_3/stdout.golden b/tests/grammar/schema/config_op/union/union_3/stdout.golden similarity index 100% rename from test/grammar/schema/config_op/union/union_3/stdout.golden rename to tests/grammar/schema/config_op/union/union_3/stdout.golden diff --git a/test/grammar/schema/default_value/default_value_0/main.k b/tests/grammar/schema/default_value/default_value_0/main.k similarity index 100% rename from test/grammar/schema/default_value/default_value_0/main.k rename to tests/grammar/schema/default_value/default_value_0/main.k diff --git a/test/grammar/schema/default_value/default_value_0/stdout.golden b/tests/grammar/schema/default_value/default_value_0/stdout.golden similarity index 100% rename from test/grammar/schema/default_value/default_value_0/stdout.golden rename to tests/grammar/schema/default_value/default_value_0/stdout.golden diff --git a/test/grammar/schema/default_value/default_value_1/main.k b/tests/grammar/schema/default_value/default_value_1/main.k similarity index 100% rename from test/grammar/schema/default_value/default_value_1/main.k rename to tests/grammar/schema/default_value/default_value_1/main.k diff --git a/test/grammar/schema/default_value/default_value_1/stdout.golden b/tests/grammar/schema/default_value/default_value_1/stdout.golden similarity index 100% rename from test/grammar/schema/default_value/default_value_1/stdout.golden rename to tests/grammar/schema/default_value/default_value_1/stdout.golden diff --git a/test/grammar/schema/default_value/default_value_2/main.k b/tests/grammar/schema/default_value/default_value_2/main.k similarity index 100% rename from test/grammar/schema/default_value/default_value_2/main.k rename to tests/grammar/schema/default_value/default_value_2/main.k diff --git a/test/grammar/schema/default_value/default_value_2/stdout.golden b/tests/grammar/schema/default_value/default_value_2/stdout.golden similarity index 100% rename from test/grammar/schema/default_value/default_value_2/stdout.golden rename to tests/grammar/schema/default_value/default_value_2/stdout.golden diff --git a/test/grammar/schema/default_value/default_value_3/main.k b/tests/grammar/schema/default_value/default_value_3/main.k similarity index 100% rename from test/grammar/schema/default_value/default_value_3/main.k rename to tests/grammar/schema/default_value/default_value_3/main.k diff --git a/test/grammar/schema/default_value/default_value_3/stdout.golden b/tests/grammar/schema/default_value/default_value_3/stdout.golden similarity index 100% rename from test/grammar/schema/default_value/default_value_3/stdout.golden rename to tests/grammar/schema/default_value/default_value_3/stdout.golden diff --git a/test/grammar/schema/deprecated/illegal_arg_fail_0/main.k b/tests/grammar/schema/deprecated/illegal_arg_fail_0/main.k similarity index 100% rename from test/grammar/schema/deprecated/illegal_arg_fail_0/main.k rename to tests/grammar/schema/deprecated/illegal_arg_fail_0/main.k diff --git a/test/grammar/schema/deprecated/illegal_arg_fail_0/stderr.golden b/tests/grammar/schema/deprecated/illegal_arg_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/illegal_arg_fail_0/stderr.golden rename to tests/grammar/schema/deprecated/illegal_arg_fail_0/stderr.golden diff --git a/test/grammar/schema/deprecated/member_simple_0/main.k b/tests/grammar/schema/deprecated/member_simple_0/main.k similarity index 100% rename from test/grammar/schema/deprecated/member_simple_0/main.k rename to tests/grammar/schema/deprecated/member_simple_0/main.k diff --git a/test/grammar/schema/deprecated/member_simple_0/stderr.golden b/tests/grammar/schema/deprecated/member_simple_0/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/member_simple_0/stderr.golden rename to tests/grammar/schema/deprecated/member_simple_0/stderr.golden diff --git a/test/grammar/schema/deprecated/member_simple_1/main.k b/tests/grammar/schema/deprecated/member_simple_1/main.k similarity index 100% rename from test/grammar/schema/deprecated/member_simple_1/main.k rename to tests/grammar/schema/deprecated/member_simple_1/main.k diff --git a/test/grammar/schema/deprecated/member_simple_1/stderr.golden b/tests/grammar/schema/deprecated/member_simple_1/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/member_simple_1/stderr.golden rename to tests/grammar/schema/deprecated/member_simple_1/stderr.golden diff --git a/test/grammar/schema/deprecated/member_simple_2/main.k b/tests/grammar/schema/deprecated/member_simple_2/main.k similarity index 100% rename from test/grammar/schema/deprecated/member_simple_2/main.k rename to tests/grammar/schema/deprecated/member_simple_2/main.k diff --git a/test/grammar/schema/deprecated/member_simple_2/stdout.golden b/tests/grammar/schema/deprecated/member_simple_2/stdout.golden similarity index 100% rename from test/grammar/schema/deprecated/member_simple_2/stdout.golden rename to tests/grammar/schema/deprecated/member_simple_2/stdout.golden diff --git a/test/grammar/schema/deprecated/member_simple_3/main.k b/tests/grammar/schema/deprecated/member_simple_3/main.k similarity index 100% rename from test/grammar/schema/deprecated/member_simple_3/main.k rename to tests/grammar/schema/deprecated/member_simple_3/main.k diff --git a/test/grammar/schema/deprecated/member_simple_3/stderr.golden b/tests/grammar/schema/deprecated/member_simple_3/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/member_simple_3/stderr.golden rename to tests/grammar/schema/deprecated/member_simple_3/stderr.golden diff --git a/test/grammar/schema/deprecated/member_standard_0/main.k b/tests/grammar/schema/deprecated/member_standard_0/main.k similarity index 100% rename from test/grammar/schema/deprecated/member_standard_0/main.k rename to tests/grammar/schema/deprecated/member_standard_0/main.k diff --git a/test/grammar/schema/deprecated/member_standard_0/stderr.golden b/tests/grammar/schema/deprecated/member_standard_0/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/member_standard_0/stderr.golden rename to tests/grammar/schema/deprecated/member_standard_0/stderr.golden diff --git a/test/grammar/schema/deprecated/member_standard_1/main.k b/tests/grammar/schema/deprecated/member_standard_1/main.k similarity index 100% rename from test/grammar/schema/deprecated/member_standard_1/main.k rename to tests/grammar/schema/deprecated/member_standard_1/main.k diff --git a/test/grammar/schema/deprecated/member_standard_1/stderr.golden b/tests/grammar/schema/deprecated/member_standard_1/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/member_standard_1/stderr.golden rename to tests/grammar/schema/deprecated/member_standard_1/stderr.golden diff --git a/test/grammar/schema/deprecated/member_standard_2/main.k b/tests/grammar/schema/deprecated/member_standard_2/main.k similarity index 100% rename from test/grammar/schema/deprecated/member_standard_2/main.k rename to tests/grammar/schema/deprecated/member_standard_2/main.k diff --git a/test/grammar/schema/deprecated/member_standard_2/stderr.golden b/tests/grammar/schema/deprecated/member_standard_2/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/member_standard_2/stderr.golden rename to tests/grammar/schema/deprecated/member_standard_2/stderr.golden diff --git a/test/grammar/schema/deprecated/member_standard_3/main.k b/tests/grammar/schema/deprecated/member_standard_3/main.k similarity index 100% rename from test/grammar/schema/deprecated/member_standard_3/main.k rename to tests/grammar/schema/deprecated/member_standard_3/main.k diff --git a/test/grammar/schema/deprecated/member_standard_3/stderr.golden b/tests/grammar/schema/deprecated/member_standard_3/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/member_standard_3/stderr.golden rename to tests/grammar/schema/deprecated/member_standard_3/stderr.golden diff --git a/test/grammar/schema/deprecated/member_standard_4/main.k b/tests/grammar/schema/deprecated/member_standard_4/main.k similarity index 100% rename from test/grammar/schema/deprecated/member_standard_4/main.k rename to tests/grammar/schema/deprecated/member_standard_4/main.k diff --git a/test/grammar/schema/deprecated/member_standard_4/stderr.golden b/tests/grammar/schema/deprecated/member_standard_4/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/member_standard_4/stderr.golden rename to tests/grammar/schema/deprecated/member_standard_4/stderr.golden diff --git a/test/grammar/schema/deprecated/member_warning_0/main.k b/tests/grammar/schema/deprecated/member_warning_0/main.k similarity index 100% rename from test/grammar/schema/deprecated/member_warning_0/main.k rename to tests/grammar/schema/deprecated/member_warning_0/main.k diff --git a/test/grammar/schema/deprecated/member_warning_0/stderr.golden b/tests/grammar/schema/deprecated/member_warning_0/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/member_warning_0/stderr.golden rename to tests/grammar/schema/deprecated/member_warning_0/stderr.golden diff --git a/test/grammar/schema/deprecated/member_warning_1/main.k b/tests/grammar/schema/deprecated/member_warning_1/main.k similarity index 100% rename from test/grammar/schema/deprecated/member_warning_1/main.k rename to tests/grammar/schema/deprecated/member_warning_1/main.k diff --git a/test/grammar/schema/deprecated/member_warning_1/stderr.golden b/tests/grammar/schema/deprecated/member_warning_1/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/member_warning_1/stderr.golden rename to tests/grammar/schema/deprecated/member_warning_1/stderr.golden diff --git a/test/grammar/schema/deprecated/schema_simple_0/main.k b/tests/grammar/schema/deprecated/schema_simple_0/main.k similarity index 100% rename from test/grammar/schema/deprecated/schema_simple_0/main.k rename to tests/grammar/schema/deprecated/schema_simple_0/main.k diff --git a/test/grammar/schema/deprecated/schema_simple_0/stderr.golden b/tests/grammar/schema/deprecated/schema_simple_0/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/schema_simple_0/stderr.golden rename to tests/grammar/schema/deprecated/schema_simple_0/stderr.golden diff --git a/test/grammar/schema/deprecated/schema_simple_1/main.k b/tests/grammar/schema/deprecated/schema_simple_1/main.k similarity index 100% rename from test/grammar/schema/deprecated/schema_simple_1/main.k rename to tests/grammar/schema/deprecated/schema_simple_1/main.k diff --git a/test/grammar/schema/deprecated/schema_simple_1/stderr.golden b/tests/grammar/schema/deprecated/schema_simple_1/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/schema_simple_1/stderr.golden rename to tests/grammar/schema/deprecated/schema_simple_1/stderr.golden diff --git a/test/grammar/schema/deprecated/schema_simple_2/main.k b/tests/grammar/schema/deprecated/schema_simple_2/main.k similarity index 100% rename from test/grammar/schema/deprecated/schema_simple_2/main.k rename to tests/grammar/schema/deprecated/schema_simple_2/main.k diff --git a/test/grammar/schema/deprecated/schema_simple_2/stdout.golden b/tests/grammar/schema/deprecated/schema_simple_2/stdout.golden similarity index 100% rename from test/grammar/schema/deprecated/schema_simple_2/stdout.golden rename to tests/grammar/schema/deprecated/schema_simple_2/stdout.golden diff --git a/test/grammar/schema/deprecated/schema_standard_0/main.k b/tests/grammar/schema/deprecated/schema_standard_0/main.k similarity index 100% rename from test/grammar/schema/deprecated/schema_standard_0/main.k rename to tests/grammar/schema/deprecated/schema_standard_0/main.k diff --git a/test/grammar/schema/deprecated/schema_standard_0/stderr.golden b/tests/grammar/schema/deprecated/schema_standard_0/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/schema_standard_0/stderr.golden rename to tests/grammar/schema/deprecated/schema_standard_0/stderr.golden diff --git a/test/grammar/schema/deprecated/schema_standard_1/main.k b/tests/grammar/schema/deprecated/schema_standard_1/main.k similarity index 100% rename from test/grammar/schema/deprecated/schema_standard_1/main.k rename to tests/grammar/schema/deprecated/schema_standard_1/main.k diff --git a/test/grammar/schema/deprecated/schema_standard_1/stderr.golden b/tests/grammar/schema/deprecated/schema_standard_1/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/schema_standard_1/stderr.golden rename to tests/grammar/schema/deprecated/schema_standard_1/stderr.golden diff --git a/test/grammar/schema/deprecated/schema_warning_0/main.k b/tests/grammar/schema/deprecated/schema_warning_0/main.k similarity index 100% rename from test/grammar/schema/deprecated/schema_warning_0/main.k rename to tests/grammar/schema/deprecated/schema_warning_0/main.k diff --git a/test/grammar/schema/deprecated/schema_warning_0/stderr.golden b/tests/grammar/schema/deprecated/schema_warning_0/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/schema_warning_0/stderr.golden rename to tests/grammar/schema/deprecated/schema_warning_0/stderr.golden diff --git a/test/grammar/schema/deprecated/schema_warning_1/main.k b/tests/grammar/schema/deprecated/schema_warning_1/main.k similarity index 100% rename from test/grammar/schema/deprecated/schema_warning_1/main.k rename to tests/grammar/schema/deprecated/schema_warning_1/main.k diff --git a/test/grammar/schema/deprecated/schema_warning_1/stderr.golden b/tests/grammar/schema/deprecated/schema_warning_1/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/schema_warning_1/stderr.golden rename to tests/grammar/schema/deprecated/schema_warning_1/stderr.golden diff --git a/test/grammar/schema/deprecated/unknown_fail_0/main.k b/tests/grammar/schema/deprecated/unknown_fail_0/main.k similarity index 100% rename from test/grammar/schema/deprecated/unknown_fail_0/main.k rename to tests/grammar/schema/deprecated/unknown_fail_0/main.k diff --git a/test/grammar/schema/deprecated/unknown_fail_0/stderr.golden b/tests/grammar/schema/deprecated/unknown_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/unknown_fail_0/stderr.golden rename to tests/grammar/schema/deprecated/unknown_fail_0/stderr.golden diff --git a/test/grammar/schema/deprecated/unknown_fail_1/main.k b/tests/grammar/schema/deprecated/unknown_fail_1/main.k similarity index 100% rename from test/grammar/schema/deprecated/unknown_fail_1/main.k rename to tests/grammar/schema/deprecated/unknown_fail_1/main.k diff --git a/test/grammar/schema/deprecated/unknown_fail_1/stderr.golden b/tests/grammar/schema/deprecated/unknown_fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/deprecated/unknown_fail_1/stderr.golden rename to tests/grammar/schema/deprecated/unknown_fail_1/stderr.golden diff --git a/test/grammar/schema/duplicated_key/duplicated_key1/main.k b/tests/grammar/schema/duplicated_key/duplicated_key1/main.k similarity index 100% rename from test/grammar/schema/duplicated_key/duplicated_key1/main.k rename to tests/grammar/schema/duplicated_key/duplicated_key1/main.k diff --git a/test/grammar/schema/duplicated_key/duplicated_key1/stdout.golden b/tests/grammar/schema/duplicated_key/duplicated_key1/stdout.golden similarity index 100% rename from test/grammar/schema/duplicated_key/duplicated_key1/stdout.golden rename to tests/grammar/schema/duplicated_key/duplicated_key1/stdout.golden diff --git a/test/grammar/schema/duplicated_key/duplicated_key2/main.k b/tests/grammar/schema/duplicated_key/duplicated_key2/main.k similarity index 100% rename from test/grammar/schema/duplicated_key/duplicated_key2/main.k rename to tests/grammar/schema/duplicated_key/duplicated_key2/main.k diff --git a/test/grammar/schema/duplicated_key/duplicated_key2/stdout.golden b/tests/grammar/schema/duplicated_key/duplicated_key2/stdout.golden similarity index 100% rename from test/grammar/schema/duplicated_key/duplicated_key2/stdout.golden rename to tests/grammar/schema/duplicated_key/duplicated_key2/stdout.golden diff --git a/test/grammar/schema/duplicated_key/duplicated_key3/main.k b/tests/grammar/schema/duplicated_key/duplicated_key3/main.k similarity index 100% rename from test/grammar/schema/duplicated_key/duplicated_key3/main.k rename to tests/grammar/schema/duplicated_key/duplicated_key3/main.k diff --git a/test/grammar/schema/duplicated_key/duplicated_key3/stdout.golden b/tests/grammar/schema/duplicated_key/duplicated_key3/stdout.golden similarity index 100% rename from test/grammar/schema/duplicated_key/duplicated_key3/stdout.golden rename to tests/grammar/schema/duplicated_key/duplicated_key3/stdout.golden diff --git a/test/grammar/schema/empty/empty_0/main.k b/tests/grammar/schema/empty/empty_0/main.k similarity index 100% rename from test/grammar/schema/empty/empty_0/main.k rename to tests/grammar/schema/empty/empty_0/main.k diff --git a/test/grammar/schema/empty/empty_0/stdout.golden b/tests/grammar/schema/empty/empty_0/stdout.golden similarity index 100% rename from test/grammar/schema/empty/empty_0/stdout.golden rename to tests/grammar/schema/empty/empty_0/stdout.golden diff --git a/test/grammar/schema/factory/test_0/main.k b/tests/grammar/schema/factory/test_0/main.k similarity index 100% rename from test/grammar/schema/factory/test_0/main.k rename to tests/grammar/schema/factory/test_0/main.k diff --git a/test/grammar/schema/factory/test_0/stdout.golden b/tests/grammar/schema/factory/test_0/stdout.golden similarity index 100% rename from test/grammar/schema/factory/test_0/stdout.golden rename to tests/grammar/schema/factory/test_0/stdout.golden diff --git a/test/grammar/schema/factory/test_1/main.k b/tests/grammar/schema/factory/test_1/main.k similarity index 100% rename from test/grammar/schema/factory/test_1/main.k rename to tests/grammar/schema/factory/test_1/main.k diff --git a/test/grammar/schema/factory/test_1/stdout.golden b/tests/grammar/schema/factory/test_1/stdout.golden similarity index 100% rename from test/grammar/schema/factory/test_1/stdout.golden rename to tests/grammar/schema/factory/test_1/stdout.golden diff --git a/test/grammar/schema/factory/test_2/main.k b/tests/grammar/schema/factory/test_2/main.k similarity index 100% rename from test/grammar/schema/factory/test_2/main.k rename to tests/grammar/schema/factory/test_2/main.k diff --git a/test/grammar/schema/factory/test_2/stdout.golden b/tests/grammar/schema/factory/test_2/stdout.golden similarity index 100% rename from test/grammar/schema/factory/test_2/stdout.golden rename to tests/grammar/schema/factory/test_2/stdout.golden diff --git a/test/grammar/schema/if_item/if_item_0/main.k b/tests/grammar/schema/if_item/if_item_0/main.k similarity index 100% rename from test/grammar/schema/if_item/if_item_0/main.k rename to tests/grammar/schema/if_item/if_item_0/main.k diff --git a/test/grammar/schema/if_item/if_item_0/stdout.golden b/tests/grammar/schema/if_item/if_item_0/stdout.golden similarity index 100% rename from test/grammar/schema/if_item/if_item_0/stdout.golden rename to tests/grammar/schema/if_item/if_item_0/stdout.golden diff --git a/test/grammar/schema/if_item/if_item_2/main.k b/tests/grammar/schema/if_item/if_item_2/main.k similarity index 100% rename from test/grammar/schema/if_item/if_item_2/main.k rename to tests/grammar/schema/if_item/if_item_2/main.k diff --git a/test/grammar/schema/if_item/if_item_2/stdout.golden b/tests/grammar/schema/if_item/if_item_2/stdout.golden similarity index 100% rename from test/grammar/schema/if_item/if_item_2/stdout.golden rename to tests/grammar/schema/if_item/if_item_2/stdout.golden diff --git a/test/grammar/schema/if_item/if_item_3/main.k b/tests/grammar/schema/if_item/if_item_3/main.k similarity index 100% rename from test/grammar/schema/if_item/if_item_3/main.k rename to tests/grammar/schema/if_item/if_item_3/main.k diff --git a/test/grammar/schema/if_item/if_item_3/stdout.golden b/tests/grammar/schema/if_item/if_item_3/stdout.golden similarity index 100% rename from test/grammar/schema/if_item/if_item_3/stdout.golden rename to tests/grammar/schema/if_item/if_item_3/stdout.golden diff --git a/test/grammar/schema/if_item/if_item_4/main.k b/tests/grammar/schema/if_item/if_item_4/main.k similarity index 100% rename from test/grammar/schema/if_item/if_item_4/main.k rename to tests/grammar/schema/if_item/if_item_4/main.k diff --git a/test/grammar/schema/if_item/if_item_4/stdout.golden b/tests/grammar/schema/if_item/if_item_4/stdout.golden similarity index 100% rename from test/grammar/schema/if_item/if_item_4/stdout.golden rename to tests/grammar/schema/if_item/if_item_4/stdout.golden diff --git a/test/grammar/schema/if_item/if_item_5/main.k b/tests/grammar/schema/if_item/if_item_5/main.k similarity index 100% rename from test/grammar/schema/if_item/if_item_5/main.k rename to tests/grammar/schema/if_item/if_item_5/main.k diff --git a/test/grammar/schema/if_item/if_item_5/stdout.golden b/tests/grammar/schema/if_item/if_item_5/stdout.golden similarity index 100% rename from test/grammar/schema/if_item/if_item_5/stdout.golden rename to tests/grammar/schema/if_item/if_item_5/stdout.golden diff --git a/test/grammar/schema/if_item/if_item_6/main.k b/tests/grammar/schema/if_item/if_item_6/main.k similarity index 100% rename from test/grammar/schema/if_item/if_item_6/main.k rename to tests/grammar/schema/if_item/if_item_6/main.k diff --git a/test/grammar/schema/if_item/if_item_6/stdout.golden b/tests/grammar/schema/if_item/if_item_6/stdout.golden similarity index 100% rename from test/grammar/schema/if_item/if_item_6/stdout.golden rename to tests/grammar/schema/if_item/if_item_6/stdout.golden diff --git a/test/grammar/schema/if_item/if_item_7/main.k b/tests/grammar/schema/if_item/if_item_7/main.k similarity index 100% rename from test/grammar/schema/if_item/if_item_7/main.k rename to tests/grammar/schema/if_item/if_item_7/main.k diff --git a/test/grammar/schema/if_item/if_item_7/stdout.golden b/tests/grammar/schema/if_item/if_item_7/stdout.golden similarity index 100% rename from test/grammar/schema/if_item/if_item_7/stdout.golden rename to tests/grammar/schema/if_item/if_item_7/stdout.golden diff --git a/test/grammar/schema/if_item/if_item_fail_0/main.k b/tests/grammar/schema/if_item/if_item_fail_0/main.k similarity index 100% rename from test/grammar/schema/if_item/if_item_fail_0/main.k rename to tests/grammar/schema/if_item/if_item_fail_0/main.k diff --git a/test/grammar/schema/if_item/if_item_fail_0/stderr.golden b/tests/grammar/schema/if_item/if_item_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/if_item/if_item_fail_0/stderr.golden rename to tests/grammar/schema/if_item/if_item_fail_0/stderr.golden diff --git a/test/grammar/schema/import/import_as/kcl.mod b/tests/grammar/schema/import/import_as/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_as/kcl.mod rename to tests/grammar/schema/import/import_as/kcl.mod diff --git a/test/grammar/schema/import/import_as/main.k b/tests/grammar/schema/import/import_as/main.k similarity index 100% rename from test/grammar/schema/import/import_as/main.k rename to tests/grammar/schema/import/import_as/main.k diff --git a/test/grammar/schema/import/import_as/pkg1/module1.k b/tests/grammar/schema/import/import_as/pkg1/module1.k similarity index 100% rename from test/grammar/schema/import/import_as/pkg1/module1.k rename to tests/grammar/schema/import/import_as/pkg1/module1.k diff --git a/test/grammar/schema/import/import_as/stdout.golden b/tests/grammar/schema/import/import_as/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_as/stdout.golden rename to tests/grammar/schema/import/import_as/stdout.golden diff --git a/test/grammar/schema/import/import_combination_0/kcl.mod b/tests/grammar/schema/import/import_combination_0/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_combination_0/kcl.mod rename to tests/grammar/schema/import/import_combination_0/kcl.mod diff --git a/test/grammar/schema/import/import_combination_0/main.k b/tests/grammar/schema/import/import_combination_0/main.k similarity index 100% rename from test/grammar/schema/import/import_combination_0/main.k rename to tests/grammar/schema/import/import_combination_0/main.k diff --git a/test/grammar/schema/import/import_combination_0/pkg/name_module.k b/tests/grammar/schema/import/import_combination_0/pkg/name_module.k similarity index 100% rename from test/grammar/schema/import/import_combination_0/pkg/name_module.k rename to tests/grammar/schema/import/import_combination_0/pkg/name_module.k diff --git a/test/grammar/schema/import/import_combination_0/stdout.golden b/tests/grammar/schema/import/import_combination_0/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_combination_0/stdout.golden rename to tests/grammar/schema/import/import_combination_0/stdout.golden diff --git a/test/grammar/schema/import/import_combination_1/kcl.mod b/tests/grammar/schema/import/import_combination_1/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_combination_1/kcl.mod rename to tests/grammar/schema/import/import_combination_1/kcl.mod diff --git a/test/grammar/schema/import/import_combination_1/main.k b/tests/grammar/schema/import/import_combination_1/main.k similarity index 100% rename from test/grammar/schema/import/import_combination_1/main.k rename to tests/grammar/schema/import/import_combination_1/main.k diff --git a/test/grammar/schema/import/import_combination_1/pkg/name.k b/tests/grammar/schema/import/import_combination_1/pkg/name.k similarity index 100% rename from test/grammar/schema/import/import_combination_1/pkg/name.k rename to tests/grammar/schema/import/import_combination_1/pkg/name.k diff --git a/test/grammar/schema/import/import_combination_1/pkg/person.k b/tests/grammar/schema/import/import_combination_1/pkg/person.k similarity index 100% rename from test/grammar/schema/import/import_combination_1/pkg/person.k rename to tests/grammar/schema/import/import_combination_1/pkg/person.k diff --git a/test/grammar/schema/import/import_combination_1/stdout.golden b/tests/grammar/schema/import/import_combination_1/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_combination_1/stdout.golden rename to tests/grammar/schema/import/import_combination_1/stdout.golden diff --git a/test/grammar/schema/import/import_dict_2_schema_0/kcl.mod b/tests/grammar/schema/import/import_dict_2_schema_0/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_0/kcl.mod rename to tests/grammar/schema/import/import_dict_2_schema_0/kcl.mod diff --git a/test/grammar/schema/import/import_dict_2_schema_0/main.k b/tests/grammar/schema/import/import_dict_2_schema_0/main.k similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_0/main.k rename to tests/grammar/schema/import/import_dict_2_schema_0/main.k diff --git a/test/grammar/schema/import/import_dict_2_schema_0/pkg/name_module.k b/tests/grammar/schema/import/import_dict_2_schema_0/pkg/name_module.k similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_0/pkg/name_module.k rename to tests/grammar/schema/import/import_dict_2_schema_0/pkg/name_module.k diff --git a/test/grammar/schema/import/import_dict_2_schema_0/stdout.golden b/tests/grammar/schema/import/import_dict_2_schema_0/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_0/stdout.golden rename to tests/grammar/schema/import/import_dict_2_schema_0/stdout.golden diff --git a/test/grammar/schema/import/import_dict_2_schema_1/kcl.mod b/tests/grammar/schema/import/import_dict_2_schema_1/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_1/kcl.mod rename to tests/grammar/schema/import/import_dict_2_schema_1/kcl.mod diff --git a/test/grammar/schema/import/import_dict_2_schema_1/main.k b/tests/grammar/schema/import/import_dict_2_schema_1/main.k similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_1/main.k rename to tests/grammar/schema/import/import_dict_2_schema_1/main.k diff --git a/test/grammar/schema/import/import_dict_2_schema_1/name/name.k b/tests/grammar/schema/import/import_dict_2_schema_1/name/name.k similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_1/name/name.k rename to tests/grammar/schema/import/import_dict_2_schema_1/name/name.k diff --git a/test/grammar/schema/import/import_dict_2_schema_1/person/person.k b/tests/grammar/schema/import/import_dict_2_schema_1/person/person.k similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_1/person/person.k rename to tests/grammar/schema/import/import_dict_2_schema_1/person/person.k diff --git a/test/grammar/schema/import/import_dict_2_schema_1/stdout.golden b/tests/grammar/schema/import/import_dict_2_schema_1/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_1/stdout.golden rename to tests/grammar/schema/import/import_dict_2_schema_1/stdout.golden diff --git a/test/grammar/schema/import/import_dict_2_schema_2/kcl.mod b/tests/grammar/schema/import/import_dict_2_schema_2/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_2/kcl.mod rename to tests/grammar/schema/import/import_dict_2_schema_2/kcl.mod diff --git a/test/grammar/schema/import/import_dict_2_schema_2/main.k b/tests/grammar/schema/import/import_dict_2_schema_2/main.k similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_2/main.k rename to tests/grammar/schema/import/import_dict_2_schema_2/main.k diff --git a/test/grammar/schema/import/import_dict_2_schema_2/name/name.k b/tests/grammar/schema/import/import_dict_2_schema_2/name/name.k similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_2/name/name.k rename to tests/grammar/schema/import/import_dict_2_schema_2/name/name.k diff --git a/test/grammar/schema/import/import_dict_2_schema_2/person/person.k b/tests/grammar/schema/import/import_dict_2_schema_2/person/person.k similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_2/person/person.k rename to tests/grammar/schema/import/import_dict_2_schema_2/person/person.k diff --git a/test/grammar/schema/import/import_dict_2_schema_2/scholar/scholar.k b/tests/grammar/schema/import/import_dict_2_schema_2/scholar/scholar.k similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_2/scholar/scholar.k rename to tests/grammar/schema/import/import_dict_2_schema_2/scholar/scholar.k diff --git a/test/grammar/schema/import/import_dict_2_schema_2/stdout.golden b/tests/grammar/schema/import/import_dict_2_schema_2/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_2/stdout.golden rename to tests/grammar/schema/import/import_dict_2_schema_2/stdout.golden diff --git a/test/grammar/schema/import/import_dict_2_schema_3/kcl.mod b/tests/grammar/schema/import/import_dict_2_schema_3/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_3/kcl.mod rename to tests/grammar/schema/import/import_dict_2_schema_3/kcl.mod diff --git a/test/grammar/schema/import/import_dict_2_schema_3/main.k b/tests/grammar/schema/import/import_dict_2_schema_3/main.k similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_3/main.k rename to tests/grammar/schema/import/import_dict_2_schema_3/main.k diff --git a/test/grammar/schema/import/import_dict_2_schema_3/name/name.k b/tests/grammar/schema/import/import_dict_2_schema_3/name/name.k similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_3/name/name.k rename to tests/grammar/schema/import/import_dict_2_schema_3/name/name.k diff --git a/test/grammar/schema/import/import_dict_2_schema_3/person/person.k b/tests/grammar/schema/import/import_dict_2_schema_3/person/person.k similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_3/person/person.k rename to tests/grammar/schema/import/import_dict_2_schema_3/person/person.k diff --git a/test/grammar/schema/import/import_dict_2_schema_3/scholar/scholar.k b/tests/grammar/schema/import/import_dict_2_schema_3/scholar/scholar.k similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_3/scholar/scholar.k rename to tests/grammar/schema/import/import_dict_2_schema_3/scholar/scholar.k diff --git a/test/grammar/schema/import/import_dict_2_schema_3/stdout.golden b/tests/grammar/schema/import/import_dict_2_schema_3/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_dict_2_schema_3/stdout.golden rename to tests/grammar/schema/import/import_dict_2_schema_3/stdout.golden diff --git a/test/grammar/schema/import/import_inherit/kcl.mod b/tests/grammar/schema/import/import_inherit/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_inherit/kcl.mod rename to tests/grammar/schema/import/import_inherit/kcl.mod diff --git a/test/grammar/schema/import/import_inherit/main.k b/tests/grammar/schema/import/import_inherit/main.k similarity index 100% rename from test/grammar/schema/import/import_inherit/main.k rename to tests/grammar/schema/import/import_inherit/main.k diff --git a/test/grammar/schema/import/import_inherit/pkg/name_module.k b/tests/grammar/schema/import/import_inherit/pkg/name_module.k similarity index 100% rename from test/grammar/schema/import/import_inherit/pkg/name_module.k rename to tests/grammar/schema/import/import_inherit/pkg/name_module.k diff --git a/test/grammar/schema/import/import_inherit/stdout.golden b/tests/grammar/schema/import/import_inherit/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_inherit/stdout.golden rename to tests/grammar/schema/import/import_inherit/stdout.golden diff --git a/test/grammar/schema/import/import_init/kcl.mod b/tests/grammar/schema/import/import_init/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_init/kcl.mod rename to tests/grammar/schema/import/import_init/kcl.mod diff --git a/test/grammar/schema/import/import_init/main.k b/tests/grammar/schema/import/import_init/main.k similarity index 100% rename from test/grammar/schema/import/import_init/main.k rename to tests/grammar/schema/import/import_init/main.k diff --git a/test/grammar/schema/import/import_init/pkg/name_module.k b/tests/grammar/schema/import/import_init/pkg/name_module.k similarity index 100% rename from test/grammar/schema/import/import_init/pkg/name_module.k rename to tests/grammar/schema/import/import_init/pkg/name_module.k diff --git a/test/grammar/schema/import/import_init/stdout.golden b/tests/grammar/schema/import/import_init/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_init/stdout.golden rename to tests/grammar/schema/import/import_init/stdout.golden diff --git a/test/grammar/schema/import/import_multi_pkgs_0/kcl.mod b/tests/grammar/schema/import/import_multi_pkgs_0/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_0/kcl.mod rename to tests/grammar/schema/import/import_multi_pkgs_0/kcl.mod diff --git a/test/grammar/schema/import/import_multi_pkgs_0/main.k b/tests/grammar/schema/import/import_multi_pkgs_0/main.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_0/main.k rename to tests/grammar/schema/import/import_multi_pkgs_0/main.k diff --git a/test/grammar/schema/import/import_multi_pkgs_0/mixins/subject_mixin.k b/tests/grammar/schema/import/import_multi_pkgs_0/mixins/subject_mixin.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_0/mixins/subject_mixin.k rename to tests/grammar/schema/import/import_multi_pkgs_0/mixins/subject_mixin.k diff --git a/test/grammar/schema/import/import_multi_pkgs_0/org/v1/subject.k b/tests/grammar/schema/import/import_multi_pkgs_0/org/v1/subject.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_0/org/v1/subject.k rename to tests/grammar/schema/import/import_multi_pkgs_0/org/v1/subject.k diff --git a/test/grammar/schema/import/import_multi_pkgs_0/person/person.k b/tests/grammar/schema/import/import_multi_pkgs_0/person/person.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_0/person/person.k rename to tests/grammar/schema/import/import_multi_pkgs_0/person/person.k diff --git a/test/grammar/schema/import/import_multi_pkgs_0/stdout.golden b/tests/grammar/schema/import/import_multi_pkgs_0/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_0/stdout.golden rename to tests/grammar/schema/import/import_multi_pkgs_0/stdout.golden diff --git a/test/grammar/schema/import/import_multi_pkgs_1/kcl.mod b/tests/grammar/schema/import/import_multi_pkgs_1/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_1/kcl.mod rename to tests/grammar/schema/import/import_multi_pkgs_1/kcl.mod diff --git a/test/grammar/schema/import/import_multi_pkgs_1/main.k b/tests/grammar/schema/import/import_multi_pkgs_1/main.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_1/main.k rename to tests/grammar/schema/import/import_multi_pkgs_1/main.k diff --git a/test/grammar/schema/import/import_multi_pkgs_1/mixins/subject_mixin.k b/tests/grammar/schema/import/import_multi_pkgs_1/mixins/subject_mixin.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_1/mixins/subject_mixin.k rename to tests/grammar/schema/import/import_multi_pkgs_1/mixins/subject_mixin.k diff --git a/test/grammar/schema/import/import_multi_pkgs_1/org/v1/subject.k b/tests/grammar/schema/import/import_multi_pkgs_1/org/v1/subject.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_1/org/v1/subject.k rename to tests/grammar/schema/import/import_multi_pkgs_1/org/v1/subject.k diff --git a/test/grammar/schema/import/import_multi_pkgs_1/person/person.k b/tests/grammar/schema/import/import_multi_pkgs_1/person/person.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_1/person/person.k rename to tests/grammar/schema/import/import_multi_pkgs_1/person/person.k diff --git a/test/grammar/schema/import/import_multi_pkgs_1/stdout.golden b/tests/grammar/schema/import/import_multi_pkgs_1/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_1/stdout.golden rename to tests/grammar/schema/import/import_multi_pkgs_1/stdout.golden diff --git a/test/grammar/schema/import/import_multi_pkgs_2/kcl.mod b/tests/grammar/schema/import/import_multi_pkgs_2/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_2/kcl.mod rename to tests/grammar/schema/import/import_multi_pkgs_2/kcl.mod diff --git a/test/grammar/schema/import/import_multi_pkgs_2/main.k b/tests/grammar/schema/import/import_multi_pkgs_2/main.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_2/main.k rename to tests/grammar/schema/import/import_multi_pkgs_2/main.k diff --git a/test/grammar/schema/import/import_multi_pkgs_2/mixins/subject_mixin.k b/tests/grammar/schema/import/import_multi_pkgs_2/mixins/subject_mixin.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_2/mixins/subject_mixin.k rename to tests/grammar/schema/import/import_multi_pkgs_2/mixins/subject_mixin.k diff --git a/test/grammar/schema/import/import_multi_pkgs_2/org/v1/subject.k b/tests/grammar/schema/import/import_multi_pkgs_2/org/v1/subject.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_2/org/v1/subject.k rename to tests/grammar/schema/import/import_multi_pkgs_2/org/v1/subject.k diff --git a/test/grammar/schema/import/import_multi_pkgs_2/person/person.k b/tests/grammar/schema/import/import_multi_pkgs_2/person/person.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_2/person/person.k rename to tests/grammar/schema/import/import_multi_pkgs_2/person/person.k diff --git a/test/grammar/schema/import/import_multi_pkgs_2/stdout.golden b/tests/grammar/schema/import/import_multi_pkgs_2/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_2/stdout.golden rename to tests/grammar/schema/import/import_multi_pkgs_2/stdout.golden diff --git a/test/grammar/schema/import/import_multi_pkgs_3/kcl.mod b/tests/grammar/schema/import/import_multi_pkgs_3/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_3/kcl.mod rename to tests/grammar/schema/import/import_multi_pkgs_3/kcl.mod diff --git a/test/grammar/schema/import/import_multi_pkgs_3/main.k b/tests/grammar/schema/import/import_multi_pkgs_3/main.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_3/main.k rename to tests/grammar/schema/import/import_multi_pkgs_3/main.k diff --git a/test/grammar/schema/import/import_multi_pkgs_3/mixins/v1/subject_mixin.k b/tests/grammar/schema/import/import_multi_pkgs_3/mixins/v1/subject_mixin.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_3/mixins/v1/subject_mixin.k rename to tests/grammar/schema/import/import_multi_pkgs_3/mixins/v1/subject_mixin.k diff --git a/test/grammar/schema/import/import_multi_pkgs_3/org/v1/subject.k b/tests/grammar/schema/import/import_multi_pkgs_3/org/v1/subject.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_3/org/v1/subject.k rename to tests/grammar/schema/import/import_multi_pkgs_3/org/v1/subject.k diff --git a/test/grammar/schema/import/import_multi_pkgs_3/person/person.k b/tests/grammar/schema/import/import_multi_pkgs_3/person/person.k similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_3/person/person.k rename to tests/grammar/schema/import/import_multi_pkgs_3/person/person.k diff --git a/test/grammar/schema/import/import_multi_pkgs_3/stdout.golden b/tests/grammar/schema/import/import_multi_pkgs_3/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_multi_pkgs_3/stdout.golden rename to tests/grammar/schema/import/import_multi_pkgs_3/stdout.golden diff --git a/test/grammar/schema/import/import_same_module_inherit/kcl.mod b/tests/grammar/schema/import/import_same_module_inherit/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_same_module_inherit/kcl.mod rename to tests/grammar/schema/import/import_same_module_inherit/kcl.mod diff --git a/test/grammar/schema/import/import_same_module_inherit/main.k b/tests/grammar/schema/import/import_same_module_inherit/main.k similarity index 100% rename from test/grammar/schema/import/import_same_module_inherit/main.k rename to tests/grammar/schema/import/import_same_module_inherit/main.k diff --git a/test/grammar/schema/import/import_same_module_inherit/pkg/name.k b/tests/grammar/schema/import/import_same_module_inherit/pkg/name.k similarity index 100% rename from test/grammar/schema/import/import_same_module_inherit/pkg/name.k rename to tests/grammar/schema/import/import_same_module_inherit/pkg/name.k diff --git a/test/grammar/schema/import/import_same_module_inherit/stdout.golden b/tests/grammar/schema/import/import_same_module_inherit/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_same_module_inherit/stdout.golden rename to tests/grammar/schema/import/import_same_module_inherit/stdout.golden diff --git a/test/grammar/schema/import/import_same_pkg/kcl.mod b/tests/grammar/schema/import/import_same_pkg/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_same_pkg/kcl.mod rename to tests/grammar/schema/import/import_same_pkg/kcl.mod diff --git a/test/grammar/schema/import/import_same_pkg/main.k b/tests/grammar/schema/import/import_same_pkg/main.k similarity index 100% rename from test/grammar/schema/import/import_same_pkg/main.k rename to tests/grammar/schema/import/import_same_pkg/main.k diff --git a/test/grammar/schema/import/import_same_pkg/pkg/alice.k b/tests/grammar/schema/import/import_same_pkg/pkg/alice.k similarity index 100% rename from test/grammar/schema/import/import_same_pkg/pkg/alice.k rename to tests/grammar/schema/import/import_same_pkg/pkg/alice.k diff --git a/test/grammar/schema/import/import_same_pkg/pkg/name.k b/tests/grammar/schema/import/import_same_pkg/pkg/name.k similarity index 100% rename from test/grammar/schema/import/import_same_pkg/pkg/name.k rename to tests/grammar/schema/import/import_same_pkg/pkg/name.k diff --git a/test/grammar/schema/import/import_same_pkg/stdout.golden b/tests/grammar/schema/import/import_same_pkg/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_same_pkg/stdout.golden rename to tests/grammar/schema/import/import_same_pkg/stdout.golden diff --git a/test/grammar/schema/import/import_same_pkg_field/kcl.mod b/tests/grammar/schema/import/import_same_pkg_field/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_same_pkg_field/kcl.mod rename to tests/grammar/schema/import/import_same_pkg_field/kcl.mod diff --git a/test/grammar/schema/import/import_same_pkg_field/main.k b/tests/grammar/schema/import/import_same_pkg_field/main.k similarity index 100% rename from test/grammar/schema/import/import_same_pkg_field/main.k rename to tests/grammar/schema/import/import_same_pkg_field/main.k diff --git a/test/grammar/schema/import/import_same_pkg_field/pkg/name.k b/tests/grammar/schema/import/import_same_pkg_field/pkg/name.k similarity index 100% rename from test/grammar/schema/import/import_same_pkg_field/pkg/name.k rename to tests/grammar/schema/import/import_same_pkg_field/pkg/name.k diff --git a/test/grammar/schema/import/import_same_pkg_field/pkg/nameable.k b/tests/grammar/schema/import/import_same_pkg_field/pkg/nameable.k similarity index 100% rename from test/grammar/schema/import/import_same_pkg_field/pkg/nameable.k rename to tests/grammar/schema/import/import_same_pkg_field/pkg/nameable.k diff --git a/test/grammar/schema/import/import_same_pkg_field/stdout.golden b/tests/grammar/schema/import/import_same_pkg_field/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_same_pkg_field/stdout.golden rename to tests/grammar/schema/import/import_same_pkg_field/stdout.golden diff --git a/test/grammar/schema/import/import_same_pkg_inherit/kcl.mod b/tests/grammar/schema/import/import_same_pkg_inherit/kcl.mod similarity index 100% rename from test/grammar/schema/import/import_same_pkg_inherit/kcl.mod rename to tests/grammar/schema/import/import_same_pkg_inherit/kcl.mod diff --git a/test/grammar/schema/import/import_same_pkg_inherit/main.k b/tests/grammar/schema/import/import_same_pkg_inherit/main.k similarity index 100% rename from test/grammar/schema/import/import_same_pkg_inherit/main.k rename to tests/grammar/schema/import/import_same_pkg_inherit/main.k diff --git a/test/grammar/schema/import/import_same_pkg_inherit/pkg/name.k b/tests/grammar/schema/import/import_same_pkg_inherit/pkg/name.k similarity index 100% rename from test/grammar/schema/import/import_same_pkg_inherit/pkg/name.k rename to tests/grammar/schema/import/import_same_pkg_inherit/pkg/name.k diff --git a/test/grammar/schema/import/import_same_pkg_inherit/pkg/nameable.k b/tests/grammar/schema/import/import_same_pkg_inherit/pkg/nameable.k similarity index 100% rename from test/grammar/schema/import/import_same_pkg_inherit/pkg/nameable.k rename to tests/grammar/schema/import/import_same_pkg_inherit/pkg/nameable.k diff --git a/test/grammar/schema/import/import_same_pkg_inherit/stdout.golden b/tests/grammar/schema/import/import_same_pkg_inherit/stdout.golden similarity index 100% rename from test/grammar/schema/import/import_same_pkg_inherit/stdout.golden rename to tests/grammar/schema/import/import_same_pkg_inherit/stdout.golden diff --git a/test/grammar/schema/index_signature/any_other_0/main.k b/tests/grammar/schema/index_signature/any_other_0/main.k similarity index 100% rename from test/grammar/schema/index_signature/any_other_0/main.k rename to tests/grammar/schema/index_signature/any_other_0/main.k diff --git a/test/grammar/schema/index_signature/any_other_0/stdout.golden b/tests/grammar/schema/index_signature/any_other_0/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/any_other_0/stdout.golden rename to tests/grammar/schema/index_signature/any_other_0/stdout.golden diff --git a/test/grammar/schema/index_signature/any_other_1/main.k b/tests/grammar/schema/index_signature/any_other_1/main.k similarity index 100% rename from test/grammar/schema/index_signature/any_other_1/main.k rename to tests/grammar/schema/index_signature/any_other_1/main.k diff --git a/test/grammar/schema/index_signature/any_other_1/stdout.golden b/tests/grammar/schema/index_signature/any_other_1/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/any_other_1/stdout.golden rename to tests/grammar/schema/index_signature/any_other_1/stdout.golden diff --git a/test/grammar/schema/index_signature/check_0/main.k b/tests/grammar/schema/index_signature/check_0/main.k similarity index 100% rename from test/grammar/schema/index_signature/check_0/main.k rename to tests/grammar/schema/index_signature/check_0/main.k diff --git a/test/grammar/schema/index_signature/check_0/stdout.golden b/tests/grammar/schema/index_signature/check_0/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/check_0/stdout.golden rename to tests/grammar/schema/index_signature/check_0/stdout.golden diff --git a/test/grammar/schema/index_signature/check_1/main.k b/tests/grammar/schema/index_signature/check_1/main.k similarity index 100% rename from test/grammar/schema/index_signature/check_1/main.k rename to tests/grammar/schema/index_signature/check_1/main.k diff --git a/test/grammar/schema/index_signature/check_1/stdout.golden b/tests/grammar/schema/index_signature/check_1/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/check_1/stdout.golden rename to tests/grammar/schema/index_signature/check_1/stdout.golden diff --git a/test/grammar/schema/index_signature/fail_0/main.k b/tests/grammar/schema/index_signature/fail_0/main.k similarity index 100% rename from test/grammar/schema/index_signature/fail_0/main.k rename to tests/grammar/schema/index_signature/fail_0/main.k diff --git a/test/grammar/schema/index_signature/fail_0/stderr.golden b/tests/grammar/schema/index_signature/fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/index_signature/fail_0/stderr.golden rename to tests/grammar/schema/index_signature/fail_0/stderr.golden diff --git a/test/grammar/schema/index_signature/fail_1/main.k b/tests/grammar/schema/index_signature/fail_1/main.k similarity index 100% rename from test/grammar/schema/index_signature/fail_1/main.k rename to tests/grammar/schema/index_signature/fail_1/main.k diff --git a/test/grammar/schema/index_signature/fail_1/stderr.golden b/tests/grammar/schema/index_signature/fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/index_signature/fail_1/stderr.golden rename to tests/grammar/schema/index_signature/fail_1/stderr.golden diff --git a/test/grammar/schema/index_signature/fail_10/main.k b/tests/grammar/schema/index_signature/fail_10/main.k similarity index 100% rename from test/grammar/schema/index_signature/fail_10/main.k rename to tests/grammar/schema/index_signature/fail_10/main.k diff --git a/test/grammar/schema/index_signature/fail_10/stderr.golden b/tests/grammar/schema/index_signature/fail_10/stderr.golden similarity index 100% rename from test/grammar/schema/index_signature/fail_10/stderr.golden rename to tests/grammar/schema/index_signature/fail_10/stderr.golden diff --git a/test/grammar/schema/index_signature/fail_11/main.k b/tests/grammar/schema/index_signature/fail_11/main.k similarity index 100% rename from test/grammar/schema/index_signature/fail_11/main.k rename to tests/grammar/schema/index_signature/fail_11/main.k diff --git a/test/grammar/schema/index_signature/fail_11/stderr.golden b/tests/grammar/schema/index_signature/fail_11/stderr.golden similarity index 100% rename from test/grammar/schema/index_signature/fail_11/stderr.golden rename to tests/grammar/schema/index_signature/fail_11/stderr.golden diff --git a/test/grammar/schema/index_signature/fail_12/main.k b/tests/grammar/schema/index_signature/fail_12/main.k similarity index 100% rename from test/grammar/schema/index_signature/fail_12/main.k rename to tests/grammar/schema/index_signature/fail_12/main.k diff --git a/test/grammar/schema/index_signature/fail_12/stderr.golden b/tests/grammar/schema/index_signature/fail_12/stderr.golden similarity index 100% rename from test/grammar/schema/index_signature/fail_12/stderr.golden rename to tests/grammar/schema/index_signature/fail_12/stderr.golden diff --git a/test/grammar/schema/index_signature/fail_2/main.k b/tests/grammar/schema/index_signature/fail_2/main.k similarity index 100% rename from test/grammar/schema/index_signature/fail_2/main.k rename to tests/grammar/schema/index_signature/fail_2/main.k diff --git a/test/grammar/schema/index_signature/fail_2/stderr.golden b/tests/grammar/schema/index_signature/fail_2/stderr.golden similarity index 100% rename from test/grammar/schema/index_signature/fail_2/stderr.golden rename to tests/grammar/schema/index_signature/fail_2/stderr.golden diff --git a/test/grammar/schema/index_signature/fail_3/main.k b/tests/grammar/schema/index_signature/fail_3/main.k similarity index 100% rename from test/grammar/schema/index_signature/fail_3/main.k rename to tests/grammar/schema/index_signature/fail_3/main.k diff --git a/test/grammar/schema/index_signature/fail_3/stderr.golden b/tests/grammar/schema/index_signature/fail_3/stderr.golden similarity index 100% rename from test/grammar/schema/index_signature/fail_3/stderr.golden rename to tests/grammar/schema/index_signature/fail_3/stderr.golden diff --git a/test/grammar/schema/index_signature/fail_4/main.k b/tests/grammar/schema/index_signature/fail_4/main.k similarity index 100% rename from test/grammar/schema/index_signature/fail_4/main.k rename to tests/grammar/schema/index_signature/fail_4/main.k diff --git a/test/grammar/schema/index_signature/fail_4/stderr.golden b/tests/grammar/schema/index_signature/fail_4/stderr.golden similarity index 100% rename from test/grammar/schema/index_signature/fail_4/stderr.golden rename to tests/grammar/schema/index_signature/fail_4/stderr.golden diff --git a/test/grammar/schema/index_signature/fail_5/main.k b/tests/grammar/schema/index_signature/fail_5/main.k similarity index 100% rename from test/grammar/schema/index_signature/fail_5/main.k rename to tests/grammar/schema/index_signature/fail_5/main.k diff --git a/test/grammar/schema/index_signature/fail_5/stderr.golden b/tests/grammar/schema/index_signature/fail_5/stderr.golden similarity index 100% rename from test/grammar/schema/index_signature/fail_5/stderr.golden rename to tests/grammar/schema/index_signature/fail_5/stderr.golden diff --git a/test/grammar/schema/index_signature/fail_6/main.k b/tests/grammar/schema/index_signature/fail_6/main.k similarity index 100% rename from test/grammar/schema/index_signature/fail_6/main.k rename to tests/grammar/schema/index_signature/fail_6/main.k diff --git a/test/grammar/schema/index_signature/fail_6/stderr.golden b/tests/grammar/schema/index_signature/fail_6/stderr.golden similarity index 100% rename from test/grammar/schema/index_signature/fail_6/stderr.golden rename to tests/grammar/schema/index_signature/fail_6/stderr.golden diff --git a/test/grammar/schema/index_signature/fail_7/main.k b/tests/grammar/schema/index_signature/fail_7/main.k similarity index 100% rename from test/grammar/schema/index_signature/fail_7/main.k rename to tests/grammar/schema/index_signature/fail_7/main.k diff --git a/test/grammar/schema/index_signature/fail_7/stderr.golden b/tests/grammar/schema/index_signature/fail_7/stderr.golden similarity index 100% rename from test/grammar/schema/index_signature/fail_7/stderr.golden rename to tests/grammar/schema/index_signature/fail_7/stderr.golden diff --git a/test/grammar/schema/index_signature/fail_8/main.k b/tests/grammar/schema/index_signature/fail_8/main.k similarity index 100% rename from test/grammar/schema/index_signature/fail_8/main.k rename to tests/grammar/schema/index_signature/fail_8/main.k diff --git a/test/grammar/schema/index_signature/fail_8/stderr.golden b/tests/grammar/schema/index_signature/fail_8/stderr.golden similarity index 100% rename from test/grammar/schema/index_signature/fail_8/stderr.golden rename to tests/grammar/schema/index_signature/fail_8/stderr.golden diff --git a/test/grammar/schema/index_signature/fail_9/main.k b/tests/grammar/schema/index_signature/fail_9/main.k similarity index 100% rename from test/grammar/schema/index_signature/fail_9/main.k rename to tests/grammar/schema/index_signature/fail_9/main.k diff --git a/test/grammar/schema/index_signature/fail_9/stderr.golden b/tests/grammar/schema/index_signature/fail_9/stderr.golden similarity index 100% rename from test/grammar/schema/index_signature/fail_9/stderr.golden rename to tests/grammar/schema/index_signature/fail_9/stderr.golden diff --git a/test/grammar/schema/index_signature/key_alias_0/main.k b/tests/grammar/schema/index_signature/key_alias_0/main.k similarity index 100% rename from test/grammar/schema/index_signature/key_alias_0/main.k rename to tests/grammar/schema/index_signature/key_alias_0/main.k diff --git a/test/grammar/schema/index_signature/key_alias_0/stdout.golden b/tests/grammar/schema/index_signature/key_alias_0/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/key_alias_0/stdout.golden rename to tests/grammar/schema/index_signature/key_alias_0/stdout.golden diff --git a/test/grammar/schema/index_signature/key_alias_1/main.k b/tests/grammar/schema/index_signature/key_alias_1/main.k similarity index 100% rename from test/grammar/schema/index_signature/key_alias_1/main.k rename to tests/grammar/schema/index_signature/key_alias_1/main.k diff --git a/test/grammar/schema/index_signature/key_alias_1/stdout.golden b/tests/grammar/schema/index_signature/key_alias_1/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/key_alias_1/stdout.golden rename to tests/grammar/schema/index_signature/key_alias_1/stdout.golden diff --git a/test/grammar/schema/index_signature/normal_0/main.k b/tests/grammar/schema/index_signature/normal_0/main.k similarity index 100% rename from test/grammar/schema/index_signature/normal_0/main.k rename to tests/grammar/schema/index_signature/normal_0/main.k diff --git a/test/grammar/schema/index_signature/normal_0/stdout.golden b/tests/grammar/schema/index_signature/normal_0/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/normal_0/stdout.golden rename to tests/grammar/schema/index_signature/normal_0/stdout.golden diff --git a/test/grammar/schema/index_signature/normal_1/main.k b/tests/grammar/schema/index_signature/normal_1/main.k similarity index 100% rename from test/grammar/schema/index_signature/normal_1/main.k rename to tests/grammar/schema/index_signature/normal_1/main.k diff --git a/test/grammar/schema/index_signature/normal_1/stdout.golden b/tests/grammar/schema/index_signature/normal_1/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/normal_1/stdout.golden rename to tests/grammar/schema/index_signature/normal_1/stdout.golden diff --git a/test/grammar/schema/index_signature/normal_10/main.k b/tests/grammar/schema/index_signature/normal_10/main.k similarity index 100% rename from test/grammar/schema/index_signature/normal_10/main.k rename to tests/grammar/schema/index_signature/normal_10/main.k diff --git a/test/grammar/schema/index_signature/normal_10/stdout.golden b/tests/grammar/schema/index_signature/normal_10/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/normal_10/stdout.golden rename to tests/grammar/schema/index_signature/normal_10/stdout.golden diff --git a/test/grammar/schema/index_signature/normal_11/main.k b/tests/grammar/schema/index_signature/normal_11/main.k similarity index 100% rename from test/grammar/schema/index_signature/normal_11/main.k rename to tests/grammar/schema/index_signature/normal_11/main.k diff --git a/test/grammar/schema/index_signature/normal_11/stdout.golden b/tests/grammar/schema/index_signature/normal_11/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/normal_11/stdout.golden rename to tests/grammar/schema/index_signature/normal_11/stdout.golden diff --git a/test/grammar/schema/index_signature/normal_2/main.k b/tests/grammar/schema/index_signature/normal_2/main.k similarity index 100% rename from test/grammar/schema/index_signature/normal_2/main.k rename to tests/grammar/schema/index_signature/normal_2/main.k diff --git a/test/grammar/schema/index_signature/normal_2/stdout.golden b/tests/grammar/schema/index_signature/normal_2/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/normal_2/stdout.golden rename to tests/grammar/schema/index_signature/normal_2/stdout.golden diff --git a/test/grammar/schema/index_signature/normal_3/main.k b/tests/grammar/schema/index_signature/normal_3/main.k similarity index 100% rename from test/grammar/schema/index_signature/normal_3/main.k rename to tests/grammar/schema/index_signature/normal_3/main.k diff --git a/test/grammar/schema/index_signature/normal_3/stdout.golden b/tests/grammar/schema/index_signature/normal_3/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/normal_3/stdout.golden rename to tests/grammar/schema/index_signature/normal_3/stdout.golden diff --git a/test/grammar/schema/index_signature/normal_4/main.k b/tests/grammar/schema/index_signature/normal_4/main.k similarity index 100% rename from test/grammar/schema/index_signature/normal_4/main.k rename to tests/grammar/schema/index_signature/normal_4/main.k diff --git a/test/grammar/schema/index_signature/normal_4/stdout.golden b/tests/grammar/schema/index_signature/normal_4/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/normal_4/stdout.golden rename to tests/grammar/schema/index_signature/normal_4/stdout.golden diff --git a/test/grammar/schema/index_signature/normal_5/main.k b/tests/grammar/schema/index_signature/normal_5/main.k similarity index 100% rename from test/grammar/schema/index_signature/normal_5/main.k rename to tests/grammar/schema/index_signature/normal_5/main.k diff --git a/test/grammar/schema/index_signature/normal_5/stdout.golden b/tests/grammar/schema/index_signature/normal_5/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/normal_5/stdout.golden rename to tests/grammar/schema/index_signature/normal_5/stdout.golden diff --git a/test/grammar/schema/index_signature/normal_6/main.k b/tests/grammar/schema/index_signature/normal_6/main.k similarity index 100% rename from test/grammar/schema/index_signature/normal_6/main.k rename to tests/grammar/schema/index_signature/normal_6/main.k diff --git a/test/grammar/schema/index_signature/normal_6/stdout.golden b/tests/grammar/schema/index_signature/normal_6/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/normal_6/stdout.golden rename to tests/grammar/schema/index_signature/normal_6/stdout.golden diff --git a/test/grammar/schema/index_signature/normal_7/main.k b/tests/grammar/schema/index_signature/normal_7/main.k similarity index 100% rename from test/grammar/schema/index_signature/normal_7/main.k rename to tests/grammar/schema/index_signature/normal_7/main.k diff --git a/test/grammar/schema/index_signature/normal_7/stdout.golden b/tests/grammar/schema/index_signature/normal_7/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/normal_7/stdout.golden rename to tests/grammar/schema/index_signature/normal_7/stdout.golden diff --git a/test/grammar/schema/index_signature/normal_8/main.k b/tests/grammar/schema/index_signature/normal_8/main.k similarity index 100% rename from test/grammar/schema/index_signature/normal_8/main.k rename to tests/grammar/schema/index_signature/normal_8/main.k diff --git a/test/grammar/schema/index_signature/normal_8/stdout.golden b/tests/grammar/schema/index_signature/normal_8/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/normal_8/stdout.golden rename to tests/grammar/schema/index_signature/normal_8/stdout.golden diff --git a/test/grammar/schema/index_signature/normal_9/main.k b/tests/grammar/schema/index_signature/normal_9/main.k similarity index 100% rename from test/grammar/schema/index_signature/normal_9/main.k rename to tests/grammar/schema/index_signature/normal_9/main.k diff --git a/test/grammar/schema/index_signature/normal_9/stdout.golden b/tests/grammar/schema/index_signature/normal_9/stdout.golden similarity index 100% rename from test/grammar/schema/index_signature/normal_9/stdout.golden rename to tests/grammar/schema/index_signature/normal_9/stdout.golden diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_0/main.k b/tests/grammar/schema/inherit/cycle_inherit_fail_0/main.k similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_0/main.k rename to tests/grammar/schema/inherit/cycle_inherit_fail_0/main.k diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_0/stderr.golden b/tests/grammar/schema/inherit/cycle_inherit_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_0/stderr.golden rename to tests/grammar/schema/inherit/cycle_inherit_fail_0/stderr.golden diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_1/main.k b/tests/grammar/schema/inherit/cycle_inherit_fail_1/main.k similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_1/main.k rename to tests/grammar/schema/inherit/cycle_inherit_fail_1/main.k diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_1/stderr.golden b/tests/grammar/schema/inherit/cycle_inherit_fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_1/stderr.golden rename to tests/grammar/schema/inherit/cycle_inherit_fail_1/stderr.golden diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_2/kcl.mod b/tests/grammar/schema/inherit/cycle_inherit_fail_2/kcl.mod similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_2/kcl.mod rename to tests/grammar/schema/inherit/cycle_inherit_fail_2/kcl.mod diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_2/main.k b/tests/grammar/schema/inherit/cycle_inherit_fail_2/main.k similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_2/main.k rename to tests/grammar/schema/inherit/cycle_inherit_fail_2/main.k diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_2/pkg/b.k b/tests/grammar/schema/inherit/cycle_inherit_fail_2/pkg/b.k similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_2/pkg/b.k rename to tests/grammar/schema/inherit/cycle_inherit_fail_2/pkg/b.k diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_2/pkg/c.k b/tests/grammar/schema/inherit/cycle_inherit_fail_2/pkg/c.k similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_2/pkg/c.k rename to tests/grammar/schema/inherit/cycle_inherit_fail_2/pkg/c.k diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_2/stderr.golden b/tests/grammar/schema/inherit/cycle_inherit_fail_2/stderr.golden similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_2/stderr.golden rename to tests/grammar/schema/inherit/cycle_inherit_fail_2/stderr.golden diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_3/kcl.mod b/tests/grammar/schema/inherit/cycle_inherit_fail_3/kcl.mod similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_3/kcl.mod rename to tests/grammar/schema/inherit/cycle_inherit_fail_3/kcl.mod diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_3/main.k b/tests/grammar/schema/inherit/cycle_inherit_fail_3/main.k similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_3/main.k rename to tests/grammar/schema/inherit/cycle_inherit_fail_3/main.k diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_3/pkg/b.k b/tests/grammar/schema/inherit/cycle_inherit_fail_3/pkg/b.k similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_3/pkg/b.k rename to tests/grammar/schema/inherit/cycle_inherit_fail_3/pkg/b.k diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_3/pkg/c.k b/tests/grammar/schema/inherit/cycle_inherit_fail_3/pkg/c.k similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_3/pkg/c.k rename to tests/grammar/schema/inherit/cycle_inherit_fail_3/pkg/c.k diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_3/stderr.golden b/tests/grammar/schema/inherit/cycle_inherit_fail_3/stderr.golden similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_3/stderr.golden rename to tests/grammar/schema/inherit/cycle_inherit_fail_3/stderr.golden diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_4/kcl.mod b/tests/grammar/schema/inherit/cycle_inherit_fail_4/kcl.mod similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_4/kcl.mod rename to tests/grammar/schema/inherit/cycle_inherit_fail_4/kcl.mod diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_4/main.k b/tests/grammar/schema/inherit/cycle_inherit_fail_4/main.k similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_4/main.k rename to tests/grammar/schema/inherit/cycle_inherit_fail_4/main.k diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_4/pkg/b.k b/tests/grammar/schema/inherit/cycle_inherit_fail_4/pkg/b.k similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_4/pkg/b.k rename to tests/grammar/schema/inherit/cycle_inherit_fail_4/pkg/b.k diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_4/pkg/c.k b/tests/grammar/schema/inherit/cycle_inherit_fail_4/pkg/c.k similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_4/pkg/c.k rename to tests/grammar/schema/inherit/cycle_inherit_fail_4/pkg/c.k diff --git a/test/grammar/schema/inherit/cycle_inherit_fail_4/stderr.golden b/tests/grammar/schema/inherit/cycle_inherit_fail_4/stderr.golden similarity index 100% rename from test/grammar/schema/inherit/cycle_inherit_fail_4/stderr.golden rename to tests/grammar/schema/inherit/cycle_inherit_fail_4/stderr.golden diff --git a/test/grammar/schema/inherit/defaulting_0/main.k b/tests/grammar/schema/inherit/defaulting_0/main.k similarity index 100% rename from test/grammar/schema/inherit/defaulting_0/main.k rename to tests/grammar/schema/inherit/defaulting_0/main.k diff --git a/test/grammar/schema/inherit/defaulting_0/stdout.golden b/tests/grammar/schema/inherit/defaulting_0/stdout.golden similarity index 100% rename from test/grammar/schema/inherit/defaulting_0/stdout.golden rename to tests/grammar/schema/inherit/defaulting_0/stdout.golden diff --git a/test/grammar/schema/inherit/defaulting_1/main.k b/tests/grammar/schema/inherit/defaulting_1/main.k similarity index 100% rename from test/grammar/schema/inherit/defaulting_1/main.k rename to tests/grammar/schema/inherit/defaulting_1/main.k diff --git a/test/grammar/schema/inherit/defaulting_1/stdout.golden b/tests/grammar/schema/inherit/defaulting_1/stdout.golden similarity index 100% rename from test/grammar/schema/inherit/defaulting_1/stdout.golden rename to tests/grammar/schema/inherit/defaulting_1/stdout.golden diff --git a/test/grammar/schema/inherit/defaulting_2/main.k b/tests/grammar/schema/inherit/defaulting_2/main.k similarity index 100% rename from test/grammar/schema/inherit/defaulting_2/main.k rename to tests/grammar/schema/inherit/defaulting_2/main.k diff --git a/test/grammar/schema/inherit/defaulting_2/stdout.golden b/tests/grammar/schema/inherit/defaulting_2/stdout.golden similarity index 100% rename from test/grammar/schema/inherit/defaulting_2/stdout.golden rename to tests/grammar/schema/inherit/defaulting_2/stdout.golden diff --git a/test/grammar/schema/inherit/defaulting_3/main.k b/tests/grammar/schema/inherit/defaulting_3/main.k similarity index 100% rename from test/grammar/schema/inherit/defaulting_3/main.k rename to tests/grammar/schema/inherit/defaulting_3/main.k diff --git a/test/grammar/schema/inherit/defaulting_3/stdout.golden b/tests/grammar/schema/inherit/defaulting_3/stdout.golden similarity index 100% rename from test/grammar/schema/inherit/defaulting_3/stdout.golden rename to tests/grammar/schema/inherit/defaulting_3/stdout.golden diff --git a/test/grammar/schema/inherit/defaulting_4/main.k b/tests/grammar/schema/inherit/defaulting_4/main.k similarity index 100% rename from test/grammar/schema/inherit/defaulting_4/main.k rename to tests/grammar/schema/inherit/defaulting_4/main.k diff --git a/test/grammar/schema/inherit/defaulting_4/stdout.golden b/tests/grammar/schema/inherit/defaulting_4/stdout.golden similarity index 100% rename from test/grammar/schema/inherit/defaulting_4/stdout.golden rename to tests/grammar/schema/inherit/defaulting_4/stdout.golden diff --git a/test/grammar/schema/inherit/illegal_inheritance_fail_0/main.k b/tests/grammar/schema/inherit/illegal_inheritance_fail_0/main.k similarity index 100% rename from test/grammar/schema/inherit/illegal_inheritance_fail_0/main.k rename to tests/grammar/schema/inherit/illegal_inheritance_fail_0/main.k diff --git a/test/grammar/schema/inherit/illegal_inheritance_fail_0/stderr.golden b/tests/grammar/schema/inherit/illegal_inheritance_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/inherit/illegal_inheritance_fail_0/stderr.golden rename to tests/grammar/schema/inherit/illegal_inheritance_fail_0/stderr.golden diff --git a/test/grammar/schema/inherit/import_0/kcl.mod b/tests/grammar/schema/inherit/import_0/kcl.mod similarity index 100% rename from test/grammar/schema/inherit/import_0/kcl.mod rename to tests/grammar/schema/inherit/import_0/kcl.mod diff --git a/test/grammar/schema/inherit/import_0/main.k b/tests/grammar/schema/inherit/import_0/main.k similarity index 100% rename from test/grammar/schema/inherit/import_0/main.k rename to tests/grammar/schema/inherit/import_0/main.k diff --git a/test/grammar/schema/inherit/import_0/pkg/module.k b/tests/grammar/schema/inherit/import_0/pkg/module.k similarity index 100% rename from test/grammar/schema/inherit/import_0/pkg/module.k rename to tests/grammar/schema/inherit/import_0/pkg/module.k diff --git a/test/grammar/schema/inherit/import_0/stdout.golden b/tests/grammar/schema/inherit/import_0/stdout.golden similarity index 100% rename from test/grammar/schema/inherit/import_0/stdout.golden rename to tests/grammar/schema/inherit/import_0/stdout.golden diff --git a/test/grammar/schema/inherit/inherit_0/kcl.mod b/tests/grammar/schema/inherit/inherit_0/kcl.mod similarity index 100% rename from test/grammar/schema/inherit/inherit_0/kcl.mod rename to tests/grammar/schema/inherit/inherit_0/kcl.mod diff --git a/test/grammar/schema/inherit/inherit_0/main.k b/tests/grammar/schema/inherit/inherit_0/main.k similarity index 100% rename from test/grammar/schema/inherit/inherit_0/main.k rename to tests/grammar/schema/inherit/inherit_0/main.k diff --git a/test/grammar/schema/inherit/inherit_0/stdout.golden b/tests/grammar/schema/inherit/inherit_0/stdout.golden similarity index 100% rename from test/grammar/schema/inherit/inherit_0/stdout.golden rename to tests/grammar/schema/inherit/inherit_0/stdout.golden diff --git a/test/grammar/schema/inherit/inherit_1/kcl.mod b/tests/grammar/schema/inherit/inherit_1/kcl.mod similarity index 100% rename from test/grammar/schema/inherit/inherit_1/kcl.mod rename to tests/grammar/schema/inherit/inherit_1/kcl.mod diff --git a/test/grammar/schema/inherit/inherit_1/main.k b/tests/grammar/schema/inherit/inherit_1/main.k similarity index 100% rename from test/grammar/schema/inherit/inherit_1/main.k rename to tests/grammar/schema/inherit/inherit_1/main.k diff --git a/test/grammar/schema/inherit/inherit_1/stdout.golden b/tests/grammar/schema/inherit/inherit_1/stdout.golden similarity index 100% rename from test/grammar/schema/inherit/inherit_1/stdout.golden rename to tests/grammar/schema/inherit/inherit_1/stdout.golden diff --git a/test/grammar/schema/inherit/inherit_2/kcl.mod b/tests/grammar/schema/inherit/inherit_2/kcl.mod similarity index 100% rename from test/grammar/schema/inherit/inherit_2/kcl.mod rename to tests/grammar/schema/inherit/inherit_2/kcl.mod diff --git a/test/grammar/schema/inherit/inherit_2/main.k b/tests/grammar/schema/inherit/inherit_2/main.k similarity index 100% rename from test/grammar/schema/inherit/inherit_2/main.k rename to tests/grammar/schema/inherit/inherit_2/main.k diff --git a/test/grammar/schema/inherit/inherit_2/stdout.golden b/tests/grammar/schema/inherit/inherit_2/stdout.golden similarity index 100% rename from test/grammar/schema/inherit/inherit_2/stdout.golden rename to tests/grammar/schema/inherit/inherit_2/stdout.golden diff --git a/test/grammar/schema/inherit/inherit_change_field_type_0/main.k b/tests/grammar/schema/inherit/inherit_change_field_type_0/main.k similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_0/main.k rename to tests/grammar/schema/inherit/inherit_change_field_type_0/main.k diff --git a/test/grammar/schema/inherit/inherit_change_field_type_0/stderr.golden b/tests/grammar/schema/inherit/inherit_change_field_type_0/stderr.golden similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_0/stderr.golden rename to tests/grammar/schema/inherit/inherit_change_field_type_0/stderr.golden diff --git a/test/grammar/schema/inherit/inherit_change_field_type_1/kcl.mod b/tests/grammar/schema/inherit/inherit_change_field_type_1/kcl.mod similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_1/kcl.mod rename to tests/grammar/schema/inherit/inherit_change_field_type_1/kcl.mod diff --git a/test/grammar/schema/inherit/inherit_change_field_type_1/main.k b/tests/grammar/schema/inherit/inherit_change_field_type_1/main.k similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_1/main.k rename to tests/grammar/schema/inherit/inherit_change_field_type_1/main.k diff --git a/test/grammar/schema/inherit/inherit_change_field_type_1/pkg/name.k b/tests/grammar/schema/inherit/inherit_change_field_type_1/pkg/name.k similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_1/pkg/name.k rename to tests/grammar/schema/inherit/inherit_change_field_type_1/pkg/name.k diff --git a/test/grammar/schema/inherit/inherit_change_field_type_1/stdout.golden b/tests/grammar/schema/inherit/inherit_change_field_type_1/stdout.golden similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_1/stdout.golden rename to tests/grammar/schema/inherit/inherit_change_field_type_1/stdout.golden diff --git a/test/grammar/schema/inherit/inherit_change_field_type_2/kcl.mod b/tests/grammar/schema/inherit/inherit_change_field_type_2/kcl.mod similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_2/kcl.mod rename to tests/grammar/schema/inherit/inherit_change_field_type_2/kcl.mod diff --git a/test/grammar/schema/inherit/inherit_change_field_type_2/main.k b/tests/grammar/schema/inherit/inherit_change_field_type_2/main.k similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_2/main.k rename to tests/grammar/schema/inherit/inherit_change_field_type_2/main.k diff --git a/test/grammar/schema/inherit/inherit_change_field_type_2/pkg/name.k b/tests/grammar/schema/inherit/inherit_change_field_type_2/pkg/name.k similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_2/pkg/name.k rename to tests/grammar/schema/inherit/inherit_change_field_type_2/pkg/name.k diff --git a/test/grammar/schema/inherit/inherit_change_field_type_2/stderr.golden b/tests/grammar/schema/inherit/inherit_change_field_type_2/stderr.golden similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_2/stderr.golden rename to tests/grammar/schema/inherit/inherit_change_field_type_2/stderr.golden diff --git a/test/grammar/schema/inherit/inherit_change_field_type_3/kcl.mod b/tests/grammar/schema/inherit/inherit_change_field_type_3/kcl.mod similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_3/kcl.mod rename to tests/grammar/schema/inherit/inherit_change_field_type_3/kcl.mod diff --git a/test/grammar/schema/inherit/inherit_change_field_type_3/main.k b/tests/grammar/schema/inherit/inherit_change_field_type_3/main.k similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_3/main.k rename to tests/grammar/schema/inherit/inherit_change_field_type_3/main.k diff --git a/test/grammar/schema/inherit/inherit_change_field_type_3/pkg/name.k b/tests/grammar/schema/inherit/inherit_change_field_type_3/pkg/name.k similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_3/pkg/name.k rename to tests/grammar/schema/inherit/inherit_change_field_type_3/pkg/name.k diff --git a/test/grammar/schema/inherit/inherit_change_field_type_3/stderr.golden b/tests/grammar/schema/inherit/inherit_change_field_type_3/stderr.golden similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_3/stderr.golden rename to tests/grammar/schema/inherit/inherit_change_field_type_3/stderr.golden diff --git a/test/grammar/schema/inherit/inherit_change_field_type_4/kcl.mod b/tests/grammar/schema/inherit/inherit_change_field_type_4/kcl.mod similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_4/kcl.mod rename to tests/grammar/schema/inherit/inherit_change_field_type_4/kcl.mod diff --git a/test/grammar/schema/inherit/inherit_change_field_type_4/main.k b/tests/grammar/schema/inherit/inherit_change_field_type_4/main.k similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_4/main.k rename to tests/grammar/schema/inherit/inherit_change_field_type_4/main.k diff --git a/test/grammar/schema/inherit/inherit_change_field_type_4/pkg/name.k b/tests/grammar/schema/inherit/inherit_change_field_type_4/pkg/name.k similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_4/pkg/name.k rename to tests/grammar/schema/inherit/inherit_change_field_type_4/pkg/name.k diff --git a/test/grammar/schema/inherit/inherit_change_field_type_4/stdout.golden b/tests/grammar/schema/inherit/inherit_change_field_type_4/stdout.golden similarity index 100% rename from test/grammar/schema/inherit/inherit_change_field_type_4/stdout.golden rename to tests/grammar/schema/inherit/inherit_change_field_type_4/stdout.golden diff --git a/test/grammar/schema/inherit/inherit_mixin_fail/main.k b/tests/grammar/schema/inherit/inherit_mixin_fail/main.k similarity index 100% rename from test/grammar/schema/inherit/inherit_mixin_fail/main.k rename to tests/grammar/schema/inherit/inherit_mixin_fail/main.k diff --git a/test/grammar/schema/inherit/inherit_mixin_fail/stderr.golden b/tests/grammar/schema/inherit/inherit_mixin_fail/stderr.golden similarity index 100% rename from test/grammar/schema/inherit/inherit_mixin_fail/stderr.golden rename to tests/grammar/schema/inherit/inherit_mixin_fail/stderr.golden diff --git a/test/grammar/schema/inherit/multi_inherit_fail_0/main.k b/tests/grammar/schema/inherit/multi_inherit_fail_0/main.k similarity index 100% rename from test/grammar/schema/inherit/multi_inherit_fail_0/main.k rename to tests/grammar/schema/inherit/multi_inherit_fail_0/main.k diff --git a/test/grammar/schema/inherit/multi_inherit_fail_0/stderr.golden b/tests/grammar/schema/inherit/multi_inherit_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/inherit/multi_inherit_fail_0/stderr.golden rename to tests/grammar/schema/inherit/multi_inherit_fail_0/stderr.golden diff --git a/test/grammar/schema/inherit/multi_inherit_fail_1/main.k b/tests/grammar/schema/inherit/multi_inherit_fail_1/main.k similarity index 100% rename from test/grammar/schema/inherit/multi_inherit_fail_1/main.k rename to tests/grammar/schema/inherit/multi_inherit_fail_1/main.k diff --git a/test/grammar/schema/inherit/multi_inherit_fail_1/stderr.golden b/tests/grammar/schema/inherit/multi_inherit_fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/inherit/multi_inherit_fail_1/stderr.golden rename to tests/grammar/schema/inherit/multi_inherit_fail_1/stderr.golden diff --git a/test/grammar/schema/init/init_0/main.k b/tests/grammar/schema/init/init_0/main.k similarity index 100% rename from test/grammar/schema/init/init_0/main.k rename to tests/grammar/schema/init/init_0/main.k diff --git a/test/grammar/schema/init/init_0/stdout.golden b/tests/grammar/schema/init/init_0/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_0/stdout.golden rename to tests/grammar/schema/init/init_0/stdout.golden diff --git a/test/grammar/schema/init/init_1/main.k b/tests/grammar/schema/init/init_1/main.k similarity index 100% rename from test/grammar/schema/init/init_1/main.k rename to tests/grammar/schema/init/init_1/main.k diff --git a/test/grammar/schema/init/init_1/stdout.golden b/tests/grammar/schema/init/init_1/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_1/stdout.golden rename to tests/grammar/schema/init/init_1/stdout.golden diff --git a/test/grammar/schema/init/init_add_member_fail_0/main.k b/tests/grammar/schema/init/init_add_member_fail_0/main.k similarity index 100% rename from test/grammar/schema/init/init_add_member_fail_0/main.k rename to tests/grammar/schema/init/init_add_member_fail_0/main.k diff --git a/test/grammar/schema/init/init_add_member_fail_0/stderr.golden b/tests/grammar/schema/init/init_add_member_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/init/init_add_member_fail_0/stderr.golden rename to tests/grammar/schema/init/init_add_member_fail_0/stderr.golden diff --git a/test/grammar/schema/init/init_add_member_fail_1/main.k b/tests/grammar/schema/init/init_add_member_fail_1/main.k similarity index 100% rename from test/grammar/schema/init/init_add_member_fail_1/main.k rename to tests/grammar/schema/init/init_add_member_fail_1/main.k diff --git a/test/grammar/schema/init/init_add_member_fail_1/stderr.golden b/tests/grammar/schema/init/init_add_member_fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/init/init_add_member_fail_1/stderr.golden rename to tests/grammar/schema/init/init_add_member_fail_1/stderr.golden diff --git a/test/grammar/schema/init/init_add_member_fail_2/main.k b/tests/grammar/schema/init/init_add_member_fail_2/main.k similarity index 100% rename from test/grammar/schema/init/init_add_member_fail_2/main.k rename to tests/grammar/schema/init/init_add_member_fail_2/main.k diff --git a/test/grammar/schema/init/init_add_member_fail_2/stderr.golden b/tests/grammar/schema/init/init_add_member_fail_2/stderr.golden similarity index 100% rename from test/grammar/schema/init/init_add_member_fail_2/stderr.golden rename to tests/grammar/schema/init/init_add_member_fail_2/stderr.golden diff --git a/test/grammar/schema/init/init_args/main.k b/tests/grammar/schema/init/init_args/main.k similarity index 100% rename from test/grammar/schema/init/init_args/main.k rename to tests/grammar/schema/init/init_args/main.k diff --git a/test/grammar/schema/init/init_args/stdout.golden b/tests/grammar/schema/init/init_args/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_args/stdout.golden rename to tests/grammar/schema/init/init_args/stdout.golden diff --git a/test/grammar/schema/init/init_args_0/main.k b/tests/grammar/schema/init/init_args_0/main.k similarity index 100% rename from test/grammar/schema/init/init_args_0/main.k rename to tests/grammar/schema/init/init_args_0/main.k diff --git a/test/grammar/schema/init/init_args_0/stdout.golden b/tests/grammar/schema/init/init_args_0/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_args_0/stdout.golden rename to tests/grammar/schema/init/init_args_0/stdout.golden diff --git a/test/grammar/schema/init/init_args_1/main.k b/tests/grammar/schema/init/init_args_1/main.k similarity index 100% rename from test/grammar/schema/init/init_args_1/main.k rename to tests/grammar/schema/init/init_args_1/main.k diff --git a/test/grammar/schema/init/init_args_1/stdout.golden b/tests/grammar/schema/init/init_args_1/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_args_1/stdout.golden rename to tests/grammar/schema/init/init_args_1/stdout.golden diff --git a/test/grammar/schema/init/init_args_2/main.k b/tests/grammar/schema/init/init_args_2/main.k similarity index 100% rename from test/grammar/schema/init/init_args_2/main.k rename to tests/grammar/schema/init/init_args_2/main.k diff --git a/test/grammar/schema/init/init_args_2/stdout.golden b/tests/grammar/schema/init/init_args_2/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_args_2/stdout.golden rename to tests/grammar/schema/init/init_args_2/stdout.golden diff --git a/test/grammar/schema/init/init_args_3/main.k b/tests/grammar/schema/init/init_args_3/main.k similarity index 100% rename from test/grammar/schema/init/init_args_3/main.k rename to tests/grammar/schema/init/init_args_3/main.k diff --git a/test/grammar/schema/init/init_args_3/stdout.golden b/tests/grammar/schema/init/init_args_3/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_args_3/stdout.golden rename to tests/grammar/schema/init/init_args_3/stdout.golden diff --git a/test/grammar/schema/init/init_assign/main.k b/tests/grammar/schema/init/init_assign/main.k similarity index 100% rename from test/grammar/schema/init/init_assign/main.k rename to tests/grammar/schema/init/init_assign/main.k diff --git a/test/grammar/schema/init/init_assign/stdout.golden b/tests/grammar/schema/init/init_assign/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_assign/stdout.golden rename to tests/grammar/schema/init/init_assign/stdout.golden diff --git a/test/grammar/schema/init/init_assign_1/main.k b/tests/grammar/schema/init/init_assign_1/main.k similarity index 100% rename from test/grammar/schema/init/init_assign_1/main.k rename to tests/grammar/schema/init/init_assign_1/main.k diff --git a/test/grammar/schema/init/init_assign_1/stdout.golden b/tests/grammar/schema/init/init_assign_1/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_assign_1/stdout.golden rename to tests/grammar/schema/init/init_assign_1/stdout.golden diff --git a/test/grammar/schema/init/init_assign_2/kcl.mod b/tests/grammar/schema/init/init_assign_2/kcl.mod similarity index 100% rename from test/grammar/schema/init/init_assign_2/kcl.mod rename to tests/grammar/schema/init/init_assign_2/kcl.mod diff --git a/test/grammar/schema/init/init_assign_2/main.k b/tests/grammar/schema/init/init_assign_2/main.k similarity index 100% rename from test/grammar/schema/init/init_assign_2/main.k rename to tests/grammar/schema/init/init_assign_2/main.k diff --git a/test/grammar/schema/init/init_assign_2/pkg/name.k b/tests/grammar/schema/init/init_assign_2/pkg/name.k similarity index 100% rename from test/grammar/schema/init/init_assign_2/pkg/name.k rename to tests/grammar/schema/init/init_assign_2/pkg/name.k diff --git a/test/grammar/schema/init/init_assign_2/stdout.golden b/tests/grammar/schema/init/init_assign_2/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_assign_2/stdout.golden rename to tests/grammar/schema/init/init_assign_2/stdout.golden diff --git a/test/grammar/schema/init/init_assign_3/kcl.mod b/tests/grammar/schema/init/init_assign_3/kcl.mod similarity index 100% rename from test/grammar/schema/init/init_assign_3/kcl.mod rename to tests/grammar/schema/init/init_assign_3/kcl.mod diff --git a/test/grammar/schema/init/init_assign_3/main.k b/tests/grammar/schema/init/init_assign_3/main.k similarity index 100% rename from test/grammar/schema/init/init_assign_3/main.k rename to tests/grammar/schema/init/init_assign_3/main.k diff --git a/test/grammar/schema/init/init_assign_3/metadata/v1/object_meta.k b/tests/grammar/schema/init/init_assign_3/metadata/v1/object_meta.k similarity index 100% rename from test/grammar/schema/init/init_assign_3/metadata/v1/object_meta.k rename to tests/grammar/schema/init/init_assign_3/metadata/v1/object_meta.k diff --git a/test/grammar/schema/init/init_assign_3/mixins/subject_mixin.k b/tests/grammar/schema/init/init_assign_3/mixins/subject_mixin.k similarity index 100% rename from test/grammar/schema/init/init_assign_3/mixins/subject_mixin.k rename to tests/grammar/schema/init/init_assign_3/mixins/subject_mixin.k diff --git a/test/grammar/schema/init/init_assign_3/org/v1/scholar.k b/tests/grammar/schema/init/init_assign_3/org/v1/scholar.k similarity index 100% rename from test/grammar/schema/init/init_assign_3/org/v1/scholar.k rename to tests/grammar/schema/init/init_assign_3/org/v1/scholar.k diff --git a/test/grammar/schema/init/init_assign_3/org/v1/school.k b/tests/grammar/schema/init/init_assign_3/org/v1/school.k similarity index 100% rename from test/grammar/schema/init/init_assign_3/org/v1/school.k rename to tests/grammar/schema/init/init_assign_3/org/v1/school.k diff --git a/test/grammar/schema/init/init_assign_3/org/v1/subject.k b/tests/grammar/schema/init/init_assign_3/org/v1/subject.k similarity index 100% rename from test/grammar/schema/init/init_assign_3/org/v1/subject.k rename to tests/grammar/schema/init/init_assign_3/org/v1/subject.k diff --git a/test/grammar/schema/init/init_assign_3/person/person.k b/tests/grammar/schema/init/init_assign_3/person/person.k similarity index 100% rename from test/grammar/schema/init/init_assign_3/person/person.k rename to tests/grammar/schema/init/init_assign_3/person/person.k diff --git a/test/grammar/schema/init/init_assign_3/stdout.golden b/tests/grammar/schema/init/init_assign_3/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_assign_3/stdout.golden rename to tests/grammar/schema/init/init_assign_3/stdout.golden diff --git a/test/grammar/schema/init/init_assign_4/main.k b/tests/grammar/schema/init/init_assign_4/main.k similarity index 100% rename from test/grammar/schema/init/init_assign_4/main.k rename to tests/grammar/schema/init/init_assign_4/main.k diff --git a/test/grammar/schema/init/init_assign_4/stdout.golden b/tests/grammar/schema/init/init_assign_4/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_assign_4/stdout.golden rename to tests/grammar/schema/init/init_assign_4/stdout.golden diff --git a/test/grammar/schema/init/init_assign_5/main.k b/tests/grammar/schema/init/init_assign_5/main.k similarity index 100% rename from test/grammar/schema/init/init_assign_5/main.k rename to tests/grammar/schema/init/init_assign_5/main.k diff --git a/test/grammar/schema/init/init_assign_5/stdout.golden b/tests/grammar/schema/init/init_assign_5/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_assign_5/stdout.golden rename to tests/grammar/schema/init/init_assign_5/stdout.golden diff --git a/test/grammar/schema/init/init_cycle_fail_0/_main.k b/tests/grammar/schema/init/init_cycle_fail_0/_main.k similarity index 100% rename from test/grammar/schema/init/init_cycle_fail_0/_main.k rename to tests/grammar/schema/init/init_cycle_fail_0/_main.k diff --git a/test/grammar/schema/init/init_cycle_fail_0/stderr.golden b/tests/grammar/schema/init/init_cycle_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/init/init_cycle_fail_0/stderr.golden rename to tests/grammar/schema/init/init_cycle_fail_0/stderr.golden diff --git a/test/grammar/schema/init/init_cycle_fail_1/_main.k b/tests/grammar/schema/init/init_cycle_fail_1/_main.k similarity index 100% rename from test/grammar/schema/init/init_cycle_fail_1/_main.k rename to tests/grammar/schema/init/init_cycle_fail_1/_main.k diff --git a/test/grammar/schema/init/init_cycle_fail_1/stderr.golden b/tests/grammar/schema/init/init_cycle_fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/init/init_cycle_fail_1/stderr.golden rename to tests/grammar/schema/init/init_cycle_fail_1/stderr.golden diff --git a/test/grammar/schema/init/init_cycle_fail_2/_main.k b/tests/grammar/schema/init/init_cycle_fail_2/_main.k similarity index 100% rename from test/grammar/schema/init/init_cycle_fail_2/_main.k rename to tests/grammar/schema/init/init_cycle_fail_2/_main.k diff --git a/test/grammar/schema/init/init_cycle_fail_2/stderr.golden b/tests/grammar/schema/init/init_cycle_fail_2/stderr.golden similarity index 100% rename from test/grammar/schema/init/init_cycle_fail_2/stderr.golden rename to tests/grammar/schema/init/init_cycle_fail_2/stderr.golden diff --git a/test/grammar/schema/init/init_dict_0/main.k b/tests/grammar/schema/init/init_dict_0/main.k similarity index 100% rename from test/grammar/schema/init/init_dict_0/main.k rename to tests/grammar/schema/init/init_dict_0/main.k diff --git a/test/grammar/schema/init/init_dict_0/stdout.golden b/tests/grammar/schema/init/init_dict_0/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_dict_0/stdout.golden rename to tests/grammar/schema/init/init_dict_0/stdout.golden diff --git a/test/grammar/schema/init/init_dict_1/main.k b/tests/grammar/schema/init/init_dict_1/main.k similarity index 100% rename from test/grammar/schema/init/init_dict_1/main.k rename to tests/grammar/schema/init/init_dict_1/main.k diff --git a/test/grammar/schema/init/init_dict_1/stdout.golden b/tests/grammar/schema/init/init_dict_1/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_dict_1/stdout.golden rename to tests/grammar/schema/init/init_dict_1/stdout.golden diff --git a/test/grammar/schema/init/init_dict_fail_0/main.k b/tests/grammar/schema/init/init_dict_fail_0/main.k similarity index 100% rename from test/grammar/schema/init/init_dict_fail_0/main.k rename to tests/grammar/schema/init/init_dict_fail_0/main.k diff --git a/test/grammar/schema/init/init_dict_fail_0/stderr.golden b/tests/grammar/schema/init/init_dict_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/init/init_dict_fail_0/stderr.golden rename to tests/grammar/schema/init/init_dict_fail_0/stderr.golden diff --git a/test/grammar/schema/init/init_err_key_fail_0/main.k b/tests/grammar/schema/init/init_err_key_fail_0/main.k similarity index 100% rename from test/grammar/schema/init/init_err_key_fail_0/main.k rename to tests/grammar/schema/init/init_err_key_fail_0/main.k diff --git a/test/grammar/schema/init/init_err_key_fail_0/stderr.golden b/tests/grammar/schema/init/init_err_key_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/init/init_err_key_fail_0/stderr.golden rename to tests/grammar/schema/init/init_err_key_fail_0/stderr.golden diff --git a/test/grammar/schema/init/init_if_0/main.k b/tests/grammar/schema/init/init_if_0/main.k similarity index 100% rename from test/grammar/schema/init/init_if_0/main.k rename to tests/grammar/schema/init/init_if_0/main.k diff --git a/test/grammar/schema/init/init_if_0/stdout.golden b/tests/grammar/schema/init/init_if_0/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_if_0/stdout.golden rename to tests/grammar/schema/init/init_if_0/stdout.golden diff --git a/test/grammar/schema/init/init_if_1/main.k b/tests/grammar/schema/init/init_if_1/main.k similarity index 100% rename from test/grammar/schema/init/init_if_1/main.k rename to tests/grammar/schema/init/init_if_1/main.k diff --git a/test/grammar/schema/init/init_if_1/stdout.golden b/tests/grammar/schema/init/init_if_1/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_if_1/stdout.golden rename to tests/grammar/schema/init/init_if_1/stdout.golden diff --git a/test/grammar/schema/init/init_if_2/main.k b/tests/grammar/schema/init/init_if_2/main.k similarity index 100% rename from test/grammar/schema/init/init_if_2/main.k rename to tests/grammar/schema/init/init_if_2/main.k diff --git a/test/grammar/schema/init/init_if_2/stdout.golden b/tests/grammar/schema/init/init_if_2/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_if_2/stdout.golden rename to tests/grammar/schema/init/init_if_2/stdout.golden diff --git a/test/grammar/schema/init/init_if_3/main.k b/tests/grammar/schema/init/init_if_3/main.k similarity index 100% rename from test/grammar/schema/init/init_if_3/main.k rename to tests/grammar/schema/init/init_if_3/main.k diff --git a/test/grammar/schema/init/init_if_3/stdout.golden b/tests/grammar/schema/init/init_if_3/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_if_3/stdout.golden rename to tests/grammar/schema/init/init_if_3/stdout.golden diff --git a/test/grammar/schema/init/init_if_4/main.k b/tests/grammar/schema/init/init_if_4/main.k similarity index 100% rename from test/grammar/schema/init/init_if_4/main.k rename to tests/grammar/schema/init/init_if_4/main.k diff --git a/test/grammar/schema/init/init_if_4/stdout.golden b/tests/grammar/schema/init/init_if_4/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_if_4/stdout.golden rename to tests/grammar/schema/init/init_if_4/stdout.golden diff --git a/test/grammar/schema/init/init_if_5/main.k b/tests/grammar/schema/init/init_if_5/main.k similarity index 100% rename from test/grammar/schema/init/init_if_5/main.k rename to tests/grammar/schema/init/init_if_5/main.k diff --git a/test/grammar/schema/init/init_if_5/stdout.golden b/tests/grammar/schema/init/init_if_5/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_if_5/stdout.golden rename to tests/grammar/schema/init/init_if_5/stdout.golden diff --git a/test/grammar/schema/init/init_if_expr_0/main.k b/tests/grammar/schema/init/init_if_expr_0/main.k similarity index 100% rename from test/grammar/schema/init/init_if_expr_0/main.k rename to tests/grammar/schema/init/init_if_expr_0/main.k diff --git a/test/grammar/schema/init/init_if_expr_0/stdout.golden b/tests/grammar/schema/init/init_if_expr_0/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_if_expr_0/stdout.golden rename to tests/grammar/schema/init/init_if_expr_0/stdout.golden diff --git a/test/grammar/schema/init/init_if_expr_1/main.k b/tests/grammar/schema/init/init_if_expr_1/main.k similarity index 100% rename from test/grammar/schema/init/init_if_expr_1/main.k rename to tests/grammar/schema/init/init_if_expr_1/main.k diff --git a/test/grammar/schema/init/init_if_expr_1/stdout.golden b/tests/grammar/schema/init/init_if_expr_1/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_if_expr_1/stdout.golden rename to tests/grammar/schema/init/init_if_expr_1/stdout.golden diff --git a/test/grammar/schema/init/init_if_nested/main.k b/tests/grammar/schema/init/init_if_nested/main.k similarity index 100% rename from test/grammar/schema/init/init_if_nested/main.k rename to tests/grammar/schema/init/init_if_nested/main.k diff --git a/test/grammar/schema/init/init_if_nested/stdout.golden b/tests/grammar/schema/init/init_if_nested/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_if_nested/stdout.golden rename to tests/grammar/schema/init/init_if_nested/stdout.golden diff --git a/test/grammar/schema/init/init_in_sub_pkg_0/kcl.mod b/tests/grammar/schema/init/init_in_sub_pkg_0/kcl.mod similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_0/kcl.mod rename to tests/grammar/schema/init/init_in_sub_pkg_0/kcl.mod diff --git a/test/grammar/schema/init/init_in_sub_pkg_0/main.k b/tests/grammar/schema/init/init_in_sub_pkg_0/main.k similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_0/main.k rename to tests/grammar/schema/init/init_in_sub_pkg_0/main.k diff --git a/test/grammar/schema/init/init_in_sub_pkg_0/pkg/person.k b/tests/grammar/schema/init/init_in_sub_pkg_0/pkg/person.k similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_0/pkg/person.k rename to tests/grammar/schema/init/init_in_sub_pkg_0/pkg/person.k diff --git a/test/grammar/schema/init/init_in_sub_pkg_0/stdout.golden b/tests/grammar/schema/init/init_in_sub_pkg_0/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_0/stdout.golden rename to tests/grammar/schema/init/init_in_sub_pkg_0/stdout.golden diff --git a/test/grammar/schema/init/init_in_sub_pkg_1/kcl.mod b/tests/grammar/schema/init/init_in_sub_pkg_1/kcl.mod similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_1/kcl.mod rename to tests/grammar/schema/init/init_in_sub_pkg_1/kcl.mod diff --git a/test/grammar/schema/init/init_in_sub_pkg_1/main.k b/tests/grammar/schema/init/init_in_sub_pkg_1/main.k similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_1/main.k rename to tests/grammar/schema/init/init_in_sub_pkg_1/main.k diff --git a/test/grammar/schema/init/init_in_sub_pkg_1/pkg/person.k b/tests/grammar/schema/init/init_in_sub_pkg_1/pkg/person.k similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_1/pkg/person.k rename to tests/grammar/schema/init/init_in_sub_pkg_1/pkg/person.k diff --git a/test/grammar/schema/init/init_in_sub_pkg_1/stdout.golden b/tests/grammar/schema/init/init_in_sub_pkg_1/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_1/stdout.golden rename to tests/grammar/schema/init/init_in_sub_pkg_1/stdout.golden diff --git a/test/grammar/schema/init/init_in_sub_pkg_2/kcl.mod b/tests/grammar/schema/init/init_in_sub_pkg_2/kcl.mod similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_2/kcl.mod rename to tests/grammar/schema/init/init_in_sub_pkg_2/kcl.mod diff --git a/test/grammar/schema/init/init_in_sub_pkg_2/main.k b/tests/grammar/schema/init/init_in_sub_pkg_2/main.k similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_2/main.k rename to tests/grammar/schema/init/init_in_sub_pkg_2/main.k diff --git a/test/grammar/schema/init/init_in_sub_pkg_2/pkg/name.k b/tests/grammar/schema/init/init_in_sub_pkg_2/pkg/name.k similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_2/pkg/name.k rename to tests/grammar/schema/init/init_in_sub_pkg_2/pkg/name.k diff --git a/test/grammar/schema/init/init_in_sub_pkg_2/pkg/person.k b/tests/grammar/schema/init/init_in_sub_pkg_2/pkg/person.k similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_2/pkg/person.k rename to tests/grammar/schema/init/init_in_sub_pkg_2/pkg/person.k diff --git a/test/grammar/schema/init/init_in_sub_pkg_2/stdout.golden b/tests/grammar/schema/init/init_in_sub_pkg_2/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_2/stdout.golden rename to tests/grammar/schema/init/init_in_sub_pkg_2/stdout.golden diff --git a/test/grammar/schema/init/init_in_sub_pkg_3/kcl.mod b/tests/grammar/schema/init/init_in_sub_pkg_3/kcl.mod similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_3/kcl.mod rename to tests/grammar/schema/init/init_in_sub_pkg_3/kcl.mod diff --git a/test/grammar/schema/init/init_in_sub_pkg_3/main.k b/tests/grammar/schema/init/init_in_sub_pkg_3/main.k similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_3/main.k rename to tests/grammar/schema/init/init_in_sub_pkg_3/main.k diff --git a/test/grammar/schema/init/init_in_sub_pkg_3/pkg1/person.k b/tests/grammar/schema/init/init_in_sub_pkg_3/pkg1/person.k similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_3/pkg1/person.k rename to tests/grammar/schema/init/init_in_sub_pkg_3/pkg1/person.k diff --git a/test/grammar/schema/init/init_in_sub_pkg_3/pkg2/name.k b/tests/grammar/schema/init/init_in_sub_pkg_3/pkg2/name.k similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_3/pkg2/name.k rename to tests/grammar/schema/init/init_in_sub_pkg_3/pkg2/name.k diff --git a/test/grammar/schema/init/init_in_sub_pkg_3/stdout.golden b/tests/grammar/schema/init/init_in_sub_pkg_3/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_in_sub_pkg_3/stdout.golden rename to tests/grammar/schema/init/init_in_sub_pkg_3/stdout.golden diff --git a/test/grammar/schema/init/init_inherit_check/main.k b/tests/grammar/schema/init/init_inherit_check/main.k similarity index 100% rename from test/grammar/schema/init/init_inherit_check/main.k rename to tests/grammar/schema/init/init_inherit_check/main.k diff --git a/test/grammar/schema/init/init_inherit_check/stdout.golden b/tests/grammar/schema/init/init_inherit_check/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_inherit_check/stdout.golden rename to tests/grammar/schema/init/init_inherit_check/stdout.golden diff --git a/test/grammar/schema/init/init_inherit_order_0/main.k b/tests/grammar/schema/init/init_inherit_order_0/main.k similarity index 100% rename from test/grammar/schema/init/init_inherit_order_0/main.k rename to tests/grammar/schema/init/init_inherit_order_0/main.k diff --git a/test/grammar/schema/init/init_inherit_order_0/stdout.golden b/tests/grammar/schema/init/init_inherit_order_0/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_inherit_order_0/stdout.golden rename to tests/grammar/schema/init/init_inherit_order_0/stdout.golden diff --git a/test/grammar/schema/init/init_inherit_order_1/main.k b/tests/grammar/schema/init/init_inherit_order_1/main.k similarity index 100% rename from test/grammar/schema/init/init_inherit_order_1/main.k rename to tests/grammar/schema/init/init_inherit_order_1/main.k diff --git a/test/grammar/schema/init/init_inherit_order_1/stdout.golden b/tests/grammar/schema/init/init_inherit_order_1/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_inherit_order_1/stdout.golden rename to tests/grammar/schema/init/init_inherit_order_1/stdout.golden diff --git a/test/grammar/schema/init/init_kwargs_0/main.k b/tests/grammar/schema/init/init_kwargs_0/main.k similarity index 100% rename from test/grammar/schema/init/init_kwargs_0/main.k rename to tests/grammar/schema/init/init_kwargs_0/main.k diff --git a/test/grammar/schema/init/init_kwargs_0/stdout.golden b/tests/grammar/schema/init/init_kwargs_0/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_kwargs_0/stdout.golden rename to tests/grammar/schema/init/init_kwargs_0/stdout.golden diff --git a/test/grammar/schema/init/init_kwargs_1/main.k b/tests/grammar/schema/init/init_kwargs_1/main.k similarity index 100% rename from test/grammar/schema/init/init_kwargs_1/main.k rename to tests/grammar/schema/init/init_kwargs_1/main.k diff --git a/test/grammar/schema/init/init_kwargs_1/stdout.golden b/tests/grammar/schema/init/init_kwargs_1/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_kwargs_1/stdout.golden rename to tests/grammar/schema/init/init_kwargs_1/stdout.golden diff --git a/test/grammar/schema/init/init_kwargs_2/main.k b/tests/grammar/schema/init/init_kwargs_2/main.k similarity index 100% rename from test/grammar/schema/init/init_kwargs_2/main.k rename to tests/grammar/schema/init/init_kwargs_2/main.k diff --git a/test/grammar/schema/init/init_kwargs_2/stdout.golden b/tests/grammar/schema/init/init_kwargs_2/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_kwargs_2/stdout.golden rename to tests/grammar/schema/init/init_kwargs_2/stdout.golden diff --git a/test/grammar/schema/init/init_kwargs_fail_0/main.k b/tests/grammar/schema/init/init_kwargs_fail_0/main.k similarity index 100% rename from test/grammar/schema/init/init_kwargs_fail_0/main.k rename to tests/grammar/schema/init/init_kwargs_fail_0/main.k diff --git a/test/grammar/schema/init/init_kwargs_fail_0/stderr.golden b/tests/grammar/schema/init/init_kwargs_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/init/init_kwargs_fail_0/stderr.golden rename to tests/grammar/schema/init/init_kwargs_fail_0/stderr.golden diff --git a/test/grammar/schema/init/init_kwargs_fail_1/main.k b/tests/grammar/schema/init/init_kwargs_fail_1/main.k similarity index 100% rename from test/grammar/schema/init/init_kwargs_fail_1/main.k rename to tests/grammar/schema/init/init_kwargs_fail_1/main.k diff --git a/test/grammar/schema/init/init_kwargs_fail_1/stderr.golden b/tests/grammar/schema/init/init_kwargs_fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/init/init_kwargs_fail_1/stderr.golden rename to tests/grammar/schema/init/init_kwargs_fail_1/stderr.golden diff --git a/test/grammar/schema/init/init_local_variable_0/main.k b/tests/grammar/schema/init/init_local_variable_0/main.k similarity index 100% rename from test/grammar/schema/init/init_local_variable_0/main.k rename to tests/grammar/schema/init/init_local_variable_0/main.k diff --git a/test/grammar/schema/init/init_local_variable_0/stdout.golden b/tests/grammar/schema/init/init_local_variable_0/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_local_variable_0/stdout.golden rename to tests/grammar/schema/init/init_local_variable_0/stdout.golden diff --git a/test/grammar/schema/init/init_local_variable_1/main.k b/tests/grammar/schema/init/init_local_variable_1/main.k similarity index 100% rename from test/grammar/schema/init/init_local_variable_1/main.k rename to tests/grammar/schema/init/init_local_variable_1/main.k diff --git a/test/grammar/schema/init/init_local_variable_1/stdout.golden b/tests/grammar/schema/init/init_local_variable_1/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_local_variable_1/stdout.golden rename to tests/grammar/schema/init/init_local_variable_1/stdout.golden diff --git a/test/grammar/schema/init/init_nested_schema_0/main.k b/tests/grammar/schema/init/init_nested_schema_0/main.k similarity index 100% rename from test/grammar/schema/init/init_nested_schema_0/main.k rename to tests/grammar/schema/init/init_nested_schema_0/main.k diff --git a/test/grammar/schema/init/init_nested_schema_0/stdout.golden b/tests/grammar/schema/init/init_nested_schema_0/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_nested_schema_0/stdout.golden rename to tests/grammar/schema/init/init_nested_schema_0/stdout.golden diff --git a/test/grammar/schema/init/init_nested_schema_1/main.k b/tests/grammar/schema/init/init_nested_schema_1/main.k similarity index 100% rename from test/grammar/schema/init/init_nested_schema_1/main.k rename to tests/grammar/schema/init/init_nested_schema_1/main.k diff --git a/test/grammar/schema/init/init_nested_schema_1/stdout.golden b/tests/grammar/schema/init/init_nested_schema_1/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_nested_schema_1/stdout.golden rename to tests/grammar/schema/init/init_nested_schema_1/stdout.golden diff --git a/test/grammar/schema/init/init_nested_schema_2/main.k b/tests/grammar/schema/init/init_nested_schema_2/main.k similarity index 100% rename from test/grammar/schema/init/init_nested_schema_2/main.k rename to tests/grammar/schema/init/init_nested_schema_2/main.k diff --git a/test/grammar/schema/init/init_nested_schema_2/stdout.golden b/tests/grammar/schema/init/init_nested_schema_2/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_nested_schema_2/stdout.golden rename to tests/grammar/schema/init/init_nested_schema_2/stdout.golden diff --git a/test/grammar/schema/init/init_option_0/main.k b/tests/grammar/schema/init/init_option_0/main.k similarity index 100% rename from test/grammar/schema/init/init_option_0/main.k rename to tests/grammar/schema/init/init_option_0/main.k diff --git a/test/grammar/schema/init/init_option_0/settings.yaml b/tests/grammar/schema/init/init_option_0/settings.yaml similarity index 100% rename from test/grammar/schema/init/init_option_0/settings.yaml rename to tests/grammar/schema/init/init_option_0/settings.yaml diff --git a/test/grammar/schema/init/init_option_0/stdout.golden b/tests/grammar/schema/init/init_option_0/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_option_0/stdout.golden rename to tests/grammar/schema/init/init_option_0/stdout.golden diff --git a/test/grammar/schema/init/init_option_1/main.k b/tests/grammar/schema/init/init_option_1/main.k similarity index 100% rename from test/grammar/schema/init/init_option_1/main.k rename to tests/grammar/schema/init/init_option_1/main.k diff --git a/test/grammar/schema/init/init_option_1/settings.yaml b/tests/grammar/schema/init/init_option_1/settings.yaml similarity index 100% rename from test/grammar/schema/init/init_option_1/settings.yaml rename to tests/grammar/schema/init/init_option_1/settings.yaml diff --git a/test/grammar/schema/init/init_option_1/stdout.golden b/tests/grammar/schema/init/init_option_1/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_option_1/stdout.golden rename to tests/grammar/schema/init/init_option_1/stdout.golden diff --git a/test/grammar/schema/init/init_outside_pkg_var_0/kcl.mod b/tests/grammar/schema/init/init_outside_pkg_var_0/kcl.mod similarity index 100% rename from test/grammar/schema/init/init_outside_pkg_var_0/kcl.mod rename to tests/grammar/schema/init/init_outside_pkg_var_0/kcl.mod diff --git a/test/grammar/schema/init/init_outside_pkg_var_0/main.k b/tests/grammar/schema/init/init_outside_pkg_var_0/main.k similarity index 100% rename from test/grammar/schema/init/init_outside_pkg_var_0/main.k rename to tests/grammar/schema/init/init_outside_pkg_var_0/main.k diff --git a/test/grammar/schema/init/init_outside_pkg_var_0/pkg/map.k b/tests/grammar/schema/init/init_outside_pkg_var_0/pkg/map.k similarity index 100% rename from test/grammar/schema/init/init_outside_pkg_var_0/pkg/map.k rename to tests/grammar/schema/init/init_outside_pkg_var_0/pkg/map.k diff --git a/test/grammar/schema/init/init_outside_pkg_var_0/stdout.golden b/tests/grammar/schema/init/init_outside_pkg_var_0/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_outside_pkg_var_0/stdout.golden rename to tests/grammar/schema/init/init_outside_pkg_var_0/stdout.golden diff --git a/test/grammar/schema/init/init_outside_pkg_var_1/kcl.mod b/tests/grammar/schema/init/init_outside_pkg_var_1/kcl.mod similarity index 100% rename from test/grammar/schema/init/init_outside_pkg_var_1/kcl.mod rename to tests/grammar/schema/init/init_outside_pkg_var_1/kcl.mod diff --git a/test/grammar/schema/init/init_outside_pkg_var_1/main.k b/tests/grammar/schema/init/init_outside_pkg_var_1/main.k similarity index 100% rename from test/grammar/schema/init/init_outside_pkg_var_1/main.k rename to tests/grammar/schema/init/init_outside_pkg_var_1/main.k diff --git a/test/grammar/schema/init/init_outside_pkg_var_1/pkg/map.k b/tests/grammar/schema/init/init_outside_pkg_var_1/pkg/map.k similarity index 100% rename from test/grammar/schema/init/init_outside_pkg_var_1/pkg/map.k rename to tests/grammar/schema/init/init_outside_pkg_var_1/pkg/map.k diff --git a/test/grammar/schema/init/init_outside_pkg_var_1/stdout.golden b/tests/grammar/schema/init/init_outside_pkg_var_1/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_outside_pkg_var_1/stdout.golden rename to tests/grammar/schema/init/init_outside_pkg_var_1/stdout.golden diff --git a/test/grammar/schema/init/init_outside_var_0/main.k b/tests/grammar/schema/init/init_outside_var_0/main.k similarity index 100% rename from test/grammar/schema/init/init_outside_var_0/main.k rename to tests/grammar/schema/init/init_outside_var_0/main.k diff --git a/test/grammar/schema/init/init_outside_var_0/stdout.golden b/tests/grammar/schema/init/init_outside_var_0/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_outside_var_0/stdout.golden rename to tests/grammar/schema/init/init_outside_var_0/stdout.golden diff --git a/test/grammar/schema/init/init_schema_0/main.k b/tests/grammar/schema/init/init_schema_0/main.k similarity index 100% rename from test/grammar/schema/init/init_schema_0/main.k rename to tests/grammar/schema/init/init_schema_0/main.k diff --git a/test/grammar/schema/init/init_schema_0/stdout.golden b/tests/grammar/schema/init/init_schema_0/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_schema_0/stdout.golden rename to tests/grammar/schema/init/init_schema_0/stdout.golden diff --git a/test/grammar/schema/init/init_schema_1/main.k b/tests/grammar/schema/init/init_schema_1/main.k similarity index 100% rename from test/grammar/schema/init/init_schema_1/main.k rename to tests/grammar/schema/init/init_schema_1/main.k diff --git a/test/grammar/schema/init/init_schema_1/stdout.golden b/tests/grammar/schema/init/init_schema_1/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_schema_1/stdout.golden rename to tests/grammar/schema/init/init_schema_1/stdout.golden diff --git a/test/grammar/schema/init/init_schema_2/main.k b/tests/grammar/schema/init/init_schema_2/main.k similarity index 100% rename from test/grammar/schema/init/init_schema_2/main.k rename to tests/grammar/schema/init/init_schema_2/main.k diff --git a/test/grammar/schema/init/init_schema_2/stdout.golden b/tests/grammar/schema/init/init_schema_2/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_schema_2/stdout.golden rename to tests/grammar/schema/init/init_schema_2/stdout.golden diff --git a/test/grammar/schema/init/init_schema_3/main.k b/tests/grammar/schema/init/init_schema_3/main.k similarity index 100% rename from test/grammar/schema/init/init_schema_3/main.k rename to tests/grammar/schema/init/init_schema_3/main.k diff --git a/test/grammar/schema/init/init_schema_3/stdout.golden b/tests/grammar/schema/init/init_schema_3/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_schema_3/stdout.golden rename to tests/grammar/schema/init/init_schema_3/stdout.golden diff --git a/test/grammar/schema/init/init_schema_4/kcl.mod b/tests/grammar/schema/init/init_schema_4/kcl.mod similarity index 100% rename from test/grammar/schema/init/init_schema_4/kcl.mod rename to tests/grammar/schema/init/init_schema_4/kcl.mod diff --git a/test/grammar/schema/init/init_schema_4/main.k b/tests/grammar/schema/init/init_schema_4/main.k similarity index 100% rename from test/grammar/schema/init/init_schema_4/main.k rename to tests/grammar/schema/init/init_schema_4/main.k diff --git a/test/grammar/schema/init/init_schema_4/pkg/inner.k b/tests/grammar/schema/init/init_schema_4/pkg/inner.k similarity index 100% rename from test/grammar/schema/init/init_schema_4/pkg/inner.k rename to tests/grammar/schema/init/init_schema_4/pkg/inner.k diff --git a/test/grammar/schema/init/init_schema_4/stdout.golden b/tests/grammar/schema/init/init_schema_4/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_schema_4/stdout.golden rename to tests/grammar/schema/init/init_schema_4/stdout.golden diff --git a/test/grammar/schema/init/init_schema_5/kcl.mod b/tests/grammar/schema/init/init_schema_5/kcl.mod similarity index 100% rename from test/grammar/schema/init/init_schema_5/kcl.mod rename to tests/grammar/schema/init/init_schema_5/kcl.mod diff --git a/test/grammar/schema/init/init_schema_5/main.k b/tests/grammar/schema/init/init_schema_5/main.k similarity index 100% rename from test/grammar/schema/init/init_schema_5/main.k rename to tests/grammar/schema/init/init_schema_5/main.k diff --git a/test/grammar/schema/init/init_schema_5/pkg/v1/inner.k b/tests/grammar/schema/init/init_schema_5/pkg/v1/inner.k similarity index 100% rename from test/grammar/schema/init/init_schema_5/pkg/v1/inner.k rename to tests/grammar/schema/init/init_schema_5/pkg/v1/inner.k diff --git a/test/grammar/schema/init/init_schema_5/stdout.golden b/tests/grammar/schema/init/init_schema_5/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_schema_5/stdout.golden rename to tests/grammar/schema/init/init_schema_5/stdout.golden diff --git a/test/grammar/schema/init/init_schema_6/main.k b/tests/grammar/schema/init/init_schema_6/main.k similarity index 100% rename from test/grammar/schema/init/init_schema_6/main.k rename to tests/grammar/schema/init/init_schema_6/main.k diff --git a/test/grammar/schema/init/init_schema_6/stdout.golden b/tests/grammar/schema/init/init_schema_6/stdout.golden similarity index 100% rename from test/grammar/schema/init/init_schema_6/stdout.golden rename to tests/grammar/schema/init/init_schema_6/stdout.golden diff --git a/test/grammar/schema/init/init_schema_fail_0/main.k b/tests/grammar/schema/init/init_schema_fail_0/main.k similarity index 100% rename from test/grammar/schema/init/init_schema_fail_0/main.k rename to tests/grammar/schema/init/init_schema_fail_0/main.k diff --git a/test/grammar/schema/init/init_schema_fail_0/stderr.golden b/tests/grammar/schema/init/init_schema_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/init/init_schema_fail_0/stderr.golden rename to tests/grammar/schema/init/init_schema_fail_0/stderr.golden diff --git a/test/grammar/schema/instances/complex/complex_0/backend.k b/tests/grammar/schema/instances/complex/complex_0/backend.k similarity index 100% rename from test/grammar/schema/instances/complex/complex_0/backend.k rename to tests/grammar/schema/instances/complex/complex_0/backend.k diff --git a/test/grammar/schema/instances/complex/complex_0/main.k b/tests/grammar/schema/instances/complex/complex_0/main.k similarity index 100% rename from test/grammar/schema/instances/complex/complex_0/main.k rename to tests/grammar/schema/instances/complex/complex_0/main.k diff --git a/test/grammar/schema/instances/complex/complex_0/settings.yaml b/tests/grammar/schema/instances/complex/complex_0/settings.yaml similarity index 100% rename from test/grammar/schema/instances/complex/complex_0/settings.yaml rename to tests/grammar/schema/instances/complex/complex_0/settings.yaml diff --git a/test/grammar/schema/instances/complex/complex_0/stdout.golden b/tests/grammar/schema/instances/complex/complex_0/stdout.golden similarity index 100% rename from test/grammar/schema/instances/complex/complex_0/stdout.golden rename to tests/grammar/schema/instances/complex/complex_0/stdout.golden diff --git a/test/grammar/schema/instances/complex/complex_1/backend.k b/tests/grammar/schema/instances/complex/complex_1/backend.k similarity index 100% rename from test/grammar/schema/instances/complex/complex_1/backend.k rename to tests/grammar/schema/instances/complex/complex_1/backend.k diff --git a/test/grammar/schema/instances/complex/complex_1/main.k b/tests/grammar/schema/instances/complex/complex_1/main.k similarity index 100% rename from test/grammar/schema/instances/complex/complex_1/main.k rename to tests/grammar/schema/instances/complex/complex_1/main.k diff --git a/test/grammar/schema/instances/complex/complex_1/settings.yaml b/tests/grammar/schema/instances/complex/complex_1/settings.yaml similarity index 100% rename from test/grammar/schema/instances/complex/complex_1/settings.yaml rename to tests/grammar/schema/instances/complex/complex_1/settings.yaml diff --git a/test/grammar/schema/instances/complex/complex_1/stdout.golden b/tests/grammar/schema/instances/complex/complex_1/stdout.golden similarity index 100% rename from test/grammar/schema/instances/complex/complex_1/stdout.golden rename to tests/grammar/schema/instances/complex/complex_1/stdout.golden diff --git a/test/grammar/schema/instances/complex/complex_2/backend.k b/tests/grammar/schema/instances/complex/complex_2/backend.k similarity index 94% rename from test/grammar/schema/instances/complex/complex_2/backend.k rename to tests/grammar/schema/instances/complex/complex_2/backend.k index 5fe279a43..20cfca856 100644 --- a/test/grammar/schema/instances/complex/complex_2/backend.k +++ b/tests/grammar/schema/instances/complex/complex_2/backend.k @@ -1,5 +1,5 @@ schema Backend: - """ existence of this attribute indicates that the model will be treated standalone by KCLVM. + """ existence of this attribute indicates that the model will be treated standalone by KCL. """ apiVersion?: str = "v1" diff --git a/test/grammar/schema/instances/complex/complex_2/main.k b/tests/grammar/schema/instances/complex/complex_2/main.k similarity index 100% rename from test/grammar/schema/instances/complex/complex_2/main.k rename to tests/grammar/schema/instances/complex/complex_2/main.k diff --git a/test/grammar/schema/instances/complex/complex_2/settings.yaml b/tests/grammar/schema/instances/complex/complex_2/settings.yaml similarity index 100% rename from test/grammar/schema/instances/complex/complex_2/settings.yaml rename to tests/grammar/schema/instances/complex/complex_2/settings.yaml diff --git a/test/grammar/schema/instances/complex/complex_2/stdout.golden b/tests/grammar/schema/instances/complex/complex_2/stdout.golden similarity index 100% rename from test/grammar/schema/instances/complex/complex_2/stdout.golden rename to tests/grammar/schema/instances/complex/complex_2/stdout.golden diff --git a/test/grammar/schema/instances/complex/complex_3/main.k b/tests/grammar/schema/instances/complex/complex_3/main.k similarity index 100% rename from test/grammar/schema/instances/complex/complex_3/main.k rename to tests/grammar/schema/instances/complex/complex_3/main.k diff --git a/test/grammar/schema/instances/complex/complex_3/stdout.golden b/tests/grammar/schema/instances/complex/complex_3/stdout.golden similarity index 100% rename from test/grammar/schema/instances/complex/complex_3/stdout.golden rename to tests/grammar/schema/instances/complex/complex_3/stdout.golden diff --git a/test/grammar/schema/instances/complex/complex_4/main.k b/tests/grammar/schema/instances/complex/complex_4/main.k similarity index 100% rename from test/grammar/schema/instances/complex/complex_4/main.k rename to tests/grammar/schema/instances/complex/complex_4/main.k diff --git a/test/grammar/schema/instances/complex/complex_4/pkg/pkg.k b/tests/grammar/schema/instances/complex/complex_4/pkg/pkg.k similarity index 100% rename from test/grammar/schema/instances/complex/complex_4/pkg/pkg.k rename to tests/grammar/schema/instances/complex/complex_4/pkg/pkg.k diff --git a/test/grammar/schema/instances/complex/complex_4/stdout.golden b/tests/grammar/schema/instances/complex/complex_4/stdout.golden similarity index 100% rename from test/grammar/schema/instances/complex/complex_4/stdout.golden rename to tests/grammar/schema/instances/complex/complex_4/stdout.golden diff --git a/test/grammar/schema/instances/complex/complex_5/main.k b/tests/grammar/schema/instances/complex/complex_5/main.k similarity index 100% rename from test/grammar/schema/instances/complex/complex_5/main.k rename to tests/grammar/schema/instances/complex/complex_5/main.k diff --git a/test/grammar/schema/instances/complex/complex_5/pkg/pkg.k b/tests/grammar/schema/instances/complex/complex_5/pkg/pkg.k similarity index 100% rename from test/grammar/schema/instances/complex/complex_5/pkg/pkg.k rename to tests/grammar/schema/instances/complex/complex_5/pkg/pkg.k diff --git a/test/grammar/schema/instances/complex/complex_5/stdout.golden b/tests/grammar/schema/instances/complex/complex_5/stdout.golden similarity index 100% rename from test/grammar/schema/instances/complex/complex_5/stdout.golden rename to tests/grammar/schema/instances/complex/complex_5/stdout.golden diff --git a/test/grammar/schema/instances/invalid/invalid_0/main.k b/tests/grammar/schema/instances/invalid/invalid_0/main.k similarity index 100% rename from test/grammar/schema/instances/invalid/invalid_0/main.k rename to tests/grammar/schema/instances/invalid/invalid_0/main.k diff --git a/test/grammar/schema/instances/invalid/invalid_0/stderr.golden b/tests/grammar/schema/instances/invalid/invalid_0/stderr.golden similarity index 100% rename from test/grammar/schema/instances/invalid/invalid_0/stderr.golden rename to tests/grammar/schema/instances/invalid/invalid_0/stderr.golden diff --git a/test/grammar/schema/instances/invalid/invalid_1/main.k b/tests/grammar/schema/instances/invalid/invalid_1/main.k similarity index 100% rename from test/grammar/schema/instances/invalid/invalid_1/main.k rename to tests/grammar/schema/instances/invalid/invalid_1/main.k diff --git a/test/grammar/schema/instances/invalid/invalid_1/stderr.golden b/tests/grammar/schema/instances/invalid/invalid_1/stderr.golden similarity index 100% rename from test/grammar/schema/instances/invalid/invalid_1/stderr.golden rename to tests/grammar/schema/instances/invalid/invalid_1/stderr.golden diff --git a/test/grammar/schema/instances/simple/simple_0/main.k b/tests/grammar/schema/instances/simple/simple_0/main.k similarity index 100% rename from test/grammar/schema/instances/simple/simple_0/main.k rename to tests/grammar/schema/instances/simple/simple_0/main.k diff --git a/test/grammar/schema/instances/simple/simple_0/stdout.golden b/tests/grammar/schema/instances/simple/simple_0/stdout.golden similarity index 100% rename from test/grammar/schema/instances/simple/simple_0/stdout.golden rename to tests/grammar/schema/instances/simple/simple_0/stdout.golden diff --git a/test/grammar/schema/instances/simple/simple_1/main.k b/tests/grammar/schema/instances/simple/simple_1/main.k similarity index 100% rename from test/grammar/schema/instances/simple/simple_1/main.k rename to tests/grammar/schema/instances/simple/simple_1/main.k diff --git a/test/grammar/schema/instances/simple/simple_1/stdout.golden b/tests/grammar/schema/instances/simple/simple_1/stdout.golden similarity index 100% rename from test/grammar/schema/instances/simple/simple_1/stdout.golden rename to tests/grammar/schema/instances/simple/simple_1/stdout.golden diff --git a/test/grammar/schema/instances/simple/simple_2/main.k b/tests/grammar/schema/instances/simple/simple_2/main.k similarity index 100% rename from test/grammar/schema/instances/simple/simple_2/main.k rename to tests/grammar/schema/instances/simple/simple_2/main.k diff --git a/test/grammar/schema/instances/simple/simple_2/stdout.golden b/tests/grammar/schema/instances/simple/simple_2/stdout.golden similarity index 100% rename from test/grammar/schema/instances/simple/simple_2/stdout.golden rename to tests/grammar/schema/instances/simple/simple_2/stdout.golden diff --git a/test/grammar/schema/instances/simple/simple_3/main.k b/tests/grammar/schema/instances/simple/simple_3/main.k similarity index 100% rename from test/grammar/schema/instances/simple/simple_3/main.k rename to tests/grammar/schema/instances/simple/simple_3/main.k diff --git a/test/grammar/schema/instances/simple/simple_3/stdout.golden b/tests/grammar/schema/instances/simple/simple_3/stdout.golden similarity index 100% rename from test/grammar/schema/instances/simple/simple_3/stdout.golden rename to tests/grammar/schema/instances/simple/simple_3/stdout.golden diff --git a/test/grammar/schema/instances/simple/simple_4/kcl.mod b/tests/grammar/schema/instances/simple/simple_4/kcl.mod similarity index 100% rename from test/grammar/schema/instances/simple/simple_4/kcl.mod rename to tests/grammar/schema/instances/simple/simple_4/kcl.mod diff --git a/test/grammar/schema/instances/simple/simple_4/main.k b/tests/grammar/schema/instances/simple/simple_4/main.k similarity index 100% rename from test/grammar/schema/instances/simple/simple_4/main.k rename to tests/grammar/schema/instances/simple/simple_4/main.k diff --git a/test/grammar/schema/instances/simple/simple_4/pkg/person.k b/tests/grammar/schema/instances/simple/simple_4/pkg/person.k similarity index 100% rename from test/grammar/schema/instances/simple/simple_4/pkg/person.k rename to tests/grammar/schema/instances/simple/simple_4/pkg/person.k diff --git a/test/grammar/schema/instances/simple/simple_4/stdout.golden b/tests/grammar/schema/instances/simple/simple_4/stdout.golden similarity index 100% rename from test/grammar/schema/instances/simple/simple_4/stdout.golden rename to tests/grammar/schema/instances/simple/simple_4/stdout.golden diff --git a/test/grammar/schema/instances/simple/simple_5/kcl.mod b/tests/grammar/schema/instances/simple/simple_5/kcl.mod similarity index 100% rename from test/grammar/schema/instances/simple/simple_5/kcl.mod rename to tests/grammar/schema/instances/simple/simple_5/kcl.mod diff --git a/test/grammar/schema/instances/simple/simple_5/main.k b/tests/grammar/schema/instances/simple/simple_5/main.k similarity index 100% rename from test/grammar/schema/instances/simple/simple_5/main.k rename to tests/grammar/schema/instances/simple/simple_5/main.k diff --git a/test/grammar/schema/instances/simple/simple_5/pkg/person.k b/tests/grammar/schema/instances/simple/simple_5/pkg/person.k similarity index 100% rename from test/grammar/schema/instances/simple/simple_5/pkg/person.k rename to tests/grammar/schema/instances/simple/simple_5/pkg/person.k diff --git a/test/grammar/schema/instances/simple/simple_5/stdout.golden b/tests/grammar/schema/instances/simple/simple_5/stdout.golden similarity index 100% rename from test/grammar/schema/instances/simple/simple_5/stdout.golden rename to tests/grammar/schema/instances/simple/simple_5/stdout.golden diff --git a/test/grammar/schema/instances/simple/simple_6/kcl.mod b/tests/grammar/schema/instances/simple/simple_6/kcl.mod similarity index 100% rename from test/grammar/schema/instances/simple/simple_6/kcl.mod rename to tests/grammar/schema/instances/simple/simple_6/kcl.mod diff --git a/test/grammar/schema/instances/simple/simple_6/main.k b/tests/grammar/schema/instances/simple/simple_6/main.k similarity index 100% rename from test/grammar/schema/instances/simple/simple_6/main.k rename to tests/grammar/schema/instances/simple/simple_6/main.k diff --git a/test/grammar/schema/instances/simple/simple_6/pkg/person.k b/tests/grammar/schema/instances/simple/simple_6/pkg/person.k similarity index 100% rename from test/grammar/schema/instances/simple/simple_6/pkg/person.k rename to tests/grammar/schema/instances/simple/simple_6/pkg/person.k diff --git a/test/grammar/schema/instances/simple/simple_6/stdout.golden b/tests/grammar/schema/instances/simple/simple_6/stdout.golden similarity index 100% rename from test/grammar/schema/instances/simple/simple_6/stdout.golden rename to tests/grammar/schema/instances/simple/simple_6/stdout.golden diff --git a/test/grammar/schema/invalid/add_attribute/main.k b/tests/grammar/schema/invalid/add_attribute/main.k similarity index 100% rename from test/grammar/schema/invalid/add_attribute/main.k rename to tests/grammar/schema/invalid/add_attribute/main.k diff --git a/test/grammar/schema/invalid/add_attribute/stderr.golden b/tests/grammar/schema/invalid/add_attribute/stderr.golden similarity index 100% rename from test/grammar/schema/invalid/add_attribute/stderr.golden rename to tests/grammar/schema/invalid/add_attribute/stderr.golden diff --git a/test/grammar/schema/invalid/add_attribute_double_star_expr/main.k b/tests/grammar/schema/invalid/add_attribute_double_star_expr/main.k similarity index 100% rename from test/grammar/schema/invalid/add_attribute_double_star_expr/main.k rename to tests/grammar/schema/invalid/add_attribute_double_star_expr/main.k diff --git a/test/grammar/schema/invalid/add_attribute_double_star_expr/stderr.golden b/tests/grammar/schema/invalid/add_attribute_double_star_expr/stderr.golden similarity index 100% rename from test/grammar/schema/invalid/add_attribute_double_star_expr/stderr.golden rename to tests/grammar/schema/invalid/add_attribute_double_star_expr/stderr.golden diff --git a/test/grammar/schema/invalid/change_field/main.k b/tests/grammar/schema/invalid/change_field/main.k similarity index 100% rename from test/grammar/schema/invalid/change_field/main.k rename to tests/grammar/schema/invalid/change_field/main.k diff --git a/test/grammar/schema/invalid/change_field/stderr.golden b/tests/grammar/schema/invalid/change_field/stderr.golden similarity index 100% rename from test/grammar/schema/invalid/change_field/stderr.golden rename to tests/grammar/schema/invalid/change_field/stderr.golden diff --git a/test/grammar/schema/invalid/no_schema/main.k b/tests/grammar/schema/invalid/no_schema/main.k similarity index 100% rename from test/grammar/schema/invalid/no_schema/main.k rename to tests/grammar/schema/invalid/no_schema/main.k diff --git a/test/grammar/schema/invalid/no_schema/stderr.golden b/tests/grammar/schema/invalid/no_schema/stderr.golden similarity index 100% rename from test/grammar/schema/invalid/no_schema/stderr.golden rename to tests/grammar/schema/invalid/no_schema/stderr.golden diff --git a/test/grammar/schema/irrelevant_order/complex_0/main.k b/tests/grammar/schema/irrelevant_order/complex_0/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/complex_0/main.k rename to tests/grammar/schema/irrelevant_order/complex_0/main.k diff --git a/test/grammar/schema/irrelevant_order/complex_0/stdout.golden b/tests/grammar/schema/irrelevant_order/complex_0/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/complex_0/stdout.golden rename to tests/grammar/schema/irrelevant_order/complex_0/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/complex_1/main.k b/tests/grammar/schema/irrelevant_order/complex_1/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/complex_1/main.k rename to tests/grammar/schema/irrelevant_order/complex_1/main.k diff --git a/test/grammar/schema/irrelevant_order/complex_1/stdout.golden b/tests/grammar/schema/irrelevant_order/complex_1/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/complex_1/stdout.golden rename to tests/grammar/schema/irrelevant_order/complex_1/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/complex_2/main.k b/tests/grammar/schema/irrelevant_order/complex_2/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/complex_2/main.k rename to tests/grammar/schema/irrelevant_order/complex_2/main.k diff --git a/test/grammar/schema/irrelevant_order/complex_2/settings.yaml b/tests/grammar/schema/irrelevant_order/complex_2/settings.yaml similarity index 100% rename from test/grammar/schema/irrelevant_order/complex_2/settings.yaml rename to tests/grammar/schema/irrelevant_order/complex_2/settings.yaml diff --git a/test/grammar/schema/irrelevant_order/complex_2/stdout.golden b/tests/grammar/schema/irrelevant_order/complex_2/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/complex_2/stdout.golden rename to tests/grammar/schema/irrelevant_order/complex_2/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/complex_3/main.k b/tests/grammar/schema/irrelevant_order/complex_3/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/complex_3/main.k rename to tests/grammar/schema/irrelevant_order/complex_3/main.k diff --git a/test/grammar/schema/irrelevant_order/complex_3/stdout.golden b/tests/grammar/schema/irrelevant_order/complex_3/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/complex_3/stdout.golden rename to tests/grammar/schema/irrelevant_order/complex_3/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/for_0/main.k b/tests/grammar/schema/irrelevant_order/for_0/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/for_0/main.k rename to tests/grammar/schema/irrelevant_order/for_0/main.k diff --git a/test/grammar/schema/irrelevant_order/for_0/stdout.golden b/tests/grammar/schema/irrelevant_order/for_0/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/for_0/stdout.golden rename to tests/grammar/schema/irrelevant_order/for_0/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/for_1/main.k b/tests/grammar/schema/irrelevant_order/for_1/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/for_1/main.k rename to tests/grammar/schema/irrelevant_order/for_1/main.k diff --git a/test/grammar/schema/irrelevant_order/for_1/stdout.golden b/tests/grammar/schema/irrelevant_order/for_1/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/for_1/stdout.golden rename to tests/grammar/schema/irrelevant_order/for_1/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/for_2/main.k b/tests/grammar/schema/irrelevant_order/for_2/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/for_2/main.k rename to tests/grammar/schema/irrelevant_order/for_2/main.k diff --git a/test/grammar/schema/irrelevant_order/for_2/stdout.golden b/tests/grammar/schema/irrelevant_order/for_2/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/for_2/stdout.golden rename to tests/grammar/schema/irrelevant_order/for_2/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/if_expr_0/main.k b/tests/grammar/schema/irrelevant_order/if_expr_0/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/if_expr_0/main.k rename to tests/grammar/schema/irrelevant_order/if_expr_0/main.k diff --git a/test/grammar/schema/irrelevant_order/if_expr_0/stdout.golden b/tests/grammar/schema/irrelevant_order/if_expr_0/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/if_expr_0/stdout.golden rename to tests/grammar/schema/irrelevant_order/if_expr_0/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/if_expr_1/main.k b/tests/grammar/schema/irrelevant_order/if_expr_1/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/if_expr_1/main.k rename to tests/grammar/schema/irrelevant_order/if_expr_1/main.k diff --git a/test/grammar/schema/irrelevant_order/if_expr_1/stdout.golden b/tests/grammar/schema/irrelevant_order/if_expr_1/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/if_expr_1/stdout.golden rename to tests/grammar/schema/irrelevant_order/if_expr_1/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/if_stmt_0/main.k b/tests/grammar/schema/irrelevant_order/if_stmt_0/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_0/main.k rename to tests/grammar/schema/irrelevant_order/if_stmt_0/main.k diff --git a/test/grammar/schema/irrelevant_order/if_stmt_0/stdout.golden b/tests/grammar/schema/irrelevant_order/if_stmt_0/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_0/stdout.golden rename to tests/grammar/schema/irrelevant_order/if_stmt_0/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/if_stmt_1/main.k b/tests/grammar/schema/irrelevant_order/if_stmt_1/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_1/main.k rename to tests/grammar/schema/irrelevant_order/if_stmt_1/main.k diff --git a/test/grammar/schema/irrelevant_order/if_stmt_1/stdout.golden b/tests/grammar/schema/irrelevant_order/if_stmt_1/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_1/stdout.golden rename to tests/grammar/schema/irrelevant_order/if_stmt_1/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/if_stmt_10/main.k b/tests/grammar/schema/irrelevant_order/if_stmt_10/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_10/main.k rename to tests/grammar/schema/irrelevant_order/if_stmt_10/main.k diff --git a/test/grammar/schema/irrelevant_order/if_stmt_10/stdout.golden b/tests/grammar/schema/irrelevant_order/if_stmt_10/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_10/stdout.golden rename to tests/grammar/schema/irrelevant_order/if_stmt_10/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/if_stmt_2/main.k b/tests/grammar/schema/irrelevant_order/if_stmt_2/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_2/main.k rename to tests/grammar/schema/irrelevant_order/if_stmt_2/main.k diff --git a/test/grammar/schema/irrelevant_order/if_stmt_2/stdout.golden b/tests/grammar/schema/irrelevant_order/if_stmt_2/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_2/stdout.golden rename to tests/grammar/schema/irrelevant_order/if_stmt_2/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/if_stmt_3/main.k b/tests/grammar/schema/irrelevant_order/if_stmt_3/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_3/main.k rename to tests/grammar/schema/irrelevant_order/if_stmt_3/main.k diff --git a/test/grammar/schema/irrelevant_order/if_stmt_3/stdout.golden b/tests/grammar/schema/irrelevant_order/if_stmt_3/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_3/stdout.golden rename to tests/grammar/schema/irrelevant_order/if_stmt_3/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/if_stmt_4/main.k b/tests/grammar/schema/irrelevant_order/if_stmt_4/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_4/main.k rename to tests/grammar/schema/irrelevant_order/if_stmt_4/main.k diff --git a/test/grammar/schema/irrelevant_order/if_stmt_4/stdout.golden b/tests/grammar/schema/irrelevant_order/if_stmt_4/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_4/stdout.golden rename to tests/grammar/schema/irrelevant_order/if_stmt_4/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/if_stmt_5/main.k b/tests/grammar/schema/irrelevant_order/if_stmt_5/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_5/main.k rename to tests/grammar/schema/irrelevant_order/if_stmt_5/main.k diff --git a/test/grammar/schema/irrelevant_order/if_stmt_5/stdout.golden b/tests/grammar/schema/irrelevant_order/if_stmt_5/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_5/stdout.golden rename to tests/grammar/schema/irrelevant_order/if_stmt_5/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/if_stmt_6/main.k b/tests/grammar/schema/irrelevant_order/if_stmt_6/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_6/main.k rename to tests/grammar/schema/irrelevant_order/if_stmt_6/main.k diff --git a/test/grammar/schema/irrelevant_order/if_stmt_6/stdout.golden b/tests/grammar/schema/irrelevant_order/if_stmt_6/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_6/stdout.golden rename to tests/grammar/schema/irrelevant_order/if_stmt_6/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/if_stmt_7/main.k b/tests/grammar/schema/irrelevant_order/if_stmt_7/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_7/main.k rename to tests/grammar/schema/irrelevant_order/if_stmt_7/main.k diff --git a/test/grammar/schema/irrelevant_order/if_stmt_7/stdout.golden b/tests/grammar/schema/irrelevant_order/if_stmt_7/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_7/stdout.golden rename to tests/grammar/schema/irrelevant_order/if_stmt_7/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/if_stmt_8/main.k b/tests/grammar/schema/irrelevant_order/if_stmt_8/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_8/main.k rename to tests/grammar/schema/irrelevant_order/if_stmt_8/main.k diff --git a/test/grammar/schema/irrelevant_order/if_stmt_8/stdout.golden b/tests/grammar/schema/irrelevant_order/if_stmt_8/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_8/stdout.golden rename to tests/grammar/schema/irrelevant_order/if_stmt_8/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/if_stmt_9/main.k b/tests/grammar/schema/irrelevant_order/if_stmt_9/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_9/main.k rename to tests/grammar/schema/irrelevant_order/if_stmt_9/main.k diff --git a/test/grammar/schema/irrelevant_order/if_stmt_9/stdout.golden b/tests/grammar/schema/irrelevant_order/if_stmt_9/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/if_stmt_9/stdout.golden rename to tests/grammar/schema/irrelevant_order/if_stmt_9/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/inherit_0/main.k b/tests/grammar/schema/irrelevant_order/inherit_0/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/inherit_0/main.k rename to tests/grammar/schema/irrelevant_order/inherit_0/main.k diff --git a/test/grammar/schema/irrelevant_order/inherit_0/stdout.golden b/tests/grammar/schema/irrelevant_order/inherit_0/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/inherit_0/stdout.golden rename to tests/grammar/schema/irrelevant_order/inherit_0/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/inherit_1/main.k b/tests/grammar/schema/irrelevant_order/inherit_1/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/inherit_1/main.k rename to tests/grammar/schema/irrelevant_order/inherit_1/main.k diff --git a/test/grammar/schema/irrelevant_order/inherit_1/stdout.golden b/tests/grammar/schema/irrelevant_order/inherit_1/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/inherit_1/stdout.golden rename to tests/grammar/schema/irrelevant_order/inherit_1/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/inherit_2/main.k b/tests/grammar/schema/irrelevant_order/inherit_2/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/inherit_2/main.k rename to tests/grammar/schema/irrelevant_order/inherit_2/main.k diff --git a/test/grammar/schema/irrelevant_order/inherit_2/stdout.golden b/tests/grammar/schema/irrelevant_order/inherit_2/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/inherit_2/stdout.golden rename to tests/grammar/schema/irrelevant_order/inherit_2/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/inherit_3/main.k b/tests/grammar/schema/irrelevant_order/inherit_3/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/inherit_3/main.k rename to tests/grammar/schema/irrelevant_order/inherit_3/main.k diff --git a/test/grammar/schema/irrelevant_order/inherit_3/stdout.golden b/tests/grammar/schema/irrelevant_order/inherit_3/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/inherit_3/stdout.golden rename to tests/grammar/schema/irrelevant_order/inherit_3/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/inherit_4/main.k b/tests/grammar/schema/irrelevant_order/inherit_4/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/inherit_4/main.k rename to tests/grammar/schema/irrelevant_order/inherit_4/main.k diff --git a/test/grammar/schema/irrelevant_order/inherit_4/stdout.golden b/tests/grammar/schema/irrelevant_order/inherit_4/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/inherit_4/stdout.golden rename to tests/grammar/schema/irrelevant_order/inherit_4/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/inherit_5/main.k b/tests/grammar/schema/irrelevant_order/inherit_5/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/inherit_5/main.k rename to tests/grammar/schema/irrelevant_order/inherit_5/main.k diff --git a/test/grammar/schema/irrelevant_order/inherit_5/stdout.golden b/tests/grammar/schema/irrelevant_order/inherit_5/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/inherit_5/stdout.golden rename to tests/grammar/schema/irrelevant_order/inherit_5/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/inherit_6/main.k b/tests/grammar/schema/irrelevant_order/inherit_6/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/inherit_6/main.k rename to tests/grammar/schema/irrelevant_order/inherit_6/main.k diff --git a/test/grammar/schema/irrelevant_order/inherit_6/stdout.golden b/tests/grammar/schema/irrelevant_order/inherit_6/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/inherit_6/stdout.golden rename to tests/grammar/schema/irrelevant_order/inherit_6/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/mixin_0/main.k b/tests/grammar/schema/irrelevant_order/mixin_0/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/mixin_0/main.k rename to tests/grammar/schema/irrelevant_order/mixin_0/main.k diff --git a/test/grammar/schema/irrelevant_order/mixin_0/stdout.golden b/tests/grammar/schema/irrelevant_order/mixin_0/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/mixin_0/stdout.golden rename to tests/grammar/schema/irrelevant_order/mixin_0/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/mixin_1/main.k b/tests/grammar/schema/irrelevant_order/mixin_1/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/mixin_1/main.k rename to tests/grammar/schema/irrelevant_order/mixin_1/main.k diff --git a/test/grammar/schema/irrelevant_order/mixin_1/stdout.golden b/tests/grammar/schema/irrelevant_order/mixin_1/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/mixin_1/stdout.golden rename to tests/grammar/schema/irrelevant_order/mixin_1/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/mixin_2/main.k b/tests/grammar/schema/irrelevant_order/mixin_2/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/mixin_2/main.k rename to tests/grammar/schema/irrelevant_order/mixin_2/main.k diff --git a/test/grammar/schema/irrelevant_order/mixin_2/stdout.golden b/tests/grammar/schema/irrelevant_order/mixin_2/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/mixin_2/stdout.golden rename to tests/grammar/schema/irrelevant_order/mixin_2/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/mixin_3/main.k b/tests/grammar/schema/irrelevant_order/mixin_3/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/mixin_3/main.k rename to tests/grammar/schema/irrelevant_order/mixin_3/main.k diff --git a/test/grammar/schema/irrelevant_order/mixin_3/stdout.golden b/tests/grammar/schema/irrelevant_order/mixin_3/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/mixin_3/stdout.golden rename to tests/grammar/schema/irrelevant_order/mixin_3/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/relaxed_0/main.k b/tests/grammar/schema/irrelevant_order/relaxed_0/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/relaxed_0/main.k rename to tests/grammar/schema/irrelevant_order/relaxed_0/main.k diff --git a/test/grammar/schema/irrelevant_order/relaxed_0/stdout.golden b/tests/grammar/schema/irrelevant_order/relaxed_0/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/relaxed_0/stdout.golden rename to tests/grammar/schema/irrelevant_order/relaxed_0/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/relaxed_1/main.k b/tests/grammar/schema/irrelevant_order/relaxed_1/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/relaxed_1/main.k rename to tests/grammar/schema/irrelevant_order/relaxed_1/main.k diff --git a/test/grammar/schema/irrelevant_order/relaxed_1/stdout.golden b/tests/grammar/schema/irrelevant_order/relaxed_1/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/relaxed_1/stdout.golden rename to tests/grammar/schema/irrelevant_order/relaxed_1/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/relaxed_2/main.k b/tests/grammar/schema/irrelevant_order/relaxed_2/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/relaxed_2/main.k rename to tests/grammar/schema/irrelevant_order/relaxed_2/main.k diff --git a/test/grammar/schema/irrelevant_order/relaxed_2/stdout.golden b/tests/grammar/schema/irrelevant_order/relaxed_2/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/relaxed_2/stdout.golden rename to tests/grammar/schema/irrelevant_order/relaxed_2/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/simple_0/main.k b/tests/grammar/schema/irrelevant_order/simple_0/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_0/main.k rename to tests/grammar/schema/irrelevant_order/simple_0/main.k diff --git a/test/grammar/schema/irrelevant_order/simple_0/stdout.golden b/tests/grammar/schema/irrelevant_order/simple_0/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_0/stdout.golden rename to tests/grammar/schema/irrelevant_order/simple_0/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/simple_1/main.k b/tests/grammar/schema/irrelevant_order/simple_1/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_1/main.k rename to tests/grammar/schema/irrelevant_order/simple_1/main.k diff --git a/test/grammar/schema/irrelevant_order/simple_1/stdout.golden b/tests/grammar/schema/irrelevant_order/simple_1/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_1/stdout.golden rename to tests/grammar/schema/irrelevant_order/simple_1/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/simple_10/main.k b/tests/grammar/schema/irrelevant_order/simple_10/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_10/main.k rename to tests/grammar/schema/irrelevant_order/simple_10/main.k diff --git a/test/grammar/schema/irrelevant_order/simple_10/stdout.golden b/tests/grammar/schema/irrelevant_order/simple_10/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_10/stdout.golden rename to tests/grammar/schema/irrelevant_order/simple_10/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/simple_11/main.k b/tests/grammar/schema/irrelevant_order/simple_11/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_11/main.k rename to tests/grammar/schema/irrelevant_order/simple_11/main.k diff --git a/test/grammar/schema/irrelevant_order/simple_11/stdout.golden b/tests/grammar/schema/irrelevant_order/simple_11/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_11/stdout.golden rename to tests/grammar/schema/irrelevant_order/simple_11/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/simple_12/main.k b/tests/grammar/schema/irrelevant_order/simple_12/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_12/main.k rename to tests/grammar/schema/irrelevant_order/simple_12/main.k diff --git a/test/grammar/schema/irrelevant_order/simple_12/stdout.golden b/tests/grammar/schema/irrelevant_order/simple_12/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_12/stdout.golden rename to tests/grammar/schema/irrelevant_order/simple_12/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/simple_2/main.k b/tests/grammar/schema/irrelevant_order/simple_2/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_2/main.k rename to tests/grammar/schema/irrelevant_order/simple_2/main.k diff --git a/test/grammar/schema/irrelevant_order/simple_2/stdout.golden b/tests/grammar/schema/irrelevant_order/simple_2/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_2/stdout.golden rename to tests/grammar/schema/irrelevant_order/simple_2/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/simple_3/main.k b/tests/grammar/schema/irrelevant_order/simple_3/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_3/main.k rename to tests/grammar/schema/irrelevant_order/simple_3/main.k diff --git a/test/grammar/schema/irrelevant_order/simple_3/stdout.golden b/tests/grammar/schema/irrelevant_order/simple_3/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_3/stdout.golden rename to tests/grammar/schema/irrelevant_order/simple_3/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/simple_4/main.k b/tests/grammar/schema/irrelevant_order/simple_4/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_4/main.k rename to tests/grammar/schema/irrelevant_order/simple_4/main.k diff --git a/test/grammar/schema/irrelevant_order/simple_4/stdout.golden b/tests/grammar/schema/irrelevant_order/simple_4/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_4/stdout.golden rename to tests/grammar/schema/irrelevant_order/simple_4/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/simple_5/main.k b/tests/grammar/schema/irrelevant_order/simple_5/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_5/main.k rename to tests/grammar/schema/irrelevant_order/simple_5/main.k diff --git a/test/grammar/schema/irrelevant_order/simple_5/stdout.golden b/tests/grammar/schema/irrelevant_order/simple_5/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_5/stdout.golden rename to tests/grammar/schema/irrelevant_order/simple_5/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/simple_6/main.k b/tests/grammar/schema/irrelevant_order/simple_6/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_6/main.k rename to tests/grammar/schema/irrelevant_order/simple_6/main.k diff --git a/test/grammar/schema/irrelevant_order/simple_6/stdout.golden b/tests/grammar/schema/irrelevant_order/simple_6/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_6/stdout.golden rename to tests/grammar/schema/irrelevant_order/simple_6/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/simple_7/main.k b/tests/grammar/schema/irrelevant_order/simple_7/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_7/main.k rename to tests/grammar/schema/irrelevant_order/simple_7/main.k diff --git a/test/grammar/schema/irrelevant_order/simple_7/stdout.golden b/tests/grammar/schema/irrelevant_order/simple_7/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_7/stdout.golden rename to tests/grammar/schema/irrelevant_order/simple_7/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/simple_8/main.k b/tests/grammar/schema/irrelevant_order/simple_8/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_8/main.k rename to tests/grammar/schema/irrelevant_order/simple_8/main.k diff --git a/test/grammar/schema/irrelevant_order/simple_8/stdout.golden b/tests/grammar/schema/irrelevant_order/simple_8/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_8/stdout.golden rename to tests/grammar/schema/irrelevant_order/simple_8/stdout.golden diff --git a/test/grammar/schema/irrelevant_order/simple_9/kcl.mod b/tests/grammar/schema/irrelevant_order/simple_9/kcl.mod similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_9/kcl.mod rename to tests/grammar/schema/irrelevant_order/simple_9/kcl.mod diff --git a/test/grammar/schema/irrelevant_order/simple_9/main.k b/tests/grammar/schema/irrelevant_order/simple_9/main.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_9/main.k rename to tests/grammar/schema/irrelevant_order/simple_9/main.k diff --git a/test/grammar/schema/irrelevant_order/simple_9/pkg/base.k b/tests/grammar/schema/irrelevant_order/simple_9/pkg/base.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_9/pkg/base.k rename to tests/grammar/schema/irrelevant_order/simple_9/pkg/base.k diff --git a/test/grammar/schema/irrelevant_order/simple_9/pkg/input.k b/tests/grammar/schema/irrelevant_order/simple_9/pkg/input.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_9/pkg/input.k rename to tests/grammar/schema/irrelevant_order/simple_9/pkg/input.k diff --git a/test/grammar/schema/irrelevant_order/simple_9/pkg/versions.k b/tests/grammar/schema/irrelevant_order/simple_9/pkg/versions.k similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_9/pkg/versions.k rename to tests/grammar/schema/irrelevant_order/simple_9/pkg/versions.k diff --git a/test/grammar/schema/irrelevant_order/simple_9/stdout.golden b/tests/grammar/schema/irrelevant_order/simple_9/stdout.golden similarity index 100% rename from test/grammar/schema/irrelevant_order/simple_9/stdout.golden rename to tests/grammar/schema/irrelevant_order/simple_9/stdout.golden diff --git a/test/grammar/schema/mixin/add_member_fail/main.k b/tests/grammar/schema/mixin/add_member_fail/main.k similarity index 100% rename from test/grammar/schema/mixin/add_member_fail/main.k rename to tests/grammar/schema/mixin/add_member_fail/main.k diff --git a/test/grammar/schema/mixin/add_member_fail/stderr.golden b/tests/grammar/schema/mixin/add_member_fail/stderr.golden similarity index 100% rename from test/grammar/schema/mixin/add_member_fail/stderr.golden rename to tests/grammar/schema/mixin/add_member_fail/stderr.golden diff --git a/test/grammar/schema/mixin/dict_2_schema_0/main.k b/tests/grammar/schema/mixin/dict_2_schema_0/main.k similarity index 100% rename from test/grammar/schema/mixin/dict_2_schema_0/main.k rename to tests/grammar/schema/mixin/dict_2_schema_0/main.k diff --git a/test/grammar/schema/mixin/dict_2_schema_0/stdout.golden b/tests/grammar/schema/mixin/dict_2_schema_0/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/dict_2_schema_0/stdout.golden rename to tests/grammar/schema/mixin/dict_2_schema_0/stdout.golden diff --git a/test/grammar/schema/mixin/dict_2_schema_1/main.k b/tests/grammar/schema/mixin/dict_2_schema_1/main.k similarity index 100% rename from test/grammar/schema/mixin/dict_2_schema_1/main.k rename to tests/grammar/schema/mixin/dict_2_schema_1/main.k diff --git a/test/grammar/schema/mixin/dict_2_schema_1/stdout.golden b/tests/grammar/schema/mixin/dict_2_schema_1/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/dict_2_schema_1/stdout.golden rename to tests/grammar/schema/mixin/dict_2_schema_1/stdout.golden diff --git a/test/grammar/schema/mixin/dict_2_schema_2/main.k b/tests/grammar/schema/mixin/dict_2_schema_2/main.k similarity index 100% rename from test/grammar/schema/mixin/dict_2_schema_2/main.k rename to tests/grammar/schema/mixin/dict_2_schema_2/main.k diff --git a/test/grammar/schema/mixin/dict_2_schema_2/stdout.golden b/tests/grammar/schema/mixin/dict_2_schema_2/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/dict_2_schema_2/stdout.golden rename to tests/grammar/schema/mixin/dict_2_schema_2/stdout.golden diff --git a/test/grammar/schema/mixin/dict_2_schema_3/kcl.mod b/tests/grammar/schema/mixin/dict_2_schema_3/kcl.mod similarity index 100% rename from test/grammar/schema/mixin/dict_2_schema_3/kcl.mod rename to tests/grammar/schema/mixin/dict_2_schema_3/kcl.mod diff --git a/test/grammar/schema/mixin/dict_2_schema_3/main.k b/tests/grammar/schema/mixin/dict_2_schema_3/main.k similarity index 100% rename from test/grammar/schema/mixin/dict_2_schema_3/main.k rename to tests/grammar/schema/mixin/dict_2_schema_3/main.k diff --git a/test/grammar/schema/mixin/dict_2_schema_3/pkg/pkg.k b/tests/grammar/schema/mixin/dict_2_schema_3/pkg/pkg.k similarity index 100% rename from test/grammar/schema/mixin/dict_2_schema_3/pkg/pkg.k rename to tests/grammar/schema/mixin/dict_2_schema_3/pkg/pkg.k diff --git a/test/grammar/schema/mixin/dict_2_schema_3/stdout.golden b/tests/grammar/schema/mixin/dict_2_schema_3/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/dict_2_schema_3/stdout.golden rename to tests/grammar/schema/mixin/dict_2_schema_3/stdout.golden diff --git a/test/grammar/schema/mixin/host-type/main.k b/tests/grammar/schema/mixin/host-type/main.k similarity index 100% rename from test/grammar/schema/mixin/host-type/main.k rename to tests/grammar/schema/mixin/host-type/main.k diff --git a/test/grammar/schema/mixin/host-type/stdout.golden b/tests/grammar/schema/mixin/host-type/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/host-type/stdout.golden rename to tests/grammar/schema/mixin/host-type/stdout.golden diff --git a/test/grammar/schema/mixin/inherit/main.k b/tests/grammar/schema/mixin/inherit/main.k similarity index 100% rename from test/grammar/schema/mixin/inherit/main.k rename to tests/grammar/schema/mixin/inherit/main.k diff --git a/test/grammar/schema/mixin/inherit/stdout.golden b/tests/grammar/schema/mixin/inherit/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/inherit/stdout.golden rename to tests/grammar/schema/mixin/inherit/stdout.golden diff --git a/test/grammar/schema/mixin/inherit_0/main.k b/tests/grammar/schema/mixin/inherit_0/main.k similarity index 100% rename from test/grammar/schema/mixin/inherit_0/main.k rename to tests/grammar/schema/mixin/inherit_0/main.k diff --git a/test/grammar/schema/mixin/inherit_0/stdout.golden b/tests/grammar/schema/mixin/inherit_0/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/inherit_0/stdout.golden rename to tests/grammar/schema/mixin/inherit_0/stdout.golden diff --git a/test/grammar/schema/mixin/inherit_1/main.k b/tests/grammar/schema/mixin/inherit_1/main.k similarity index 100% rename from test/grammar/schema/mixin/inherit_1/main.k rename to tests/grammar/schema/mixin/inherit_1/main.k diff --git a/test/grammar/schema/mixin/inherit_1/stdout.golden b/tests/grammar/schema/mixin/inherit_1/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/inherit_1/stdout.golden rename to tests/grammar/schema/mixin/inherit_1/stdout.golden diff --git a/test/grammar/schema/mixin/init_dict/main.k b/tests/grammar/schema/mixin/init_dict/main.k similarity index 100% rename from test/grammar/schema/mixin/init_dict/main.k rename to tests/grammar/schema/mixin/init_dict/main.k diff --git a/test/grammar/schema/mixin/init_dict/stdout.golden b/tests/grammar/schema/mixin/init_dict/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/init_dict/stdout.golden rename to tests/grammar/schema/mixin/init_dict/stdout.golden diff --git a/test/grammar/schema/mixin/invalid_name_failure/main.k b/tests/grammar/schema/mixin/invalid_name_failure/main.k similarity index 100% rename from test/grammar/schema/mixin/invalid_name_failure/main.k rename to tests/grammar/schema/mixin/invalid_name_failure/main.k diff --git a/test/grammar/schema/mixin/invalid_name_failure/stderr.golden b/tests/grammar/schema/mixin/invalid_name_failure/stderr.golden similarity index 100% rename from test/grammar/schema/mixin/invalid_name_failure/stderr.golden rename to tests/grammar/schema/mixin/invalid_name_failure/stderr.golden diff --git a/test/grammar/schema/mixin/multi_mixins_0/main.k b/tests/grammar/schema/mixin/multi_mixins_0/main.k similarity index 100% rename from test/grammar/schema/mixin/multi_mixins_0/main.k rename to tests/grammar/schema/mixin/multi_mixins_0/main.k diff --git a/test/grammar/schema/mixin/multi_mixins_0/stdout.golden b/tests/grammar/schema/mixin/multi_mixins_0/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/multi_mixins_0/stdout.golden rename to tests/grammar/schema/mixin/multi_mixins_0/stdout.golden diff --git a/test/grammar/schema/mixin/multi_mixins_1/main.k b/tests/grammar/schema/mixin/multi_mixins_1/main.k similarity index 100% rename from test/grammar/schema/mixin/multi_mixins_1/main.k rename to tests/grammar/schema/mixin/multi_mixins_1/main.k diff --git a/test/grammar/schema/mixin/multi_mixins_1/stdout.golden b/tests/grammar/schema/mixin/multi_mixins_1/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/multi_mixins_1/stdout.golden rename to tests/grammar/schema/mixin/multi_mixins_1/stdout.golden diff --git a/test/grammar/schema/mixin/package_mixin/kcl.mod b/tests/grammar/schema/mixin/package_mixin/kcl.mod similarity index 100% rename from test/grammar/schema/mixin/package_mixin/kcl.mod rename to tests/grammar/schema/mixin/package_mixin/kcl.mod diff --git a/test/grammar/schema/mixin/package_mixin/main.k b/tests/grammar/schema/mixin/package_mixin/main.k similarity index 100% rename from test/grammar/schema/mixin/package_mixin/main.k rename to tests/grammar/schema/mixin/package_mixin/main.k diff --git a/test/grammar/schema/mixin/package_mixin/pkg/container.k b/tests/grammar/schema/mixin/package_mixin/pkg/container.k similarity index 100% rename from test/grammar/schema/mixin/package_mixin/pkg/container.k rename to tests/grammar/schema/mixin/package_mixin/pkg/container.k diff --git a/test/grammar/schema/mixin/package_mixin/pkg/container_mixin.k b/tests/grammar/schema/mixin/package_mixin/pkg/container_mixin.k similarity index 100% rename from test/grammar/schema/mixin/package_mixin/pkg/container_mixin.k rename to tests/grammar/schema/mixin/package_mixin/pkg/container_mixin.k diff --git a/test/grammar/schema/mixin/package_mixin/stdout.golden b/tests/grammar/schema/mixin/package_mixin/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/package_mixin/stdout.golden rename to tests/grammar/schema/mixin/package_mixin/stdout.golden diff --git a/test/grammar/schema/mixin/relaxed_schema/main.k b/tests/grammar/schema/mixin/relaxed_schema/main.k similarity index 100% rename from test/grammar/schema/mixin/relaxed_schema/main.k rename to tests/grammar/schema/mixin/relaxed_schema/main.k diff --git a/test/grammar/schema/mixin/relaxed_schema/stdout.golden b/tests/grammar/schema/mixin/relaxed_schema/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/relaxed_schema/stdout.golden rename to tests/grammar/schema/mixin/relaxed_schema/stdout.golden diff --git a/test/grammar/schema/mixin/schema_field_append_list/main.k b/tests/grammar/schema/mixin/schema_field_append_list/main.k similarity index 100% rename from test/grammar/schema/mixin/schema_field_append_list/main.k rename to tests/grammar/schema/mixin/schema_field_append_list/main.k diff --git a/test/grammar/schema/mixin/schema_field_append_list/stdout.golden b/tests/grammar/schema/mixin/schema_field_append_list/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/schema_field_append_list/stdout.golden rename to tests/grammar/schema/mixin/schema_field_append_list/stdout.golden diff --git a/test/grammar/schema/mixin/schema_field_change_mixin/main.k b/tests/grammar/schema/mixin/schema_field_change_mixin/main.k similarity index 100% rename from test/grammar/schema/mixin/schema_field_change_mixin/main.k rename to tests/grammar/schema/mixin/schema_field_change_mixin/main.k diff --git a/test/grammar/schema/mixin/schema_field_change_mixin/stdout.golden b/tests/grammar/schema/mixin/schema_field_change_mixin/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/schema_field_change_mixin/stdout.golden rename to tests/grammar/schema/mixin/schema_field_change_mixin/stdout.golden diff --git a/test/grammar/schema/mixin/schema_field_change_private/main.k b/tests/grammar/schema/mixin/schema_field_change_private/main.k similarity index 100% rename from test/grammar/schema/mixin/schema_field_change_private/main.k rename to tests/grammar/schema/mixin/schema_field_change_private/main.k diff --git a/test/grammar/schema/mixin/schema_field_change_private/stdout.golden b/tests/grammar/schema/mixin/schema_field_change_private/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/schema_field_change_private/stdout.golden rename to tests/grammar/schema/mixin/schema_field_change_private/stdout.golden diff --git a/test/grammar/schema/mixin/simple/main.k b/tests/grammar/schema/mixin/simple/main.k similarity index 100% rename from test/grammar/schema/mixin/simple/main.k rename to tests/grammar/schema/mixin/simple/main.k diff --git a/test/grammar/schema/mixin/simple/stdout.golden b/tests/grammar/schema/mixin/simple/stdout.golden similarity index 100% rename from test/grammar/schema/mixin/simple/stdout.golden rename to tests/grammar/schema/mixin/simple/stdout.golden diff --git a/test/grammar/schema/modification/modification_0/main.k b/tests/grammar/schema/modification/modification_0/main.k similarity index 100% rename from test/grammar/schema/modification/modification_0/main.k rename to tests/grammar/schema/modification/modification_0/main.k diff --git a/test/grammar/schema/modification/modification_0/stdout.golden b/tests/grammar/schema/modification/modification_0/stdout.golden similarity index 100% rename from test/grammar/schema/modification/modification_0/stdout.golden rename to tests/grammar/schema/modification/modification_0/stdout.golden diff --git a/test/grammar/schema/modification/modification_1/main.k b/tests/grammar/schema/modification/modification_1/main.k similarity index 100% rename from test/grammar/schema/modification/modification_1/main.k rename to tests/grammar/schema/modification/modification_1/main.k diff --git a/test/grammar/schema/modification/modification_1/stdout.golden b/tests/grammar/schema/modification/modification_1/stdout.golden similarity index 100% rename from test/grammar/schema/modification/modification_1/stdout.golden rename to tests/grammar/schema/modification/modification_1/stdout.golden diff --git a/test/grammar/schema/optional_attr/fail_0/main.k b/tests/grammar/schema/optional_attr/fail_0/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_0/main.k rename to tests/grammar/schema/optional_attr/fail_0/main.k diff --git a/test/grammar/schema/optional_attr/fail_0/stderr.golden b/tests/grammar/schema/optional_attr/fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_0/stderr.golden rename to tests/grammar/schema/optional_attr/fail_0/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_1/main.k b/tests/grammar/schema/optional_attr/fail_1/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_1/main.k rename to tests/grammar/schema/optional_attr/fail_1/main.k diff --git a/test/grammar/schema/optional_attr/fail_1/stderr.golden b/tests/grammar/schema/optional_attr/fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_1/stderr.golden rename to tests/grammar/schema/optional_attr/fail_1/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_10/main.k b/tests/grammar/schema/optional_attr/fail_10/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_10/main.k rename to tests/grammar/schema/optional_attr/fail_10/main.k diff --git a/test/grammar/schema/optional_attr/fail_10/stderr.golden b/tests/grammar/schema/optional_attr/fail_10/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_10/stderr.golden rename to tests/grammar/schema/optional_attr/fail_10/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_11/main.k b/tests/grammar/schema/optional_attr/fail_11/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_11/main.k rename to tests/grammar/schema/optional_attr/fail_11/main.k diff --git a/test/grammar/schema/optional_attr/fail_11/stderr.golden b/tests/grammar/schema/optional_attr/fail_11/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_11/stderr.golden rename to tests/grammar/schema/optional_attr/fail_11/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_12/main.k b/tests/grammar/schema/optional_attr/fail_12/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_12/main.k rename to tests/grammar/schema/optional_attr/fail_12/main.k diff --git a/test/grammar/schema/optional_attr/fail_12/stderr.golden b/tests/grammar/schema/optional_attr/fail_12/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_12/stderr.golden rename to tests/grammar/schema/optional_attr/fail_12/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_13/main.k b/tests/grammar/schema/optional_attr/fail_13/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_13/main.k rename to tests/grammar/schema/optional_attr/fail_13/main.k diff --git a/test/grammar/schema/optional_attr/fail_13/stderr.golden b/tests/grammar/schema/optional_attr/fail_13/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_13/stderr.golden rename to tests/grammar/schema/optional_attr/fail_13/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_14/main.k b/tests/grammar/schema/optional_attr/fail_14/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_14/main.k rename to tests/grammar/schema/optional_attr/fail_14/main.k diff --git a/test/grammar/schema/optional_attr/fail_14/stderr.golden b/tests/grammar/schema/optional_attr/fail_14/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_14/stderr.golden rename to tests/grammar/schema/optional_attr/fail_14/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_15/main.k b/tests/grammar/schema/optional_attr/fail_15/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_15/main.k rename to tests/grammar/schema/optional_attr/fail_15/main.k diff --git a/test/grammar/schema/optional_attr/fail_15/stderr.golden b/tests/grammar/schema/optional_attr/fail_15/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_15/stderr.golden rename to tests/grammar/schema/optional_attr/fail_15/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_16/main.k b/tests/grammar/schema/optional_attr/fail_16/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_16/main.k rename to tests/grammar/schema/optional_attr/fail_16/main.k diff --git a/test/grammar/schema/optional_attr/fail_16/stderr.golden b/tests/grammar/schema/optional_attr/fail_16/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_16/stderr.golden rename to tests/grammar/schema/optional_attr/fail_16/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_17/main.k b/tests/grammar/schema/optional_attr/fail_17/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_17/main.k rename to tests/grammar/schema/optional_attr/fail_17/main.k diff --git a/test/grammar/schema/optional_attr/fail_17/stderr.golden b/tests/grammar/schema/optional_attr/fail_17/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_17/stderr.golden rename to tests/grammar/schema/optional_attr/fail_17/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_18/main.k b/tests/grammar/schema/optional_attr/fail_18/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_18/main.k rename to tests/grammar/schema/optional_attr/fail_18/main.k diff --git a/test/grammar/schema/optional_attr/fail_18/stderr.golden b/tests/grammar/schema/optional_attr/fail_18/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_18/stderr.golden rename to tests/grammar/schema/optional_attr/fail_18/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_19/main.k b/tests/grammar/schema/optional_attr/fail_19/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_19/main.k rename to tests/grammar/schema/optional_attr/fail_19/main.k diff --git a/test/grammar/schema/optional_attr/fail_19/stderr.golden b/tests/grammar/schema/optional_attr/fail_19/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_19/stderr.golden rename to tests/grammar/schema/optional_attr/fail_19/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_2/main.k b/tests/grammar/schema/optional_attr/fail_2/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_2/main.k rename to tests/grammar/schema/optional_attr/fail_2/main.k diff --git a/test/grammar/schema/optional_attr/fail_2/stderr.golden b/tests/grammar/schema/optional_attr/fail_2/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_2/stderr.golden rename to tests/grammar/schema/optional_attr/fail_2/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_20/main.k b/tests/grammar/schema/optional_attr/fail_20/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_20/main.k rename to tests/grammar/schema/optional_attr/fail_20/main.k diff --git a/test/grammar/schema/optional_attr/fail_20/stderr.golden b/tests/grammar/schema/optional_attr/fail_20/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_20/stderr.golden rename to tests/grammar/schema/optional_attr/fail_20/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_21/_main.k b/tests/grammar/schema/optional_attr/fail_21/_main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_21/_main.k rename to tests/grammar/schema/optional_attr/fail_21/_main.k diff --git a/test/grammar/schema/optional_attr/fail_21/stderr.golden b/tests/grammar/schema/optional_attr/fail_21/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_21/stderr.golden rename to tests/grammar/schema/optional_attr/fail_21/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_3/main.k b/tests/grammar/schema/optional_attr/fail_3/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_3/main.k rename to tests/grammar/schema/optional_attr/fail_3/main.k diff --git a/test/grammar/schema/optional_attr/fail_3/stderr.golden b/tests/grammar/schema/optional_attr/fail_3/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_3/stderr.golden rename to tests/grammar/schema/optional_attr/fail_3/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_4/main.k b/tests/grammar/schema/optional_attr/fail_4/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_4/main.k rename to tests/grammar/schema/optional_attr/fail_4/main.k diff --git a/test/grammar/schema/optional_attr/fail_4/stderr.golden b/tests/grammar/schema/optional_attr/fail_4/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_4/stderr.golden rename to tests/grammar/schema/optional_attr/fail_4/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_5/main.k b/tests/grammar/schema/optional_attr/fail_5/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_5/main.k rename to tests/grammar/schema/optional_attr/fail_5/main.k diff --git a/test/grammar/schema/optional_attr/fail_5/stderr.golden b/tests/grammar/schema/optional_attr/fail_5/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_5/stderr.golden rename to tests/grammar/schema/optional_attr/fail_5/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_6/main.k b/tests/grammar/schema/optional_attr/fail_6/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_6/main.k rename to tests/grammar/schema/optional_attr/fail_6/main.k diff --git a/test/grammar/schema/optional_attr/fail_6/stderr.golden b/tests/grammar/schema/optional_attr/fail_6/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_6/stderr.golden rename to tests/grammar/schema/optional_attr/fail_6/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_7/main.k b/tests/grammar/schema/optional_attr/fail_7/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_7/main.k rename to tests/grammar/schema/optional_attr/fail_7/main.k diff --git a/test/grammar/schema/optional_attr/fail_7/stderr.golden b/tests/grammar/schema/optional_attr/fail_7/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_7/stderr.golden rename to tests/grammar/schema/optional_attr/fail_7/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_8/main.k b/tests/grammar/schema/optional_attr/fail_8/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_8/main.k rename to tests/grammar/schema/optional_attr/fail_8/main.k diff --git a/test/grammar/schema/optional_attr/fail_8/stderr.golden b/tests/grammar/schema/optional_attr/fail_8/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_8/stderr.golden rename to tests/grammar/schema/optional_attr/fail_8/stderr.golden diff --git a/test/grammar/schema/optional_attr/fail_9/main.k b/tests/grammar/schema/optional_attr/fail_9/main.k similarity index 100% rename from test/grammar/schema/optional_attr/fail_9/main.k rename to tests/grammar/schema/optional_attr/fail_9/main.k diff --git a/test/grammar/schema/optional_attr/fail_9/stderr.golden b/tests/grammar/schema/optional_attr/fail_9/stderr.golden similarity index 100% rename from test/grammar/schema/optional_attr/fail_9/stderr.golden rename to tests/grammar/schema/optional_attr/fail_9/stderr.golden diff --git a/test/grammar/schema/optional_attr/inherit_0/main.k b/tests/grammar/schema/optional_attr/inherit_0/main.k similarity index 100% rename from test/grammar/schema/optional_attr/inherit_0/main.k rename to tests/grammar/schema/optional_attr/inherit_0/main.k diff --git a/test/grammar/schema/optional_attr/inherit_0/stdout.golden b/tests/grammar/schema/optional_attr/inherit_0/stdout.golden similarity index 100% rename from test/grammar/schema/optional_attr/inherit_0/stdout.golden rename to tests/grammar/schema/optional_attr/inherit_0/stdout.golden diff --git a/test/grammar/schema/optional_attr/inherit_1/main.k b/tests/grammar/schema/optional_attr/inherit_1/main.k similarity index 100% rename from test/grammar/schema/optional_attr/inherit_1/main.k rename to tests/grammar/schema/optional_attr/inherit_1/main.k diff --git a/test/grammar/schema/optional_attr/inherit_1/stdout.golden b/tests/grammar/schema/optional_attr/inherit_1/stdout.golden similarity index 100% rename from test/grammar/schema/optional_attr/inherit_1/stdout.golden rename to tests/grammar/schema/optional_attr/inherit_1/stdout.golden diff --git a/test/grammar/schema/optional_attr/inherit_2/main.k b/tests/grammar/schema/optional_attr/inherit_2/main.k similarity index 100% rename from test/grammar/schema/optional_attr/inherit_2/main.k rename to tests/grammar/schema/optional_attr/inherit_2/main.k diff --git a/test/grammar/schema/optional_attr/inherit_2/stdout.golden b/tests/grammar/schema/optional_attr/inherit_2/stdout.golden similarity index 100% rename from test/grammar/schema/optional_attr/inherit_2/stdout.golden rename to tests/grammar/schema/optional_attr/inherit_2/stdout.golden diff --git a/test/grammar/schema/optional_attr/inherit_3/main.k b/tests/grammar/schema/optional_attr/inherit_3/main.k similarity index 100% rename from test/grammar/schema/optional_attr/inherit_3/main.k rename to tests/grammar/schema/optional_attr/inherit_3/main.k diff --git a/test/grammar/schema/optional_attr/inherit_3/stdout.golden b/tests/grammar/schema/optional_attr/inherit_3/stdout.golden similarity index 100% rename from test/grammar/schema/optional_attr/inherit_3/stdout.golden rename to tests/grammar/schema/optional_attr/inherit_3/stdout.golden diff --git a/test/grammar/schema/optional_attr/inherit_4/main.k b/tests/grammar/schema/optional_attr/inherit_4/main.k similarity index 100% rename from test/grammar/schema/optional_attr/inherit_4/main.k rename to tests/grammar/schema/optional_attr/inherit_4/main.k diff --git a/test/grammar/schema/optional_attr/inherit_4/stdout.golden b/tests/grammar/schema/optional_attr/inherit_4/stdout.golden similarity index 100% rename from test/grammar/schema/optional_attr/inherit_4/stdout.golden rename to tests/grammar/schema/optional_attr/inherit_4/stdout.golden diff --git a/test/grammar/schema/optional_attr/inherit_5/main.k b/tests/grammar/schema/optional_attr/inherit_5/main.k similarity index 100% rename from test/grammar/schema/optional_attr/inherit_5/main.k rename to tests/grammar/schema/optional_attr/inherit_5/main.k diff --git a/test/grammar/schema/optional_attr/inherit_5/stdout.golden b/tests/grammar/schema/optional_attr/inherit_5/stdout.golden similarity index 100% rename from test/grammar/schema/optional_attr/inherit_5/stdout.golden rename to tests/grammar/schema/optional_attr/inherit_5/stdout.golden diff --git a/test/grammar/schema/optional_attr/inherit_6/main.k b/tests/grammar/schema/optional_attr/inherit_6/main.k similarity index 100% rename from test/grammar/schema/optional_attr/inherit_6/main.k rename to tests/grammar/schema/optional_attr/inherit_6/main.k diff --git a/test/grammar/schema/optional_attr/inherit_6/stdout.golden b/tests/grammar/schema/optional_attr/inherit_6/stdout.golden similarity index 100% rename from test/grammar/schema/optional_attr/inherit_6/stdout.golden rename to tests/grammar/schema/optional_attr/inherit_6/stdout.golden diff --git a/test/grammar/schema/optional_attr/inherit_7/main.k b/tests/grammar/schema/optional_attr/inherit_7/main.k similarity index 100% rename from test/grammar/schema/optional_attr/inherit_7/main.k rename to tests/grammar/schema/optional_attr/inherit_7/main.k diff --git a/test/grammar/schema/optional_attr/inherit_7/stdout.golden b/tests/grammar/schema/optional_attr/inherit_7/stdout.golden similarity index 100% rename from test/grammar/schema/optional_attr/inherit_7/stdout.golden rename to tests/grammar/schema/optional_attr/inherit_7/stdout.golden diff --git a/test/grammar/schema/optional_attr/simple_0/main.k b/tests/grammar/schema/optional_attr/simple_0/main.k similarity index 100% rename from test/grammar/schema/optional_attr/simple_0/main.k rename to tests/grammar/schema/optional_attr/simple_0/main.k diff --git a/test/grammar/schema/optional_attr/simple_0/stdout.golden b/tests/grammar/schema/optional_attr/simple_0/stdout.golden similarity index 100% rename from test/grammar/schema/optional_attr/simple_0/stdout.golden rename to tests/grammar/schema/optional_attr/simple_0/stdout.golden diff --git a/test/grammar/schema/optional_attr/simple_1/main.k b/tests/grammar/schema/optional_attr/simple_1/main.k similarity index 100% rename from test/grammar/schema/optional_attr/simple_1/main.k rename to tests/grammar/schema/optional_attr/simple_1/main.k diff --git a/test/grammar/schema/optional_attr/simple_1/stdout.golden b/tests/grammar/schema/optional_attr/simple_1/stdout.golden similarity index 100% rename from test/grammar/schema/optional_attr/simple_1/stdout.golden rename to tests/grammar/schema/optional_attr/simple_1/stdout.golden diff --git a/test/grammar/schema/partial_eval/partial_eval_0/main.k b/tests/grammar/schema/partial_eval/partial_eval_0/main.k similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_0/main.k rename to tests/grammar/schema/partial_eval/partial_eval_0/main.k diff --git a/test/grammar/schema/partial_eval/partial_eval_0/stdout.golden b/tests/grammar/schema/partial_eval/partial_eval_0/stdout.golden similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_0/stdout.golden rename to tests/grammar/schema/partial_eval/partial_eval_0/stdout.golden diff --git a/test/grammar/schema/partial_eval/partial_eval_1/main.k b/tests/grammar/schema/partial_eval/partial_eval_1/main.k similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_1/main.k rename to tests/grammar/schema/partial_eval/partial_eval_1/main.k diff --git a/test/grammar/schema/partial_eval/partial_eval_1/stdout.golden b/tests/grammar/schema/partial_eval/partial_eval_1/stdout.golden similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_1/stdout.golden rename to tests/grammar/schema/partial_eval/partial_eval_1/stdout.golden diff --git a/test/grammar/schema/partial_eval/partial_eval_2/main.k b/tests/grammar/schema/partial_eval/partial_eval_2/main.k similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_2/main.k rename to tests/grammar/schema/partial_eval/partial_eval_2/main.k diff --git a/test/grammar/schema/partial_eval/partial_eval_2/stdout.golden b/tests/grammar/schema/partial_eval/partial_eval_2/stdout.golden similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_2/stdout.golden rename to tests/grammar/schema/partial_eval/partial_eval_2/stdout.golden diff --git a/test/grammar/schema/partial_eval/partial_eval_3/main.k b/tests/grammar/schema/partial_eval/partial_eval_3/main.k similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_3/main.k rename to tests/grammar/schema/partial_eval/partial_eval_3/main.k diff --git a/test/grammar/schema/partial_eval/partial_eval_3/stdout.golden b/tests/grammar/schema/partial_eval/partial_eval_3/stdout.golden similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_3/stdout.golden rename to tests/grammar/schema/partial_eval/partial_eval_3/stdout.golden diff --git a/test/grammar/schema/partial_eval/partial_eval_4/main.k b/tests/grammar/schema/partial_eval/partial_eval_4/main.k similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_4/main.k rename to tests/grammar/schema/partial_eval/partial_eval_4/main.k diff --git a/test/grammar/schema/partial_eval/partial_eval_4/stdout.golden b/tests/grammar/schema/partial_eval/partial_eval_4/stdout.golden similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_4/stdout.golden rename to tests/grammar/schema/partial_eval/partial_eval_4/stdout.golden diff --git a/test/grammar/schema/partial_eval/partial_eval_5/_main.k b/tests/grammar/schema/partial_eval/partial_eval_5/_main.k similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_5/_main.k rename to tests/grammar/schema/partial_eval/partial_eval_5/_main.k diff --git a/test/grammar/schema/partial_eval/partial_eval_5/stdout.golden b/tests/grammar/schema/partial_eval/partial_eval_5/stdout.golden similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_5/stdout.golden rename to tests/grammar/schema/partial_eval/partial_eval_5/stdout.golden diff --git a/test/grammar/schema/partial_eval/partial_eval_6/main.k b/tests/grammar/schema/partial_eval/partial_eval_6/main.k similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_6/main.k rename to tests/grammar/schema/partial_eval/partial_eval_6/main.k diff --git a/test/grammar/schema/partial_eval/partial_eval_6/stdout.golden b/tests/grammar/schema/partial_eval/partial_eval_6/stdout.golden similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_6/stdout.golden rename to tests/grammar/schema/partial_eval/partial_eval_6/stdout.golden diff --git a/test/grammar/schema/partial_eval/partial_eval_7/main.k b/tests/grammar/schema/partial_eval/partial_eval_7/main.k similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_7/main.k rename to tests/grammar/schema/partial_eval/partial_eval_7/main.k diff --git a/test/grammar/schema/partial_eval/partial_eval_7/stdout.golden b/tests/grammar/schema/partial_eval/partial_eval_7/stdout.golden similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_7/stdout.golden rename to tests/grammar/schema/partial_eval/partial_eval_7/stdout.golden diff --git a/test/grammar/schema/partial_eval/partial_eval_8/main.k b/tests/grammar/schema/partial_eval/partial_eval_8/main.k similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_8/main.k rename to tests/grammar/schema/partial_eval/partial_eval_8/main.k diff --git a/test/grammar/schema/partial_eval/partial_eval_8/stdout.golden b/tests/grammar/schema/partial_eval/partial_eval_8/stdout.golden similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_8/stdout.golden rename to tests/grammar/schema/partial_eval/partial_eval_8/stdout.golden diff --git a/test/grammar/schema/partial_eval/partial_eval_fail_0/main.k b/tests/grammar/schema/partial_eval/partial_eval_fail_0/main.k similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_fail_0/main.k rename to tests/grammar/schema/partial_eval/partial_eval_fail_0/main.k diff --git a/test/grammar/schema/partial_eval/partial_eval_fail_0/stderr.golden b/tests/grammar/schema/partial_eval/partial_eval_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_fail_0/stderr.golden rename to tests/grammar/schema/partial_eval/partial_eval_fail_0/stderr.golden diff --git a/test/grammar/schema/partial_eval/partial_eval_fail_1/main.k b/tests/grammar/schema/partial_eval/partial_eval_fail_1/main.k similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_fail_1/main.k rename to tests/grammar/schema/partial_eval/partial_eval_fail_1/main.k diff --git a/test/grammar/schema/partial_eval/partial_eval_fail_1/stderr.golden b/tests/grammar/schema/partial_eval/partial_eval_fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_fail_1/stderr.golden rename to tests/grammar/schema/partial_eval/partial_eval_fail_1/stderr.golden diff --git a/test/grammar/schema/partial_eval/partial_eval_fail_2/main.k b/tests/grammar/schema/partial_eval/partial_eval_fail_2/main.k similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_fail_2/main.k rename to tests/grammar/schema/partial_eval/partial_eval_fail_2/main.k diff --git a/test/grammar/schema/partial_eval/partial_eval_fail_2/stderr.golden b/tests/grammar/schema/partial_eval/partial_eval_fail_2/stderr.golden similarity index 100% rename from test/grammar/schema/partial_eval/partial_eval_fail_2/stderr.golden rename to tests/grammar/schema/partial_eval/partial_eval_fail_2/stderr.golden diff --git a/test/grammar/schema/relaxed/complex/main.k b/tests/grammar/schema/relaxed/complex/main.k similarity index 100% rename from test/grammar/schema/relaxed/complex/main.k rename to tests/grammar/schema/relaxed/complex/main.k diff --git a/test/grammar/schema/relaxed/complex/stdout.golden b/tests/grammar/schema/relaxed/complex/stdout.golden similarity index 100% rename from test/grammar/schema/relaxed/complex/stdout.golden rename to tests/grammar/schema/relaxed/complex/stdout.golden diff --git a/test/grammar/schema/relaxed/fail_0/_main.k b/tests/grammar/schema/relaxed/fail_0/_main.k similarity index 100% rename from test/grammar/schema/relaxed/fail_0/_main.k rename to tests/grammar/schema/relaxed/fail_0/_main.k diff --git a/test/grammar/schema/relaxed/fail_0/stderr.golden b/tests/grammar/schema/relaxed/fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/relaxed/fail_0/stderr.golden rename to tests/grammar/schema/relaxed/fail_0/stderr.golden diff --git a/test/grammar/schema/relaxed/fail_1/_main.k b/tests/grammar/schema/relaxed/fail_1/_main.k similarity index 100% rename from test/grammar/schema/relaxed/fail_1/_main.k rename to tests/grammar/schema/relaxed/fail_1/_main.k diff --git a/test/grammar/schema/relaxed/fail_1/stderr.golden b/tests/grammar/schema/relaxed/fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/relaxed/fail_1/stderr.golden rename to tests/grammar/schema/relaxed/fail_1/stderr.golden diff --git a/test/grammar/schema/relaxed/simple/main.k b/tests/grammar/schema/relaxed/simple/main.k similarity index 100% rename from test/grammar/schema/relaxed/simple/main.k rename to tests/grammar/schema/relaxed/simple/main.k diff --git a/test/grammar/schema/relaxed/simple/stdout.golden b/tests/grammar/schema/relaxed/simple/stdout.golden similarity index 100% rename from test/grammar/schema/relaxed/simple/stdout.golden rename to tests/grammar/schema/relaxed/simple/stdout.golden diff --git a/test/grammar/schema/rule/fail/main.k b/tests/grammar/schema/rule/fail/main.k similarity index 100% rename from test/grammar/schema/rule/fail/main.k rename to tests/grammar/schema/rule/fail/main.k diff --git a/test/grammar/schema/rule/fail/stderr.golden b/tests/grammar/schema/rule/fail/stderr.golden similarity index 100% rename from test/grammar/schema/rule/fail/stderr.golden rename to tests/grammar/schema/rule/fail/stderr.golden diff --git a/test/grammar/schema/rule/rule_with_index_signature/main.k b/tests/grammar/schema/rule/rule_with_index_signature/main.k similarity index 100% rename from test/grammar/schema/rule/rule_with_index_signature/main.k rename to tests/grammar/schema/rule/rule_with_index_signature/main.k diff --git a/test/grammar/schema/rule/rule_with_index_signature/stdout.golden b/tests/grammar/schema/rule/rule_with_index_signature/stdout.golden similarity index 100% rename from test/grammar/schema/rule/rule_with_index_signature/stdout.golden rename to tests/grammar/schema/rule/rule_with_index_signature/stdout.golden diff --git a/test/grammar/schema/rule/simple/main.k b/tests/grammar/schema/rule/simple/main.k similarity index 100% rename from test/grammar/schema/rule/simple/main.k rename to tests/grammar/schema/rule/simple/main.k diff --git a/test/grammar/schema/rule/simple/stdout.golden b/tests/grammar/schema/rule/simple/stdout.golden similarity index 100% rename from test/grammar/schema/rule/simple/stdout.golden rename to tests/grammar/schema/rule/simple/stdout.golden diff --git a/test/grammar/schema/same_name_fail/main.k b/tests/grammar/schema/same_name_fail/main.k similarity index 100% rename from test/grammar/schema/same_name_fail/main.k rename to tests/grammar/schema/same_name_fail/main.k diff --git a/test/grammar/schema/same_name_fail/stderr.golden b/tests/grammar/schema/same_name_fail/stderr.golden similarity index 100% rename from test/grammar/schema/same_name_fail/stderr.golden rename to tests/grammar/schema/same_name_fail/stderr.golden diff --git a/test/grammar/schema/simple/main.k b/tests/grammar/schema/simple/main.k similarity index 100% rename from test/grammar/schema/simple/main.k rename to tests/grammar/schema/simple/main.k diff --git a/test/grammar/schema/simple/stdout.golden b/tests/grammar/schema/simple/stdout.golden similarity index 100% rename from test/grammar/schema/simple/stdout.golden rename to tests/grammar/schema/simple/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_0/main.k b/tests/grammar/schema/stmt_block/stmt_block_0/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_0/main.k rename to tests/grammar/schema/stmt_block/stmt_block_0/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_0/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_0/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_0/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_0/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_1/main.k b/tests/grammar/schema/stmt_block/stmt_block_1/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_1/main.k rename to tests/grammar/schema/stmt_block/stmt_block_1/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_1/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_1/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_1/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_1/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_10/main.k b/tests/grammar/schema/stmt_block/stmt_block_10/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_10/main.k rename to tests/grammar/schema/stmt_block/stmt_block_10/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_10/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_10/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_10/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_10/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_11/main.k b/tests/grammar/schema/stmt_block/stmt_block_11/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_11/main.k rename to tests/grammar/schema/stmt_block/stmt_block_11/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_11/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_11/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_11/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_11/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_12/main.k b/tests/grammar/schema/stmt_block/stmt_block_12/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_12/main.k rename to tests/grammar/schema/stmt_block/stmt_block_12/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_12/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_12/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_12/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_12/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_13/main.k b/tests/grammar/schema/stmt_block/stmt_block_13/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_13/main.k rename to tests/grammar/schema/stmt_block/stmt_block_13/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_13/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_13/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_13/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_13/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_14/main.k b/tests/grammar/schema/stmt_block/stmt_block_14/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_14/main.k rename to tests/grammar/schema/stmt_block/stmt_block_14/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_14/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_14/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_14/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_14/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_15/main.k b/tests/grammar/schema/stmt_block/stmt_block_15/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_15/main.k rename to tests/grammar/schema/stmt_block/stmt_block_15/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_15/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_15/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_15/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_15/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_16/main.k b/tests/grammar/schema/stmt_block/stmt_block_16/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_16/main.k rename to tests/grammar/schema/stmt_block/stmt_block_16/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_16/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_16/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_16/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_16/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_17/main.k b/tests/grammar/schema/stmt_block/stmt_block_17/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_17/main.k rename to tests/grammar/schema/stmt_block/stmt_block_17/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_17/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_17/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_17/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_17/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_18/main.k b/tests/grammar/schema/stmt_block/stmt_block_18/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_18/main.k rename to tests/grammar/schema/stmt_block/stmt_block_18/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_18/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_18/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_18/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_18/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_19/main.k b/tests/grammar/schema/stmt_block/stmt_block_19/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_19/main.k rename to tests/grammar/schema/stmt_block/stmt_block_19/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_19/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_19/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_19/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_19/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_2/main.k b/tests/grammar/schema/stmt_block/stmt_block_2/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_2/main.k rename to tests/grammar/schema/stmt_block/stmt_block_2/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_2/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_2/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_2/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_2/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_20/main.k b/tests/grammar/schema/stmt_block/stmt_block_20/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_20/main.k rename to tests/grammar/schema/stmt_block/stmt_block_20/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_20/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_20/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_20/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_20/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_21/main.k b/tests/grammar/schema/stmt_block/stmt_block_21/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_21/main.k rename to tests/grammar/schema/stmt_block/stmt_block_21/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_21/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_21/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_21/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_21/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_22/main.k b/tests/grammar/schema/stmt_block/stmt_block_22/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_22/main.k rename to tests/grammar/schema/stmt_block/stmt_block_22/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_22/settings.yaml b/tests/grammar/schema/stmt_block/stmt_block_22/settings.yaml similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_22/settings.yaml rename to tests/grammar/schema/stmt_block/stmt_block_22/settings.yaml diff --git a/test/grammar/schema/stmt_block/stmt_block_22/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_22/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_22/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_22/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_23/main.k b/tests/grammar/schema/stmt_block/stmt_block_23/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_23/main.k rename to tests/grammar/schema/stmt_block/stmt_block_23/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_23/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_23/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_23/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_23/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_24/main.k b/tests/grammar/schema/stmt_block/stmt_block_24/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_24/main.k rename to tests/grammar/schema/stmt_block/stmt_block_24/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_24/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_24/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_24/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_24/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_25/main.k b/tests/grammar/schema/stmt_block/stmt_block_25/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_25/main.k rename to tests/grammar/schema/stmt_block/stmt_block_25/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_25/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_25/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_25/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_25/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_26/main.k b/tests/grammar/schema/stmt_block/stmt_block_26/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_26/main.k rename to tests/grammar/schema/stmt_block/stmt_block_26/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_26/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_26/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_26/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_26/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_27/main.k b/tests/grammar/schema/stmt_block/stmt_block_27/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_27/main.k rename to tests/grammar/schema/stmt_block/stmt_block_27/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_27/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_27/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_27/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_27/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_28/main.k b/tests/grammar/schema/stmt_block/stmt_block_28/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_28/main.k rename to tests/grammar/schema/stmt_block/stmt_block_28/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_28/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_28/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_28/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_28/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_29/main.k b/tests/grammar/schema/stmt_block/stmt_block_29/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_29/main.k rename to tests/grammar/schema/stmt_block/stmt_block_29/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_29/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_29/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_29/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_29/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_3/main.k b/tests/grammar/schema/stmt_block/stmt_block_3/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_3/main.k rename to tests/grammar/schema/stmt_block/stmt_block_3/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_3/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_3/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_3/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_3/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_30/main.k b/tests/grammar/schema/stmt_block/stmt_block_30/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_30/main.k rename to tests/grammar/schema/stmt_block/stmt_block_30/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_30/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_30/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_30/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_30/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_31/main.k b/tests/grammar/schema/stmt_block/stmt_block_31/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_31/main.k rename to tests/grammar/schema/stmt_block/stmt_block_31/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_31/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_31/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_31/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_31/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_32/main.k b/tests/grammar/schema/stmt_block/stmt_block_32/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_32/main.k rename to tests/grammar/schema/stmt_block/stmt_block_32/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_32/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_32/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_32/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_32/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_33/main.k b/tests/grammar/schema/stmt_block/stmt_block_33/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_33/main.k rename to tests/grammar/schema/stmt_block/stmt_block_33/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_33/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_33/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_33/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_33/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_34/main.k b/tests/grammar/schema/stmt_block/stmt_block_34/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_34/main.k rename to tests/grammar/schema/stmt_block/stmt_block_34/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_34/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_34/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_34/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_34/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_4/main.k b/tests/grammar/schema/stmt_block/stmt_block_4/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_4/main.k rename to tests/grammar/schema/stmt_block/stmt_block_4/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_4/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_4/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_4/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_4/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_5/main.k b/tests/grammar/schema/stmt_block/stmt_block_5/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_5/main.k rename to tests/grammar/schema/stmt_block/stmt_block_5/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_5/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_5/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_5/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_5/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_6/main.k b/tests/grammar/schema/stmt_block/stmt_block_6/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_6/main.k rename to tests/grammar/schema/stmt_block/stmt_block_6/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_6/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_6/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_6/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_6/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_7/main.k b/tests/grammar/schema/stmt_block/stmt_block_7/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_7/main.k rename to tests/grammar/schema/stmt_block/stmt_block_7/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_7/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_7/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_7/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_7/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_8/main.k b/tests/grammar/schema/stmt_block/stmt_block_8/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_8/main.k rename to tests/grammar/schema/stmt_block/stmt_block_8/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_8/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_8/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_8/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_8/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_9/main.k b/tests/grammar/schema/stmt_block/stmt_block_9/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_9/main.k rename to tests/grammar/schema/stmt_block/stmt_block_9/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_9/stdout.golden b/tests/grammar/schema/stmt_block/stmt_block_9/stdout.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_9/stdout.golden rename to tests/grammar/schema/stmt_block/stmt_block_9/stdout.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_cycle_fail_0/_main.k b/tests/grammar/schema/stmt_block/stmt_block_cycle_fail_0/_main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_cycle_fail_0/_main.k rename to tests/grammar/schema/stmt_block/stmt_block_cycle_fail_0/_main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_cycle_fail_0/stderr.golden b/tests/grammar/schema/stmt_block/stmt_block_cycle_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_cycle_fail_0/stderr.golden rename to tests/grammar/schema/stmt_block/stmt_block_cycle_fail_0/stderr.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_cycle_fail_1/_main.k b/tests/grammar/schema/stmt_block/stmt_block_cycle_fail_1/_main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_cycle_fail_1/_main.k rename to tests/grammar/schema/stmt_block/stmt_block_cycle_fail_1/_main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_cycle_fail_1/stderr.golden b/tests/grammar/schema/stmt_block/stmt_block_cycle_fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_cycle_fail_1/stderr.golden rename to tests/grammar/schema/stmt_block/stmt_block_cycle_fail_1/stderr.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_fail_0/main.k b/tests/grammar/schema/stmt_block/stmt_block_fail_0/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_fail_0/main.k rename to tests/grammar/schema/stmt_block/stmt_block_fail_0/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_fail_0/stderr.golden b/tests/grammar/schema/stmt_block/stmt_block_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_fail_0/stderr.golden rename to tests/grammar/schema/stmt_block/stmt_block_fail_0/stderr.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_fail_1/main.k b/tests/grammar/schema/stmt_block/stmt_block_fail_1/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_fail_1/main.k rename to tests/grammar/schema/stmt_block/stmt_block_fail_1/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_fail_1/stderr.golden b/tests/grammar/schema/stmt_block/stmt_block_fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_fail_1/stderr.golden rename to tests/grammar/schema/stmt_block/stmt_block_fail_1/stderr.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_fail_2/main.k b/tests/grammar/schema/stmt_block/stmt_block_fail_2/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_fail_2/main.k rename to tests/grammar/schema/stmt_block/stmt_block_fail_2/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_fail_2/stderr.golden b/tests/grammar/schema/stmt_block/stmt_block_fail_2/stderr.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_fail_2/stderr.golden rename to tests/grammar/schema/stmt_block/stmt_block_fail_2/stderr.golden diff --git a/test/grammar/schema/stmt_block/stmt_block_fail_3/main.k b/tests/grammar/schema/stmt_block/stmt_block_fail_3/main.k similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_fail_3/main.k rename to tests/grammar/schema/stmt_block/stmt_block_fail_3/main.k diff --git a/test/grammar/schema/stmt_block/stmt_block_fail_3/stderr.golden b/tests/grammar/schema/stmt_block/stmt_block_fail_3/stderr.golden similarity index 100% rename from test/grammar/schema/stmt_block/stmt_block_fail_3/stderr.golden rename to tests/grammar/schema/stmt_block/stmt_block_fail_3/stderr.golden diff --git a/test/grammar/schema/str_attr/str_attr_0/main.k b/tests/grammar/schema/str_attr/str_attr_0/main.k similarity index 100% rename from test/grammar/schema/str_attr/str_attr_0/main.k rename to tests/grammar/schema/str_attr/str_attr_0/main.k diff --git a/test/grammar/schema/str_attr/str_attr_0/stdout.golden b/tests/grammar/schema/str_attr/str_attr_0/stdout.golden similarity index 100% rename from test/grammar/schema/str_attr/str_attr_0/stdout.golden rename to tests/grammar/schema/str_attr/str_attr_0/stdout.golden diff --git a/test/grammar/schema/str_attr/str_attr_1/main.k b/tests/grammar/schema/str_attr/str_attr_1/main.k similarity index 100% rename from test/grammar/schema/str_attr/str_attr_1/main.k rename to tests/grammar/schema/str_attr/str_attr_1/main.k diff --git a/test/grammar/schema/str_attr/str_attr_1/stdout.golden b/tests/grammar/schema/str_attr/str_attr_1/stdout.golden similarity index 100% rename from test/grammar/schema/str_attr/str_attr_1/stdout.golden rename to tests/grammar/schema/str_attr/str_attr_1/stdout.golden diff --git a/test/grammar/schema/string_attr/simple_0/main.k b/tests/grammar/schema/string_attr/simple_0/main.k similarity index 100% rename from test/grammar/schema/string_attr/simple_0/main.k rename to tests/grammar/schema/string_attr/simple_0/main.k diff --git a/test/grammar/schema/string_attr/simple_0/stdout.golden b/tests/grammar/schema/string_attr/simple_0/stdout.golden similarity index 100% rename from test/grammar/schema/string_attr/simple_0/stdout.golden rename to tests/grammar/schema/string_attr/simple_0/stdout.golden diff --git a/test/grammar/schema/string_attr/simple_1/main.k b/tests/grammar/schema/string_attr/simple_1/main.k similarity index 100% rename from test/grammar/schema/string_attr/simple_1/main.k rename to tests/grammar/schema/string_attr/simple_1/main.k diff --git a/test/grammar/schema/string_attr/simple_1/stdout.golden b/tests/grammar/schema/string_attr/simple_1/stdout.golden similarity index 100% rename from test/grammar/schema/string_attr/simple_1/stdout.golden rename to tests/grammar/schema/string_attr/simple_1/stdout.golden diff --git a/test/grammar/schema/type/combination/main.k b/tests/grammar/schema/type/combination/main.k similarity index 100% rename from test/grammar/schema/type/combination/main.k rename to tests/grammar/schema/type/combination/main.k diff --git a/test/grammar/schema/type/combination/stdout.golden b/tests/grammar/schema/type/combination/stdout.golden similarity index 100% rename from test/grammar/schema/type/combination/stdout.golden rename to tests/grammar/schema/type/combination/stdout.golden diff --git a/test/grammar/schema/type/combination_1/main.k b/tests/grammar/schema/type/combination_1/main.k similarity index 100% rename from test/grammar/schema/type/combination_1/main.k rename to tests/grammar/schema/type/combination_1/main.k diff --git a/test/grammar/schema/type/combination_1/stdout.golden b/tests/grammar/schema/type/combination_1/stdout.golden similarity index 100% rename from test/grammar/schema/type/combination_1/stdout.golden rename to tests/grammar/schema/type/combination_1/stdout.golden diff --git a/test/grammar/schema/type/combination_2/main.k b/tests/grammar/schema/type/combination_2/main.k similarity index 100% rename from test/grammar/schema/type/combination_2/main.k rename to tests/grammar/schema/type/combination_2/main.k diff --git a/test/grammar/schema/type/combination_2/stdout.golden b/tests/grammar/schema/type/combination_2/stdout.golden similarity index 100% rename from test/grammar/schema/type/combination_2/stdout.golden rename to tests/grammar/schema/type/combination_2/stdout.golden diff --git a/test/grammar/schema/type/combination_3/main.k b/tests/grammar/schema/type/combination_3/main.k similarity index 100% rename from test/grammar/schema/type/combination_3/main.k rename to tests/grammar/schema/type/combination_3/main.k diff --git a/test/grammar/schema/type/combination_3/stdout.golden b/tests/grammar/schema/type/combination_3/stdout.golden similarity index 100% rename from test/grammar/schema/type/combination_3/stdout.golden rename to tests/grammar/schema/type/combination_3/stdout.golden diff --git a/test/grammar/schema/type/combination_4/main.k b/tests/grammar/schema/type/combination_4/main.k similarity index 100% rename from test/grammar/schema/type/combination_4/main.k rename to tests/grammar/schema/type/combination_4/main.k diff --git a/test/grammar/schema/type/combination_4/stdout.golden b/tests/grammar/schema/type/combination_4/stdout.golden similarity index 100% rename from test/grammar/schema/type/combination_4/stdout.golden rename to tests/grammar/schema/type/combination_4/stdout.golden diff --git a/test/grammar/schema/type/combination_5_type_fail/main.k b/tests/grammar/schema/type/combination_5_type_fail/main.k similarity index 100% rename from test/grammar/schema/type/combination_5_type_fail/main.k rename to tests/grammar/schema/type/combination_5_type_fail/main.k diff --git a/test/grammar/schema/type/combination_5_type_fail/stderr.golden b/tests/grammar/schema/type/combination_5_type_fail/stderr.golden similarity index 100% rename from test/grammar/schema/type/combination_5_type_fail/stderr.golden rename to tests/grammar/schema/type/combination_5_type_fail/stderr.golden diff --git a/test/grammar/schema/type/config_expr_index_signature_fail/main.k b/tests/grammar/schema/type/config_expr_index_signature_fail/main.k similarity index 100% rename from test/grammar/schema/type/config_expr_index_signature_fail/main.k rename to tests/grammar/schema/type/config_expr_index_signature_fail/main.k diff --git a/test/grammar/schema/type/config_expr_index_signature_fail/stderr.golden b/tests/grammar/schema/type/config_expr_index_signature_fail/stderr.golden similarity index 100% rename from test/grammar/schema/type/config_expr_index_signature_fail/stderr.golden rename to tests/grammar/schema/type/config_expr_index_signature_fail/stderr.golden diff --git a/test/grammar/schema/type/config_expr_type_fail_0/main.k b/tests/grammar/schema/type/config_expr_type_fail_0/main.k similarity index 100% rename from test/grammar/schema/type/config_expr_type_fail_0/main.k rename to tests/grammar/schema/type/config_expr_type_fail_0/main.k diff --git a/test/grammar/schema/type/config_expr_type_fail_0/stderr.golden b/tests/grammar/schema/type/config_expr_type_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/type/config_expr_type_fail_0/stderr.golden rename to tests/grammar/schema/type/config_expr_type_fail_0/stderr.golden diff --git a/test/grammar/schema/type/config_expr_type_fail_1/main.k b/tests/grammar/schema/type/config_expr_type_fail_1/main.k similarity index 100% rename from test/grammar/schema/type/config_expr_type_fail_1/main.k rename to tests/grammar/schema/type/config_expr_type_fail_1/main.k diff --git a/test/grammar/schema/type/config_expr_type_fail_1/stderr.golden b/tests/grammar/schema/type/config_expr_type_fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/type/config_expr_type_fail_1/stderr.golden rename to tests/grammar/schema/type/config_expr_type_fail_1/stderr.golden diff --git a/test/grammar/schema/type/config_expr_type_fail_2/main.k b/tests/grammar/schema/type/config_expr_type_fail_2/main.k similarity index 100% rename from test/grammar/schema/type/config_expr_type_fail_2/main.k rename to tests/grammar/schema/type/config_expr_type_fail_2/main.k diff --git a/test/grammar/schema/type/config_expr_type_fail_2/stderr.golden b/tests/grammar/schema/type/config_expr_type_fail_2/stderr.golden similarity index 100% rename from test/grammar/schema/type/config_expr_type_fail_2/stderr.golden rename to tests/grammar/schema/type/config_expr_type_fail_2/stderr.golden diff --git a/test/grammar/schema/type/config_expr_type_fail_3/main.k b/tests/grammar/schema/type/config_expr_type_fail_3/main.k similarity index 100% rename from test/grammar/schema/type/config_expr_type_fail_3/main.k rename to tests/grammar/schema/type/config_expr_type_fail_3/main.k diff --git a/test/grammar/schema/type/config_expr_type_fail_3/stderr.golden b/tests/grammar/schema/type/config_expr_type_fail_3/stderr.golden similarity index 100% rename from test/grammar/schema/type/config_expr_type_fail_3/stderr.golden rename to tests/grammar/schema/type/config_expr_type_fail_3/stderr.golden diff --git a/test/grammar/schema/type/dict_0/main.k b/tests/grammar/schema/type/dict_0/main.k similarity index 100% rename from test/grammar/schema/type/dict_0/main.k rename to tests/grammar/schema/type/dict_0/main.k diff --git a/test/grammar/schema/type/dict_0/stdout.golden b/tests/grammar/schema/type/dict_0/stdout.golden similarity index 100% rename from test/grammar/schema/type/dict_0/stdout.golden rename to tests/grammar/schema/type/dict_0/stdout.golden diff --git a/test/grammar/schema/type/dict_1/main.k b/tests/grammar/schema/type/dict_1/main.k similarity index 100% rename from test/grammar/schema/type/dict_1/main.k rename to tests/grammar/schema/type/dict_1/main.k diff --git a/test/grammar/schema/type/dict_1/stdout.golden b/tests/grammar/schema/type/dict_1/stdout.golden similarity index 100% rename from test/grammar/schema/type/dict_1/stdout.golden rename to tests/grammar/schema/type/dict_1/stdout.golden diff --git a/test/grammar/schema/type/dict_2/main.k b/tests/grammar/schema/type/dict_2/main.k similarity index 100% rename from test/grammar/schema/type/dict_2/main.k rename to tests/grammar/schema/type/dict_2/main.k diff --git a/test/grammar/schema/type/dict_2/stdout.golden b/tests/grammar/schema/type/dict_2/stdout.golden similarity index 100% rename from test/grammar/schema/type/dict_2/stdout.golden rename to tests/grammar/schema/type/dict_2/stdout.golden diff --git a/test/grammar/schema/type/dict_4/main.k b/tests/grammar/schema/type/dict_4/main.k similarity index 100% rename from test/grammar/schema/type/dict_4/main.k rename to tests/grammar/schema/type/dict_4/main.k diff --git a/test/grammar/schema/type/dict_4/stdout.golden b/tests/grammar/schema/type/dict_4/stdout.golden similarity index 100% rename from test/grammar/schema/type/dict_4/stdout.golden rename to tests/grammar/schema/type/dict_4/stdout.golden diff --git a/test/grammar/schema/type/dict_5/main.k b/tests/grammar/schema/type/dict_5/main.k similarity index 100% rename from test/grammar/schema/type/dict_5/main.k rename to tests/grammar/schema/type/dict_5/main.k diff --git a/test/grammar/schema/type/dict_5/stdout.golden b/tests/grammar/schema/type/dict_5/stdout.golden similarity index 100% rename from test/grammar/schema/type/dict_5/stdout.golden rename to tests/grammar/schema/type/dict_5/stdout.golden diff --git a/test/grammar/schema/type/dict_6/main.k b/tests/grammar/schema/type/dict_6/main.k similarity index 100% rename from test/grammar/schema/type/dict_6/main.k rename to tests/grammar/schema/type/dict_6/main.k diff --git a/test/grammar/schema/type/dict_6/stdout.golden b/tests/grammar/schema/type/dict_6/stdout.golden similarity index 100% rename from test/grammar/schema/type/dict_6/stdout.golden rename to tests/grammar/schema/type/dict_6/stdout.golden diff --git a/test/grammar/schema/type/dict_7/main.k b/tests/grammar/schema/type/dict_7/main.k similarity index 100% rename from test/grammar/schema/type/dict_7/main.k rename to tests/grammar/schema/type/dict_7/main.k diff --git a/test/grammar/schema/type/dict_7/stdout.golden b/tests/grammar/schema/type/dict_7/stdout.golden similarity index 100% rename from test/grammar/schema/type/dict_7/stdout.golden rename to tests/grammar/schema/type/dict_7/stdout.golden diff --git a/test/grammar/schema/type/dict_8/main.k b/tests/grammar/schema/type/dict_8/main.k similarity index 100% rename from test/grammar/schema/type/dict_8/main.k rename to tests/grammar/schema/type/dict_8/main.k diff --git a/test/grammar/schema/type/dict_8/stdout.golden b/tests/grammar/schema/type/dict_8/stdout.golden similarity index 100% rename from test/grammar/schema/type/dict_8/stdout.golden rename to tests/grammar/schema/type/dict_8/stdout.golden diff --git a/test/grammar/schema/type/dict_fail_0/main.k b/tests/grammar/schema/type/dict_fail_0/main.k similarity index 100% rename from test/grammar/schema/type/dict_fail_0/main.k rename to tests/grammar/schema/type/dict_fail_0/main.k diff --git a/test/grammar/schema/type/dict_fail_0/stderr.golden b/tests/grammar/schema/type/dict_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/type/dict_fail_0/stderr.golden rename to tests/grammar/schema/type/dict_fail_0/stderr.golden diff --git a/test/grammar/schema/type/dict_nested_0/main.k b/tests/grammar/schema/type/dict_nested_0/main.k similarity index 100% rename from test/grammar/schema/type/dict_nested_0/main.k rename to tests/grammar/schema/type/dict_nested_0/main.k diff --git a/test/grammar/schema/type/dict_nested_0/stdout.golden b/tests/grammar/schema/type/dict_nested_0/stdout.golden similarity index 100% rename from test/grammar/schema/type/dict_nested_0/stdout.golden rename to tests/grammar/schema/type/dict_nested_0/stdout.golden diff --git a/test/grammar/schema/type/dict_nested_1/main.k b/tests/grammar/schema/type/dict_nested_1/main.k similarity index 100% rename from test/grammar/schema/type/dict_nested_1/main.k rename to tests/grammar/schema/type/dict_nested_1/main.k diff --git a/test/grammar/schema/type/dict_nested_1/stdout.golden b/tests/grammar/schema/type/dict_nested_1/stdout.golden similarity index 100% rename from test/grammar/schema/type/dict_nested_1/stdout.golden rename to tests/grammar/schema/type/dict_nested_1/stdout.golden diff --git a/test/grammar/schema/type/dict_nested_2/kcl.mod b/tests/grammar/schema/type/dict_nested_2/kcl.mod similarity index 100% rename from test/grammar/schema/type/dict_nested_2/kcl.mod rename to tests/grammar/schema/type/dict_nested_2/kcl.mod diff --git a/test/grammar/schema/type/dict_nested_2/main.k b/tests/grammar/schema/type/dict_nested_2/main.k similarity index 100% rename from test/grammar/schema/type/dict_nested_2/main.k rename to tests/grammar/schema/type/dict_nested_2/main.k diff --git a/test/grammar/schema/type/dict_nested_2/pkg/container.k b/tests/grammar/schema/type/dict_nested_2/pkg/container.k similarity index 100% rename from test/grammar/schema/type/dict_nested_2/pkg/container.k rename to tests/grammar/schema/type/dict_nested_2/pkg/container.k diff --git a/test/grammar/schema/type/dict_nested_2/pkg/person.k b/tests/grammar/schema/type/dict_nested_2/pkg/person.k similarity index 100% rename from test/grammar/schema/type/dict_nested_2/pkg/person.k rename to tests/grammar/schema/type/dict_nested_2/pkg/person.k diff --git a/test/grammar/schema/type/dict_nested_2/stdout.golden b/tests/grammar/schema/type/dict_nested_2/stdout.golden similarity index 100% rename from test/grammar/schema/type/dict_nested_2/stdout.golden rename to tests/grammar/schema/type/dict_nested_2/stdout.golden diff --git a/test/grammar/schema/type/dict_nested_fail_0/main.k b/tests/grammar/schema/type/dict_nested_fail_0/main.k similarity index 100% rename from test/grammar/schema/type/dict_nested_fail_0/main.k rename to tests/grammar/schema/type/dict_nested_fail_0/main.k diff --git a/test/grammar/schema/type/dict_nested_fail_0/stderr.golden b/tests/grammar/schema/type/dict_nested_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/type/dict_nested_fail_0/stderr.golden rename to tests/grammar/schema/type/dict_nested_fail_0/stderr.golden diff --git a/test/grammar/schema/type/list/main.k b/tests/grammar/schema/type/list/main.k similarity index 100% rename from test/grammar/schema/type/list/main.k rename to tests/grammar/schema/type/list/main.k diff --git a/test/grammar/schema/type/list/stdout.golden b/tests/grammar/schema/type/list/stdout.golden similarity index 100% rename from test/grammar/schema/type/list/stdout.golden rename to tests/grammar/schema/type/list/stdout.golden diff --git a/test/grammar/schema/type/list_nested_0/main.k b/tests/grammar/schema/type/list_nested_0/main.k similarity index 100% rename from test/grammar/schema/type/list_nested_0/main.k rename to tests/grammar/schema/type/list_nested_0/main.k diff --git a/test/grammar/schema/type/list_nested_0/stdout.golden b/tests/grammar/schema/type/list_nested_0/stdout.golden similarity index 100% rename from test/grammar/schema/type/list_nested_0/stdout.golden rename to tests/grammar/schema/type/list_nested_0/stdout.golden diff --git a/test/grammar/schema/type/list_nested_1/main.k b/tests/grammar/schema/type/list_nested_1/main.k similarity index 100% rename from test/grammar/schema/type/list_nested_1/main.k rename to tests/grammar/schema/type/list_nested_1/main.k diff --git a/test/grammar/schema/type/list_nested_1/stdout.golden b/tests/grammar/schema/type/list_nested_1/stdout.golden similarity index 100% rename from test/grammar/schema/type/list_nested_1/stdout.golden rename to tests/grammar/schema/type/list_nested_1/stdout.golden diff --git a/test/grammar/schema/type/list_nested_2/main.k b/tests/grammar/schema/type/list_nested_2/main.k similarity index 100% rename from test/grammar/schema/type/list_nested_2/main.k rename to tests/grammar/schema/type/list_nested_2/main.k diff --git a/test/grammar/schema/type/list_nested_2/stdout.golden b/tests/grammar/schema/type/list_nested_2/stdout.golden similarity index 100% rename from test/grammar/schema/type/list_nested_2/stdout.golden rename to tests/grammar/schema/type/list_nested_2/stdout.golden diff --git a/test/grammar/schema/type/multi_types_0/main.k b/tests/grammar/schema/type/multi_types_0/main.k similarity index 100% rename from test/grammar/schema/type/multi_types_0/main.k rename to tests/grammar/schema/type/multi_types_0/main.k diff --git a/test/grammar/schema/type/multi_types_0/stdout.golden b/tests/grammar/schema/type/multi_types_0/stdout.golden similarity index 100% rename from test/grammar/schema/type/multi_types_0/stdout.golden rename to tests/grammar/schema/type/multi_types_0/stdout.golden diff --git a/test/grammar/schema/type/multi_types_1/main.k b/tests/grammar/schema/type/multi_types_1/main.k similarity index 100% rename from test/grammar/schema/type/multi_types_1/main.k rename to tests/grammar/schema/type/multi_types_1/main.k diff --git a/test/grammar/schema/type/multi_types_1/stderr.golden b/tests/grammar/schema/type/multi_types_1/stderr.golden similarity index 100% rename from test/grammar/schema/type/multi_types_1/stderr.golden rename to tests/grammar/schema/type/multi_types_1/stderr.golden diff --git a/test/grammar/schema/type/multi_types_2/main.k b/tests/grammar/schema/type/multi_types_2/main.k similarity index 100% rename from test/grammar/schema/type/multi_types_2/main.k rename to tests/grammar/schema/type/multi_types_2/main.k diff --git a/test/grammar/schema/type/multi_types_2/stdout.golden b/tests/grammar/schema/type/multi_types_2/stdout.golden similarity index 100% rename from test/grammar/schema/type/multi_types_2/stdout.golden rename to tests/grammar/schema/type/multi_types_2/stdout.golden diff --git a/test/grammar/schema/type/multi_types_3/main.k b/tests/grammar/schema/type/multi_types_3/main.k similarity index 100% rename from test/grammar/schema/type/multi_types_3/main.k rename to tests/grammar/schema/type/multi_types_3/main.k diff --git a/test/grammar/schema/type/multi_types_3/stdout.golden b/tests/grammar/schema/type/multi_types_3/stdout.golden similarity index 100% rename from test/grammar/schema/type/multi_types_3/stdout.golden rename to tests/grammar/schema/type/multi_types_3/stdout.golden diff --git a/test/grammar/schema/type/multi_types_4/main.k b/tests/grammar/schema/type/multi_types_4/main.k similarity index 100% rename from test/grammar/schema/type/multi_types_4/main.k rename to tests/grammar/schema/type/multi_types_4/main.k diff --git a/test/grammar/schema/type/multi_types_4/stdout.golden b/tests/grammar/schema/type/multi_types_4/stdout.golden similarity index 100% rename from test/grammar/schema/type/multi_types_4/stdout.golden rename to tests/grammar/schema/type/multi_types_4/stdout.golden diff --git a/test/grammar/schema/type/multi_types_5/main.k b/tests/grammar/schema/type/multi_types_5/main.k similarity index 100% rename from test/grammar/schema/type/multi_types_5/main.k rename to tests/grammar/schema/type/multi_types_5/main.k diff --git a/test/grammar/schema/type/multi_types_5/stdout.golden b/tests/grammar/schema/type/multi_types_5/stdout.golden similarity index 100% rename from test/grammar/schema/type/multi_types_5/stdout.golden rename to tests/grammar/schema/type/multi_types_5/stdout.golden diff --git a/test/grammar/schema/type/multi_types_6/main.k b/tests/grammar/schema/type/multi_types_6/main.k similarity index 100% rename from test/grammar/schema/type/multi_types_6/main.k rename to tests/grammar/schema/type/multi_types_6/main.k diff --git a/test/grammar/schema/type/multi_types_6/stdout.golden b/tests/grammar/schema/type/multi_types_6/stdout.golden similarity index 100% rename from test/grammar/schema/type/multi_types_6/stdout.golden rename to tests/grammar/schema/type/multi_types_6/stdout.golden diff --git a/test/grammar/schema/type/multi_types_7/main.k b/tests/grammar/schema/type/multi_types_7/main.k similarity index 100% rename from test/grammar/schema/type/multi_types_7/main.k rename to tests/grammar/schema/type/multi_types_7/main.k diff --git a/test/grammar/schema/type/multi_types_7/stdout.golden b/tests/grammar/schema/type/multi_types_7/stdout.golden similarity index 100% rename from test/grammar/schema/type/multi_types_7/stdout.golden rename to tests/grammar/schema/type/multi_types_7/stdout.golden diff --git a/test/grammar/schema/type/type_dict_0/main.k b/tests/grammar/schema/type/type_dict_0/main.k similarity index 100% rename from test/grammar/schema/type/type_dict_0/main.k rename to tests/grammar/schema/type/type_dict_0/main.k diff --git a/test/grammar/schema/type/type_dict_0/stdout.golden b/tests/grammar/schema/type/type_dict_0/stdout.golden similarity index 100% rename from test/grammar/schema/type/type_dict_0/stdout.golden rename to tests/grammar/schema/type/type_dict_0/stdout.golden diff --git a/test/grammar/schema/type/type_dict_1/main.k b/tests/grammar/schema/type/type_dict_1/main.k similarity index 100% rename from test/grammar/schema/type/type_dict_1/main.k rename to tests/grammar/schema/type/type_dict_1/main.k diff --git a/test/grammar/schema/type/type_dict_1/stdout.golden b/tests/grammar/schema/type/type_dict_1/stdout.golden similarity index 100% rename from test/grammar/schema/type/type_dict_1/stdout.golden rename to tests/grammar/schema/type/type_dict_1/stdout.golden diff --git a/test/grammar/schema/type/type_dict_2/main.k b/tests/grammar/schema/type/type_dict_2/main.k similarity index 100% rename from test/grammar/schema/type/type_dict_2/main.k rename to tests/grammar/schema/type/type_dict_2/main.k diff --git a/test/grammar/schema/type/type_dict_2/stdout.golden b/tests/grammar/schema/type/type_dict_2/stdout.golden similarity index 100% rename from test/grammar/schema/type/type_dict_2/stdout.golden rename to tests/grammar/schema/type/type_dict_2/stdout.golden diff --git a/test/grammar/schema/type/type_dict_3/main.k b/tests/grammar/schema/type/type_dict_3/main.k similarity index 100% rename from test/grammar/schema/type/type_dict_3/main.k rename to tests/grammar/schema/type/type_dict_3/main.k diff --git a/test/grammar/schema/type/type_dict_3/stdout.golden b/tests/grammar/schema/type/type_dict_3/stdout.golden similarity index 100% rename from test/grammar/schema/type/type_dict_3/stdout.golden rename to tests/grammar/schema/type/type_dict_3/stdout.golden diff --git a/test/grammar/schema/type/type_dict_4/main.k b/tests/grammar/schema/type/type_dict_4/main.k similarity index 100% rename from test/grammar/schema/type/type_dict_4/main.k rename to tests/grammar/schema/type/type_dict_4/main.k diff --git a/test/grammar/schema/type/type_dict_4/stdout.golden b/tests/grammar/schema/type/type_dict_4/stdout.golden similarity index 100% rename from test/grammar/schema/type/type_dict_4/stdout.golden rename to tests/grammar/schema/type/type_dict_4/stdout.golden diff --git a/test/grammar/schema/type/type_dict_5/main.k b/tests/grammar/schema/type/type_dict_5/main.k similarity index 100% rename from test/grammar/schema/type/type_dict_5/main.k rename to tests/grammar/schema/type/type_dict_5/main.k diff --git a/test/grammar/schema/type/type_dict_5/stdout.golden b/tests/grammar/schema/type/type_dict_5/stdout.golden similarity index 100% rename from test/grammar/schema/type/type_dict_5/stdout.golden rename to tests/grammar/schema/type/type_dict_5/stdout.golden diff --git a/test/grammar/schema/type/type_dict_6/main.k b/tests/grammar/schema/type/type_dict_6/main.k similarity index 100% rename from test/grammar/schema/type/type_dict_6/main.k rename to tests/grammar/schema/type/type_dict_6/main.k diff --git a/test/grammar/schema/type/type_dict_6/stdout.golden b/tests/grammar/schema/type/type_dict_6/stdout.golden similarity index 100% rename from test/grammar/schema/type/type_dict_6/stdout.golden rename to tests/grammar/schema/type/type_dict_6/stdout.golden diff --git a/test/grammar/schema/type/type_dict_fail_0/main.k b/tests/grammar/schema/type/type_dict_fail_0/main.k similarity index 100% rename from test/grammar/schema/type/type_dict_fail_0/main.k rename to tests/grammar/schema/type/type_dict_fail_0/main.k diff --git a/test/grammar/schema/type/type_dict_fail_0/stderr.golden b/tests/grammar/schema/type/type_dict_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_dict_fail_0/stderr.golden rename to tests/grammar/schema/type/type_dict_fail_0/stderr.golden diff --git a/test/grammar/schema/type/type_empty_any_0/main.k b/tests/grammar/schema/type/type_empty_any_0/main.k similarity index 100% rename from test/grammar/schema/type/type_empty_any_0/main.k rename to tests/grammar/schema/type/type_empty_any_0/main.k diff --git a/test/grammar/schema/type/type_empty_any_0/stdout.golden b/tests/grammar/schema/type/type_empty_any_0/stdout.golden similarity index 100% rename from test/grammar/schema/type/type_empty_any_0/stdout.golden rename to tests/grammar/schema/type/type_empty_any_0/stdout.golden diff --git a/test/grammar/schema/type/type_empty_any_1/main.k b/tests/grammar/schema/type/type_empty_any_1/main.k similarity index 100% rename from test/grammar/schema/type/type_empty_any_1/main.k rename to tests/grammar/schema/type/type_empty_any_1/main.k diff --git a/test/grammar/schema/type/type_empty_any_1/stdout.golden b/tests/grammar/schema/type/type_empty_any_1/stdout.golden similarity index 100% rename from test/grammar/schema/type/type_empty_any_1/stdout.golden rename to tests/grammar/schema/type/type_empty_any_1/stdout.golden diff --git a/test/grammar/schema/type/type_fail_0/main.k b/tests/grammar/schema/type/type_fail_0/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_0/main.k rename to tests/grammar/schema/type/type_fail_0/main.k diff --git a/test/grammar/schema/type/type_fail_0/stderr.golden b/tests/grammar/schema/type/type_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_0/stderr.golden rename to tests/grammar/schema/type/type_fail_0/stderr.golden diff --git a/test/grammar/schema/type/type_fail_1/main.k b/tests/grammar/schema/type/type_fail_1/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_1/main.k rename to tests/grammar/schema/type/type_fail_1/main.k diff --git a/test/grammar/schema/type/type_fail_1/stderr.golden b/tests/grammar/schema/type/type_fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_1/stderr.golden rename to tests/grammar/schema/type/type_fail_1/stderr.golden diff --git a/test/grammar/schema/type/type_fail_10/main.k b/tests/grammar/schema/type/type_fail_10/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_10/main.k rename to tests/grammar/schema/type/type_fail_10/main.k diff --git a/test/grammar/schema/type/type_fail_10/stderr.golden b/tests/grammar/schema/type/type_fail_10/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_10/stderr.golden rename to tests/grammar/schema/type/type_fail_10/stderr.golden diff --git a/test/grammar/schema/type/type_fail_11/main.k b/tests/grammar/schema/type/type_fail_11/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_11/main.k rename to tests/grammar/schema/type/type_fail_11/main.k diff --git a/test/grammar/schema/type/type_fail_11/stderr.golden b/tests/grammar/schema/type/type_fail_11/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_11/stderr.golden rename to tests/grammar/schema/type/type_fail_11/stderr.golden diff --git a/test/grammar/schema/type/type_fail_12/main.k b/tests/grammar/schema/type/type_fail_12/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_12/main.k rename to tests/grammar/schema/type/type_fail_12/main.k diff --git a/test/grammar/schema/type/type_fail_12/stderr.golden b/tests/grammar/schema/type/type_fail_12/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_12/stderr.golden rename to tests/grammar/schema/type/type_fail_12/stderr.golden diff --git a/test/grammar/schema/type/type_fail_13/main.k b/tests/grammar/schema/type/type_fail_13/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_13/main.k rename to tests/grammar/schema/type/type_fail_13/main.k diff --git a/test/grammar/schema/type/type_fail_13/stderr.golden b/tests/grammar/schema/type/type_fail_13/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_13/stderr.golden rename to tests/grammar/schema/type/type_fail_13/stderr.golden diff --git a/test/grammar/schema/type/type_fail_14/main.k b/tests/grammar/schema/type/type_fail_14/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_14/main.k rename to tests/grammar/schema/type/type_fail_14/main.k diff --git a/test/grammar/schema/type/type_fail_14/stderr.golden b/tests/grammar/schema/type/type_fail_14/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_14/stderr.golden rename to tests/grammar/schema/type/type_fail_14/stderr.golden diff --git a/test/grammar/schema/type/type_fail_15/main.k b/tests/grammar/schema/type/type_fail_15/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_15/main.k rename to tests/grammar/schema/type/type_fail_15/main.k diff --git a/test/grammar/schema/type/type_fail_15/stderr.golden b/tests/grammar/schema/type/type_fail_15/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_15/stderr.golden rename to tests/grammar/schema/type/type_fail_15/stderr.golden diff --git a/test/grammar/schema/type/type_fail_16/main.k b/tests/grammar/schema/type/type_fail_16/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_16/main.k rename to tests/grammar/schema/type/type_fail_16/main.k diff --git a/test/grammar/schema/type/type_fail_16/stderr.golden b/tests/grammar/schema/type/type_fail_16/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_16/stderr.golden rename to tests/grammar/schema/type/type_fail_16/stderr.golden diff --git a/test/grammar/schema/type/type_fail_17/main.k b/tests/grammar/schema/type/type_fail_17/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_17/main.k rename to tests/grammar/schema/type/type_fail_17/main.k diff --git a/test/grammar/schema/type/type_fail_17/stderr.golden b/tests/grammar/schema/type/type_fail_17/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_17/stderr.golden rename to tests/grammar/schema/type/type_fail_17/stderr.golden diff --git a/test/grammar/schema/type/type_fail_18/main.k b/tests/grammar/schema/type/type_fail_18/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_18/main.k rename to tests/grammar/schema/type/type_fail_18/main.k diff --git a/test/grammar/schema/type/type_fail_18/stderr.golden b/tests/grammar/schema/type/type_fail_18/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_18/stderr.golden rename to tests/grammar/schema/type/type_fail_18/stderr.golden diff --git a/test/grammar/schema/type/type_fail_19/kcl.mod b/tests/grammar/schema/type/type_fail_19/kcl.mod similarity index 100% rename from test/grammar/schema/type/type_fail_19/kcl.mod rename to tests/grammar/schema/type/type_fail_19/kcl.mod diff --git a/test/grammar/schema/type/type_fail_19/main.k b/tests/grammar/schema/type/type_fail_19/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_19/main.k rename to tests/grammar/schema/type/type_fail_19/main.k diff --git a/test/grammar/schema/type/type_fail_19/pkg/info.k b/tests/grammar/schema/type/type_fail_19/pkg/info.k similarity index 100% rename from test/grammar/schema/type/type_fail_19/pkg/info.k rename to tests/grammar/schema/type/type_fail_19/pkg/info.k diff --git a/test/grammar/schema/type/type_fail_19/stderr.golden b/tests/grammar/schema/type/type_fail_19/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_19/stderr.golden rename to tests/grammar/schema/type/type_fail_19/stderr.golden diff --git a/test/grammar/schema/type/type_fail_2/main.k b/tests/grammar/schema/type/type_fail_2/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_2/main.k rename to tests/grammar/schema/type/type_fail_2/main.k diff --git a/test/grammar/schema/type/type_fail_2/stderr.golden b/tests/grammar/schema/type/type_fail_2/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_2/stderr.golden rename to tests/grammar/schema/type/type_fail_2/stderr.golden diff --git a/test/grammar/schema/type/type_fail_20/kcl.mod b/tests/grammar/schema/type/type_fail_20/kcl.mod similarity index 100% rename from test/grammar/schema/type/type_fail_20/kcl.mod rename to tests/grammar/schema/type/type_fail_20/kcl.mod diff --git a/test/grammar/schema/type/type_fail_20/main.k b/tests/grammar/schema/type/type_fail_20/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_20/main.k rename to tests/grammar/schema/type/type_fail_20/main.k diff --git a/test/grammar/schema/type/type_fail_20/pkg/info.k b/tests/grammar/schema/type/type_fail_20/pkg/info.k similarity index 100% rename from test/grammar/schema/type/type_fail_20/pkg/info.k rename to tests/grammar/schema/type/type_fail_20/pkg/info.k diff --git a/test/grammar/schema/type/type_fail_20/stderr.golden b/tests/grammar/schema/type/type_fail_20/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_20/stderr.golden rename to tests/grammar/schema/type/type_fail_20/stderr.golden diff --git a/test/grammar/schema/type/type_fail_21/kcl.mod b/tests/grammar/schema/type/type_fail_21/kcl.mod similarity index 100% rename from test/grammar/schema/type/type_fail_21/kcl.mod rename to tests/grammar/schema/type/type_fail_21/kcl.mod diff --git a/test/grammar/schema/type/type_fail_21/main.k b/tests/grammar/schema/type/type_fail_21/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_21/main.k rename to tests/grammar/schema/type/type_fail_21/main.k diff --git a/test/grammar/schema/type/type_fail_21/pkg/info.k b/tests/grammar/schema/type/type_fail_21/pkg/info.k similarity index 100% rename from test/grammar/schema/type/type_fail_21/pkg/info.k rename to tests/grammar/schema/type/type_fail_21/pkg/info.k diff --git a/test/grammar/schema/type/type_fail_21/stderr.golden b/tests/grammar/schema/type/type_fail_21/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_21/stderr.golden rename to tests/grammar/schema/type/type_fail_21/stderr.golden diff --git a/test/grammar/schema/type/type_fail_22/main.k b/tests/grammar/schema/type/type_fail_22/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_22/main.k rename to tests/grammar/schema/type/type_fail_22/main.k diff --git a/test/grammar/schema/type/type_fail_22/stderr.golden b/tests/grammar/schema/type/type_fail_22/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_22/stderr.golden rename to tests/grammar/schema/type/type_fail_22/stderr.golden diff --git a/test/grammar/schema/type/type_fail_24/kcl.mod b/tests/grammar/schema/type/type_fail_24/kcl.mod similarity index 100% rename from test/grammar/schema/type/type_fail_24/kcl.mod rename to tests/grammar/schema/type/type_fail_24/kcl.mod diff --git a/test/grammar/schema/type/type_fail_24/main.k b/tests/grammar/schema/type/type_fail_24/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_24/main.k rename to tests/grammar/schema/type/type_fail_24/main.k diff --git a/test/grammar/schema/type/type_fail_24/pkg/container.k b/tests/grammar/schema/type/type_fail_24/pkg/container.k similarity index 100% rename from test/grammar/schema/type/type_fail_24/pkg/container.k rename to tests/grammar/schema/type/type_fail_24/pkg/container.k diff --git a/test/grammar/schema/type/type_fail_24/pkg/person.k b/tests/grammar/schema/type/type_fail_24/pkg/person.k similarity index 100% rename from test/grammar/schema/type/type_fail_24/pkg/person.k rename to tests/grammar/schema/type/type_fail_24/pkg/person.k diff --git a/test/grammar/schema/type/type_fail_24/stderr.golden b/tests/grammar/schema/type/type_fail_24/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_24/stderr.golden rename to tests/grammar/schema/type/type_fail_24/stderr.golden diff --git a/test/grammar/schema/type/type_fail_25/main.k b/tests/grammar/schema/type/type_fail_25/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_25/main.k rename to tests/grammar/schema/type/type_fail_25/main.k diff --git a/test/grammar/schema/type/type_fail_25/stderr.golden b/tests/grammar/schema/type/type_fail_25/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_25/stderr.golden rename to tests/grammar/schema/type/type_fail_25/stderr.golden diff --git a/test/grammar/schema/type/type_fail_26/main.k b/tests/grammar/schema/type/type_fail_26/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_26/main.k rename to tests/grammar/schema/type/type_fail_26/main.k diff --git a/test/grammar/schema/type/type_fail_26/stderr.golden b/tests/grammar/schema/type/type_fail_26/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_26/stderr.golden rename to tests/grammar/schema/type/type_fail_26/stderr.golden diff --git a/test/grammar/schema/type/type_fail_27/main.k b/tests/grammar/schema/type/type_fail_27/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_27/main.k rename to tests/grammar/schema/type/type_fail_27/main.k diff --git a/test/grammar/schema/type/type_fail_27/stderr.golden b/tests/grammar/schema/type/type_fail_27/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_27/stderr.golden rename to tests/grammar/schema/type/type_fail_27/stderr.golden diff --git a/test/grammar/schema/type/type_fail_3/main.k b/tests/grammar/schema/type/type_fail_3/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_3/main.k rename to tests/grammar/schema/type/type_fail_3/main.k diff --git a/test/grammar/schema/type/type_fail_3/stderr.golden b/tests/grammar/schema/type/type_fail_3/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_3/stderr.golden rename to tests/grammar/schema/type/type_fail_3/stderr.golden diff --git a/test/grammar/schema/type/type_fail_4/main.k b/tests/grammar/schema/type/type_fail_4/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_4/main.k rename to tests/grammar/schema/type/type_fail_4/main.k diff --git a/test/grammar/schema/type/type_fail_4/stderr.golden b/tests/grammar/schema/type/type_fail_4/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_4/stderr.golden rename to tests/grammar/schema/type/type_fail_4/stderr.golden diff --git a/test/grammar/schema/type/type_fail_5/main.k b/tests/grammar/schema/type/type_fail_5/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_5/main.k rename to tests/grammar/schema/type/type_fail_5/main.k diff --git a/test/grammar/schema/type/type_fail_5/stderr.golden b/tests/grammar/schema/type/type_fail_5/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_5/stderr.golden rename to tests/grammar/schema/type/type_fail_5/stderr.golden diff --git a/test/grammar/schema/type/type_fail_6/main.k b/tests/grammar/schema/type/type_fail_6/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_6/main.k rename to tests/grammar/schema/type/type_fail_6/main.k diff --git a/test/grammar/schema/type/type_fail_6/stderr.golden b/tests/grammar/schema/type/type_fail_6/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_6/stderr.golden rename to tests/grammar/schema/type/type_fail_6/stderr.golden diff --git a/test/grammar/schema/type/type_fail_7/main.k b/tests/grammar/schema/type/type_fail_7/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_7/main.k rename to tests/grammar/schema/type/type_fail_7/main.k diff --git a/test/grammar/schema/type/type_fail_7/stderr.golden b/tests/grammar/schema/type/type_fail_7/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_7/stderr.golden rename to tests/grammar/schema/type/type_fail_7/stderr.golden diff --git a/test/grammar/schema/type/type_fail_8/main.k b/tests/grammar/schema/type/type_fail_8/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_8/main.k rename to tests/grammar/schema/type/type_fail_8/main.k diff --git a/test/grammar/schema/type/type_fail_8/stderr.golden b/tests/grammar/schema/type/type_fail_8/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_8/stderr.golden rename to tests/grammar/schema/type/type_fail_8/stderr.golden diff --git a/test/grammar/schema/type/type_fail_9/main.k b/tests/grammar/schema/type/type_fail_9/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_9/main.k rename to tests/grammar/schema/type/type_fail_9/main.k diff --git a/test/grammar/schema/type/type_fail_9/stderr.golden b/tests/grammar/schema/type/type_fail_9/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_9/stderr.golden rename to tests/grammar/schema/type/type_fail_9/stderr.golden diff --git a/test/grammar/schema/type/type_fail_default_value_0/main.k b/tests/grammar/schema/type/type_fail_default_value_0/main.k similarity index 100% rename from test/grammar/schema/type/type_fail_default_value_0/main.k rename to tests/grammar/schema/type/type_fail_default_value_0/main.k diff --git a/test/grammar/schema/type/type_fail_default_value_0/stderr.golden b/tests/grammar/schema/type/type_fail_default_value_0/stderr.golden similarity index 100% rename from test/grammar/schema/type/type_fail_default_value_0/stderr.golden rename to tests/grammar/schema/type/type_fail_default_value_0/stderr.golden diff --git a/test/grammar/schema/type/type_list/main.k b/tests/grammar/schema/type/type_list/main.k similarity index 100% rename from test/grammar/schema/type/type_list/main.k rename to tests/grammar/schema/type/type_list/main.k diff --git a/test/grammar/schema/type/type_list/stdout.golden b/tests/grammar/schema/type/type_list/stdout.golden similarity index 100% rename from test/grammar/schema/type/type_list/stdout.golden rename to tests/grammar/schema/type/type_list/stdout.golden diff --git a/test/grammar/schema/type/type_schema_list_0/main.k b/tests/grammar/schema/type/type_schema_list_0/main.k similarity index 100% rename from test/grammar/schema/type/type_schema_list_0/main.k rename to tests/grammar/schema/type/type_schema_list_0/main.k diff --git a/test/grammar/schema/type/type_schema_list_0/stdout.golden b/tests/grammar/schema/type/type_schema_list_0/stdout.golden similarity index 100% rename from test/grammar/schema/type/type_schema_list_0/stdout.golden rename to tests/grammar/schema/type/type_schema_list_0/stdout.golden diff --git a/test/grammar/schema/type/type_schema_list_1/main.k b/tests/grammar/schema/type/type_schema_list_1/main.k similarity index 100% rename from test/grammar/schema/type/type_schema_list_1/main.k rename to tests/grammar/schema/type/type_schema_list_1/main.k diff --git a/test/grammar/schema/type/type_schema_list_1/stdout.golden b/tests/grammar/schema/type/type_schema_list_1/stdout.golden similarity index 100% rename from test/grammar/schema/type/type_schema_list_1/stdout.golden rename to tests/grammar/schema/type/type_schema_list_1/stdout.golden diff --git a/test/grammar/schema/type/type_value_0/main.k b/tests/grammar/schema/type/type_value_0/main.k similarity index 100% rename from test/grammar/schema/type/type_value_0/main.k rename to tests/grammar/schema/type/type_value_0/main.k diff --git a/test/grammar/schema/type/type_value_0/stdout.golden b/tests/grammar/schema/type/type_value_0/stdout.golden similarity index 100% rename from test/grammar/schema/type/type_value_0/stdout.golden rename to tests/grammar/schema/type/type_value_0/stdout.golden diff --git a/test/grammar/schema/type/type_value_1/main.k b/tests/grammar/schema/type/type_value_1/main.k similarity index 100% rename from test/grammar/schema/type/type_value_1/main.k rename to tests/grammar/schema/type/type_value_1/main.k diff --git a/test/grammar/schema/type/type_value_1/stdout.golden b/tests/grammar/schema/type/type_value_1/stdout.golden similarity index 100% rename from test/grammar/schema/type/type_value_1/stdout.golden rename to tests/grammar/schema/type/type_value_1/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_full/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_full/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full/stdout.golden b/tests/grammar/schema/type_annotation/defaults/default_values_full/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full/stdout.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_full/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full_0/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_full_0/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full_0/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_full_0/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full_0/stdout.golden b/tests/grammar/schema/type_annotation/defaults/default_values_full_0/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full_0/stdout.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_full_0/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full_1/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_full_1/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full_1/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_full_1/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full_1/stdout.golden b/tests/grammar/schema/type_annotation/defaults/default_values_full_1/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full_1/stdout.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_full_1/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full_2/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_full_2/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full_2/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_full_2/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full_2/stdout.golden b/tests/grammar/schema/type_annotation/defaults/default_values_full_2/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full_2/stdout.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_full_2/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full_3/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_full_3/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full_3/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_full_3/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full_3/stdout.golden b/tests/grammar/schema/type_annotation/defaults/default_values_full_3/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full_3/stdout.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_full_3/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full_4/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_full_4/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full_4/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_full_4/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full_4/stdout.golden b/tests/grammar/schema/type_annotation/defaults/default_values_full_4/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full_4/stdout.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_full_4/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full_5/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_full_5/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full_5/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_full_5/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full_5/stdout.golden b/tests/grammar/schema/type_annotation/defaults/default_values_full_5/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full_5/stdout.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_full_5/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full_6/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_full_6/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full_6/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_full_6/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_full_6/stdout.golden b/tests/grammar/schema/type_annotation/defaults/default_values_full_6/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_full_6/stdout.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_full_6/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full/stdout.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full/stdout.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_0/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_0/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_0/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_0/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_0/stdout.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_0/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_0/stdout.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_0/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_1/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_1/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_1/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_1/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_1/stdout.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_1/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_1/stdout.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_1/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_2/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_2/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_2/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_2/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_2/stdout.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_2/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_2/stdout.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_2/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_3/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_3/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_3/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_3/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_3/stdout.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_3/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_3/stdout.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_3/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_4/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_4/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_4/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_4/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_4/stdout.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_4/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_4/stdout.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_4/stdout.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_0/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_0/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_0/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_0/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_0/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_0/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_0/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_0/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_1/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_1/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_1/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_1/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_1/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_1/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_1/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_1/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_10/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_10/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_10/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_10/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_10/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_10/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_10/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_10/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_11/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_11/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_11/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_11/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_11/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_11/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_11/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_11/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_12/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_12/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_12/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_12/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_12/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_12/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_12/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_12/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_13/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_13/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_13/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_13/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_13/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_13/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_13/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_13/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_14/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_14/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_14/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_14/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_14/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_14/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_14/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_14/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_15/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_15/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_15/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_15/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_15/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_15/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_15/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_15/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_16/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_16/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_16/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_16/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_16/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_16/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_16/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_16/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_17/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_17/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_17/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_17/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_17/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_17/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_17/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_17/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_18/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_18/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_18/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_18/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_18/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_18/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_18/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_18/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_19/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_19/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_19/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_19/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_19/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_19/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_19/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_19/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_2/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_2/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_2/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_2/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_2/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_2/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_2/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_2/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_20/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_20/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_20/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_20/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_20/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_20/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_20/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_20/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_21/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_21/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_21/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_21/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_21/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_21/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_21/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_21/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_22/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_22/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_22/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_22/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_22/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_22/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_22/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_22/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_23/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_23/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_23/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_23/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_23/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_23/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_23/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_23/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_24/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_24/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_24/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_24/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_24/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_24/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_24/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_24/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_25/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_25/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_25/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_25/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_25/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_25/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_25/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_25/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_26/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_26/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_26/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_26/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_26/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_26/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_26/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_26/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_27/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_27/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_27/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_27/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_27/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_27/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_27/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_27/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_28/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_28/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_28/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_28/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_28/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_28/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_28/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_28/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_29/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_29/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_29/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_29/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_29/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_29/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_29/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_29/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_3/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_3/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_3/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_3/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_3/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_3/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_3/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_3/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_30/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_30/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_30/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_30/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_30/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_30/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_30/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_30/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_4/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_4/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_4/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_4/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_4/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_4/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_4/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_4/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_5/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_5/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_5/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_5/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_5/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_5/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_5/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_5/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_6/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_6/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_6/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_6/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_6/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_6/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_6/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_6/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_7/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_7/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_7/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_7/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_7/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_7/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_7/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_7/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_8/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_8/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_8/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_8/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_8/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_8/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_8/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_8/stderr.golden diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_9/main.k b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_9/main.k similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_9/main.k rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_9/main.k diff --git a/test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_9/stderr.golden b/tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_9/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_9/stderr.golden rename to tests/grammar/schema/type_annotation/defaults/default_values_not_full_invalid_9/stderr.golden diff --git a/test/grammar/schema/type_annotation/type_annotation_inconsistent/main.k b/tests/grammar/schema/type_annotation/type_annotation_inconsistent/main.k similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_inconsistent/main.k rename to tests/grammar/schema/type_annotation/type_annotation_inconsistent/main.k diff --git a/test/grammar/schema/type_annotation/type_annotation_inconsistent/stderr.golden b/tests/grammar/schema/type_annotation/type_annotation_inconsistent/stderr.golden similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_inconsistent/stderr.golden rename to tests/grammar/schema/type_annotation/type_annotation_inconsistent/stderr.golden diff --git a/test/grammar/schema/type_annotation/type_annotation_not_full/main.k b/tests/grammar/schema/type_annotation/type_annotation_not_full/main.k similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_not_full/main.k rename to tests/grammar/schema/type_annotation/type_annotation_not_full/main.k diff --git a/test/grammar/schema/type_annotation/type_annotation_not_full/stdout.golden b/tests/grammar/schema/type_annotation/type_annotation_not_full/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_not_full/stdout.golden rename to tests/grammar/schema/type_annotation/type_annotation_not_full/stdout.golden diff --git a/test/grammar/schema/type_annotation/type_annotation_not_full_0/main.k b/tests/grammar/schema/type_annotation/type_annotation_not_full_0/main.k similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_not_full_0/main.k rename to tests/grammar/schema/type_annotation/type_annotation_not_full_0/main.k diff --git a/test/grammar/schema/type_annotation/type_annotation_not_full_0/stdout.golden b/tests/grammar/schema/type_annotation/type_annotation_not_full_0/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_not_full_0/stdout.golden rename to tests/grammar/schema/type_annotation/type_annotation_not_full_0/stdout.golden diff --git a/test/grammar/schema/type_annotation/type_annotation_not_full_1/main.k b/tests/grammar/schema/type_annotation/type_annotation_not_full_1/main.k similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_not_full_1/main.k rename to tests/grammar/schema/type_annotation/type_annotation_not_full_1/main.k diff --git a/test/grammar/schema/type_annotation/type_annotation_not_full_1/stdout.golden b/tests/grammar/schema/type_annotation/type_annotation_not_full_1/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_not_full_1/stdout.golden rename to tests/grammar/schema/type_annotation/type_annotation_not_full_1/stdout.golden diff --git a/test/grammar/schema/type_annotation/type_annotation_not_full_2/main.k b/tests/grammar/schema/type_annotation/type_annotation_not_full_2/main.k similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_not_full_2/main.k rename to tests/grammar/schema/type_annotation/type_annotation_not_full_2/main.k diff --git a/test/grammar/schema/type_annotation/type_annotation_not_full_2/stdout.golden b/tests/grammar/schema/type_annotation/type_annotation_not_full_2/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_not_full_2/stdout.golden rename to tests/grammar/schema/type_annotation/type_annotation_not_full_2/stdout.golden diff --git a/test/grammar/schema/type_annotation/type_annotation_schema_0/main.k b/tests/grammar/schema/type_annotation/type_annotation_schema_0/main.k similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_schema_0/main.k rename to tests/grammar/schema/type_annotation/type_annotation_schema_0/main.k diff --git a/test/grammar/schema/type_annotation/type_annotation_schema_0/stdout.golden b/tests/grammar/schema/type_annotation/type_annotation_schema_0/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_schema_0/stdout.golden rename to tests/grammar/schema/type_annotation/type_annotation_schema_0/stdout.golden diff --git a/test/grammar/schema/type_annotation/type_annotation_schema_1/main.k b/tests/grammar/schema/type_annotation/type_annotation_schema_1/main.k similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_schema_1/main.k rename to tests/grammar/schema/type_annotation/type_annotation_schema_1/main.k diff --git a/test/grammar/schema/type_annotation/type_annotation_schema_1/stdout.golden b/tests/grammar/schema/type_annotation/type_annotation_schema_1/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_schema_1/stdout.golden rename to tests/grammar/schema/type_annotation/type_annotation_schema_1/stdout.golden diff --git a/test/grammar/schema/type_annotation/type_annotation_schema_2/main.k b/tests/grammar/schema/type_annotation/type_annotation_schema_2/main.k similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_schema_2/main.k rename to tests/grammar/schema/type_annotation/type_annotation_schema_2/main.k diff --git a/test/grammar/schema/type_annotation/type_annotation_schema_2/stdout.golden b/tests/grammar/schema/type_annotation/type_annotation_schema_2/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_schema_2/stdout.golden rename to tests/grammar/schema/type_annotation/type_annotation_schema_2/stdout.golden diff --git a/test/grammar/schema/type_annotation/type_annotation_schema_3/main.k b/tests/grammar/schema/type_annotation/type_annotation_schema_3/main.k similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_schema_3/main.k rename to tests/grammar/schema/type_annotation/type_annotation_schema_3/main.k diff --git a/test/grammar/schema/type_annotation/type_annotation_schema_3/stdout.golden b/tests/grammar/schema/type_annotation/type_annotation_schema_3/stdout.golden similarity index 100% rename from test/grammar/schema/type_annotation/type_annotation_schema_3/stdout.golden rename to tests/grammar/schema/type_annotation/type_annotation_schema_3/stdout.golden diff --git a/test/grammar/schema/union/arguments/keyword_argument_0/main.k b/tests/grammar/schema/union/arguments/keyword_argument_0/main.k similarity index 100% rename from test/grammar/schema/union/arguments/keyword_argument_0/main.k rename to tests/grammar/schema/union/arguments/keyword_argument_0/main.k diff --git a/test/grammar/schema/union/arguments/keyword_argument_0/stdout.golden b/tests/grammar/schema/union/arguments/keyword_argument_0/stdout.golden similarity index 100% rename from test/grammar/schema/union/arguments/keyword_argument_0/stdout.golden rename to tests/grammar/schema/union/arguments/keyword_argument_0/stdout.golden diff --git a/test/grammar/schema/union/arguments/keyword_argument_1/main.k b/tests/grammar/schema/union/arguments/keyword_argument_1/main.k similarity index 100% rename from test/grammar/schema/union/arguments/keyword_argument_1/main.k rename to tests/grammar/schema/union/arguments/keyword_argument_1/main.k diff --git a/test/grammar/schema/union/arguments/keyword_argument_1/stdout.golden b/tests/grammar/schema/union/arguments/keyword_argument_1/stdout.golden similarity index 100% rename from test/grammar/schema/union/arguments/keyword_argument_1/stdout.golden rename to tests/grammar/schema/union/arguments/keyword_argument_1/stdout.golden diff --git a/test/grammar/schema/union/arguments/single_argument_0/main.k b/tests/grammar/schema/union/arguments/single_argument_0/main.k similarity index 100% rename from test/grammar/schema/union/arguments/single_argument_0/main.k rename to tests/grammar/schema/union/arguments/single_argument_0/main.k diff --git a/test/grammar/schema/union/arguments/single_argument_0/stdout.golden b/tests/grammar/schema/union/arguments/single_argument_0/stdout.golden similarity index 100% rename from test/grammar/schema/union/arguments/single_argument_0/stdout.golden rename to tests/grammar/schema/union/arguments/single_argument_0/stdout.golden diff --git a/test/grammar/schema/union/arguments/single_argument_1/main.k b/tests/grammar/schema/union/arguments/single_argument_1/main.k similarity index 100% rename from test/grammar/schema/union/arguments/single_argument_1/main.k rename to tests/grammar/schema/union/arguments/single_argument_1/main.k diff --git a/test/grammar/schema/union/arguments/single_argument_1/stdout.golden b/tests/grammar/schema/union/arguments/single_argument_1/stdout.golden similarity index 100% rename from test/grammar/schema/union/arguments/single_argument_1/stdout.golden rename to tests/grammar/schema/union/arguments/single_argument_1/stdout.golden diff --git a/test/grammar/schema/union/arguments/single_argument_2/main.k b/tests/grammar/schema/union/arguments/single_argument_2/main.k similarity index 100% rename from test/grammar/schema/union/arguments/single_argument_2/main.k rename to tests/grammar/schema/union/arguments/single_argument_2/main.k diff --git a/test/grammar/schema/union/arguments/single_argument_2/stdout.golden b/tests/grammar/schema/union/arguments/single_argument_2/stdout.golden similarity index 100% rename from test/grammar/schema/union/arguments/single_argument_2/stdout.golden rename to tests/grammar/schema/union/arguments/single_argument_2/stdout.golden diff --git a/test/grammar/schema/union/binary_union/bin_union_fail_0/main.k b/tests/grammar/schema/union/binary_union/bin_union_fail_0/main.k similarity index 100% rename from test/grammar/schema/union/binary_union/bin_union_fail_0/main.k rename to tests/grammar/schema/union/binary_union/bin_union_fail_0/main.k diff --git a/test/grammar/schema/union/binary_union/bin_union_fail_0/stderr.golden b/tests/grammar/schema/union/binary_union/bin_union_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/union/binary_union/bin_union_fail_0/stderr.golden rename to tests/grammar/schema/union/binary_union/bin_union_fail_0/stderr.golden diff --git a/test/grammar/schema/union/binary_union/bin_union_fail_1/main.k b/tests/grammar/schema/union/binary_union/bin_union_fail_1/main.k similarity index 100% rename from test/grammar/schema/union/binary_union/bin_union_fail_1/main.k rename to tests/grammar/schema/union/binary_union/bin_union_fail_1/main.k diff --git a/test/grammar/schema/union/binary_union/bin_union_fail_1/stderr.golden b/tests/grammar/schema/union/binary_union/bin_union_fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/union/binary_union/bin_union_fail_1/stderr.golden rename to tests/grammar/schema/union/binary_union/bin_union_fail_1/stderr.golden diff --git a/test/grammar/schema/union/binary_union/bin_union_fail_2/main.k b/tests/grammar/schema/union/binary_union/bin_union_fail_2/main.k similarity index 100% rename from test/grammar/schema/union/binary_union/bin_union_fail_2/main.k rename to tests/grammar/schema/union/binary_union/bin_union_fail_2/main.k diff --git a/test/grammar/schema/union/binary_union/bin_union_fail_2/stderr.golden b/tests/grammar/schema/union/binary_union/bin_union_fail_2/stderr.golden similarity index 100% rename from test/grammar/schema/union/binary_union/bin_union_fail_2/stderr.golden rename to tests/grammar/schema/union/binary_union/bin_union_fail_2/stderr.golden diff --git a/test/grammar/schema/union/binary_union/bin_union_fail_3/main.k b/tests/grammar/schema/union/binary_union/bin_union_fail_3/main.k similarity index 100% rename from test/grammar/schema/union/binary_union/bin_union_fail_3/main.k rename to tests/grammar/schema/union/binary_union/bin_union_fail_3/main.k diff --git a/test/grammar/schema/union/binary_union/bin_union_fail_3/stderr.golden b/tests/grammar/schema/union/binary_union/bin_union_fail_3/stderr.golden similarity index 100% rename from test/grammar/schema/union/binary_union/bin_union_fail_3/stderr.golden rename to tests/grammar/schema/union/binary_union/bin_union_fail_3/stderr.golden diff --git a/test/grammar/schema/union/binary_union/bin_union_fail_4/main.k b/tests/grammar/schema/union/binary_union/bin_union_fail_4/main.k similarity index 100% rename from test/grammar/schema/union/binary_union/bin_union_fail_4/main.k rename to tests/grammar/schema/union/binary_union/bin_union_fail_4/main.k diff --git a/test/grammar/schema/union/binary_union/bin_union_fail_4/stderr.golden b/tests/grammar/schema/union/binary_union/bin_union_fail_4/stderr.golden similarity index 100% rename from test/grammar/schema/union/binary_union/bin_union_fail_4/stderr.golden rename to tests/grammar/schema/union/binary_union/bin_union_fail_4/stderr.golden diff --git a/test/grammar/schema/union/binary_union/binary_union_0/main.k b/tests/grammar/schema/union/binary_union/binary_union_0/main.k similarity index 100% rename from test/grammar/schema/union/binary_union/binary_union_0/main.k rename to tests/grammar/schema/union/binary_union/binary_union_0/main.k diff --git a/test/grammar/schema/union/binary_union/binary_union_0/stdout.golden b/tests/grammar/schema/union/binary_union/binary_union_0/stdout.golden similarity index 100% rename from test/grammar/schema/union/binary_union/binary_union_0/stdout.golden rename to tests/grammar/schema/union/binary_union/binary_union_0/stdout.golden diff --git a/test/grammar/schema/union/binary_union/binary_union_1/main.k b/tests/grammar/schema/union/binary_union/binary_union_1/main.k similarity index 100% rename from test/grammar/schema/union/binary_union/binary_union_1/main.k rename to tests/grammar/schema/union/binary_union/binary_union_1/main.k diff --git a/test/grammar/schema/union/binary_union/binary_union_1/stdout.golden b/tests/grammar/schema/union/binary_union/binary_union_1/stdout.golden similarity index 100% rename from test/grammar/schema/union/binary_union/binary_union_1/stdout.golden rename to tests/grammar/schema/union/binary_union/binary_union_1/stdout.golden diff --git a/test/grammar/schema/union/binary_union/binary_union_2/main.k b/tests/grammar/schema/union/binary_union/binary_union_2/main.k similarity index 100% rename from test/grammar/schema/union/binary_union/binary_union_2/main.k rename to tests/grammar/schema/union/binary_union/binary_union_2/main.k diff --git a/test/grammar/schema/union/binary_union/binary_union_2/stdout.golden b/tests/grammar/schema/union/binary_union/binary_union_2/stdout.golden similarity index 100% rename from test/grammar/schema/union/binary_union/binary_union_2/stdout.golden rename to tests/grammar/schema/union/binary_union/binary_union_2/stdout.golden diff --git a/test/grammar/schema/union/binary_union/binary_union_3/main.k b/tests/grammar/schema/union/binary_union/binary_union_3/main.k similarity index 100% rename from test/grammar/schema/union/binary_union/binary_union_3/main.k rename to tests/grammar/schema/union/binary_union/binary_union_3/main.k diff --git a/test/grammar/schema/union/binary_union/binary_union_3/stdout.golden b/tests/grammar/schema/union/binary_union/binary_union_3/stdout.golden similarity index 100% rename from test/grammar/schema/union/binary_union/binary_union_3/stdout.golden rename to tests/grammar/schema/union/binary_union/binary_union_3/stdout.golden diff --git a/test/grammar/schema/union/binary_union/binary_union_4/main.k b/tests/grammar/schema/union/binary_union/binary_union_4/main.k similarity index 100% rename from test/grammar/schema/union/binary_union/binary_union_4/main.k rename to tests/grammar/schema/union/binary_union/binary_union_4/main.k diff --git a/test/grammar/schema/union/binary_union/binary_union_4/stdout.golden b/tests/grammar/schema/union/binary_union/binary_union_4/stdout.golden similarity index 100% rename from test/grammar/schema/union/binary_union/binary_union_4/stdout.golden rename to tests/grammar/schema/union/binary_union/binary_union_4/stdout.golden diff --git a/test/grammar/schema/union/binary_union/binary_union_5/main.k b/tests/grammar/schema/union/binary_union/binary_union_5/main.k similarity index 100% rename from test/grammar/schema/union/binary_union/binary_union_5/main.k rename to tests/grammar/schema/union/binary_union/binary_union_5/main.k diff --git a/test/grammar/schema/union/binary_union/binary_union_5/stdout.golden b/tests/grammar/schema/union/binary_union/binary_union_5/stdout.golden similarity index 100% rename from test/grammar/schema/union/binary_union/binary_union_5/stdout.golden rename to tests/grammar/schema/union/binary_union/binary_union_5/stdout.golden diff --git a/test/grammar/schema/union/datatype/valid/main.k b/tests/grammar/schema/union/datatype/valid/main.k similarity index 100% rename from test/grammar/schema/union/datatype/valid/main.k rename to tests/grammar/schema/union/datatype/valid/main.k diff --git a/test/grammar/schema/union/datatype/valid/stdout.golden b/tests/grammar/schema/union/datatype/valid/stdout.golden similarity index 100% rename from test/grammar/schema/union/datatype/valid/stdout.golden rename to tests/grammar/schema/union/datatype/valid/stdout.golden diff --git a/test/grammar/schema/union/dict/instance_0/main.k b/tests/grammar/schema/union/dict/instance_0/main.k similarity index 100% rename from test/grammar/schema/union/dict/instance_0/main.k rename to tests/grammar/schema/union/dict/instance_0/main.k diff --git a/test/grammar/schema/union/dict/instance_0/stdout.golden b/tests/grammar/schema/union/dict/instance_0/stdout.golden similarity index 100% rename from test/grammar/schema/union/dict/instance_0/stdout.golden rename to tests/grammar/schema/union/dict/instance_0/stdout.golden diff --git a/test/grammar/schema/union/dict/schema_0/main.k b/tests/grammar/schema/union/dict/schema_0/main.k similarity index 100% rename from test/grammar/schema/union/dict/schema_0/main.k rename to tests/grammar/schema/union/dict/schema_0/main.k diff --git a/test/grammar/schema/union/dict/schema_0/stdout.golden b/tests/grammar/schema/union/dict/schema_0/stdout.golden similarity index 100% rename from test/grammar/schema/union/dict/schema_0/stdout.golden rename to tests/grammar/schema/union/dict/schema_0/stdout.golden diff --git a/test/grammar/schema/union/fail/fail_0/main.k b/tests/grammar/schema/union/fail/fail_0/main.k similarity index 100% rename from test/grammar/schema/union/fail/fail_0/main.k rename to tests/grammar/schema/union/fail/fail_0/main.k diff --git a/test/grammar/schema/union/fail/fail_0/stderr.golden b/tests/grammar/schema/union/fail/fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/union/fail/fail_0/stderr.golden rename to tests/grammar/schema/union/fail/fail_0/stderr.golden diff --git a/test/grammar/schema/union/fail/fail_1/main.k b/tests/grammar/schema/union/fail/fail_1/main.k similarity index 100% rename from test/grammar/schema/union/fail/fail_1/main.k rename to tests/grammar/schema/union/fail/fail_1/main.k diff --git a/test/grammar/schema/union/fail/fail_1/stderr.golden b/tests/grammar/schema/union/fail/fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/union/fail/fail_1/stderr.golden rename to tests/grammar/schema/union/fail/fail_1/stderr.golden diff --git a/test/grammar/schema/union/fail/fail_2/main.k b/tests/grammar/schema/union/fail/fail_2/main.k similarity index 100% rename from test/grammar/schema/union/fail/fail_2/main.k rename to tests/grammar/schema/union/fail/fail_2/main.k diff --git a/test/grammar/schema/union/fail/fail_2/stderr.golden b/tests/grammar/schema/union/fail/fail_2/stderr.golden similarity index 100% rename from test/grammar/schema/union/fail/fail_2/stderr.golden rename to tests/grammar/schema/union/fail/fail_2/stderr.golden diff --git a/test/grammar/schema/union/fail/fail_3/main.k b/tests/grammar/schema/union/fail/fail_3/main.k similarity index 100% rename from test/grammar/schema/union/fail/fail_3/main.k rename to tests/grammar/schema/union/fail/fail_3/main.k diff --git a/test/grammar/schema/union/fail/fail_3/stderr.golden b/tests/grammar/schema/union/fail/fail_3/stderr.golden similarity index 100% rename from test/grammar/schema/union/fail/fail_3/stderr.golden rename to tests/grammar/schema/union/fail/fail_3/stderr.golden diff --git a/test/grammar/schema/union/fail/fail_4/main.k b/tests/grammar/schema/union/fail/fail_4/main.k similarity index 100% rename from test/grammar/schema/union/fail/fail_4/main.k rename to tests/grammar/schema/union/fail/fail_4/main.k diff --git a/test/grammar/schema/union/fail/fail_4/stderr.golden b/tests/grammar/schema/union/fail/fail_4/stderr.golden similarity index 100% rename from test/grammar/schema/union/fail/fail_4/stderr.golden rename to tests/grammar/schema/union/fail/fail_4/stderr.golden diff --git a/test/grammar/schema/union/list/instance_0/main.k b/tests/grammar/schema/union/list/instance_0/main.k similarity index 100% rename from test/grammar/schema/union/list/instance_0/main.k rename to tests/grammar/schema/union/list/instance_0/main.k diff --git a/test/grammar/schema/union/list/instance_0/stdout.golden b/tests/grammar/schema/union/list/instance_0/stdout.golden similarity index 100% rename from test/grammar/schema/union/list/instance_0/stdout.golden rename to tests/grammar/schema/union/list/instance_0/stdout.golden diff --git a/test/grammar/schema/union/list/schema_0/main.k b/tests/grammar/schema/union/list/schema_0/main.k similarity index 100% rename from test/grammar/schema/union/list/schema_0/main.k rename to tests/grammar/schema/union/list/schema_0/main.k diff --git a/test/grammar/schema/union/list/schema_0/stdout.golden b/tests/grammar/schema/union/list/schema_0/stdout.golden similarity index 100% rename from test/grammar/schema/union/list/schema_0/stdout.golden rename to tests/grammar/schema/union/list/schema_0/stdout.golden diff --git a/test/grammar/schema/union/list/schema_1/main.k b/tests/grammar/schema/union/list/schema_1/main.k similarity index 100% rename from test/grammar/schema/union/list/schema_1/main.k rename to tests/grammar/schema/union/list/schema_1/main.k diff --git a/test/grammar/schema/union/list/schema_1/stdout.golden b/tests/grammar/schema/union/list/schema_1/stdout.golden similarity index 100% rename from test/grammar/schema/union/list/schema_1/stdout.golden rename to tests/grammar/schema/union/list/schema_1/stdout.golden diff --git a/test/grammar/schema/union/list/schema_2/kcl.mod b/tests/grammar/schema/union/list/schema_2/kcl.mod similarity index 100% rename from test/grammar/schema/union/list/schema_2/kcl.mod rename to tests/grammar/schema/union/list/schema_2/kcl.mod diff --git a/test/grammar/schema/union/list/schema_2/main.k b/tests/grammar/schema/union/list/schema_2/main.k similarity index 100% rename from test/grammar/schema/union/list/schema_2/main.k rename to tests/grammar/schema/union/list/schema_2/main.k diff --git a/test/grammar/schema/union/list/schema_2/stdout.golden b/tests/grammar/schema/union/list/schema_2/stdout.golden similarity index 100% rename from test/grammar/schema/union/list/schema_2/stdout.golden rename to tests/grammar/schema/union/list/schema_2/stdout.golden diff --git a/test/grammar/schema/union/list/schema_2/temp/temp.k b/tests/grammar/schema/union/list/schema_2/temp/temp.k similarity index 100% rename from test/grammar/schema/union/list/schema_2/temp/temp.k rename to tests/grammar/schema/union/list/schema_2/temp/temp.k diff --git a/test/grammar/schema/union/list/variable_fail_0/main.k b/tests/grammar/schema/union/list/variable_fail_0/main.k similarity index 100% rename from test/grammar/schema/union/list/variable_fail_0/main.k rename to tests/grammar/schema/union/list/variable_fail_0/main.k diff --git a/test/grammar/schema/union/list/variable_fail_0/stderr.golden b/tests/grammar/schema/union/list/variable_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/union/list/variable_fail_0/stderr.golden rename to tests/grammar/schema/union/list/variable_fail_0/stderr.golden diff --git a/test/grammar/schema/union/variable_fail/int/main.k b/tests/grammar/schema/union/variable_fail/int/main.k similarity index 100% rename from test/grammar/schema/union/variable_fail/int/main.k rename to tests/grammar/schema/union/variable_fail/int/main.k diff --git a/test/grammar/schema/union/variable_fail/int/stderr.golden b/tests/grammar/schema/union/variable_fail/int/stderr.golden similarity index 100% rename from test/grammar/schema/union/variable_fail/int/stderr.golden rename to tests/grammar/schema/union/variable_fail/int/stderr.golden diff --git a/test/grammar/schema/union/variable_fail/list/main.k b/tests/grammar/schema/union/variable_fail/list/main.k similarity index 100% rename from test/grammar/schema/union/variable_fail/list/main.k rename to tests/grammar/schema/union/variable_fail/list/main.k diff --git a/test/grammar/schema/union/variable_fail/list/stderr.golden b/tests/grammar/schema/union/variable_fail/list/stderr.golden similarity index 100% rename from test/grammar/schema/union/variable_fail/list/stderr.golden rename to tests/grammar/schema/union/variable_fail/list/stderr.golden diff --git a/test/grammar/schema/var_not_define_fail/var_not_define_fail_0/main.k b/tests/grammar/schema/var_not_define_fail/var_not_define_fail_0/main.k similarity index 100% rename from test/grammar/schema/var_not_define_fail/var_not_define_fail_0/main.k rename to tests/grammar/schema/var_not_define_fail/var_not_define_fail_0/main.k diff --git a/test/grammar/schema/var_not_define_fail/var_not_define_fail_0/stderr.golden b/tests/grammar/schema/var_not_define_fail/var_not_define_fail_0/stderr.golden similarity index 100% rename from test/grammar/schema/var_not_define_fail/var_not_define_fail_0/stderr.golden rename to tests/grammar/schema/var_not_define_fail/var_not_define_fail_0/stderr.golden diff --git a/test/grammar/schema/var_not_define_fail/var_not_define_fail_1/main.k b/tests/grammar/schema/var_not_define_fail/var_not_define_fail_1/main.k similarity index 100% rename from test/grammar/schema/var_not_define_fail/var_not_define_fail_1/main.k rename to tests/grammar/schema/var_not_define_fail/var_not_define_fail_1/main.k diff --git a/test/grammar/schema/var_not_define_fail/var_not_define_fail_1/stderr.golden b/tests/grammar/schema/var_not_define_fail/var_not_define_fail_1/stderr.golden similarity index 100% rename from test/grammar/schema/var_not_define_fail/var_not_define_fail_1/stderr.golden rename to tests/grammar/schema/var_not_define_fail/var_not_define_fail_1/stderr.golden diff --git a/test/grammar/schema/without_brakets/test_0/main.k b/tests/grammar/schema/without_brakets/test_0/main.k similarity index 100% rename from test/grammar/schema/without_brakets/test_0/main.k rename to tests/grammar/schema/without_brakets/test_0/main.k diff --git a/test/grammar/schema/without_brakets/test_0/stdout.golden b/tests/grammar/schema/without_brakets/test_0/stdout.golden similarity index 100% rename from test/grammar/schema/without_brakets/test_0/stdout.golden rename to tests/grammar/schema/without_brakets/test_0/stdout.golden diff --git a/test/grammar/schema/without_brakets/test_1/main.k b/tests/grammar/schema/without_brakets/test_1/main.k similarity index 100% rename from test/grammar/schema/without_brakets/test_1/main.k rename to tests/grammar/schema/without_brakets/test_1/main.k diff --git a/test/grammar/schema/without_brakets/test_1/stdout.golden b/tests/grammar/schema/without_brakets/test_1/stdout.golden similarity index 100% rename from test/grammar/schema/without_brakets/test_1/stdout.golden rename to tests/grammar/schema/without_brakets/test_1/stdout.golden diff --git a/test/grammar/schema/without_brakets/test_2/main.k b/tests/grammar/schema/without_brakets/test_2/main.k similarity index 100% rename from test/grammar/schema/without_brakets/test_2/main.k rename to tests/grammar/schema/without_brakets/test_2/main.k diff --git a/test/grammar/schema/without_brakets/test_2/stdout.golden b/tests/grammar/schema/without_brakets/test_2/stdout.golden similarity index 100% rename from test/grammar/schema/without_brakets/test_2/stdout.golden rename to tests/grammar/schema/without_brakets/test_2/stdout.golden diff --git a/test/grammar/show_hidden/config/main.k b/tests/grammar/show_hidden/config/main.k similarity index 100% rename from test/grammar/show_hidden/config/main.k rename to tests/grammar/show_hidden/config/main.k diff --git a/test/grammar/show_hidden/config/settings.yaml b/tests/grammar/show_hidden/config/settings.yaml similarity index 100% rename from test/grammar/show_hidden/config/settings.yaml rename to tests/grammar/show_hidden/config/settings.yaml diff --git a/test/grammar/show_hidden/config/stdout.golden b/tests/grammar/show_hidden/config/stdout.golden similarity index 100% rename from test/grammar/show_hidden/config/stdout.golden rename to tests/grammar/show_hidden/config/stdout.golden diff --git a/test/grammar/show_hidden/schema/main.k b/tests/grammar/show_hidden/schema/main.k similarity index 100% rename from test/grammar/show_hidden/schema/main.k rename to tests/grammar/show_hidden/schema/main.k diff --git a/test/grammar/show_hidden/schema/settings.yaml b/tests/grammar/show_hidden/schema/settings.yaml similarity index 100% rename from test/grammar/show_hidden/schema/settings.yaml rename to tests/grammar/show_hidden/schema/settings.yaml diff --git a/test/grammar/show_hidden/schema/stdout.golden b/tests/grammar/show_hidden/schema/stdout.golden similarity index 100% rename from test/grammar/show_hidden/schema/stdout.golden rename to tests/grammar/show_hidden/schema/stdout.golden diff --git a/test/grammar/show_hidden/simple/main.k b/tests/grammar/show_hidden/simple/main.k similarity index 100% rename from test/grammar/show_hidden/simple/main.k rename to tests/grammar/show_hidden/simple/main.k diff --git a/test/grammar/show_hidden/simple/settings.yaml b/tests/grammar/show_hidden/simple/settings.yaml similarity index 100% rename from test/grammar/show_hidden/simple/settings.yaml rename to tests/grammar/show_hidden/simple/settings.yaml diff --git a/test/grammar/show_hidden/simple/stdout.golden b/tests/grammar/show_hidden/simple/stdout.golden similarity index 100% rename from test/grammar/show_hidden/simple/stdout.golden rename to tests/grammar/show_hidden/simple/stdout.golden diff --git a/test/grammar/sort_keys/config/main.k b/tests/grammar/sort_keys/config/main.k similarity index 100% rename from test/grammar/sort_keys/config/main.k rename to tests/grammar/sort_keys/config/main.k diff --git a/test/grammar/sort_keys/config/settings.yaml b/tests/grammar/sort_keys/config/settings.yaml similarity index 100% rename from test/grammar/sort_keys/config/settings.yaml rename to tests/grammar/sort_keys/config/settings.yaml diff --git a/test/grammar/sort_keys/config/stdout.golden b/tests/grammar/sort_keys/config/stdout.golden similarity index 100% rename from test/grammar/sort_keys/config/stdout.golden rename to tests/grammar/sort_keys/config/stdout.golden diff --git a/test/grammar/sort_keys/hello/main.k b/tests/grammar/sort_keys/hello/main.k similarity index 100% rename from test/grammar/sort_keys/hello/main.k rename to tests/grammar/sort_keys/hello/main.k diff --git a/test/grammar/sort_keys/hello/settings.yaml b/tests/grammar/sort_keys/hello/settings.yaml similarity index 100% rename from test/grammar/sort_keys/hello/settings.yaml rename to tests/grammar/sort_keys/hello/settings.yaml diff --git a/test/grammar/sort_keys/hello/stdout.golden b/tests/grammar/sort_keys/hello/stdout.golden similarity index 100% rename from test/grammar/sort_keys/hello/stdout.golden rename to tests/grammar/sort_keys/hello/stdout.golden diff --git a/test/grammar/sort_keys/schema/main.k b/tests/grammar/sort_keys/schema/main.k similarity index 100% rename from test/grammar/sort_keys/schema/main.k rename to tests/grammar/sort_keys/schema/main.k diff --git a/test/grammar/sort_keys/schema/settings.yaml b/tests/grammar/sort_keys/schema/settings.yaml similarity index 100% rename from test/grammar/sort_keys/schema/settings.yaml rename to tests/grammar/sort_keys/schema/settings.yaml diff --git a/test/grammar/sort_keys/schema/stdout.golden b/tests/grammar/sort_keys/schema/stdout.golden similarity index 100% rename from test/grammar/sort_keys/schema/stdout.golden rename to tests/grammar/sort_keys/schema/stdout.golden diff --git a/test/grammar/syntax/else_if_token/main.k b/tests/grammar/syntax/else_if_token/main.k similarity index 100% rename from test/grammar/syntax/else_if_token/main.k rename to tests/grammar/syntax/else_if_token/main.k diff --git a/test/grammar/syntax/else_if_token/stderr.golden b/tests/grammar/syntax/else_if_token/stderr.golden similarity index 100% rename from test/grammar/syntax/else_if_token/stderr.golden rename to tests/grammar/syntax/else_if_token/stderr.golden diff --git a/test/grammar/syntax/general/multiple_assign/case0/main.k b/tests/grammar/syntax/general/multiple_assign/case0/main.k similarity index 100% rename from test/grammar/syntax/general/multiple_assign/case0/main.k rename to tests/grammar/syntax/general/multiple_assign/case0/main.k diff --git a/test/grammar/syntax/general/multiple_assign/case0/stderr.golden b/tests/grammar/syntax/general/multiple_assign/case0/stderr.golden similarity index 100% rename from test/grammar/syntax/general/multiple_assign/case0/stderr.golden rename to tests/grammar/syntax/general/multiple_assign/case0/stderr.golden diff --git a/test/grammar/syntax/general/multiple_assign/case1/main.k b/tests/grammar/syntax/general/multiple_assign/case1/main.k similarity index 100% rename from test/grammar/syntax/general/multiple_assign/case1/main.k rename to tests/grammar/syntax/general/multiple_assign/case1/main.k diff --git a/test/grammar/syntax/general/multiple_assign/case1/stderr.golden b/tests/grammar/syntax/general/multiple_assign/case1/stderr.golden similarity index 100% rename from test/grammar/syntax/general/multiple_assign/case1/stderr.golden rename to tests/grammar/syntax/general/multiple_assign/case1/stderr.golden diff --git a/test/grammar/syntax/general/unnamed/case0/main.k b/tests/grammar/syntax/general/unnamed/case0/main.k similarity index 100% rename from test/grammar/syntax/general/unnamed/case0/main.k rename to tests/grammar/syntax/general/unnamed/case0/main.k diff --git a/test/grammar/syntax/general/unnamed/case0/stderr.golden b/tests/grammar/syntax/general/unnamed/case0/stderr.golden similarity index 100% rename from test/grammar/syntax/general/unnamed/case0/stderr.golden rename to tests/grammar/syntax/general/unnamed/case0/stderr.golden diff --git a/test/grammar/syntax/indent/indent_error_0/main.k b/tests/grammar/syntax/indent/indent_error_0/main.k similarity index 100% rename from test/grammar/syntax/indent/indent_error_0/main.k rename to tests/grammar/syntax/indent/indent_error_0/main.k diff --git a/test/grammar/syntax/indent/indent_error_0/stderr.golden b/tests/grammar/syntax/indent/indent_error_0/stderr.golden similarity index 100% rename from test/grammar/syntax/indent/indent_error_0/stderr.golden rename to tests/grammar/syntax/indent/indent_error_0/stderr.golden diff --git a/test/grammar/syntax/indent/indent_error_1/main.k b/tests/grammar/syntax/indent/indent_error_1/main.k similarity index 100% rename from test/grammar/syntax/indent/indent_error_1/main.k rename to tests/grammar/syntax/indent/indent_error_1/main.k diff --git a/test/grammar/syntax/indent/indent_error_1/stderr.golden b/tests/grammar/syntax/indent/indent_error_1/stderr.golden similarity index 100% rename from test/grammar/syntax/indent/indent_error_1/stderr.golden rename to tests/grammar/syntax/indent/indent_error_1/stderr.golden diff --git a/test/grammar/syntax/tab/tab_error_0/main.k b/tests/grammar/syntax/tab/tab_error_0/main.k similarity index 100% rename from test/grammar/syntax/tab/tab_error_0/main.k rename to tests/grammar/syntax/tab/tab_error_0/main.k diff --git a/test/grammar/syntax/tab/tab_error_0/stderr.golden b/tests/grammar/syntax/tab/tab_error_0/stderr.golden similarity index 100% rename from test/grammar/syntax/tab/tab_error_0/stderr.golden rename to tests/grammar/syntax/tab/tab_error_0/stderr.golden diff --git a/test/grammar/syntax/tab/tab_error_1/main.k b/tests/grammar/syntax/tab/tab_error_1/main.k similarity index 100% rename from test/grammar/syntax/tab/tab_error_1/main.k rename to tests/grammar/syntax/tab/tab_error_1/main.k diff --git a/test/grammar/syntax/tab/tab_error_1/stderr.golden b/tests/grammar/syntax/tab/tab_error_1/stderr.golden similarity index 100% rename from test/grammar/syntax/tab/tab_error_1/stderr.golden rename to tests/grammar/syntax/tab/tab_error_1/stderr.golden diff --git a/test/grammar/syntax/tab/tab_normal_0/main.k b/tests/grammar/syntax/tab/tab_normal_0/main.k similarity index 100% rename from test/grammar/syntax/tab/tab_normal_0/main.k rename to tests/grammar/syntax/tab/tab_normal_0/main.k diff --git a/test/grammar/syntax/tab/tab_normal_0/stdout.golden b/tests/grammar/syntax/tab/tab_normal_0/stdout.golden similarity index 100% rename from test/grammar/syntax/tab/tab_normal_0/stdout.golden rename to tests/grammar/syntax/tab/tab_normal_0/stdout.golden diff --git a/test/grammar/syntax/underline/main.k b/tests/grammar/syntax/underline/main.k similarity index 100% rename from test/grammar/syntax/underline/main.k rename to tests/grammar/syntax/underline/main.k diff --git a/test/grammar/syntax/underline/stderr.golden b/tests/grammar/syntax/underline/stderr.golden similarity index 100% rename from test/grammar/syntax/underline/stderr.golden rename to tests/grammar/syntax/underline/stderr.golden diff --git a/kclvm/tests/integration/grammar/test_grammar.py b/tests/grammar/test_grammar.py similarity index 96% rename from kclvm/tests/integration/grammar/test_grammar.py rename to tests/grammar/test_grammar.py index 88f15fbd7..a657a28cb 100644 --- a/kclvm/tests/integration/grammar/test_grammar.py +++ b/tests/grammar/test_grammar.py @@ -10,7 +10,6 @@ STDOUT_GOLDEN = "stdout.golden" STDERR_GOLDEN = "stderr.golden" SETTINGS_FILE = "settings.yaml" -TEST_PATH = "test/grammar" # Ruamel YAML instance ruamel_yaml = YAML(pure=True) @@ -68,7 +67,7 @@ def generate_golden_file(py_file_name): if os.path.isfile(py_file_name): try: process = subprocess.Popen( - ["kclvm", py_file_name], + ["kcl", py_file_name], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=dict(os.environ), @@ -97,9 +96,7 @@ def read_settings_file(settings_file_name): print("##### K Language Grammar Test Suite #####") -test_path = pathlib.Path(__file__).parent.parent.parent.parent.parent.joinpath( - TEST_PATH -) +test_path = pathlib.Path(__file__).parent test_dirs = find_test_dirs(str(test_path), "") @@ -117,7 +114,7 @@ def remove_extra_empty_lines(text): def test_grammar(test_dir): print("Testing {}".format(test_dir)) test_settings = read_settings_file(os.path.join(test_dir, SETTINGS_FILE)) - kcl_command = ["kclvm_cli", "run", TEST_FILE] + kcl_command = ["libkcl", "run", TEST_FILE] if test_settings and test_settings["kcl_options"]: kcl_command.extend(test_settings["kcl_options"].split()) process = subprocess.Popen( diff --git a/test/grammar/types/any/any_01/main.k b/tests/grammar/types/any/any_01/main.k similarity index 100% rename from test/grammar/types/any/any_01/main.k rename to tests/grammar/types/any/any_01/main.k diff --git a/test/grammar/types/any/any_01/stdout.golden b/tests/grammar/types/any/any_01/stdout.golden similarity index 100% rename from test/grammar/types/any/any_01/stdout.golden rename to tests/grammar/types/any/any_01/stdout.golden diff --git a/test/grammar/types/args/call_expr_err_too_few_args_0/main.k b/tests/grammar/types/args/call_expr_err_too_few_args_0/main.k similarity index 100% rename from test/grammar/types/args/call_expr_err_too_few_args_0/main.k rename to tests/grammar/types/args/call_expr_err_too_few_args_0/main.k diff --git a/test/grammar/types/args/call_expr_err_too_few_args_0/stderr.golden b/tests/grammar/types/args/call_expr_err_too_few_args_0/stderr.golden similarity index 100% rename from test/grammar/types/args/call_expr_err_too_few_args_0/stderr.golden rename to tests/grammar/types/args/call_expr_err_too_few_args_0/stderr.golden diff --git a/test/grammar/types/args/call_expr_err_too_few_args_1/main.k b/tests/grammar/types/args/call_expr_err_too_few_args_1/main.k similarity index 100% rename from test/grammar/types/args/call_expr_err_too_few_args_1/main.k rename to tests/grammar/types/args/call_expr_err_too_few_args_1/main.k diff --git a/test/grammar/types/args/call_expr_err_too_few_args_1/stderr.golden b/tests/grammar/types/args/call_expr_err_too_few_args_1/stderr.golden similarity index 100% rename from test/grammar/types/args/call_expr_err_too_few_args_1/stderr.golden rename to tests/grammar/types/args/call_expr_err_too_few_args_1/stderr.golden diff --git a/test/grammar/types/args/lambda_types_01/main.k b/tests/grammar/types/args/lambda_types_01/main.k similarity index 100% rename from test/grammar/types/args/lambda_types_01/main.k rename to tests/grammar/types/args/lambda_types_01/main.k diff --git a/test/grammar/types/args/lambda_types_01/stdout.golden b/tests/grammar/types/args/lambda_types_01/stdout.golden similarity index 100% rename from test/grammar/types/args/lambda_types_01/stdout.golden rename to tests/grammar/types/args/lambda_types_01/stdout.golden diff --git a/test/grammar/types/args/lambda_types_02/main.k b/tests/grammar/types/args/lambda_types_02/main.k similarity index 100% rename from test/grammar/types/args/lambda_types_02/main.k rename to tests/grammar/types/args/lambda_types_02/main.k diff --git a/test/grammar/types/args/lambda_types_02/stdout.golden b/tests/grammar/types/args/lambda_types_02/stdout.golden similarity index 100% rename from test/grammar/types/args/lambda_types_02/stdout.golden rename to tests/grammar/types/args/lambda_types_02/stdout.golden diff --git a/test/grammar/types/args/lambda_types_03/main.k b/tests/grammar/types/args/lambda_types_03/main.k similarity index 100% rename from test/grammar/types/args/lambda_types_03/main.k rename to tests/grammar/types/args/lambda_types_03/main.k diff --git a/test/grammar/types/args/lambda_types_03/stdout.golden b/tests/grammar/types/args/lambda_types_03/stdout.golden similarity index 100% rename from test/grammar/types/args/lambda_types_03/stdout.golden rename to tests/grammar/types/args/lambda_types_03/stdout.golden diff --git a/test/grammar/types/args/lambda_types_err_01/main.k b/tests/grammar/types/args/lambda_types_err_01/main.k similarity index 100% rename from test/grammar/types/args/lambda_types_err_01/main.k rename to tests/grammar/types/args/lambda_types_err_01/main.k diff --git a/test/grammar/types/args/lambda_types_err_01/stderr.golden b/tests/grammar/types/args/lambda_types_err_01/stderr.golden similarity index 100% rename from test/grammar/types/args/lambda_types_err_01/stderr.golden rename to tests/grammar/types/args/lambda_types_err_01/stderr.golden diff --git a/test/grammar/types/args/lambda_types_err_02/main.k b/tests/grammar/types/args/lambda_types_err_02/main.k similarity index 100% rename from test/grammar/types/args/lambda_types_err_02/main.k rename to tests/grammar/types/args/lambda_types_err_02/main.k diff --git a/test/grammar/types/args/lambda_types_err_02/stderr.golden b/tests/grammar/types/args/lambda_types_err_02/stderr.golden similarity index 100% rename from test/grammar/types/args/lambda_types_err_02/stderr.golden rename to tests/grammar/types/args/lambda_types_err_02/stderr.golden diff --git a/test/grammar/types/args/schema_types_01/main.k b/tests/grammar/types/args/schema_types_01/main.k similarity index 100% rename from test/grammar/types/args/schema_types_01/main.k rename to tests/grammar/types/args/schema_types_01/main.k diff --git a/test/grammar/types/args/schema_types_01/stdout.golden b/tests/grammar/types/args/schema_types_01/stdout.golden similarity index 100% rename from test/grammar/types/args/schema_types_01/stdout.golden rename to tests/grammar/types/args/schema_types_01/stdout.golden diff --git a/test/grammar/types/args/schema_types_02_schema/kcl.mod b/tests/grammar/types/args/schema_types_02_schema/kcl.mod similarity index 100% rename from test/grammar/types/args/schema_types_02_schema/kcl.mod rename to tests/grammar/types/args/schema_types_02_schema/kcl.mod diff --git a/test/grammar/types/args/schema_types_02_schema/main.k b/tests/grammar/types/args/schema_types_02_schema/main.k similarity index 100% rename from test/grammar/types/args/schema_types_02_schema/main.k rename to tests/grammar/types/args/schema_types_02_schema/main.k diff --git a/test/grammar/types/args/schema_types_02_schema/stdout.golden b/tests/grammar/types/args/schema_types_02_schema/stdout.golden similarity index 100% rename from test/grammar/types/args/schema_types_02_schema/stdout.golden rename to tests/grammar/types/args/schema_types_02_schema/stdout.golden diff --git a/test/grammar/types/args/schema_types_02_schema/sub/sub.k b/tests/grammar/types/args/schema_types_02_schema/sub/sub.k similarity index 100% rename from test/grammar/types/args/schema_types_02_schema/sub/sub.k rename to tests/grammar/types/args/schema_types_02_schema/sub/sub.k diff --git a/test/grammar/types/args/schema_types_03_list/main.k b/tests/grammar/types/args/schema_types_03_list/main.k similarity index 100% rename from test/grammar/types/args/schema_types_03_list/main.k rename to tests/grammar/types/args/schema_types_03_list/main.k diff --git a/test/grammar/types/args/schema_types_03_list/stdout.golden b/tests/grammar/types/args/schema_types_03_list/stdout.golden similarity index 100% rename from test/grammar/types/args/schema_types_03_list/stdout.golden rename to tests/grammar/types/args/schema_types_03_list/stdout.golden diff --git a/test/grammar/types/args/schema_types_04_partial/main.k b/tests/grammar/types/args/schema_types_04_partial/main.k similarity index 100% rename from test/grammar/types/args/schema_types_04_partial/main.k rename to tests/grammar/types/args/schema_types_04_partial/main.k diff --git a/test/grammar/types/args/schema_types_04_partial/stdout.golden b/tests/grammar/types/args/schema_types_04_partial/stdout.golden similarity index 100% rename from test/grammar/types/args/schema_types_04_partial/stdout.golden rename to tests/grammar/types/args/schema_types_04_partial/stdout.golden diff --git a/test/grammar/types/args/schema_types_05_without_config/main.k b/tests/grammar/types/args/schema_types_05_without_config/main.k similarity index 100% rename from test/grammar/types/args/schema_types_05_without_config/main.k rename to tests/grammar/types/args/schema_types_05_without_config/main.k diff --git a/test/grammar/types/args/schema_types_05_without_config/stdout.golden b/tests/grammar/types/args/schema_types_05_without_config/stdout.golden similarity index 100% rename from test/grammar/types/args/schema_types_05_without_config/stdout.golden rename to tests/grammar/types/args/schema_types_05_without_config/stdout.golden diff --git a/test/grammar/types/args/schema_types_06_kwargs/main.k b/tests/grammar/types/args/schema_types_06_kwargs/main.k similarity index 100% rename from test/grammar/types/args/schema_types_06_kwargs/main.k rename to tests/grammar/types/args/schema_types_06_kwargs/main.k diff --git a/test/grammar/types/args/schema_types_06_kwargs/stdout.golden b/tests/grammar/types/args/schema_types_06_kwargs/stdout.golden similarity index 100% rename from test/grammar/types/args/schema_types_06_kwargs/stdout.golden rename to tests/grammar/types/args/schema_types_06_kwargs/stdout.golden diff --git a/test/grammar/types/args/schema_types_07_union_types/main.k b/tests/grammar/types/args/schema_types_07_union_types/main.k similarity index 100% rename from test/grammar/types/args/schema_types_07_union_types/main.k rename to tests/grammar/types/args/schema_types_07_union_types/main.k diff --git a/test/grammar/types/args/schema_types_07_union_types/stdout.golden b/tests/grammar/types/args/schema_types_07_union_types/stdout.golden similarity index 100% rename from test/grammar/types/args/schema_types_07_union_types/stdout.golden rename to tests/grammar/types/args/schema_types_07_union_types/stdout.golden diff --git a/test/grammar/types/args/schema_types_err_01/main.k b/tests/grammar/types/args/schema_types_err_01/main.k similarity index 100% rename from test/grammar/types/args/schema_types_err_01/main.k rename to tests/grammar/types/args/schema_types_err_01/main.k diff --git a/test/grammar/types/args/schema_types_err_01/stderr.golden b/tests/grammar/types/args/schema_types_err_01/stderr.golden similarity index 100% rename from test/grammar/types/args/schema_types_err_01/stderr.golden rename to tests/grammar/types/args/schema_types_err_01/stderr.golden diff --git a/test/grammar/types/args/schema_types_err_02_schema/kcl.mod b/tests/grammar/types/args/schema_types_err_02_schema/kcl.mod similarity index 100% rename from test/grammar/types/args/schema_types_err_02_schema/kcl.mod rename to tests/grammar/types/args/schema_types_err_02_schema/kcl.mod diff --git a/test/grammar/types/args/schema_types_err_02_schema/main.k b/tests/grammar/types/args/schema_types_err_02_schema/main.k similarity index 100% rename from test/grammar/types/args/schema_types_err_02_schema/main.k rename to tests/grammar/types/args/schema_types_err_02_schema/main.k diff --git a/test/grammar/types/args/schema_types_err_02_schema/stderr.golden b/tests/grammar/types/args/schema_types_err_02_schema/stderr.golden similarity index 100% rename from test/grammar/types/args/schema_types_err_02_schema/stderr.golden rename to tests/grammar/types/args/schema_types_err_02_schema/stderr.golden diff --git a/test/grammar/types/args/schema_types_err_02_schema/sub/sub.k b/tests/grammar/types/args/schema_types_err_02_schema/sub/sub.k similarity index 100% rename from test/grammar/types/args/schema_types_err_02_schema/sub/sub.k rename to tests/grammar/types/args/schema_types_err_02_schema/sub/sub.k diff --git a/test/grammar/types/args/schema_types_err_03_list/main.k b/tests/grammar/types/args/schema_types_err_03_list/main.k similarity index 100% rename from test/grammar/types/args/schema_types_err_03_list/main.k rename to tests/grammar/types/args/schema_types_err_03_list/main.k diff --git a/test/grammar/types/args/schema_types_err_03_list/stderr.golden b/tests/grammar/types/args/schema_types_err_03_list/stderr.golden similarity index 100% rename from test/grammar/types/args/schema_types_err_03_list/stderr.golden rename to tests/grammar/types/args/schema_types_err_03_list/stderr.golden diff --git a/test/grammar/types/args/schema_types_err_04_without_config/main.k b/tests/grammar/types/args/schema_types_err_04_without_config/main.k similarity index 100% rename from test/grammar/types/args/schema_types_err_04_without_config/main.k rename to tests/grammar/types/args/schema_types_err_04_without_config/main.k diff --git a/test/grammar/types/args/schema_types_err_04_without_config/stderr.golden b/tests/grammar/types/args/schema_types_err_04_without_config/stderr.golden similarity index 100% rename from test/grammar/types/args/schema_types_err_04_without_config/stderr.golden rename to tests/grammar/types/args/schema_types_err_04_without_config/stderr.golden diff --git a/test/grammar/types/args/schema_types_err_05_kwargs/main.k b/tests/grammar/types/args/schema_types_err_05_kwargs/main.k similarity index 100% rename from test/grammar/types/args/schema_types_err_05_kwargs/main.k rename to tests/grammar/types/args/schema_types_err_05_kwargs/main.k diff --git a/test/grammar/types/args/schema_types_err_05_kwargs/stderr.golden b/tests/grammar/types/args/schema_types_err_05_kwargs/stderr.golden similarity index 100% rename from test/grammar/types/args/schema_types_err_05_kwargs/stderr.golden rename to tests/grammar/types/args/schema_types_err_05_kwargs/stderr.golden diff --git a/test/grammar/types/args/schema_types_err_too_many_args_0/main.k b/tests/grammar/types/args/schema_types_err_too_many_args_0/main.k similarity index 100% rename from test/grammar/types/args/schema_types_err_too_many_args_0/main.k rename to tests/grammar/types/args/schema_types_err_too_many_args_0/main.k diff --git a/test/grammar/types/args/schema_types_err_too_many_args_0/stderr.golden b/tests/grammar/types/args/schema_types_err_too_many_args_0/stderr.golden similarity index 100% rename from test/grammar/types/args/schema_types_err_too_many_args_0/stderr.golden rename to tests/grammar/types/args/schema_types_err_too_many_args_0/stderr.golden diff --git a/test/grammar/types/args/schema_types_err_too_many_args_1/main.k b/tests/grammar/types/args/schema_types_err_too_many_args_1/main.k similarity index 100% rename from test/grammar/types/args/schema_types_err_too_many_args_1/main.k rename to tests/grammar/types/args/schema_types_err_too_many_args_1/main.k diff --git a/test/grammar/types/args/schema_types_err_too_many_args_1/stderr.golden b/tests/grammar/types/args/schema_types_err_too_many_args_1/stderr.golden similarity index 100% rename from test/grammar/types/args/schema_types_err_too_many_args_1/stderr.golden rename to tests/grammar/types/args/schema_types_err_too_many_args_1/stderr.golden diff --git a/test/grammar/types/args/schema_types_err_too_many_args_2/main.k b/tests/grammar/types/args/schema_types_err_too_many_args_2/main.k similarity index 100% rename from test/grammar/types/args/schema_types_err_too_many_args_2/main.k rename to tests/grammar/types/args/schema_types_err_too_many_args_2/main.k diff --git a/test/grammar/types/args/schema_types_err_too_many_args_2/stderr.golden b/tests/grammar/types/args/schema_types_err_too_many_args_2/stderr.golden similarity index 100% rename from test/grammar/types/args/schema_types_err_too_many_args_2/stderr.golden rename to tests/grammar/types/args/schema_types_err_too_many_args_2/stderr.golden diff --git a/test/grammar/types/binary_expr/binary_expr_0/main.k b/tests/grammar/types/binary_expr/binary_expr_0/main.k similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_0/main.k rename to tests/grammar/types/binary_expr/binary_expr_0/main.k diff --git a/test/grammar/types/binary_expr/binary_expr_0/stdout.golden b/tests/grammar/types/binary_expr/binary_expr_0/stdout.golden similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_0/stdout.golden rename to tests/grammar/types/binary_expr/binary_expr_0/stdout.golden diff --git a/test/grammar/types/binary_expr/binary_expr_1/main.k b/tests/grammar/types/binary_expr/binary_expr_1/main.k similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_1/main.k rename to tests/grammar/types/binary_expr/binary_expr_1/main.k diff --git a/test/grammar/types/binary_expr/binary_expr_1/stdout.golden b/tests/grammar/types/binary_expr/binary_expr_1/stdout.golden similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_1/stdout.golden rename to tests/grammar/types/binary_expr/binary_expr_1/stdout.golden diff --git a/test/grammar/types/binary_expr/binary_expr_2/main.k b/tests/grammar/types/binary_expr/binary_expr_2/main.k similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_2/main.k rename to tests/grammar/types/binary_expr/binary_expr_2/main.k diff --git a/test/grammar/types/binary_expr/binary_expr_2/stdout.golden b/tests/grammar/types/binary_expr/binary_expr_2/stdout.golden similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_2/stdout.golden rename to tests/grammar/types/binary_expr/binary_expr_2/stdout.golden diff --git a/test/grammar/types/binary_expr/binary_expr_3/main.k b/tests/grammar/types/binary_expr/binary_expr_3/main.k similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_3/main.k rename to tests/grammar/types/binary_expr/binary_expr_3/main.k diff --git a/test/grammar/types/binary_expr/binary_expr_3/stdout.golden b/tests/grammar/types/binary_expr/binary_expr_3/stdout.golden similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_3/stdout.golden rename to tests/grammar/types/binary_expr/binary_expr_3/stdout.golden diff --git a/test/grammar/types/binary_expr/binary_expr_4/main.k b/tests/grammar/types/binary_expr/binary_expr_4/main.k similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_4/main.k rename to tests/grammar/types/binary_expr/binary_expr_4/main.k diff --git a/test/grammar/types/binary_expr/binary_expr_4/stdout.golden b/tests/grammar/types/binary_expr/binary_expr_4/stdout.golden similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_4/stdout.golden rename to tests/grammar/types/binary_expr/binary_expr_4/stdout.golden diff --git a/test/grammar/types/binary_expr/binary_expr_fail_0/main.k b/tests/grammar/types/binary_expr/binary_expr_fail_0/main.k similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_fail_0/main.k rename to tests/grammar/types/binary_expr/binary_expr_fail_0/main.k diff --git a/test/grammar/types/binary_expr/binary_expr_fail_0/stderr.golden b/tests/grammar/types/binary_expr/binary_expr_fail_0/stderr.golden similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_fail_0/stderr.golden rename to tests/grammar/types/binary_expr/binary_expr_fail_0/stderr.golden diff --git a/test/grammar/types/binary_expr/binary_expr_fail_1/main.k b/tests/grammar/types/binary_expr/binary_expr_fail_1/main.k similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_fail_1/main.k rename to tests/grammar/types/binary_expr/binary_expr_fail_1/main.k diff --git a/test/grammar/types/binary_expr/binary_expr_fail_1/stderr.golden b/tests/grammar/types/binary_expr/binary_expr_fail_1/stderr.golden similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_fail_1/stderr.golden rename to tests/grammar/types/binary_expr/binary_expr_fail_1/stderr.golden diff --git a/test/grammar/types/binary_expr/binary_expr_fail_2/main.k b/tests/grammar/types/binary_expr/binary_expr_fail_2/main.k similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_fail_2/main.k rename to tests/grammar/types/binary_expr/binary_expr_fail_2/main.k diff --git a/test/grammar/types/binary_expr/binary_expr_fail_2/stderr.golden b/tests/grammar/types/binary_expr/binary_expr_fail_2/stderr.golden similarity index 100% rename from test/grammar/types/binary_expr/binary_expr_fail_2/stderr.golden rename to tests/grammar/types/binary_expr/binary_expr_fail_2/stderr.golden diff --git a/test/grammar/types/config/config_ty_0/main.k b/tests/grammar/types/config/config_ty_0/main.k similarity index 100% rename from test/grammar/types/config/config_ty_0/main.k rename to tests/grammar/types/config/config_ty_0/main.k diff --git a/test/grammar/types/config/config_ty_0/stdout.golden b/tests/grammar/types/config/config_ty_0/stdout.golden similarity index 100% rename from test/grammar/types/config/config_ty_0/stdout.golden rename to tests/grammar/types/config/config_ty_0/stdout.golden diff --git a/test/grammar/types/config/config_ty_1/main.k b/tests/grammar/types/config/config_ty_1/main.k similarity index 100% rename from test/grammar/types/config/config_ty_1/main.k rename to tests/grammar/types/config/config_ty_1/main.k diff --git a/test/grammar/types/config/config_ty_1/stdout.golden b/tests/grammar/types/config/config_ty_1/stdout.golden similarity index 100% rename from test/grammar/types/config/config_ty_1/stdout.golden rename to tests/grammar/types/config/config_ty_1/stdout.golden diff --git a/test/grammar/types/config/config_ty_2/main.k b/tests/grammar/types/config/config_ty_2/main.k similarity index 100% rename from test/grammar/types/config/config_ty_2/main.k rename to tests/grammar/types/config/config_ty_2/main.k diff --git a/test/grammar/types/config/config_ty_2/stdout.golden b/tests/grammar/types/config/config_ty_2/stdout.golden similarity index 100% rename from test/grammar/types/config/config_ty_2/stdout.golden rename to tests/grammar/types/config/config_ty_2/stdout.golden diff --git a/test/grammar/types/config/config_ty_3/main.k b/tests/grammar/types/config/config_ty_3/main.k similarity index 100% rename from test/grammar/types/config/config_ty_3/main.k rename to tests/grammar/types/config/config_ty_3/main.k diff --git a/test/grammar/types/config/config_ty_3/stdout.golden b/tests/grammar/types/config/config_ty_3/stdout.golden similarity index 100% rename from test/grammar/types/config/config_ty_3/stdout.golden rename to tests/grammar/types/config/config_ty_3/stdout.golden diff --git a/test/grammar/types/interpolation/interpolation_0/main.k b/tests/grammar/types/interpolation/interpolation_0/main.k similarity index 100% rename from test/grammar/types/interpolation/interpolation_0/main.k rename to tests/grammar/types/interpolation/interpolation_0/main.k diff --git a/test/grammar/types/interpolation/interpolation_0/stdout.golden b/tests/grammar/types/interpolation/interpolation_0/stdout.golden similarity index 100% rename from test/grammar/types/interpolation/interpolation_0/stdout.golden rename to tests/grammar/types/interpolation/interpolation_0/stdout.golden diff --git a/test/grammar/types/interpolation/interpolation_1/main.k b/tests/grammar/types/interpolation/interpolation_1/main.k similarity index 100% rename from test/grammar/types/interpolation/interpolation_1/main.k rename to tests/grammar/types/interpolation/interpolation_1/main.k diff --git a/test/grammar/types/interpolation/interpolation_1/stdout.golden b/tests/grammar/types/interpolation/interpolation_1/stdout.golden similarity index 100% rename from test/grammar/types/interpolation/interpolation_1/stdout.golden rename to tests/grammar/types/interpolation/interpolation_1/stdout.golden diff --git a/test/grammar/types/literal/lit_01/main.k b/tests/grammar/types/literal/lit_01/main.k similarity index 100% rename from test/grammar/types/literal/lit_01/main.k rename to tests/grammar/types/literal/lit_01/main.k diff --git a/test/grammar/types/literal/lit_01/stdout.golden b/tests/grammar/types/literal/lit_01/stdout.golden similarity index 100% rename from test/grammar/types/literal/lit_01/stdout.golden rename to tests/grammar/types/literal/lit_01/stdout.golden diff --git a/test/grammar/types/literal/lit_02_union/main.k b/tests/grammar/types/literal/lit_02_union/main.k similarity index 100% rename from test/grammar/types/literal/lit_02_union/main.k rename to tests/grammar/types/literal/lit_02_union/main.k diff --git a/test/grammar/types/literal/lit_02_union/stdout.golden b/tests/grammar/types/literal/lit_02_union/stdout.golden similarity index 100% rename from test/grammar/types/literal/lit_02_union/stdout.golden rename to tests/grammar/types/literal/lit_02_union/stdout.golden diff --git a/test/grammar/types/literal/lit_03_int_none/main.k b/tests/grammar/types/literal/lit_03_int_none/main.k similarity index 100% rename from test/grammar/types/literal/lit_03_int_none/main.k rename to tests/grammar/types/literal/lit_03_int_none/main.k diff --git a/test/grammar/types/literal/lit_03_int_none/stdout.golden b/tests/grammar/types/literal/lit_03_int_none/stdout.golden similarity index 100% rename from test/grammar/types/literal/lit_03_int_none/stdout.golden rename to tests/grammar/types/literal/lit_03_int_none/stdout.golden diff --git a/test/grammar/types/literal/lit_04_unit/main.k b/tests/grammar/types/literal/lit_04_unit/main.k similarity index 100% rename from test/grammar/types/literal/lit_04_unit/main.k rename to tests/grammar/types/literal/lit_04_unit/main.k diff --git a/test/grammar/types/literal/lit_04_unit/stdout.golden b/tests/grammar/types/literal/lit_04_unit/stdout.golden similarity index 100% rename from test/grammar/types/literal/lit_04_unit/stdout.golden rename to tests/grammar/types/literal/lit_04_unit/stdout.golden diff --git a/test/grammar/types/literal/lit_05_dict_key_lit_union/main.k b/tests/grammar/types/literal/lit_05_dict_key_lit_union/main.k similarity index 100% rename from test/grammar/types/literal/lit_05_dict_key_lit_union/main.k rename to tests/grammar/types/literal/lit_05_dict_key_lit_union/main.k diff --git a/test/grammar/types/literal/lit_05_dict_key_lit_union/stdout.golden b/tests/grammar/types/literal/lit_05_dict_key_lit_union/stdout.golden similarity index 100% rename from test/grammar/types/literal/lit_05_dict_key_lit_union/stdout.golden rename to tests/grammar/types/literal/lit_05_dict_key_lit_union/stdout.golden diff --git a/test/grammar/types/literal/lit_06_entry_id_key/main.k b/tests/grammar/types/literal/lit_06_entry_id_key/main.k similarity index 100% rename from test/grammar/types/literal/lit_06_entry_id_key/main.k rename to tests/grammar/types/literal/lit_06_entry_id_key/main.k diff --git a/test/grammar/types/literal/lit_06_entry_id_key/stdout.golden b/tests/grammar/types/literal/lit_06_entry_id_key/stdout.golden similarity index 100% rename from test/grammar/types/literal/lit_06_entry_id_key/stdout.golden rename to tests/grammar/types/literal/lit_06_entry_id_key/stdout.golden diff --git a/test/grammar/types/literal/lit_07_uf8_str_union/main.k b/tests/grammar/types/literal/lit_07_uf8_str_union/main.k similarity index 100% rename from test/grammar/types/literal/lit_07_uf8_str_union/main.k rename to tests/grammar/types/literal/lit_07_uf8_str_union/main.k diff --git a/test/grammar/types/literal/lit_07_uf8_str_union/stdout.golden b/tests/grammar/types/literal/lit_07_uf8_str_union/stdout.golden similarity index 100% rename from test/grammar/types/literal/lit_07_uf8_str_union/stdout.golden rename to tests/grammar/types/literal/lit_07_uf8_str_union/stdout.golden diff --git a/test/grammar/types/literal/lit_err_01_bool_01/main.k b/tests/grammar/types/literal/lit_err_01_bool_01/main.k similarity index 100% rename from test/grammar/types/literal/lit_err_01_bool_01/main.k rename to tests/grammar/types/literal/lit_err_01_bool_01/main.k diff --git a/test/grammar/types/literal/lit_err_01_bool_01/stderr.golden b/tests/grammar/types/literal/lit_err_01_bool_01/stderr.golden similarity index 100% rename from test/grammar/types/literal/lit_err_01_bool_01/stderr.golden rename to tests/grammar/types/literal/lit_err_01_bool_01/stderr.golden diff --git a/test/grammar/types/literal/lit_err_01_bool_02/main.k b/tests/grammar/types/literal/lit_err_01_bool_02/main.k similarity index 100% rename from test/grammar/types/literal/lit_err_01_bool_02/main.k rename to tests/grammar/types/literal/lit_err_01_bool_02/main.k diff --git a/test/grammar/types/literal/lit_err_01_bool_02/stderr.golden b/tests/grammar/types/literal/lit_err_01_bool_02/stderr.golden similarity index 100% rename from test/grammar/types/literal/lit_err_01_bool_02/stderr.golden rename to tests/grammar/types/literal/lit_err_01_bool_02/stderr.golden diff --git a/test/grammar/types/literal/lit_err_02_int_01/main.k b/tests/grammar/types/literal/lit_err_02_int_01/main.k similarity index 100% rename from test/grammar/types/literal/lit_err_02_int_01/main.k rename to tests/grammar/types/literal/lit_err_02_int_01/main.k diff --git a/test/grammar/types/literal/lit_err_02_int_01/stderr.golden b/tests/grammar/types/literal/lit_err_02_int_01/stderr.golden similarity index 100% rename from test/grammar/types/literal/lit_err_02_int_01/stderr.golden rename to tests/grammar/types/literal/lit_err_02_int_01/stderr.golden diff --git a/test/grammar/types/literal/lit_err_02_int_02/main.k b/tests/grammar/types/literal/lit_err_02_int_02/main.k similarity index 100% rename from test/grammar/types/literal/lit_err_02_int_02/main.k rename to tests/grammar/types/literal/lit_err_02_int_02/main.k diff --git a/test/grammar/types/literal/lit_err_02_int_02/stderr.golden b/tests/grammar/types/literal/lit_err_02_int_02/stderr.golden similarity index 100% rename from test/grammar/types/literal/lit_err_02_int_02/stderr.golden rename to tests/grammar/types/literal/lit_err_02_int_02/stderr.golden diff --git a/test/grammar/types/literal/lit_err_03_float_01/main.k b/tests/grammar/types/literal/lit_err_03_float_01/main.k similarity index 100% rename from test/grammar/types/literal/lit_err_03_float_01/main.k rename to tests/grammar/types/literal/lit_err_03_float_01/main.k diff --git a/test/grammar/types/literal/lit_err_03_float_01/stderr.golden b/tests/grammar/types/literal/lit_err_03_float_01/stderr.golden similarity index 100% rename from test/grammar/types/literal/lit_err_03_float_01/stderr.golden rename to tests/grammar/types/literal/lit_err_03_float_01/stderr.golden diff --git a/test/grammar/types/literal/lit_err_03_float_02/main.k b/tests/grammar/types/literal/lit_err_03_float_02/main.k similarity index 100% rename from test/grammar/types/literal/lit_err_03_float_02/main.k rename to tests/grammar/types/literal/lit_err_03_float_02/main.k diff --git a/test/grammar/types/literal/lit_err_03_float_02/stderr.golden b/tests/grammar/types/literal/lit_err_03_float_02/stderr.golden similarity index 100% rename from test/grammar/types/literal/lit_err_03_float_02/stderr.golden rename to tests/grammar/types/literal/lit_err_03_float_02/stderr.golden diff --git a/test/grammar/types/literal/lit_err_04_str_01/main.k b/tests/grammar/types/literal/lit_err_04_str_01/main.k similarity index 100% rename from test/grammar/types/literal/lit_err_04_str_01/main.k rename to tests/grammar/types/literal/lit_err_04_str_01/main.k diff --git a/test/grammar/types/literal/lit_err_04_str_01/stderr.golden b/tests/grammar/types/literal/lit_err_04_str_01/stderr.golden similarity index 100% rename from test/grammar/types/literal/lit_err_04_str_01/stderr.golden rename to tests/grammar/types/literal/lit_err_04_str_01/stderr.golden diff --git a/test/grammar/types/literal/lit_err_04_str_02/main.k b/tests/grammar/types/literal/lit_err_04_str_02/main.k similarity index 100% rename from test/grammar/types/literal/lit_err_04_str_02/main.k rename to tests/grammar/types/literal/lit_err_04_str_02/main.k diff --git a/test/grammar/types/literal/lit_err_04_str_02/stderr.golden b/tests/grammar/types/literal/lit_err_04_str_02/stderr.golden similarity index 100% rename from test/grammar/types/literal/lit_err_04_str_02/stderr.golden rename to tests/grammar/types/literal/lit_err_04_str_02/stderr.golden diff --git a/test/grammar/types/literal/lit_err_05_union_01/main.k b/tests/grammar/types/literal/lit_err_05_union_01/main.k similarity index 100% rename from test/grammar/types/literal/lit_err_05_union_01/main.k rename to tests/grammar/types/literal/lit_err_05_union_01/main.k diff --git a/test/grammar/types/literal/lit_err_05_union_01/stderr.golden b/tests/grammar/types/literal/lit_err_05_union_01/stderr.golden similarity index 100% rename from test/grammar/types/literal/lit_err_05_union_01/stderr.golden rename to tests/grammar/types/literal/lit_err_05_union_01/stderr.golden diff --git a/test/grammar/types/literal/lit_err_06_unit/main.k b/tests/grammar/types/literal/lit_err_06_unit/main.k similarity index 100% rename from test/grammar/types/literal/lit_err_06_unit/main.k rename to tests/grammar/types/literal/lit_err_06_unit/main.k diff --git a/test/grammar/types/literal/lit_err_06_unit/stderr.golden b/tests/grammar/types/literal/lit_err_06_unit/stderr.golden similarity index 100% rename from test/grammar/types/literal/lit_err_06_unit/stderr.golden rename to tests/grammar/types/literal/lit_err_06_unit/stderr.golden diff --git a/test/grammar/types/loop/loop_0/main.k b/tests/grammar/types/loop/loop_0/main.k similarity index 100% rename from test/grammar/types/loop/loop_0/main.k rename to tests/grammar/types/loop/loop_0/main.k diff --git a/test/grammar/types/loop/loop_0/stdout.golden b/tests/grammar/types/loop/loop_0/stdout.golden similarity index 100% rename from test/grammar/types/loop/loop_0/stdout.golden rename to tests/grammar/types/loop/loop_0/stdout.golden diff --git a/test/grammar/types/loop/loop_1/main.k b/tests/grammar/types/loop/loop_1/main.k similarity index 100% rename from test/grammar/types/loop/loop_1/main.k rename to tests/grammar/types/loop/loop_1/main.k diff --git a/test/grammar/types/loop/loop_1/stdout.golden b/tests/grammar/types/loop/loop_1/stdout.golden similarity index 100% rename from test/grammar/types/loop/loop_1/stdout.golden rename to tests/grammar/types/loop/loop_1/stdout.golden diff --git a/test/grammar/types/runtime_ty/runtime_ty_0/main.k b/tests/grammar/types/runtime_ty/runtime_ty_0/main.k similarity index 100% rename from test/grammar/types/runtime_ty/runtime_ty_0/main.k rename to tests/grammar/types/runtime_ty/runtime_ty_0/main.k diff --git a/test/grammar/types/runtime_ty/runtime_ty_0/stdout.golden b/tests/grammar/types/runtime_ty/runtime_ty_0/stdout.golden similarity index 100% rename from test/grammar/types/runtime_ty/runtime_ty_0/stdout.golden rename to tests/grammar/types/runtime_ty/runtime_ty_0/stdout.golden diff --git a/test/grammar/types/runtime_ty/runtime_ty_1/main.k b/tests/grammar/types/runtime_ty/runtime_ty_1/main.k similarity index 100% rename from test/grammar/types/runtime_ty/runtime_ty_1/main.k rename to tests/grammar/types/runtime_ty/runtime_ty_1/main.k diff --git a/test/grammar/types/runtime_ty/runtime_ty_1/stdout.golden b/tests/grammar/types/runtime_ty/runtime_ty_1/stdout.golden similarity index 100% rename from test/grammar/types/runtime_ty/runtime_ty_1/stdout.golden rename to tests/grammar/types/runtime_ty/runtime_ty_1/stdout.golden diff --git a/test/grammar/types/runtime_ty/runtime_ty_err_0/main.k b/tests/grammar/types/runtime_ty/runtime_ty_err_0/main.k similarity index 100% rename from test/grammar/types/runtime_ty/runtime_ty_err_0/main.k rename to tests/grammar/types/runtime_ty/runtime_ty_err_0/main.k diff --git a/test/grammar/types/runtime_ty/runtime_ty_err_0/stderr.golden b/tests/grammar/types/runtime_ty/runtime_ty_err_0/stderr.golden similarity index 100% rename from test/grammar/types/runtime_ty/runtime_ty_err_0/stderr.golden rename to tests/grammar/types/runtime_ty/runtime_ty_err_0/stderr.golden diff --git a/test/grammar/types/runtime_ty/runtime_ty_err_1/main.k b/tests/grammar/types/runtime_ty/runtime_ty_err_1/main.k similarity index 100% rename from test/grammar/types/runtime_ty/runtime_ty_err_1/main.k rename to tests/grammar/types/runtime_ty/runtime_ty_err_1/main.k diff --git a/test/grammar/types/runtime_ty/runtime_ty_err_1/stderr.golden b/tests/grammar/types/runtime_ty/runtime_ty_err_1/stderr.golden similarity index 100% rename from test/grammar/types/runtime_ty/runtime_ty_err_1/stderr.golden rename to tests/grammar/types/runtime_ty/runtime_ty_err_1/stderr.golden diff --git a/test/grammar/types/type_alias/type_alias_0/main.k b/tests/grammar/types/type_alias/type_alias_0/main.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_0/main.k rename to tests/grammar/types/type_alias/type_alias_0/main.k diff --git a/test/grammar/types/type_alias/type_alias_0/stdout.golden b/tests/grammar/types/type_alias/type_alias_0/stdout.golden similarity index 100% rename from test/grammar/types/type_alias/type_alias_0/stdout.golden rename to tests/grammar/types/type_alias/type_alias_0/stdout.golden diff --git a/test/grammar/types/type_alias/type_alias_1/main.k b/tests/grammar/types/type_alias/type_alias_1/main.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_1/main.k rename to tests/grammar/types/type_alias/type_alias_1/main.k diff --git a/test/grammar/types/type_alias/type_alias_1/stdout.golden b/tests/grammar/types/type_alias/type_alias_1/stdout.golden similarity index 100% rename from test/grammar/types/type_alias/type_alias_1/stdout.golden rename to tests/grammar/types/type_alias/type_alias_1/stdout.golden diff --git a/test/grammar/types/type_alias/type_alias_2/main.k b/tests/grammar/types/type_alias/type_alias_2/main.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_2/main.k rename to tests/grammar/types/type_alias/type_alias_2/main.k diff --git a/test/grammar/types/type_alias/type_alias_2/stdout.golden b/tests/grammar/types/type_alias/type_alias_2/stdout.golden similarity index 100% rename from test/grammar/types/type_alias/type_alias_2/stdout.golden rename to tests/grammar/types/type_alias/type_alias_2/stdout.golden diff --git a/test/grammar/types/type_alias/type_alias_3/main.k b/tests/grammar/types/type_alias/type_alias_3/main.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_3/main.k rename to tests/grammar/types/type_alias/type_alias_3/main.k diff --git a/test/grammar/types/type_alias/type_alias_3/stdout.golden b/tests/grammar/types/type_alias/type_alias_3/stdout.golden similarity index 100% rename from test/grammar/types/type_alias/type_alias_3/stdout.golden rename to tests/grammar/types/type_alias/type_alias_3/stdout.golden diff --git a/test/grammar/types/type_alias/type_alias_4/main.k b/tests/grammar/types/type_alias/type_alias_4/main.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_4/main.k rename to tests/grammar/types/type_alias/type_alias_4/main.k diff --git a/test/grammar/types/type_alias/type_alias_4/stdout.golden b/tests/grammar/types/type_alias/type_alias_4/stdout.golden similarity index 100% rename from test/grammar/types/type_alias/type_alias_4/stdout.golden rename to tests/grammar/types/type_alias/type_alias_4/stdout.golden diff --git a/test/grammar/types/type_alias/type_alias_5/main.k b/tests/grammar/types/type_alias/type_alias_5/main.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_5/main.k rename to tests/grammar/types/type_alias/type_alias_5/main.k diff --git a/test/grammar/types/type_alias/type_alias_5/stdout.golden b/tests/grammar/types/type_alias/type_alias_5/stdout.golden similarity index 100% rename from test/grammar/types/type_alias/type_alias_5/stdout.golden rename to tests/grammar/types/type_alias/type_alias_5/stdout.golden diff --git a/test/grammar/types/type_alias/type_alias_6/main.k b/tests/grammar/types/type_alias/type_alias_6/main.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_6/main.k rename to tests/grammar/types/type_alias/type_alias_6/main.k diff --git a/test/grammar/types/type_alias/type_alias_6/stdout.golden b/tests/grammar/types/type_alias/type_alias_6/stdout.golden similarity index 100% rename from test/grammar/types/type_alias/type_alias_6/stdout.golden rename to tests/grammar/types/type_alias/type_alias_6/stdout.golden diff --git a/test/grammar/types/type_alias/type_alias_7/kcl.mod b/tests/grammar/types/type_alias/type_alias_7/kcl.mod similarity index 100% rename from test/grammar/types/type_alias/type_alias_7/kcl.mod rename to tests/grammar/types/type_alias/type_alias_7/kcl.mod diff --git a/test/grammar/types/type_alias/type_alias_7/main.k b/tests/grammar/types/type_alias/type_alias_7/main.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_7/main.k rename to tests/grammar/types/type_alias/type_alias_7/main.k diff --git a/test/grammar/types/type_alias/type_alias_7/pkg/pkg.k b/tests/grammar/types/type_alias/type_alias_7/pkg/pkg.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_7/pkg/pkg.k rename to tests/grammar/types/type_alias/type_alias_7/pkg/pkg.k diff --git a/test/grammar/types/type_alias/type_alias_7/stdout.golden b/tests/grammar/types/type_alias/type_alias_7/stdout.golden similarity index 100% rename from test/grammar/types/type_alias/type_alias_7/stdout.golden rename to tests/grammar/types/type_alias/type_alias_7/stdout.golden diff --git a/test/grammar/types/type_alias/type_alias_8/kcl.mod b/tests/grammar/types/type_alias/type_alias_8/kcl.mod similarity index 100% rename from test/grammar/types/type_alias/type_alias_8/kcl.mod rename to tests/grammar/types/type_alias/type_alias_8/kcl.mod diff --git a/test/grammar/types/type_alias/type_alias_8/main.k b/tests/grammar/types/type_alias/type_alias_8/main.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_8/main.k rename to tests/grammar/types/type_alias/type_alias_8/main.k diff --git a/test/grammar/types/type_alias/type_alias_8/pkg/pkg.k b/tests/grammar/types/type_alias/type_alias_8/pkg/pkg.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_8/pkg/pkg.k rename to tests/grammar/types/type_alias/type_alias_8/pkg/pkg.k diff --git a/test/grammar/types/type_alias/type_alias_8/stdout.golden b/tests/grammar/types/type_alias/type_alias_8/stdout.golden similarity index 100% rename from test/grammar/types/type_alias/type_alias_8/stdout.golden rename to tests/grammar/types/type_alias/type_alias_8/stdout.golden diff --git a/test/grammar/types/type_alias/type_alias_err_0/main.k b/tests/grammar/types/type_alias/type_alias_err_0/main.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_err_0/main.k rename to tests/grammar/types/type_alias/type_alias_err_0/main.k diff --git a/test/grammar/types/type_alias/type_alias_err_0/stderr.golden b/tests/grammar/types/type_alias/type_alias_err_0/stderr.golden similarity index 100% rename from test/grammar/types/type_alias/type_alias_err_0/stderr.golden rename to tests/grammar/types/type_alias/type_alias_err_0/stderr.golden diff --git a/test/grammar/types/type_alias/type_alias_err_1/main.k b/tests/grammar/types/type_alias/type_alias_err_1/main.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_err_1/main.k rename to tests/grammar/types/type_alias/type_alias_err_1/main.k diff --git a/test/grammar/types/type_alias/type_alias_err_1/stderr.golden b/tests/grammar/types/type_alias/type_alias_err_1/stderr.golden similarity index 100% rename from test/grammar/types/type_alias/type_alias_err_1/stderr.golden rename to tests/grammar/types/type_alias/type_alias_err_1/stderr.golden diff --git a/test/grammar/types/type_alias/type_alias_err_2/main.k b/tests/grammar/types/type_alias/type_alias_err_2/main.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_err_2/main.k rename to tests/grammar/types/type_alias/type_alias_err_2/main.k diff --git a/test/grammar/types/type_alias/type_alias_err_2/stderr.golden b/tests/grammar/types/type_alias/type_alias_err_2/stderr.golden similarity index 100% rename from test/grammar/types/type_alias/type_alias_err_2/stderr.golden rename to tests/grammar/types/type_alias/type_alias_err_2/stderr.golden diff --git a/test/grammar/types/type_alias/type_alias_err_3/main.k b/tests/grammar/types/type_alias/type_alias_err_3/main.k similarity index 100% rename from test/grammar/types/type_alias/type_alias_err_3/main.k rename to tests/grammar/types/type_alias/type_alias_err_3/main.k diff --git a/test/grammar/types/type_alias/type_alias_err_3/stderr.golden b/tests/grammar/types/type_alias/type_alias_err_3/stderr.golden similarity index 100% rename from test/grammar/types/type_alias/type_alias_err_3/stderr.golden rename to tests/grammar/types/type_alias/type_alias_err_3/stderr.golden diff --git a/test/grammar/types/type_as/type_as_0/main.k b/tests/grammar/types/type_as/type_as_0/main.k similarity index 100% rename from test/grammar/types/type_as/type_as_0/main.k rename to tests/grammar/types/type_as/type_as_0/main.k diff --git a/test/grammar/types/type_as/type_as_0/stdout.golden b/tests/grammar/types/type_as/type_as_0/stdout.golden similarity index 100% rename from test/grammar/types/type_as/type_as_0/stdout.golden rename to tests/grammar/types/type_as/type_as_0/stdout.golden diff --git a/test/grammar/types/type_as/type_as_1/main.k b/tests/grammar/types/type_as/type_as_1/main.k similarity index 100% rename from test/grammar/types/type_as/type_as_1/main.k rename to tests/grammar/types/type_as/type_as_1/main.k diff --git a/test/grammar/types/type_as/type_as_1/stdout.golden b/tests/grammar/types/type_as/type_as_1/stdout.golden similarity index 100% rename from test/grammar/types/type_as/type_as_1/stdout.golden rename to tests/grammar/types/type_as/type_as_1/stdout.golden diff --git a/test/grammar/types/type_as/type_as_2/main.k b/tests/grammar/types/type_as/type_as_2/main.k similarity index 100% rename from test/grammar/types/type_as/type_as_2/main.k rename to tests/grammar/types/type_as/type_as_2/main.k diff --git a/test/grammar/types/type_as/type_as_2/stdout.golden b/tests/grammar/types/type_as/type_as_2/stdout.golden similarity index 100% rename from test/grammar/types/type_as/type_as_2/stdout.golden rename to tests/grammar/types/type_as/type_as_2/stdout.golden diff --git a/test/grammar/types/type_as/type_as_3/main.k b/tests/grammar/types/type_as/type_as_3/main.k similarity index 100% rename from test/grammar/types/type_as/type_as_3/main.k rename to tests/grammar/types/type_as/type_as_3/main.k diff --git a/test/grammar/types/type_as/type_as_3/stdout.golden b/tests/grammar/types/type_as/type_as_3/stdout.golden similarity index 100% rename from test/grammar/types/type_as/type_as_3/stdout.golden rename to tests/grammar/types/type_as/type_as_3/stdout.golden diff --git a/test/grammar/types/type_as/type_as_4/kcl.mod b/tests/grammar/types/type_as/type_as_4/kcl.mod similarity index 100% rename from test/grammar/types/type_as/type_as_4/kcl.mod rename to tests/grammar/types/type_as/type_as_4/kcl.mod diff --git a/test/grammar/types/type_as/type_as_4/main.k b/tests/grammar/types/type_as/type_as_4/main.k similarity index 100% rename from test/grammar/types/type_as/type_as_4/main.k rename to tests/grammar/types/type_as/type_as_4/main.k diff --git a/test/grammar/types/type_as/type_as_4/pkg/pkg.k b/tests/grammar/types/type_as/type_as_4/pkg/pkg.k similarity index 100% rename from test/grammar/types/type_as/type_as_4/pkg/pkg.k rename to tests/grammar/types/type_as/type_as_4/pkg/pkg.k diff --git a/test/grammar/types/type_as/type_as_4/stdout.golden b/tests/grammar/types/type_as/type_as_4/stdout.golden similarity index 100% rename from test/grammar/types/type_as/type_as_4/stdout.golden rename to tests/grammar/types/type_as/type_as_4/stdout.golden diff --git a/test/grammar/types/type_as/type_as_5/kcl.mod b/tests/grammar/types/type_as/type_as_5/kcl.mod similarity index 100% rename from test/grammar/types/type_as/type_as_5/kcl.mod rename to tests/grammar/types/type_as/type_as_5/kcl.mod diff --git a/test/grammar/types/type_as/type_as_5/main.k b/tests/grammar/types/type_as/type_as_5/main.k similarity index 100% rename from test/grammar/types/type_as/type_as_5/main.k rename to tests/grammar/types/type_as/type_as_5/main.k diff --git a/test/grammar/types/type_as/type_as_5/pkg/pkg.k b/tests/grammar/types/type_as/type_as_5/pkg/pkg.k similarity index 100% rename from test/grammar/types/type_as/type_as_5/pkg/pkg.k rename to tests/grammar/types/type_as/type_as_5/pkg/pkg.k diff --git a/test/grammar/types/type_as/type_as_5/stdout.golden b/tests/grammar/types/type_as/type_as_5/stdout.golden similarity index 100% rename from test/grammar/types/type_as/type_as_5/stdout.golden rename to tests/grammar/types/type_as/type_as_5/stdout.golden diff --git a/test/grammar/types/type_as/type_as_6/main.k b/tests/grammar/types/type_as/type_as_6/main.k similarity index 100% rename from test/grammar/types/type_as/type_as_6/main.k rename to tests/grammar/types/type_as/type_as_6/main.k diff --git a/test/grammar/types/type_as/type_as_6/stdout.golden b/tests/grammar/types/type_as/type_as_6/stdout.golden similarity index 100% rename from test/grammar/types/type_as/type_as_6/stdout.golden rename to tests/grammar/types/type_as/type_as_6/stdout.golden diff --git a/test/grammar/types/type_as/type_as_err_0/main.k b/tests/grammar/types/type_as/type_as_err_0/main.k similarity index 100% rename from test/grammar/types/type_as/type_as_err_0/main.k rename to tests/grammar/types/type_as/type_as_err_0/main.k diff --git a/test/grammar/types/type_as/type_as_err_0/stderr.golden b/tests/grammar/types/type_as/type_as_err_0/stderr.golden similarity index 100% rename from test/grammar/types/type_as/type_as_err_0/stderr.golden rename to tests/grammar/types/type_as/type_as_err_0/stderr.golden diff --git a/test/grammar/types/type_as/type_as_err_1/main.k b/tests/grammar/types/type_as/type_as_err_1/main.k similarity index 100% rename from test/grammar/types/type_as/type_as_err_1/main.k rename to tests/grammar/types/type_as/type_as_err_1/main.k diff --git a/test/grammar/types/type_as/type_as_err_1/stderr.golden b/tests/grammar/types/type_as/type_as_err_1/stderr.golden similarity index 100% rename from test/grammar/types/type_as/type_as_err_1/stderr.golden rename to tests/grammar/types/type_as/type_as_err_1/stderr.golden diff --git a/test/grammar/types/type_as/type_as_err_2/main.k b/tests/grammar/types/type_as/type_as_err_2/main.k similarity index 100% rename from test/grammar/types/type_as/type_as_err_2/main.k rename to tests/grammar/types/type_as/type_as_err_2/main.k diff --git a/test/grammar/types/type_as/type_as_err_2/stderr.golden b/tests/grammar/types/type_as/type_as_err_2/stderr.golden similarity index 100% rename from test/grammar/types/type_as/type_as_err_2/stderr.golden rename to tests/grammar/types/type_as/type_as_err_2/stderr.golden diff --git a/test/grammar/types/type_as/type_as_err_3/base/base.k b/tests/grammar/types/type_as/type_as_err_3/base/base.k similarity index 100% rename from test/grammar/types/type_as/type_as_err_3/base/base.k rename to tests/grammar/types/type_as/type_as_err_3/base/base.k diff --git a/test/grammar/types/type_as/type_as_err_3/child/child.k b/tests/grammar/types/type_as/type_as_err_3/child/child.k similarity index 100% rename from test/grammar/types/type_as/type_as_err_3/child/child.k rename to tests/grammar/types/type_as/type_as_err_3/child/child.k diff --git a/test/grammar/types/type_as/type_as_err_3/kcl.mod b/tests/grammar/types/type_as/type_as_err_3/kcl.mod similarity index 100% rename from test/grammar/types/type_as/type_as_err_3/kcl.mod rename to tests/grammar/types/type_as/type_as_err_3/kcl.mod diff --git a/test/grammar/types/type_as/type_as_err_3/main.k b/tests/grammar/types/type_as/type_as_err_3/main.k similarity index 100% rename from test/grammar/types/type_as/type_as_err_3/main.k rename to tests/grammar/types/type_as/type_as_err_3/main.k diff --git a/test/grammar/types/type_as/type_as_err_3/stderr.golden b/tests/grammar/types/type_as/type_as_err_3/stderr.golden similarity index 100% rename from test/grammar/types/type_as/type_as_err_3/stderr.golden rename to tests/grammar/types/type_as/type_as_err_3/stderr.golden diff --git a/test/grammar/types/type_as/type_as_err_4/base/base.k b/tests/grammar/types/type_as/type_as_err_4/base/base.k similarity index 100% rename from test/grammar/types/type_as/type_as_err_4/base/base.k rename to tests/grammar/types/type_as/type_as_err_4/base/base.k diff --git a/test/grammar/types/type_as/type_as_err_4/child/child.k b/tests/grammar/types/type_as/type_as_err_4/child/child.k similarity index 100% rename from test/grammar/types/type_as/type_as_err_4/child/child.k rename to tests/grammar/types/type_as/type_as_err_4/child/child.k diff --git a/test/grammar/types/type_as/type_as_err_4/kcl.mod b/tests/grammar/types/type_as/type_as_err_4/kcl.mod similarity index 100% rename from test/grammar/types/type_as/type_as_err_4/kcl.mod rename to tests/grammar/types/type_as/type_as_err_4/kcl.mod diff --git a/test/grammar/types/type_as/type_as_err_4/main.k b/tests/grammar/types/type_as/type_as_err_4/main.k similarity index 100% rename from test/grammar/types/type_as/type_as_err_4/main.k rename to tests/grammar/types/type_as/type_as_err_4/main.k diff --git a/test/grammar/types/type_as/type_as_err_4/stderr.golden b/tests/grammar/types/type_as/type_as_err_4/stderr.golden similarity index 100% rename from test/grammar/types/type_as/type_as_err_4/stderr.golden rename to tests/grammar/types/type_as/type_as_err_4/stderr.golden diff --git a/test/grammar/types/union_expr/union_expr_0/main.k b/tests/grammar/types/union_expr/union_expr_0/main.k similarity index 100% rename from test/grammar/types/union_expr/union_expr_0/main.k rename to tests/grammar/types/union_expr/union_expr_0/main.k diff --git a/test/grammar/types/union_expr/union_expr_0/stdout.golden b/tests/grammar/types/union_expr/union_expr_0/stdout.golden similarity index 100% rename from test/grammar/types/union_expr/union_expr_0/stdout.golden rename to tests/grammar/types/union_expr/union_expr_0/stdout.golden diff --git a/test/grammar/types/union_expr/union_expr_1/main.k b/tests/grammar/types/union_expr/union_expr_1/main.k similarity index 100% rename from test/grammar/types/union_expr/union_expr_1/main.k rename to tests/grammar/types/union_expr/union_expr_1/main.k diff --git a/test/grammar/types/union_expr/union_expr_1/stdout.golden b/tests/grammar/types/union_expr/union_expr_1/stdout.golden similarity index 100% rename from test/grammar/types/union_expr/union_expr_1/stdout.golden rename to tests/grammar/types/union_expr/union_expr_1/stdout.golden diff --git a/test/grammar/types/union_expr/union_expr_fail_0/main.k b/tests/grammar/types/union_expr/union_expr_fail_0/main.k similarity index 100% rename from test/grammar/types/union_expr/union_expr_fail_0/main.k rename to tests/grammar/types/union_expr/union_expr_fail_0/main.k diff --git a/test/grammar/types/union_expr/union_expr_fail_0/stderr.golden b/tests/grammar/types/union_expr/union_expr_fail_0/stderr.golden similarity index 100% rename from test/grammar/types/union_expr/union_expr_fail_0/stderr.golden rename to tests/grammar/types/union_expr/union_expr_fail_0/stderr.golden diff --git a/test/grammar/types/union_expr/union_expr_fail_1/main.k b/tests/grammar/types/union_expr/union_expr_fail_1/main.k similarity index 100% rename from test/grammar/types/union_expr/union_expr_fail_1/main.k rename to tests/grammar/types/union_expr/union_expr_fail_1/main.k diff --git a/test/grammar/types/union_expr/union_expr_fail_1/stderr.golden b/tests/grammar/types/union_expr/union_expr_fail_1/stderr.golden similarity index 100% rename from test/grammar/types/union_expr/union_expr_fail_1/stderr.golden rename to tests/grammar/types/union_expr/union_expr_fail_1/stderr.golden diff --git a/test/grammar/types/union_expr/union_expr_fail_2/main.k b/tests/grammar/types/union_expr/union_expr_fail_2/main.k similarity index 100% rename from test/grammar/types/union_expr/union_expr_fail_2/main.k rename to tests/grammar/types/union_expr/union_expr_fail_2/main.k diff --git a/test/grammar/types/union_expr/union_expr_fail_2/stderr.golden b/tests/grammar/types/union_expr/union_expr_fail_2/stderr.golden similarity index 100% rename from test/grammar/types/union_expr/union_expr_fail_2/stderr.golden rename to tests/grammar/types/union_expr/union_expr_fail_2/stderr.golden diff --git a/test/grammar/types/union_ty/union_ty_0/main.k b/tests/grammar/types/union_ty/union_ty_0/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_0/main.k rename to tests/grammar/types/union_ty/union_ty_0/main.k diff --git a/test/grammar/types/union_ty/union_ty_0/stdout.golden b/tests/grammar/types/union_ty/union_ty_0/stdout.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_0/stdout.golden rename to tests/grammar/types/union_ty/union_ty_0/stdout.golden diff --git a/test/grammar/types/union_ty/union_ty_1/main.k b/tests/grammar/types/union_ty/union_ty_1/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_1/main.k rename to tests/grammar/types/union_ty/union_ty_1/main.k diff --git a/test/grammar/types/union_ty/union_ty_1/stdout.golden b/tests/grammar/types/union_ty/union_ty_1/stdout.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_1/stdout.golden rename to tests/grammar/types/union_ty/union_ty_1/stdout.golden diff --git a/test/grammar/types/union_ty/union_ty_10/main.k b/tests/grammar/types/union_ty/union_ty_10/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_10/main.k rename to tests/grammar/types/union_ty/union_ty_10/main.k diff --git a/test/grammar/types/union_ty/union_ty_10/stdout.golden b/tests/grammar/types/union_ty/union_ty_10/stdout.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_10/stdout.golden rename to tests/grammar/types/union_ty/union_ty_10/stdout.golden diff --git a/test/grammar/types/union_ty/union_ty_11/main.k b/tests/grammar/types/union_ty/union_ty_11/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_11/main.k rename to tests/grammar/types/union_ty/union_ty_11/main.k diff --git a/test/grammar/types/union_ty/union_ty_11/stdout.golden b/tests/grammar/types/union_ty/union_ty_11/stdout.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_11/stdout.golden rename to tests/grammar/types/union_ty/union_ty_11/stdout.golden diff --git a/test/grammar/types/union_ty/union_ty_12/main.k b/tests/grammar/types/union_ty/union_ty_12/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_12/main.k rename to tests/grammar/types/union_ty/union_ty_12/main.k diff --git a/test/grammar/types/union_ty/union_ty_12/stdout.golden b/tests/grammar/types/union_ty/union_ty_12/stdout.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_12/stdout.golden rename to tests/grammar/types/union_ty/union_ty_12/stdout.golden diff --git a/test/grammar/types/union_ty/union_ty_2/main.k b/tests/grammar/types/union_ty/union_ty_2/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_2/main.k rename to tests/grammar/types/union_ty/union_ty_2/main.k diff --git a/test/grammar/types/union_ty/union_ty_2/stdout.golden b/tests/grammar/types/union_ty/union_ty_2/stdout.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_2/stdout.golden rename to tests/grammar/types/union_ty/union_ty_2/stdout.golden diff --git a/test/grammar/types/union_ty/union_ty_3/main.k b/tests/grammar/types/union_ty/union_ty_3/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_3/main.k rename to tests/grammar/types/union_ty/union_ty_3/main.k diff --git a/test/grammar/types/union_ty/union_ty_3/stdout.golden b/tests/grammar/types/union_ty/union_ty_3/stdout.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_3/stdout.golden rename to tests/grammar/types/union_ty/union_ty_3/stdout.golden diff --git a/test/grammar/types/union_ty/union_ty_4/main.k b/tests/grammar/types/union_ty/union_ty_4/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_4/main.k rename to tests/grammar/types/union_ty/union_ty_4/main.k diff --git a/test/grammar/types/union_ty/union_ty_4/stdout.golden b/tests/grammar/types/union_ty/union_ty_4/stdout.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_4/stdout.golden rename to tests/grammar/types/union_ty/union_ty_4/stdout.golden diff --git a/test/grammar/types/union_ty/union_ty_5/main.k b/tests/grammar/types/union_ty/union_ty_5/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_5/main.k rename to tests/grammar/types/union_ty/union_ty_5/main.k diff --git a/test/grammar/types/union_ty/union_ty_5/stdout.golden b/tests/grammar/types/union_ty/union_ty_5/stdout.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_5/stdout.golden rename to tests/grammar/types/union_ty/union_ty_5/stdout.golden diff --git a/test/grammar/types/union_ty/union_ty_6/main.k b/tests/grammar/types/union_ty/union_ty_6/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_6/main.k rename to tests/grammar/types/union_ty/union_ty_6/main.k diff --git a/test/grammar/types/union_ty/union_ty_6/stdout.golden b/tests/grammar/types/union_ty/union_ty_6/stdout.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_6/stdout.golden rename to tests/grammar/types/union_ty/union_ty_6/stdout.golden diff --git a/test/grammar/types/union_ty/union_ty_7/main.k b/tests/grammar/types/union_ty/union_ty_7/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_7/main.k rename to tests/grammar/types/union_ty/union_ty_7/main.k diff --git a/test/grammar/types/union_ty/union_ty_7/stdout.golden b/tests/grammar/types/union_ty/union_ty_7/stdout.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_7/stdout.golden rename to tests/grammar/types/union_ty/union_ty_7/stdout.golden diff --git a/test/grammar/types/union_ty/union_ty_8/main.k b/tests/grammar/types/union_ty/union_ty_8/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_8/main.k rename to tests/grammar/types/union_ty/union_ty_8/main.k diff --git a/test/grammar/types/union_ty/union_ty_8/stdout.golden b/tests/grammar/types/union_ty/union_ty_8/stdout.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_8/stdout.golden rename to tests/grammar/types/union_ty/union_ty_8/stdout.golden diff --git a/test/grammar/types/union_ty/union_ty_9/main.k b/tests/grammar/types/union_ty/union_ty_9/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_9/main.k rename to tests/grammar/types/union_ty/union_ty_9/main.k diff --git a/test/grammar/types/union_ty/union_ty_9/stdout.golden b/tests/grammar/types/union_ty/union_ty_9/stdout.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_9/stdout.golden rename to tests/grammar/types/union_ty/union_ty_9/stdout.golden diff --git a/test/grammar/types/union_ty/union_ty_err_0/main.k b/tests/grammar/types/union_ty/union_ty_err_0/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_err_0/main.k rename to tests/grammar/types/union_ty/union_ty_err_0/main.k diff --git a/test/grammar/types/union_ty/union_ty_err_0/stderr.golden b/tests/grammar/types/union_ty/union_ty_err_0/stderr.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_err_0/stderr.golden rename to tests/grammar/types/union_ty/union_ty_err_0/stderr.golden diff --git a/test/grammar/types/union_ty/union_ty_err_1/main.k b/tests/grammar/types/union_ty/union_ty_err_1/main.k similarity index 100% rename from test/grammar/types/union_ty/union_ty_err_1/main.k rename to tests/grammar/types/union_ty/union_ty_err_1/main.k diff --git a/test/grammar/types/union_ty/union_ty_err_1/stderr.golden b/tests/grammar/types/union_ty/union_ty_err_1/stderr.golden similarity index 100% rename from test/grammar/types/union_ty/union_ty_err_1/stderr.golden rename to tests/grammar/types/union_ty/union_ty_err_1/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_0/main.k b/tests/grammar/types/var_type_annotation/type_fail_0/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_0/main.k rename to tests/grammar/types/var_type_annotation/type_fail_0/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_0/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_0/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_0/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_0/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_1/main.k b/tests/grammar/types/var_type_annotation/type_fail_1/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_1/main.k rename to tests/grammar/types/var_type_annotation/type_fail_1/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_1/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_1/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_1/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_1/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_10/main.k b/tests/grammar/types/var_type_annotation/type_fail_10/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_10/main.k rename to tests/grammar/types/var_type_annotation/type_fail_10/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_10/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_10/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_10/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_10/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_11/main.k b/tests/grammar/types/var_type_annotation/type_fail_11/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_11/main.k rename to tests/grammar/types/var_type_annotation/type_fail_11/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_11/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_11/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_11/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_11/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_12/main.k b/tests/grammar/types/var_type_annotation/type_fail_12/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_12/main.k rename to tests/grammar/types/var_type_annotation/type_fail_12/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_12/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_12/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_12/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_12/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_13/main.k b/tests/grammar/types/var_type_annotation/type_fail_13/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_13/main.k rename to tests/grammar/types/var_type_annotation/type_fail_13/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_13/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_13/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_13/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_13/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_14/main.k b/tests/grammar/types/var_type_annotation/type_fail_14/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_14/main.k rename to tests/grammar/types/var_type_annotation/type_fail_14/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_14/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_14/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_14/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_14/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_15/main.k b/tests/grammar/types/var_type_annotation/type_fail_15/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_15/main.k rename to tests/grammar/types/var_type_annotation/type_fail_15/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_15/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_15/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_15/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_15/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_2/main.k b/tests/grammar/types/var_type_annotation/type_fail_2/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_2/main.k rename to tests/grammar/types/var_type_annotation/type_fail_2/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_2/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_2/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_2/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_2/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_3/main.k b/tests/grammar/types/var_type_annotation/type_fail_3/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_3/main.k rename to tests/grammar/types/var_type_annotation/type_fail_3/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_3/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_3/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_3/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_3/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_4/main.k b/tests/grammar/types/var_type_annotation/type_fail_4/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_4/main.k rename to tests/grammar/types/var_type_annotation/type_fail_4/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_4/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_4/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_4/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_4/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_5/main.k b/tests/grammar/types/var_type_annotation/type_fail_5/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_5/main.k rename to tests/grammar/types/var_type_annotation/type_fail_5/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_5/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_5/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_5/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_5/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_6/main.k b/tests/grammar/types/var_type_annotation/type_fail_6/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_6/main.k rename to tests/grammar/types/var_type_annotation/type_fail_6/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_6/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_6/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_6/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_6/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_7/main.k b/tests/grammar/types/var_type_annotation/type_fail_7/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_7/main.k rename to tests/grammar/types/var_type_annotation/type_fail_7/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_7/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_7/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_7/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_7/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_8/main.k b/tests/grammar/types/var_type_annotation/type_fail_8/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_8/main.k rename to tests/grammar/types/var_type_annotation/type_fail_8/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_8/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_8/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_8/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_8/stderr.golden diff --git a/test/grammar/types/var_type_annotation/type_fail_9/main.k b/tests/grammar/types/var_type_annotation/type_fail_9/main.k similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_9/main.k rename to tests/grammar/types/var_type_annotation/type_fail_9/main.k diff --git a/test/grammar/types/var_type_annotation/type_fail_9/stderr.golden b/tests/grammar/types/var_type_annotation/type_fail_9/stderr.golden similarity index 100% rename from test/grammar/types/var_type_annotation/type_fail_9/stderr.golden rename to tests/grammar/types/var_type_annotation/type_fail_9/stderr.golden diff --git a/test/grammar/unification/append_0/main.k b/tests/grammar/unification/append_0/main.k similarity index 100% rename from test/grammar/unification/append_0/main.k rename to tests/grammar/unification/append_0/main.k diff --git a/test/grammar/unification/append_0/stdout.golden b/tests/grammar/unification/append_0/stdout.golden similarity index 100% rename from test/grammar/unification/append_0/stdout.golden rename to tests/grammar/unification/append_0/stdout.golden diff --git a/test/grammar/unification/append_1/main.k b/tests/grammar/unification/append_1/main.k similarity index 100% rename from test/grammar/unification/append_1/main.k rename to tests/grammar/unification/append_1/main.k diff --git a/test/grammar/unification/append_1/stdout.golden b/tests/grammar/unification/append_1/stdout.golden similarity index 100% rename from test/grammar/unification/append_1/stdout.golden rename to tests/grammar/unification/append_1/stdout.golden diff --git a/test/grammar/unification/append_2/main.k b/tests/grammar/unification/append_2/main.k similarity index 100% rename from test/grammar/unification/append_2/main.k rename to tests/grammar/unification/append_2/main.k diff --git a/test/grammar/unification/append_2/stdout.golden b/tests/grammar/unification/append_2/stdout.golden similarity index 100% rename from test/grammar/unification/append_2/stdout.golden rename to tests/grammar/unification/append_2/stdout.golden diff --git a/test/grammar/unification/collection_if_0/main.k b/tests/grammar/unification/collection_if_0/main.k similarity index 100% rename from test/grammar/unification/collection_if_0/main.k rename to tests/grammar/unification/collection_if_0/main.k diff --git a/test/grammar/unification/collection_if_0/stdout.golden b/tests/grammar/unification/collection_if_0/stdout.golden similarity index 100% rename from test/grammar/unification/collection_if_0/stdout.golden rename to tests/grammar/unification/collection_if_0/stdout.golden diff --git a/test/grammar/unification/collection_if_1/main.k b/tests/grammar/unification/collection_if_1/main.k similarity index 100% rename from test/grammar/unification/collection_if_1/main.k rename to tests/grammar/unification/collection_if_1/main.k diff --git a/test/grammar/unification/collection_if_1/stdout.golden b/tests/grammar/unification/collection_if_1/stdout.golden similarity index 100% rename from test/grammar/unification/collection_if_1/stdout.golden rename to tests/grammar/unification/collection_if_1/stdout.golden diff --git a/test/grammar/unification/empty_0/main.k b/tests/grammar/unification/empty_0/main.k similarity index 100% rename from test/grammar/unification/empty_0/main.k rename to tests/grammar/unification/empty_0/main.k diff --git a/test/grammar/unification/empty_0/stdout.golden b/tests/grammar/unification/empty_0/stdout.golden similarity index 100% rename from test/grammar/unification/empty_0/stdout.golden rename to tests/grammar/unification/empty_0/stdout.golden diff --git a/test/grammar/unification/empty_1/main.k b/tests/grammar/unification/empty_1/main.k similarity index 100% rename from test/grammar/unification/empty_1/main.k rename to tests/grammar/unification/empty_1/main.k diff --git a/test/grammar/unification/empty_1/stdout.golden b/tests/grammar/unification/empty_1/stdout.golden similarity index 100% rename from test/grammar/unification/empty_1/stdout.golden rename to tests/grammar/unification/empty_1/stdout.golden diff --git a/test/grammar/unification/fail_0/main.k b/tests/grammar/unification/fail_0/main.k similarity index 100% rename from test/grammar/unification/fail_0/main.k rename to tests/grammar/unification/fail_0/main.k diff --git a/test/grammar/unification/fail_0/stderr.golden b/tests/grammar/unification/fail_0/stderr.golden similarity index 100% rename from test/grammar/unification/fail_0/stderr.golden rename to tests/grammar/unification/fail_0/stderr.golden diff --git a/test/grammar/unification/fail_1/main.k b/tests/grammar/unification/fail_1/main.k similarity index 100% rename from test/grammar/unification/fail_1/main.k rename to tests/grammar/unification/fail_1/main.k diff --git a/test/grammar/unification/fail_1/stderr.golden b/tests/grammar/unification/fail_1/stderr.golden similarity index 100% rename from test/grammar/unification/fail_1/stderr.golden rename to tests/grammar/unification/fail_1/stderr.golden diff --git a/test/grammar/unification/fail_2/main.k b/tests/grammar/unification/fail_2/main.k similarity index 100% rename from test/grammar/unification/fail_2/main.k rename to tests/grammar/unification/fail_2/main.k diff --git a/test/grammar/unification/fail_2/stderr.golden b/tests/grammar/unification/fail_2/stderr.golden similarity index 100% rename from test/grammar/unification/fail_2/stderr.golden rename to tests/grammar/unification/fail_2/stderr.golden diff --git a/test/grammar/unification/fail_3/main.k b/tests/grammar/unification/fail_3/main.k similarity index 100% rename from test/grammar/unification/fail_3/main.k rename to tests/grammar/unification/fail_3/main.k diff --git a/test/grammar/unification/fail_3/stderr.golden b/tests/grammar/unification/fail_3/stderr.golden similarity index 100% rename from test/grammar/unification/fail_3/stderr.golden rename to tests/grammar/unification/fail_3/stderr.golden diff --git a/test/grammar/unification/instances_0/main.k b/tests/grammar/unification/instances_0/main.k similarity index 100% rename from test/grammar/unification/instances_0/main.k rename to tests/grammar/unification/instances_0/main.k diff --git a/test/grammar/unification/instances_0/stdout.golden b/tests/grammar/unification/instances_0/stdout.golden similarity index 100% rename from test/grammar/unification/instances_0/stdout.golden rename to tests/grammar/unification/instances_0/stdout.golden diff --git a/test/grammar/unification/instances_1/main.k b/tests/grammar/unification/instances_1/main.k similarity index 100% rename from test/grammar/unification/instances_1/main.k rename to tests/grammar/unification/instances_1/main.k diff --git a/test/grammar/unification/instances_1/stdout.golden b/tests/grammar/unification/instances_1/stdout.golden similarity index 100% rename from test/grammar/unification/instances_1/stdout.golden rename to tests/grammar/unification/instances_1/stdout.golden diff --git a/test/grammar/unification/multi_file_compile_0/main.k b/tests/grammar/unification/multi_file_compile_0/main.k similarity index 100% rename from test/grammar/unification/multi_file_compile_0/main.k rename to tests/grammar/unification/multi_file_compile_0/main.k diff --git a/test/grammar/unification/multi_file_compile_0/settings.yaml b/tests/grammar/unification/multi_file_compile_0/settings.yaml similarity index 100% rename from test/grammar/unification/multi_file_compile_0/settings.yaml rename to tests/grammar/unification/multi_file_compile_0/settings.yaml diff --git a/test/grammar/unification/multi_file_compile_0/stack.k b/tests/grammar/unification/multi_file_compile_0/stack.k similarity index 100% rename from test/grammar/unification/multi_file_compile_0/stack.k rename to tests/grammar/unification/multi_file_compile_0/stack.k diff --git a/test/grammar/unification/multi_file_compile_0/stdout.golden b/tests/grammar/unification/multi_file_compile_0/stdout.golden similarity index 100% rename from test/grammar/unification/multi_file_compile_0/stdout.golden rename to tests/grammar/unification/multi_file_compile_0/stdout.golden diff --git a/test/grammar/unification/multi_file_compile_1/main.k b/tests/grammar/unification/multi_file_compile_1/main.k similarity index 100% rename from test/grammar/unification/multi_file_compile_1/main.k rename to tests/grammar/unification/multi_file_compile_1/main.k diff --git a/test/grammar/unification/multi_file_compile_1/settings.yaml b/tests/grammar/unification/multi_file_compile_1/settings.yaml similarity index 100% rename from test/grammar/unification/multi_file_compile_1/settings.yaml rename to tests/grammar/unification/multi_file_compile_1/settings.yaml diff --git a/test/grammar/unification/multi_file_compile_1/stack.k b/tests/grammar/unification/multi_file_compile_1/stack.k similarity index 100% rename from test/grammar/unification/multi_file_compile_1/stack.k rename to tests/grammar/unification/multi_file_compile_1/stack.k diff --git a/test/grammar/unification/multi_file_compile_1/stdout.golden b/tests/grammar/unification/multi_file_compile_1/stdout.golden similarity index 100% rename from test/grammar/unification/multi_file_compile_1/stdout.golden rename to tests/grammar/unification/multi_file_compile_1/stdout.golden diff --git a/test/grammar/unification/nest_var_0/main.k b/tests/grammar/unification/nest_var_0/main.k similarity index 100% rename from test/grammar/unification/nest_var_0/main.k rename to tests/grammar/unification/nest_var_0/main.k diff --git a/test/grammar/unification/nest_var_0/stdout.golden b/tests/grammar/unification/nest_var_0/stdout.golden similarity index 100% rename from test/grammar/unification/nest_var_0/stdout.golden rename to tests/grammar/unification/nest_var_0/stdout.golden diff --git a/test/grammar/unification/nest_var_1/main.k b/tests/grammar/unification/nest_var_1/main.k similarity index 100% rename from test/grammar/unification/nest_var_1/main.k rename to tests/grammar/unification/nest_var_1/main.k diff --git a/test/grammar/unification/nest_var_1/stdout.golden b/tests/grammar/unification/nest_var_1/stdout.golden similarity index 100% rename from test/grammar/unification/nest_var_1/stdout.golden rename to tests/grammar/unification/nest_var_1/stdout.golden diff --git a/test/grammar/unification/override_0/main.k b/tests/grammar/unification/override_0/main.k similarity index 100% rename from test/grammar/unification/override_0/main.k rename to tests/grammar/unification/override_0/main.k diff --git a/test/grammar/unification/override_0/stdout.golden b/tests/grammar/unification/override_0/stdout.golden similarity index 100% rename from test/grammar/unification/override_0/stdout.golden rename to tests/grammar/unification/override_0/stdout.golden diff --git a/test/grammar/unification/override_1/main.k b/tests/grammar/unification/override_1/main.k similarity index 100% rename from test/grammar/unification/override_1/main.k rename to tests/grammar/unification/override_1/main.k diff --git a/test/grammar/unification/override_1/stdout.golden b/tests/grammar/unification/override_1/stdout.golden similarity index 100% rename from test/grammar/unification/override_1/stdout.golden rename to tests/grammar/unification/override_1/stdout.golden diff --git a/test/grammar/unification/pkg_schema_0/kcl.mod b/tests/grammar/unification/pkg_schema_0/kcl.mod similarity index 100% rename from test/grammar/unification/pkg_schema_0/kcl.mod rename to tests/grammar/unification/pkg_schema_0/kcl.mod diff --git a/test/grammar/unification/pkg_schema_0/main.k b/tests/grammar/unification/pkg_schema_0/main.k similarity index 100% rename from test/grammar/unification/pkg_schema_0/main.k rename to tests/grammar/unification/pkg_schema_0/main.k diff --git a/test/grammar/unification/pkg_schema_0/pkg/pkg.k b/tests/grammar/unification/pkg_schema_0/pkg/pkg.k similarity index 100% rename from test/grammar/unification/pkg_schema_0/pkg/pkg.k rename to tests/grammar/unification/pkg_schema_0/pkg/pkg.k diff --git a/test/grammar/unification/pkg_schema_0/stdout.golden b/tests/grammar/unification/pkg_schema_0/stdout.golden similarity index 100% rename from test/grammar/unification/pkg_schema_0/stdout.golden rename to tests/grammar/unification/pkg_schema_0/stdout.golden diff --git a/test/grammar/unification/pkg_schema_1/kcl.mod b/tests/grammar/unification/pkg_schema_1/kcl.mod similarity index 100% rename from test/grammar/unification/pkg_schema_1/kcl.mod rename to tests/grammar/unification/pkg_schema_1/kcl.mod diff --git a/test/grammar/unification/pkg_schema_1/main.k b/tests/grammar/unification/pkg_schema_1/main.k similarity index 100% rename from test/grammar/unification/pkg_schema_1/main.k rename to tests/grammar/unification/pkg_schema_1/main.k diff --git a/test/grammar/unification/pkg_schema_1/pkg/pkg.k b/tests/grammar/unification/pkg_schema_1/pkg/pkg.k similarity index 100% rename from test/grammar/unification/pkg_schema_1/pkg/pkg.k rename to tests/grammar/unification/pkg_schema_1/pkg/pkg.k diff --git a/test/grammar/unification/pkg_schema_1/pkg/pkg/pkg.k b/tests/grammar/unification/pkg_schema_1/pkg/pkg/pkg.k similarity index 100% rename from test/grammar/unification/pkg_schema_1/pkg/pkg/pkg.k rename to tests/grammar/unification/pkg_schema_1/pkg/pkg/pkg.k diff --git a/test/grammar/unification/pkg_schema_1/stdout.golden b/tests/grammar/unification/pkg_schema_1/stdout.golden similarity index 100% rename from test/grammar/unification/pkg_schema_1/stdout.golden rename to tests/grammar/unification/pkg_schema_1/stdout.golden diff --git a/test/grammar/unification/schema_simple_0/main.k b/tests/grammar/unification/schema_simple_0/main.k similarity index 100% rename from test/grammar/unification/schema_simple_0/main.k rename to tests/grammar/unification/schema_simple_0/main.k diff --git a/test/grammar/unification/schema_simple_0/stdout.golden b/tests/grammar/unification/schema_simple_0/stdout.golden similarity index 100% rename from test/grammar/unification/schema_simple_0/stdout.golden rename to tests/grammar/unification/schema_simple_0/stdout.golden diff --git a/test/grammar/unification/schema_simple_1/main.k b/tests/grammar/unification/schema_simple_1/main.k similarity index 100% rename from test/grammar/unification/schema_simple_1/main.k rename to tests/grammar/unification/schema_simple_1/main.k diff --git a/test/grammar/unification/schema_simple_1/stdout.golden b/tests/grammar/unification/schema_simple_1/stdout.golden similarity index 100% rename from test/grammar/unification/schema_simple_1/stdout.golden rename to tests/grammar/unification/schema_simple_1/stdout.golden diff --git a/test/grammar/unification/schema_simple_10/main.k b/tests/grammar/unification/schema_simple_10/main.k similarity index 100% rename from test/grammar/unification/schema_simple_10/main.k rename to tests/grammar/unification/schema_simple_10/main.k diff --git a/test/grammar/unification/schema_simple_10/stdout.golden b/tests/grammar/unification/schema_simple_10/stdout.golden similarity index 100% rename from test/grammar/unification/schema_simple_10/stdout.golden rename to tests/grammar/unification/schema_simple_10/stdout.golden diff --git a/test/grammar/unification/schema_simple_11/main.k b/tests/grammar/unification/schema_simple_11/main.k similarity index 100% rename from test/grammar/unification/schema_simple_11/main.k rename to tests/grammar/unification/schema_simple_11/main.k diff --git a/test/grammar/unification/schema_simple_11/stdout.golden b/tests/grammar/unification/schema_simple_11/stdout.golden similarity index 100% rename from test/grammar/unification/schema_simple_11/stdout.golden rename to tests/grammar/unification/schema_simple_11/stdout.golden diff --git a/test/grammar/unification/schema_simple_2/main.k b/tests/grammar/unification/schema_simple_2/main.k similarity index 100% rename from test/grammar/unification/schema_simple_2/main.k rename to tests/grammar/unification/schema_simple_2/main.k diff --git a/test/grammar/unification/schema_simple_2/stdout.golden b/tests/grammar/unification/schema_simple_2/stdout.golden similarity index 100% rename from test/grammar/unification/schema_simple_2/stdout.golden rename to tests/grammar/unification/schema_simple_2/stdout.golden diff --git a/test/grammar/unification/schema_simple_3/main.k b/tests/grammar/unification/schema_simple_3/main.k similarity index 100% rename from test/grammar/unification/schema_simple_3/main.k rename to tests/grammar/unification/schema_simple_3/main.k diff --git a/test/grammar/unification/schema_simple_3/stdout.golden b/tests/grammar/unification/schema_simple_3/stdout.golden similarity index 100% rename from test/grammar/unification/schema_simple_3/stdout.golden rename to tests/grammar/unification/schema_simple_3/stdout.golden diff --git a/test/grammar/unification/schema_simple_4/main.k b/tests/grammar/unification/schema_simple_4/main.k similarity index 100% rename from test/grammar/unification/schema_simple_4/main.k rename to tests/grammar/unification/schema_simple_4/main.k diff --git a/test/grammar/unification/schema_simple_4/stdout.golden b/tests/grammar/unification/schema_simple_4/stdout.golden similarity index 100% rename from test/grammar/unification/schema_simple_4/stdout.golden rename to tests/grammar/unification/schema_simple_4/stdout.golden diff --git a/test/grammar/unification/schema_simple_5/main.k b/tests/grammar/unification/schema_simple_5/main.k similarity index 100% rename from test/grammar/unification/schema_simple_5/main.k rename to tests/grammar/unification/schema_simple_5/main.k diff --git a/test/grammar/unification/schema_simple_5/stdout.golden b/tests/grammar/unification/schema_simple_5/stdout.golden similarity index 100% rename from test/grammar/unification/schema_simple_5/stdout.golden rename to tests/grammar/unification/schema_simple_5/stdout.golden diff --git a/test/grammar/unification/schema_simple_6/main.k b/tests/grammar/unification/schema_simple_6/main.k similarity index 100% rename from test/grammar/unification/schema_simple_6/main.k rename to tests/grammar/unification/schema_simple_6/main.k diff --git a/test/grammar/unification/schema_simple_6/stdout.golden b/tests/grammar/unification/schema_simple_6/stdout.golden similarity index 100% rename from test/grammar/unification/schema_simple_6/stdout.golden rename to tests/grammar/unification/schema_simple_6/stdout.golden diff --git a/test/grammar/unification/schema_simple_7/main.k b/tests/grammar/unification/schema_simple_7/main.k similarity index 100% rename from test/grammar/unification/schema_simple_7/main.k rename to tests/grammar/unification/schema_simple_7/main.k diff --git a/test/grammar/unification/schema_simple_7/stdout.golden b/tests/grammar/unification/schema_simple_7/stdout.golden similarity index 100% rename from test/grammar/unification/schema_simple_7/stdout.golden rename to tests/grammar/unification/schema_simple_7/stdout.golden diff --git a/test/grammar/unification/schema_simple_8/main.k b/tests/grammar/unification/schema_simple_8/main.k similarity index 100% rename from test/grammar/unification/schema_simple_8/main.k rename to tests/grammar/unification/schema_simple_8/main.k diff --git a/test/grammar/unification/schema_simple_8/stdout.golden b/tests/grammar/unification/schema_simple_8/stdout.golden similarity index 100% rename from test/grammar/unification/schema_simple_8/stdout.golden rename to tests/grammar/unification/schema_simple_8/stdout.golden diff --git a/test/grammar/unification/schema_simple_9/main.k b/tests/grammar/unification/schema_simple_9/main.k similarity index 100% rename from test/grammar/unification/schema_simple_9/main.k rename to tests/grammar/unification/schema_simple_9/main.k diff --git a/test/grammar/unification/schema_simple_9/stdout.golden b/tests/grammar/unification/schema_simple_9/stdout.golden similarity index 100% rename from test/grammar/unification/schema_simple_9/stdout.golden rename to tests/grammar/unification/schema_simple_9/stdout.golden diff --git a/test/grammar/unification/schema_with_args_0/main.k b/tests/grammar/unification/schema_with_args_0/main.k similarity index 100% rename from test/grammar/unification/schema_with_args_0/main.k rename to tests/grammar/unification/schema_with_args_0/main.k diff --git a/test/grammar/unification/schema_with_args_0/stdout.golden b/tests/grammar/unification/schema_with_args_0/stdout.golden similarity index 100% rename from test/grammar/unification/schema_with_args_0/stdout.golden rename to tests/grammar/unification/schema_with_args_0/stdout.golden diff --git a/test/grammar/unification/str_interpolation/main.k b/tests/grammar/unification/str_interpolation/main.k similarity index 100% rename from test/grammar/unification/str_interpolation/main.k rename to tests/grammar/unification/str_interpolation/main.k diff --git a/test/grammar/unification/str_interpolation/stdout.golden b/tests/grammar/unification/str_interpolation/stdout.golden similarity index 100% rename from test/grammar/unification/str_interpolation/stdout.golden rename to tests/grammar/unification/str_interpolation/stdout.golden diff --git a/test/grammar/unification/subscript_0/main.k b/tests/grammar/unification/subscript_0/main.k similarity index 100% rename from test/grammar/unification/subscript_0/main.k rename to tests/grammar/unification/subscript_0/main.k diff --git a/test/grammar/unification/subscript_0/stdout.golden b/tests/grammar/unification/subscript_0/stdout.golden similarity index 100% rename from test/grammar/unification/subscript_0/stdout.golden rename to tests/grammar/unification/subscript_0/stdout.golden diff --git a/test/grammar/unification/subscript_1/main.k b/tests/grammar/unification/subscript_1/main.k similarity index 100% rename from test/grammar/unification/subscript_1/main.k rename to tests/grammar/unification/subscript_1/main.k diff --git a/test/grammar/unification/subscript_1/stdout.golden b/tests/grammar/unification/subscript_1/stdout.golden similarity index 100% rename from test/grammar/unification/subscript_1/stdout.golden rename to tests/grammar/unification/subscript_1/stdout.golden diff --git a/test/grammar/unification/unpack_0/main.k b/tests/grammar/unification/unpack_0/main.k similarity index 100% rename from test/grammar/unification/unpack_0/main.k rename to tests/grammar/unification/unpack_0/main.k diff --git a/test/grammar/unification/unpack_0/stdout.golden b/tests/grammar/unification/unpack_0/stdout.golden similarity index 100% rename from test/grammar/unification/unpack_0/stdout.golden rename to tests/grammar/unification/unpack_0/stdout.golden diff --git a/test/grammar/unification/unpack_1/main.k b/tests/grammar/unification/unpack_1/main.k similarity index 100% rename from test/grammar/unification/unpack_1/main.k rename to tests/grammar/unification/unpack_1/main.k diff --git a/test/grammar/unification/unpack_1/stdout.golden b/tests/grammar/unification/unpack_1/stdout.golden similarity index 100% rename from test/grammar/unification/unpack_1/stdout.golden rename to tests/grammar/unification/unpack_1/stdout.golden diff --git a/test/grammar/variable/export/default/main.k b/tests/grammar/variable/export/default/main.k similarity index 100% rename from test/grammar/variable/export/default/main.k rename to tests/grammar/variable/export/default/main.k diff --git a/test/grammar/variable/export/default/stdout.golden b/tests/grammar/variable/export/default/stdout.golden similarity index 100% rename from test/grammar/variable/export/default/stdout.golden rename to tests/grammar/variable/export/default/stdout.golden diff --git a/test/grammar/variable/export/if_expr_0/main.k b/tests/grammar/variable/export/if_expr_0/main.k similarity index 100% rename from test/grammar/variable/export/if_expr_0/main.k rename to tests/grammar/variable/export/if_expr_0/main.k diff --git a/test/grammar/variable/export/if_expr_0/stdout.golden b/tests/grammar/variable/export/if_expr_0/stdout.golden similarity index 100% rename from test/grammar/variable/export/if_expr_0/stdout.golden rename to tests/grammar/variable/export/if_expr_0/stdout.golden diff --git a/test/grammar/variable/export/if_expr_1/main.k b/tests/grammar/variable/export/if_expr_1/main.k similarity index 100% rename from test/grammar/variable/export/if_expr_1/main.k rename to tests/grammar/variable/export/if_expr_1/main.k diff --git a/test/grammar/variable/export/if_expr_1/stdout.golden b/tests/grammar/variable/export/if_expr_1/stdout.golden similarity index 100% rename from test/grammar/variable/export/if_expr_1/stdout.golden rename to tests/grammar/variable/export/if_expr_1/stdout.golden diff --git a/test/grammar/variable/export/if_stmt_0/main.k b/tests/grammar/variable/export/if_stmt_0/main.k similarity index 100% rename from test/grammar/variable/export/if_stmt_0/main.k rename to tests/grammar/variable/export/if_stmt_0/main.k diff --git a/test/grammar/variable/export/if_stmt_0/stdout.golden b/tests/grammar/variable/export/if_stmt_0/stdout.golden similarity index 100% rename from test/grammar/variable/export/if_stmt_0/stdout.golden rename to tests/grammar/variable/export/if_stmt_0/stdout.golden diff --git a/test/grammar/variable/export/if_stmt_1/main.k b/tests/grammar/variable/export/if_stmt_1/main.k similarity index 100% rename from test/grammar/variable/export/if_stmt_1/main.k rename to tests/grammar/variable/export/if_stmt_1/main.k diff --git a/test/grammar/variable/export/if_stmt_1/stdout.golden b/tests/grammar/variable/export/if_stmt_1/stdout.golden similarity index 100% rename from test/grammar/variable/export/if_stmt_1/stdout.golden rename to tests/grammar/variable/export/if_stmt_1/stdout.golden diff --git a/test/grammar/variable/export/immutable_0/main.k b/tests/grammar/variable/export/immutable_0/main.k similarity index 100% rename from test/grammar/variable/export/immutable_0/main.k rename to tests/grammar/variable/export/immutable_0/main.k diff --git a/test/grammar/variable/export/immutable_0/stderr.golden b/tests/grammar/variable/export/immutable_0/stderr.golden similarity index 100% rename from test/grammar/variable/export/immutable_0/stderr.golden rename to tests/grammar/variable/export/immutable_0/stderr.golden diff --git a/test/grammar/variable/export/immutable_1/main.k b/tests/grammar/variable/export/immutable_1/main.k similarity index 100% rename from test/grammar/variable/export/immutable_1/main.k rename to tests/grammar/variable/export/immutable_1/main.k diff --git a/test/grammar/variable/export/immutable_1/stderr.golden b/tests/grammar/variable/export/immutable_1/stderr.golden similarity index 100% rename from test/grammar/variable/export/immutable_1/stderr.golden rename to tests/grammar/variable/export/immutable_1/stderr.golden diff --git a/test/grammar/variable/export/immutable_2/main.k b/tests/grammar/variable/export/immutable_2/main.k similarity index 100% rename from test/grammar/variable/export/immutable_2/main.k rename to tests/grammar/variable/export/immutable_2/main.k diff --git a/test/grammar/variable/export/immutable_2/stderr.golden b/tests/grammar/variable/export/immutable_2/stderr.golden similarity index 100% rename from test/grammar/variable/export/immutable_2/stderr.golden rename to tests/grammar/variable/export/immutable_2/stderr.golden diff --git a/test/grammar/variable/unexport/default/main.k b/tests/grammar/variable/unexport/default/main.k similarity index 100% rename from test/grammar/variable/unexport/default/main.k rename to tests/grammar/variable/unexport/default/main.k diff --git a/test/grammar/variable/unexport/default/stdout.golden b/tests/grammar/variable/unexport/default/stdout.golden similarity index 100% rename from test/grammar/variable/unexport/default/stdout.golden rename to tests/grammar/variable/unexport/default/stdout.golden diff --git a/test/grammar/variable/unexport/for_0/main.k b/tests/grammar/variable/unexport/for_0/main.k similarity index 100% rename from test/grammar/variable/unexport/for_0/main.k rename to tests/grammar/variable/unexport/for_0/main.k diff --git a/test/grammar/variable/unexport/for_0/stdout.golden b/tests/grammar/variable/unexport/for_0/stdout.golden similarity index 100% rename from test/grammar/variable/unexport/for_0/stdout.golden rename to tests/grammar/variable/unexport/for_0/stdout.golden diff --git a/test/grammar/variable/unexport/for_1/main.k b/tests/grammar/variable/unexport/for_1/main.k similarity index 100% rename from test/grammar/variable/unexport/for_1/main.k rename to tests/grammar/variable/unexport/for_1/main.k diff --git a/test/grammar/variable/unexport/for_1/stdout.golden b/tests/grammar/variable/unexport/for_1/stdout.golden similarity index 100% rename from test/grammar/variable/unexport/for_1/stdout.golden rename to tests/grammar/variable/unexport/for_1/stdout.golden diff --git a/test/grammar/variable/unexport/if_stmt_0/main.k b/tests/grammar/variable/unexport/if_stmt_0/main.k similarity index 100% rename from test/grammar/variable/unexport/if_stmt_0/main.k rename to tests/grammar/variable/unexport/if_stmt_0/main.k diff --git a/test/grammar/variable/unexport/if_stmt_0/stdout.golden b/tests/grammar/variable/unexport/if_stmt_0/stdout.golden similarity index 100% rename from test/grammar/variable/unexport/if_stmt_0/stdout.golden rename to tests/grammar/variable/unexport/if_stmt_0/stdout.golden diff --git a/test/grammar/variable/unexport/if_stmt_1/main.k b/tests/grammar/variable/unexport/if_stmt_1/main.k similarity index 100% rename from test/grammar/variable/unexport/if_stmt_1/main.k rename to tests/grammar/variable/unexport/if_stmt_1/main.k diff --git a/test/grammar/variable/unexport/if_stmt_1/stdout.golden b/tests/grammar/variable/unexport/if_stmt_1/stdout.golden similarity index 100% rename from test/grammar/variable/unexport/if_stmt_1/stdout.golden rename to tests/grammar/variable/unexport/if_stmt_1/stdout.golden diff --git a/test/grammar/variable/unexport/unique_key_normal_0/main.k b/tests/grammar/variable/unexport/unique_key_normal_0/main.k similarity index 100% rename from test/grammar/variable/unexport/unique_key_normal_0/main.k rename to tests/grammar/variable/unexport/unique_key_normal_0/main.k diff --git a/test/grammar/variable/unexport/unique_key_normal_0/stdout.golden b/tests/grammar/variable/unexport/unique_key_normal_0/stdout.golden similarity index 100% rename from test/grammar/variable/unexport/unique_key_normal_0/stdout.golden rename to tests/grammar/variable/unexport/unique_key_normal_0/stdout.golden diff --git a/test/grammar/variable/unexport/unique_key_normal_1/main.k b/tests/grammar/variable/unexport/unique_key_normal_1/main.k similarity index 100% rename from test/grammar/variable/unexport/unique_key_normal_1/main.k rename to tests/grammar/variable/unexport/unique_key_normal_1/main.k diff --git a/test/grammar/variable/unexport/unique_key_normal_1/stdout.golden b/tests/grammar/variable/unexport/unique_key_normal_1/stdout.golden similarity index 100% rename from test/grammar/variable/unexport/unique_key_normal_1/stdout.golden rename to tests/grammar/variable/unexport/unique_key_normal_1/stdout.golden diff --git a/kclvm/tests/test_units/runtime/base32/test_base32.py b/tests/runtime/base32/test_base32.py similarity index 94% rename from kclvm/tests/test_units/runtime/base32/test_base32.py rename to tests/runtime/base32/test_base32.py index f460a8c3d..39e466183 100644 --- a/kclvm/tests/test_units/runtime/base32/test_base32.py +++ b/tests/runtime/base32/test_base32.py @@ -1,15 +1,15 @@ -import kclvm_runtime +import kcl_runtime import os import tempfile import subprocess import unittest import sys -# Add the parent directory to the path to import kclvm_runtime +# Add the parent directory to the path to import kcl_runtime parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(parent_dir) -_Dylib = kclvm_runtime.KclvmRuntimeDylib() +_Dylib = kcl_runtime.KclRuntimeDylib() class kclx_Base32: diff --git a/kclvm/tests/test_units/runtime/base64/test_base64.py b/tests/runtime/base64/test_base64.py similarity index 94% rename from kclvm/tests/test_units/runtime/base64/test_base64.py rename to tests/runtime/base64/test_base64.py index 7eeef9143..641240eab 100644 --- a/kclvm/tests/test_units/runtime/base64/test_base64.py +++ b/tests/runtime/base64/test_base64.py @@ -1,24 +1,24 @@ # Copyright The KCL Authors. All rights reserved. -import typing import unittest import sys import os -# Add the parent directory to the path to import kclvm_runtime +import kcl_runtime as kcl_runtime + +# Add the parent directory to the path to import kcl_runtime parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(parent_dir) -import kclvm_runtime # https://github.com/python/cpython/blob/main/Lib/test/test_base64.py # encode(value: str, encoding: str = "utf-8") -> str # decode(value: str, encoding: str = "utf-8") -> str -# kclvm_base64_encode -# kclvm_base64_decode +# kcl_base64_encode +# kcl_base64_decode -_Dylib = kclvm_runtime.KclvmRuntimeDylib() +_Dylib = kcl_runtime.KclRuntimeDylib() class kclx_Base64: diff --git a/kclvm/tests/test_units/runtime/crypto/test_crypto.py b/tests/runtime/crypto/test_crypto.py similarity index 97% rename from kclvm/tests/test_units/runtime/crypto/test_crypto.py rename to tests/runtime/crypto/test_crypto.py index 8224964f9..4a30c0fe4 100644 --- a/kclvm/tests/test_units/runtime/crypto/test_crypto.py +++ b/tests/runtime/crypto/test_crypto.py @@ -1,9 +1,8 @@ # Copyright The KCL Authors. All rights reserved. -import typing import unittest -import kclvm_runtime +import kcl_runtime as kcl_runtime # md5(value: str, encoding: str = "utf-8") -> str # sha1(value: str, encoding: str = "utf-8") -> str @@ -12,7 +11,7 @@ # sha384(value: str, encoding: str = "utf-8") -> str # sha512(value: str, encoding: str = "utf-8") -> str -_Dylib = kclvm_runtime.KclvmRuntimeDylib() +_Dylib = kcl_runtime.KclRuntimeDylib() class BaseTest(unittest.TestCase): @@ -80,7 +79,7 @@ def test_sha512(self): self.sha512(""), "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", ) - + def test_blake3(self): self.assertEqual( self.blake3(""), diff --git a/kclvm/tests/test_units/runtime/datetime/test_datetime.py b/tests/runtime/datetime/test_datetime.py similarity index 82% rename from kclvm/tests/test_units/runtime/datetime/test_datetime.py rename to tests/runtime/datetime/test_datetime.py index 70d1675a1..ceeb99c42 100644 --- a/kclvm/tests/test_units/runtime/datetime/test_datetime.py +++ b/tests/runtime/datetime/test_datetime.py @@ -1,13 +1,12 @@ # Copyright The KCL Authors. All rights reserved. -import typing import unittest -import kclvm_runtime +import kcl_runtime as kcl_runtime # https://github.com/python/cpython/blob/main/Lib/test -_Dylib = kclvm_runtime.KclvmRuntimeDylib() +_Dylib = kcl_runtime.KclRuntimeDylib() class kclx_Crypto: diff --git a/kclvm/tests/test_units/runtime/json/test_json.py b/tests/runtime/json/test_json.py similarity index 82% rename from kclvm/tests/test_units/runtime/json/test_json.py rename to tests/runtime/json/test_json.py index 2bdd1fccb..90213039c 100644 --- a/kclvm/tests/test_units/runtime/json/test_json.py +++ b/tests/runtime/json/test_json.py @@ -1,13 +1,12 @@ # Copyright The KCL Authors. All rights reserved. -import typing import unittest -import kclvm_runtime +import kcl_runtime as kcl_runtime # https://github.com/python/cpython/blob/main/Lib/test -_Dylib = kclvm_runtime.KclvmRuntimeDylib() +_Dylib = kcl_runtime.KclRuntimeDylib() class kclx_Json: diff --git a/tests/runtime/kcl_runtime.py b/tests/runtime/kcl_runtime.py new file mode 100644 index 000000000..dcc2b4152 --- /dev/null +++ b/tests/runtime/kcl_runtime.py @@ -0,0 +1,104 @@ +# Copyright The KCL Authors. All rights reserved. + +import ctypes +import json +import os +import sys + + +def _find_default_dylib_path() -> str: + _executable_root = os.path.dirname(os.environ.get("KCL_LIB_PATH") or sys.executable) + + pathList = [ + f"{_executable_root}/lib/libkcl.dylib", + f"{_executable_root}/lib/libkcl.so", + f"{_executable_root}/bin/libkcl.dylib", + f"{_executable_root}/bin/libkcl.so", + f"{_executable_root}/libkcl.dylib", + f"{_executable_root}/libkcl.so", + f"{_executable_root}\\bin\\kcl.dll", + f"{_executable_root}\\kcl.dll", + f"{os.path.dirname(__file__)}/../../target/release/libkcl.dylib", + f"{os.path.dirname(__file__)}/../../target/release/libkcl.so", + f"{os.path.dirname(__file__)}\\..\\..\\target\\release\\kcl.dll", + f"{os.path.dirname(__file__)}/../../target/debug/libkcl.dylib", + f"{os.path.dirname(__file__)}/../../target/debug/libkcl.so", + f"{os.path.dirname(__file__)}\\..\\..\\target\\debug\\kcl.dll", + ] + + for s in pathList: + if os.path.exists(s): + return s + return "" + + +class KclRuntimeDylib: + def __init__(self, dllpath: str = None): + if dllpath is None: + dllpath = _find_default_dylib_path() + if not dllpath: + raise f"kcl runtime lib not found" + + self.dllpath = dllpath + self._app_dll = ctypes.cdll.LoadLibrary(dllpath) + self._app_lib = ctypes.CDLL(dllpath) + self.ctx = None + + # kcl_context_t* kcl_context_new(); + self._app_lib.kcl_context_new.restype = ctypes.c_void_p + + # void kcl_context_delete(kcl_context_t* p); + self._app_lib.kcl_context_delete.argtypes = [ + ctypes.c_void_p, + ] + + # const char* kcl_context_invoke(kcl_context_t* p, const char* method, const char* args, const char* kwargs); + self._app_lib.kcl_context_invoke.restype = ctypes.c_char_p + self._app_lib.kcl_context_invoke.argtypes = [ + ctypes.c_void_p, + ctypes.c_char_p, + ctypes.c_char_p, + ctypes.c_char_p, + ] + + def _kcl_context_new(self) -> ctypes.c_void_p: + return self._app_lib.kcl_context_new() + + def kcl_context_delete(self, ctx: ctypes.c_void_p): + self._app_lib.kcl_context_delete(ctx) + + def _kcl_context_invoke( + self, ctx: ctypes.c_void_p, method: str, args: str, kwargs: str + ) -> any: + jsonValue = self._app_lib.kcl_context_invoke( + ctx, method.encode(), args.encode(), kwargs.encode() + ) + return json.loads(jsonValue) + + def Path(self) -> str: + return self.dllpath + + def Invoke(self, method: str, *args, **kwargs) -> any: + if self.ctx is None: + self.ctx = self._kcl_context_new() + + if not method.startswith("kcl_"): + if method.startswith("str."): + # str.startswith => kcl_builtin_str_startswith + method = f'kcl_builtin_{method.replace(".", "_")}' + elif "." in method: + # regex.match => kcl_regex_match + method = ( + f'kcl_{method.replace(".", "_")}' # json.encode => kcl_json_encode + ) + else: + method = f"kcl_builtin_{method}" # print => kcl_builtin_print + + return self._kcl_context_invoke( + self.ctx, method, json.dumps(args), json.dumps(kwargs) + ) + + +if __name__ == "__main__": + dylib = KclRuntimeDylib() + dylib.Invoke(f"print", "hello kcl") diff --git a/kclvm/tests/test_units/runtime/math/test_math.py b/tests/runtime/math/test_math.py similarity index 98% rename from kclvm/tests/test_units/runtime/math/test_math.py rename to tests/runtime/math/test_math.py index 18feb84b7..86cbfa7f5 100644 --- a/kclvm/tests/test_units/runtime/math/test_math.py +++ b/tests/runtime/math/test_math.py @@ -6,12 +6,12 @@ import math as pymath import struct -import kclvm_runtime +import kcl_runtime as kcl_runtime # https://github.com/python/cpython/blob/main/Lib/test/test_math.py -_Dylib = kclvm_runtime.KclvmRuntimeDylib() +_Dylib = kcl_runtime.KclRuntimeDylib() eps = 1e-05 @@ -89,7 +89,7 @@ def to_ulps(x): """ n = struct.unpack(" bool: return self.dylib.Invoke(f"net.is_global_unicast_IP", value) + def is_link_local_multicast_IP(self, value: str) -> bool: return self.dylib.Invoke(f"net.is_link_local_multicast_IP", value) + def is_interface_local_multicast_IP(self, value: str) -> bool: return self.dylib.Invoke(f"net.is_interface_local_multicast_IP", value) + def is_multicast_IP(self, value: str) -> bool: return self.dylib.Invoke(f"net.is_multicast_IP", value) + def is_loopback_IP(self, value: str) -> bool: return self.dylib.Invoke(f"net.is_loopback_IP", value) + def is_link_local_unicast_IP(self, value: str) -> bool: return self.dylib.Invoke(f"net.is_link_local_unicast_IP", value) + def is_unspecified_IP(self, value: str) -> bool: return self.dylib.Invoke(f"net.is_unspecified_IP", value) kclxnet = kclx_Net(_Dylib) + class BaseTest(unittest.TestCase): def test_is_interface_local_multicast_IP(self): self.assertFalse(kclxnet.is_interface_local_multicast_IP("224.0.0.0")) self.assertTrue(kclxnet.is_interface_local_multicast_IP("ff11::1")) + def test_is_link_local_multicast_IP(self): self.assertTrue(kclxnet.is_link_local_multicast_IP("ff12::1")) + def test_is_global_unicast_IP(self): self.assertTrue(kclxnet.is_global_unicast_IP("2607:f8b0:4005:802::200e")) self.assertTrue(kclxnet.is_global_unicast_IP("64:ff9b::800:1")) self.assertTrue(kclxnet.is_global_unicast_IP("220.181.108.89")) + def test_is_multicast_IP(self): self.assertTrue(kclxnet.is_multicast_IP("239.255.255.255")) + def test_is_loopback_IP(self): self.assertTrue(kclxnet.is_loopback_IP("127.0.0.1")) + def test_is_link_local_unicast_IP(self): self.assertTrue(kclxnet.is_link_local_unicast_IP("fe80::2012:1")) + def test_is_unspecified_IP(self): self.assertTrue(kclxnet.is_unspecified_IP("0.0.0.0")) + if __name__ == "__main__": unittest.main() diff --git a/kclvm/tests/test_units/runtime/regex/test_regex.py b/tests/runtime/regex/test_regex.py similarity index 98% rename from kclvm/tests/test_units/runtime/regex/test_regex.py rename to tests/runtime/regex/test_regex.py index 351b8199b..2a9c5776d 100644 --- a/kclvm/tests/test_units/runtime/regex/test_regex.py +++ b/tests/runtime/regex/test_regex.py @@ -3,18 +3,18 @@ import typing import unittest -import kclvm_runtime +import kcl_runtime as kcl_runtime # https://github.com/python/cpython/blob/main/Lib/test/test_re.py -# kclvm_regex_compile, -# kclvm_regex_findall, -# kclvm_regex_match, -# kclvm_regex_replace, -# kclvm_regex_search, -# kclvm_regex_split, +# kcl_regex_compile, +# kcl_regex_findall, +# kcl_regex_match, +# kcl_regex_replace, +# kcl_regex_search, +# kcl_regex_split, -_Dylib = kclvm_runtime.KclvmRuntimeDylib() +_Dylib = kcl_runtime.KclRuntimeDylib() class kclx_Regex: diff --git a/kclvm/tests/test_units/runtime/str/test_str.py b/tests/runtime/str/test_str.py similarity index 99% rename from kclvm/tests/test_units/runtime/str/test_str.py rename to tests/runtime/str/test_str.py index e9a7ac488..10264cf89 100644 --- a/kclvm/tests/test_units/runtime/str/test_str.py +++ b/tests/runtime/str/test_str.py @@ -3,9 +3,9 @@ import sys import unittest -import kclvm_runtime +import kcl_runtime as kcl_runtime -dylib = kclvm_runtime.KclvmRuntimeDylib() +dylib = kcl_runtime.KclRuntimeDylib() # https://github.com/python/cpython/blob/main/Lib/test/string_tests.py @@ -532,8 +532,8 @@ def test_removeprefix(self): self.checkequal(" ", " aa ", "removeprefix", " aa") self.checkequal("", " aa ", "removeprefix", " aa ") - s = 'foobarfoo' - s_ref='foobarfoo' + s = "foobarfoo" + s_ref = "foobarfoo" self.checkequal(s_ref[1:], s, "removeprefix", "f") self.checkequal(s_ref[2:], s, "removeprefix", "fo") @@ -547,8 +547,8 @@ def test_removeprefix(self): self.checkequal(s_ref, s, "removeprefix", "afoo") self.checkequal(s_ref, s, "removeprefix", "*foo") - s_uc = '😱foobarfoo🖖' - s_ref_uc = '😱foobarfoo🖖' + s_uc = "😱foobarfoo🖖" + s_ref_uc = "😱foobarfoo🖖" self.checkequal(s_ref_uc[1:], s_uc, "removeprefix", "😱") self.checkequal(s_ref_uc[3:], s_uc, "removeprefix", "😱fo") @@ -567,8 +567,8 @@ def test_removesuffix(self): self.checkequal(" ", " aa ", "removesuffix", "aa ") self.checkequal("", " aa ", "removesuffix", " aa ") - s = 'foobarfoo' - s_ref='foobarfoo' + s = "foobarfoo" + s_ref = "foobarfoo" self.checkequal(s_ref[:-1], s, "removesuffix", "o") self.checkequal(s_ref[:-2], s, "removesuffix", "oo") @@ -582,8 +582,8 @@ def test_removesuffix(self): self.checkequal(s_ref, s, "removesuffix", "afoo") self.checkequal(s_ref, s, "removesuffix", "*foo") - s_uc = '😱foobarfoo🖖' - s_ref_uc = '😱foobarfoo🖖' + s_uc = "😱foobarfoo🖖" + s_ref_uc = "😱foobarfoo🖖" self.checkequal(s_ref_uc[:-1], s_uc, "removesuffix", "🖖") self.checkequal(s_ref_uc[:-3], s_uc, "removesuffix", "oo🖖") diff --git a/kclvm/tests/test_units/runtime/units/test_units.py b/tests/runtime/units/test_units.py similarity index 82% rename from kclvm/tests/test_units/runtime/units/test_units.py rename to tests/runtime/units/test_units.py index cd45fd57d..f39e2597b 100644 --- a/kclvm/tests/test_units/runtime/units/test_units.py +++ b/tests/runtime/units/test_units.py @@ -1,13 +1,12 @@ # Copyright The KCL Authors. All rights reserved. -import typing import unittest -import kclvm_runtime +import kcl_runtime as kcl_runtime # https://github.com/python/cpython/blob/main/Lib/test -_Dylib = kclvm_runtime.KclvmRuntimeDylib() +_Dylib = kcl_runtime.KclRuntimeDylib() class kclx_Units: diff --git a/kclvm/tests/test_units/runtime/yaml/test_yaml.py b/tests/runtime/yaml/test_yaml.py similarity index 82% rename from kclvm/tests/test_units/runtime/yaml/test_yaml.py rename to tests/runtime/yaml/test_yaml.py index d067e3aa9..2b6705b1f 100644 --- a/kclvm/tests/test_units/runtime/yaml/test_yaml.py +++ b/tests/runtime/yaml/test_yaml.py @@ -1,13 +1,12 @@ # Copyright The KCL Authors. All rights reserved. -import typing import unittest -import kclvm_runtime +import kcl_runtime as kcl_runtime # https://github.com/python/cpython/blob/main/Lib/test -_Dylib = kclvm_runtime.KclvmRuntimeDylib() +_Dylib = kcl_runtime.KclRuntimeDylib() class kclx_Yaml:

PathPrefix for P +where + P: AsRef, +{ + #[cfg(not(target_os = "windows"))] + /// On non-Windows systems, this method does not make any modifications to the file path. + /// + /// # Examples + /// + /// ```rust + /// use std::path::Path; + /// use kcl_utils::path::PathPrefix; + /// + /// let path = Path::new(".").canonicalize().unwrap(); + /// assert_eq!( + /// path.clone().adjust_canonicalization(), + /// path.display().to_string() + /// ); + /// ``` + fn adjust_canonicalization(&self) -> String { + self.as_ref().display().to_string() + } + + #[cfg(target_os = "windows")] + /// For kcl on windows, the "\\?\ " will cause the obj file to not be found when linking by "cl.exe". + /// + /// Slicing this path directly is not a good solution, + /// we will find a more fluent way to solve this problem in the future. @zongz + /// Note: On windows systems, a file path that is too long may cause "cl.exe" to crash. + /// For more information, see doc in trait [`PathPrefix`]. + /// + /// # Examples + /// + /// ```rust + /// use std::path::Path; + /// use kcl_utils::path::PathPrefix; + /// + /// let path = Path::new(".").canonicalize().unwrap(); + /// assert!(path.display().to_string().contains("\\\\?\\")); + /// assert!(!path.adjust_canonicalization().contains("\\\\?\\")); + /// ``` + fn adjust_canonicalization(&self) -> String { + const VERBATIM_PREFIX: &str = r#"\\?\"#; + const ESCAPE_VERBATIM_PREFIX: &str = r#"\\\\?\\"#; + let p = self.as_ref().display().to_string(); + if p.starts_with(VERBATIM_PREFIX) { + p[VERBATIM_PREFIX.len()..].to_string() + } else if p.starts_with(ESCAPE_VERBATIM_PREFIX) { + p[ESCAPE_VERBATIM_PREFIX.len()..].to_string() + } else { + p + } + } +} + +/// Convert windows drive letter to upcase +pub fn convert_windows_drive_letter(path: &str) -> String { + #[cfg(target_os = "windows")] + { + let regex = regex::Regex::new(r"(?i)^\\\\\?\\[a-z]:\\").unwrap(); + const VERBATIM_PREFIX: &str = r#"\\?\"#; + let mut p = path.to_string(); + if p.starts_with(VERBATIM_PREFIX) && regex.is_match(&p) { + let drive_letter = p[VERBATIM_PREFIX.len()..VERBATIM_PREFIX.len() + 1].to_string(); + p.replace_range( + VERBATIM_PREFIX.len()..VERBATIM_PREFIX.len() + 1, + &drive_letter.to_uppercase(), + ); + } + let regex = regex::Regex::new(r"[a-z]:\\").unwrap(); + if regex.is_match(&p) { + let drive_letter = p[0..1].to_string(); + p.replace_range(0..1, &drive_letter.to_uppercase()); + } + p + } + #[cfg(not(target_os = "windows"))] + { + path.to_owned() + } +} + +#[test] +fn test_convert_drive_letter() { + #[cfg(target_os = "windows")] + { + let path = r"\\?\d:\xx"; + assert_eq!(convert_windows_drive_letter(path), r"\\?\D:\xx".to_string()); + + let path = r"d:\xx"; + assert_eq!(convert_windows_drive_letter(path), r"D:\xx".to_string()); + } + #[cfg(not(target_os = "windows"))] + { + let path = r".\xx"; + assert_eq!(convert_windows_drive_letter(path), path.to_string()); + } +} + +#[test] +#[cfg(target_os = "windows")] +fn test_adjust_canonicalization() { + let path = Path::new(".").canonicalize().unwrap(); + assert!(path.display().to_string().contains("\\\\?\\")); + assert!(!path.adjust_canonicalization().contains("\\\\?\\")); +} + +#[test] +#[cfg(not(target_os = "windows"))] +fn test_adjust_canonicalization1() { + let path = Path::new(".").canonicalize().unwrap(); + assert_eq!( + path.clone().adjust_canonicalization(), + path.display().to_string() + ); +} + +#[inline] +pub fn is_dir(path: &str) -> bool { + std::path::Path::new(path).is_dir() +} + +#[inline] +pub fn is_absolute(path: &str) -> bool { + std::path::Path::new(path).is_absolute() +} + +#[inline] +pub fn path_exist(path: &str) -> bool { + std::path::Path::new(path).exists() +} diff --git a/kclvm/utils/src/pkgpath.rs b/crates/utils/src/pkgpath.rs similarity index 97% rename from kclvm/utils/src/pkgpath.rs rename to crates/utils/src/pkgpath.rs index ca837359e..8b4495e0f 100644 --- a/kclvm/utils/src/pkgpath.rs +++ b/crates/utils/src/pkgpath.rs @@ -1,6 +1,6 @@ //! This file primarily offers utils for working with kcl package paths. -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; /// Remove the external package name prefix from the current import absolute path. /// diff --git a/crates/version/Cargo.toml b/crates/version/Cargo.toml new file mode 100644 index 000000000..750f986d0 --- /dev/null +++ b/crates/version/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "kcl-version" +version.workspace = true +edition.workspace = true + +[build-dependencies] +vergen-gitcl = { version = "1.0.0", features = ["rustc"] } + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/kclvm/version/build.rs b/crates/version/build.rs similarity index 100% rename from kclvm/version/build.rs rename to crates/version/build.rs diff --git a/crates/version/src/lib.rs b/crates/version/src/lib.rs new file mode 100644 index 000000000..d03e0d2f8 --- /dev/null +++ b/crates/version/src/lib.rs @@ -0,0 +1,29 @@ +//! Copyright The KCL Authors. All rights reserved. + +pub const VERSION: &str = env!("CARGO_PKG_VERSION"); +pub const CHECK_SUM: &str = "c020ab3eb4b9179219d6837a57f5d323"; +pub const GIT_SHA: &str = env!("VERGEN_GIT_SHA"); +pub const HOST_TRIPLE: &str = env!("VERGEN_RUSTC_HOST_TRIPLE"); + +/// Get KCL full version string with the format `{version}-{check_sum}`. +#[inline] +pub fn get_version_string() -> String { + format!("{}-{}", VERSION, CHECK_SUM) +} + +/// Get KCL build git sha. +#[inline] +pub fn get_git_sha() -> &'static str { + option_env!("KCL_BUILD_GIT_SHA").unwrap_or_else(|| GIT_SHA) +} + +/// Get version info including version string, platform. +#[inline] +pub fn get_version_info() -> String { + format!( + "Version: {}\r\nPlatform: {}\r\nGitCommit: {}", + get_version_string(), + HOST_TRIPLE, + get_git_sha(), + ) +} diff --git a/docs/dev_guide/2.quick_start.md b/docs/dev_guide/2.quick_start.md index 1d8d3c239..e7f7255a6 100644 --- a/docs/dev_guide/2.quick_start.md +++ b/docs/dev_guide/2.quick_start.md @@ -27,44 +27,16 @@ The following hardware is recommended. ### Dependencies -#### Docker - -- `docker` - -In the top level of the `kcl-lang/kcl` repo and run: - -```sh -make sh-in-docker -``` - -Using a docker image is our recommended way, of course, you can also configure your local development environment according to the following content. - #### macOS and OS X - `git` - `Rust 1.84+` -- `LLVM 12` (Optional, only for the LLVM backend and release) - `Python 3.7+` (Optional, only for integration tests) -You'll need LLVM installed and `llvm-config` in your `PATH`. Just download from [LLVM 12](https://releases.llvm.org/download.html) or install `llvm@12` using `brew`. - -```sh -# llvm@12 (Optional, only for the LLVM backend and release) -brew install llvm@12 -``` - -Add the LLVM installation location to `LLVM_SYS_120_PREFIX` and the `$PATH`. - -```sh -export LLVM_SYS_120_PREFIX= -export PATH=/bin:$PATH -``` - #### Linux - `git` - `Rust 1.84+` -- `LLVM 12` (Optional, only for the LLVM backend and release) - `Python3 Building Dependencies` (Optional, only for integration tests) For UNIX based systems, you can run: @@ -78,13 +50,6 @@ yum-builddep -y python3 yum install -y zlib* yum install -y openssl-devel yum install -y glibc-static - -# clang-12 & llvm-12 (Optional, only for the LLVM backend and release), if llvm is not found, you can use ./scripts/build-llvm/build.sh to build llvm-12 locally. -yum -y install clang -clang --version -yum -y install llvm-devel -yum -y install libffi-devel -ln -s /usr/lib64/libtinfo.so.6 /usr/lib64/libtinfo.so ``` On Debian, Ubuntu, and other apt based systems, you can run: @@ -96,22 +61,14 @@ apt-get install -y git wget curl apt-get install -y make gcc patch apt-get install -y python-dev libffi-dev apt-get install -y zlib1g-dev ncurses-dev build-essential libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev - -# clang-12 & llvm-12 (Optional, only for the LLVM backend and release), if llvm is not found, you can use ./scripts/build-llvm/build.sh to build llvm-12 locally. -apt-get install -y clang-12 lld-12 -ln -sf /usr/bin/clang-12 /usr/bin/clang -ln -sf /usr/bin/wasm-ld-12 /usr/bin/wasm-ld ``` #### Windows - `git` - `Rust 1.84+` -- `LLVM 12` (Optional, only for the LLVM backend and release) - `Python 3.7+` (Only for integration tests) -Please add the LLVM installation location to `LLVM_SYS_120_PREFIX` and the `$PATH`. - ### Cloning You can just do a normal git clone: @@ -144,14 +101,14 @@ make build In the top level of the `kcl-lang/kcl` repo and run: ```sh -.\build.ps1 +.\scripts\build.ps1 ``` ### Building for Different Targets #### wasm32-wasip1 -In the folder `kclvm` of the `kcl-lang/kcl` repo and run: +In the top level of of the `kcl-lang/kcl` repo and run: ```shell make build-wasm diff --git a/docs/dev_guide/4.architecture.md b/docs/dev_guide/4.architecture.md index 16fdfef13..34c37f311 100644 --- a/docs/dev_guide/4.architecture.md +++ b/docs/dev_guide/4.architecture.md @@ -28,7 +28,7 @@ The compiling phase translates the resolved AST into an intermediate representat ### Evaluating -After compilation, the evaluating phase executes the program using the IR including AST and LLVM IR. During this phase, the compiler can evaluate expressions, compute values, and perform optimizations that are runtime-specific. +After compilation, the evaluating phase executes the program using the IR including AST. During this phase, the compiler can evaluate expressions, compute values, and perform optimizations that are runtime-specific. ### Runtime @@ -58,7 +58,7 @@ KCL provides APIs and SDKs for multiple programming languages, allowing develope | Term | Meaning | | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -| AST | The abstract syntax tree produced by the `kclvm_ast` crate; reflects user syntax very closely. | +| AST | The abstract syntax tree produced by the `kcl_ast` crate; reflects user syntax very closely. | | Lexer | A tool that converts the input code into a stream of tokens for parsing. | | Parser | A tool that constructs an AST from a stream of tokens. | | Namer | The compiler component responsible for assigning unique names to language entities and ensuring they are used consistently throughout the program. | diff --git a/docs/dev_guide/5.source_code.md b/docs/dev_guide/5.source_code.md index 3bbe4c989..58611c09a 100644 --- a/docs/dev_guide/5.source_code.md +++ b/docs/dev_guide/5.source_code.md @@ -6,19 +6,19 @@ The `kcl-lang/kcl` repository consists of a single large cargo workspace. The repository consists of three main directories: -+ `kclvm` contains the source code for the KCL core. It consists of many crates that together make up the compiler. ++ `crates` contains the source code for the KCL core. It consists of many crates that together make up the compiler. + `compiler_base` contains a set of basic libraries for compilers, which are dependent on `kcl` + `scripts` contains the source code and image build scripts. -+ `test` contains the compiler grammar integration tests. ++ `tests` contains the compiler grammar integration tests. -## Core Code (kclvm) +## Core Code -`kclvm` contains the source code for the KCL core. It consists of many crates that together make up the compiler. +`crates` contains the source code for the KCL core. It consists of many crates that together make up the compiler. + `api` contains over ten important APIs of KCL, including parsing code, running code, toolchain APIs, etc. It is the interface layer of KCL Rust core and other multi language SDKs of KCL, such as kcl-go, kcl-py, and kcl-java. + `ast` contains the core Abstract Syntax Tree (AST), tree walker and token definitions. + `ast_pretty` contains the tools and utilities to format and print the AST in a human-readable way. -+ `cmd` houses the command-line interface tools, enabling the users to interact with the compiler via the command-line such as `kclvm_cli` binary. ++ `cmd` houses the command-line interface tools, enabling the users to interact with the compiler via the command-line such as `libkcl` binary. + `compiler` contains the main compilation logic, responsible for converting the high-level KCL code into an intermediate representation before it is executed further. + `config` holds configuration-related code, including parsing command-line arguments, handling configuration files, and managing compiler settings. + `error` includes definitions and handlers for error messages, diagnostics, and compiler warnings to assist with debugging and user feedback. diff --git a/docs/dev_guide/6.languager_server.md b/docs/dev_guide/6.languager_server.md index 085fe6598..cef1e0099 100644 --- a/docs/dev_guide/6.languager_server.md +++ b/docs/dev_guide/6.languager_server.md @@ -115,13 +115,13 @@ If you have prepared a kcl development environment, you can use the script we pr For MacOS and Linux ```bash -./run.sh +./scripts/build.sh ``` For Windows ```bash -./build.ps1 +.\scripts\build.ps1 ``` Alternatively, you can use cargo to build kcl-language-server: @@ -130,7 +130,7 @@ Alternatively, you can use cargo to build kcl-language-server: make build-lsp ``` -The built language server will be at `kclvm/target/release/kcl-language-server` +The built language server will be at `target/release/kcl-language-server` 1. Add kcl-language-server to PATH diff --git a/kclvm/Cargo.lock b/kclvm/Cargo.lock deleted file mode 100644 index fb93d48aa..000000000 --- a/kclvm/Cargo.lock +++ /dev/null @@ -1,5562 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 4 - -[[package]] -name = "addr2line" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" -dependencies = [ - "gimli", -] - -[[package]] -name = "adler2" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" - -[[package]] -name = "aho-corasick" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" -dependencies = [ - "memchr", -] - -[[package]] -name = "always-assert" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4436e0292ab1bb631b42973c61205e704475fe8126af845c8d923c0996328127" -dependencies = [ - "log", -] - -[[package]] -name = "android_system_properties" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" -dependencies = [ - "libc", -] - -[[package]] -name = "anes" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299" - -[[package]] -name = "annotate-snippets" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccaf7e9dfbb6ab22c82e473cd1a8a7bd313c19a5b7e40970f3d89ef5a5c9e81e" -dependencies = [ - "unicode-width", - "yansi-term", -] - -[[package]] -name = "anstream" -version = "0.6.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78" - -[[package]] -name = "anstyle-parse" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e231f6134f61b71076a3eab506c379d4f36122f2af15a9ff04415ea4c3339e2" -dependencies = [ - "windows-sys 0.60.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e0633414522a32ffaac8ac6cc8f748e090c5717661fddeea04219e2344f5f2a" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.60.2", -] - -[[package]] -name = "anyhow" -version = "1.0.100" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61" -dependencies = [ - "backtrace", -] - -[[package]] -name = "arrayref" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" - -[[package]] -name = "arrayvec" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" - -[[package]] -name = "async-stream" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" -dependencies = [ - "async-stream-impl", - "futures-core", - "pin-project-lite", -] - -[[package]] -name = "async-stream-impl" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "atomic-waker" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" - -[[package]] -name = "autocfg" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" - -[[package]] -name = "backtrace" -version = "0.3.76" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" -dependencies = [ - "addr2line", - "cfg-if 1.0.4", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", - "windows-link 0.2.1", -] - -[[package]] -name = "base-x" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cbbc9d0964165b47557570cce6c952866c2678457aca742aafc9fb771d30270" - -[[package]] -name = "base32" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23ce669cd6c8588f79e15cf450314f9638f967fc5770ff1c7c1deb0925ea7cfa" - -[[package]] -name = "base64" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "bit-set" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0700ddab506f33b20a03b13996eccd309a48e5ff77d0d95926aa0210fb4e95f1" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" - -[[package]] -name = "bitmaps" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "031043d04099746d8db04daf1fa424b2bc8bd69d92b25962dcde24da39ab64a2" -dependencies = [ - "typenum", -] - -[[package]] -name = "blake3" -version = "1.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3888aaa89e4b2a40fca9848e400f6a658a5a3978de7be858e209cafa8be9a4a0" -dependencies = [ - "arrayref", - "arrayvec", - "cc", - "cfg-if 1.0.4", - "constant_time_eq", -] - -[[package]] -name = "block-buffer" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0940dc441f31689269e10ac70eb1002a3a1d3ad1390e030043662eb7fe4688b" -dependencies = [ - "block-padding", - "byte-tools", - "byteorder", - "generic-array 0.12.4", -] - -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "generic-array 0.14.9", -] - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array 0.14.9", -] - -[[package]] -name = "block-padding" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa79dedbb091f449f1f39e53edf88d5dbe95f895dae6135a8d7b881fb5af73f5" -dependencies = [ - "byte-tools", -] - -[[package]] -name = "bstr" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" -dependencies = [ - "lazy_static", - "memchr", - "regex-automata 0.1.10", -] - -[[package]] -name = "bumpalo" -version = "3.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43" - -[[package]] -name = "byte-tools" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3b5ca7a04898ad4bcd41c90c5285445ff5b791899bb1b0abdd2a2aa791211d7" - -[[package]] -name = "byteorder" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" - -[[package]] -name = "bytes" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" - -[[package]] -name = "cast" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" - -[[package]] -name = "cc" -version = "1.2.43" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "739eb0f94557554b3ca9a86d2d37bebd49c5e6d0c1d2bda35ba5bdac830befc2" -dependencies = [ - "find-msvc-tools", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - -[[package]] -name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "cfg_aliases" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" - -[[package]] -name = "chrono" -version = "0.4.42" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "145052bdd345b87320e369255277e3fb5152762ad123a901ef5c262dd38fe8d2" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link 0.2.1", -] - -[[package]] -name = "ciborium" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" -dependencies = [ - "ciborium-io", - "ciborium-ll", - "serde", -] - -[[package]] -name = "ciborium-io" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" - -[[package]] -name = "ciborium-ll" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" -dependencies = [ - "ciborium-io", - "half", -] - -[[package]] -name = "cidr" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd1b64030216239a2e7c364b13cd96a2097ebf0dfe5025f2dedee14a23f2ab60" - -[[package]] -name = "clap" -version = "4.5.50" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c2cfd7bf8a6017ddaa4e32ffe7403d547790db06bd171c1c53926faab501623" -dependencies = [ - "clap_builder", -] - -[[package]] -name = "clap_builder" -version = "4.5.50" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a4c05b9e80c5ccd3a7ef080ad7b6ba7d6fc00a985b8b157197075677c82c7a0" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim 0.11.1", -] - -[[package]] -name = "clap_lex" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1d728cc89cf3aee9ff92b05e62b19ee65a02b5702cff7d5a377e32c6ae29d8d" - -[[package]] -name = "colorchoice" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75" - -[[package]] -name = "compiler_base_error" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32e6a143200e9657a565b093fde64a590af93884d1f820829db6461de1ff0086" -dependencies = [ - "anyhow", - "compiler_base_macros", - "compiler_base_span", - "fluent", - "pretty_assertions", - "rustc_errors", - "rustc_span", - "termcolor", - "unic-langid", - "walkdir", -] - -[[package]] -name = "compiler_base_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21900034f34b69f860a5ff66e0577b8e66d310090b04bf0334afea9a041e0cee" - -[[package]] -name = "compiler_base_session" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67411f0b5421d9c9f045ec08c4d01fe3861197d11215d1e2e448be663aff9ad9" -dependencies = [ - "anyhow", - "compiler_base_error", - "compiler_base_span", -] - -[[package]] -name = "compiler_base_span" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a42aae2adfa4b418441ede52835f3c96e9ca63d595f0ac861d94935757e9cb2e" -dependencies = [ - "rustc_span", -] - -[[package]] -name = "console" -version = "0.15.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "054ccb5b10f9f2cbf51eb355ca1d05c2d279ce1804688d0db74b4733a5aeafd8" -dependencies = [ - "encode_unicode", - "libc", - "once_cell", - "windows-sys 0.59.0", -] - -[[package]] -name = "const_fn" -version = "0.4.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f8a2ca5ac02d09563609681103aada9e1777d54fc57a5acd7a41404f9c93b6e" - -[[package]] -name = "constant_time_eq" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c74b8349d32d297c9134b8c88677813a227df8f779daa29bfc29c183fe3dca6" - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "crc32fast" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" -dependencies = [ - "cfg-if 1.0.4", -] - -[[package]] -name = "criterion" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f" -dependencies = [ - "anes", - "cast", - "ciborium", - "clap", - "criterion-plot", - "is-terminal", - "itertools", - "num-traits", - "once_cell", - "oorandom", - "plotters", - "rayon", - "regex", - "serde", - "serde_derive", - "serde_json", - "tinytemplate", - "walkdir", -] - -[[package]] -name = "criterion-plot" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1" -dependencies = [ - "cast", - "itertools", -] - -[[package]] -name = "crossbeam-channel" -version = "0.5.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" -dependencies = [ - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" -dependencies = [ - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" - -[[package]] -name = "crunchy" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" - -[[package]] -name = "crypto-common" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" -dependencies = [ - "generic-array 0.14.9", - "typenum", -] - -[[package]] -name = "darling" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" -dependencies = [ - "darling_core", - "darling_macro", -] - -[[package]] -name = "darling_core" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim 0.11.1", - "syn 2.0.108", -] - -[[package]] -name = "darling_macro" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" -dependencies = [ - "darling_core", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "dashmap" -version = "5.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978747c1d849a7d2ee5e8adc0159961c48fb7e5db2f06af6723b80123bb53856" -dependencies = [ - "cfg-if 1.0.4", - "hashbrown 0.14.5", - "lock_api", - "once_cell", - "parking_lot_core 0.9.12", -] - -[[package]] -name = "deranged" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ececcb659e7ba858fb4f10388c250a7252eb0a27373f1a72b8748afdd248e587" -dependencies = [ - "powerfmt", -] - -[[package]] -name = "derive_builder" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" -dependencies = [ - "derive_builder_macro", -] - -[[package]] -name = "derive_builder_core" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" -dependencies = [ - "darling", - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "derive_builder_macro" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" -dependencies = [ - "derive_builder_core", - "syn 2.0.108", -] - -[[package]] -name = "diff" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" - -[[package]] -name = "digest" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3d0c8c8752312f9713efd397ff63acb9f85585afbf179282e720e7704954dd5" -dependencies = [ - "generic-array 0.12.4", -] - -[[package]] -name = "digest" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" -dependencies = [ - "generic-array 0.14.9", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer 0.10.4", - "crypto-common", - "subtle", -] - -[[package]] -name = "dirs" -version = "5.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" -dependencies = [ - "dirs-sys", -] - -[[package]] -name = "dirs-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" -dependencies = [ - "libc", - "option-ext", - "redox_users", - "windows-sys 0.48.0", -] - -[[package]] -name = "discard" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "212d0f5754cb6769937f4501cc0e67f4f4483c8d2c3e1e922ee9edbe4ab4c7c0" - -[[package]] -name = "displaydoc" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "dissimilar" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8975ffdaa0ef3661bfe02dbdcc06c9f829dfafe6a3c474de366a8d5e44276921" - -[[package]] -name = "dns-lookup" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf5597a4b7fe5275fc9dcf88ce26326bc8e4cb87d0130f33752d4c5f717793cf" -dependencies = [ - "cfg-if 1.0.4", - "libc", - "socket2", - "windows-sys 0.60.2", -] - -[[package]] -name = "either" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" - -[[package]] -name = "ena" -version = "0.14.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d248bdd43ce613d87415282f69b9bb99d947d290b10962dd6c56233312c2ad5" -dependencies = [ - "log", -] - -[[package]] -name = "encode_unicode" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" - -[[package]] -name = "encoding_rs" -version = "0.8.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" -dependencies = [ - "cfg-if 1.0.4", -] - -[[package]] -name = "enquote" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06c36cb11dbde389f4096111698d8b567c0720e3452fd5ac3e6b4e47e1939932" -dependencies = [ - "thiserror 1.0.69", -] - -[[package]] -name = "env_filter" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bf3c259d255ca70051b30e2e95b5446cdb8949ac4cd22c0d7fd634d89f568e2" -dependencies = [ - "log", - "regex", -] - -[[package]] -name = "env_logger" -version = "0.11.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f" -dependencies = [ - "anstream", - "anstyle", - "env_filter", - "jiff", - "log", -] - -[[package]] -name = "equivalent" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" - -[[package]] -name = "erased-serde" -version = "0.4.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89e8918065695684b2b0702da20382d5ae6065cf3327bc2d6436bd49a71ce9f3" -dependencies = [ - "serde", - "serde_core", - "typeid", -] - -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "expect-test" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63af43ff4431e848fb47472a920f14fa71c24de13255a5692e93d4e90302acb0" -dependencies = [ - "dissimilar", - "once_cell", -] - -[[package]] -name = "fancy-regex" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d6b8560a05112eb52f04b00e5d3790c0dd75d9d980eb8a122fb23b92a623ccf" -dependencies = [ - "bit-set", - "regex", -] - -[[package]] -name = "fastrand" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" - -[[package]] -name = "filetime" -version = "0.2.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc0505cd1b6fa6580283f6bdf70a73fcf4aba1184038c90902b92b3dd0df63ed" -dependencies = [ - "cfg-if 1.0.4", - "libc", - "libredox", - "windows-sys 0.60.2", -] - -[[package]] -name = "find-msvc-tools" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52051878f80a721bb68ebfbc930e07b65ba72f2da88968ea5c06fd6ca3d3a127" - -[[package]] -name = "fixedbitset" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80" - -[[package]] -name = "flate2" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfe33edd8e85a12a67454e37f8c75e730830d83e313556ab9ebf9ee7fbeb3bfb" -dependencies = [ - "crc32fast", - "miniz_oxide", -] - -[[package]] -name = "fluent" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb74634707bebd0ce645a981148e8fb8c7bccd4c33c652aeffd28bf2f96d555a" -dependencies = [ - "fluent-bundle", - "unic-langid", -] - -[[package]] -name = "fluent-bundle" -version = "0.15.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fe0a21ee80050c678013f82edf4b705fe2f26f1f9877593d13198612503f493" -dependencies = [ - "fluent-langneg", - "fluent-syntax", - "intl-memoizer", - "intl_pluralrules", - "rustc-hash 1.1.0", - "self_cell 0.10.3", - "smallvec", - "unic-langid", -] - -[[package]] -name = "fluent-langneg" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7eebbe59450baee8282d71676f3bfed5689aeab00b27545e83e5f14b1195e8b0" -dependencies = [ - "unic-langid", -] - -[[package]] -name = "fluent-syntax" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a530c4694a6a8d528794ee9bbd8ba0122e779629ac908d15ad5a7ae7763a33d" -dependencies = [ - "thiserror 1.0.69", -] - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "form_urlencoded" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "fsevent-sys" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" -dependencies = [ - "libc", -] - -[[package]] -name = "fslock" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04412b8935272e3a9bae6f48c7bfff74c2911f60525404edfdd28e49884c3bfb" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "fst" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ab85b9b05e3978cc9a9cf8fea7f01b494e1a09ed3037e16ba39edc7a29eb61a" - -[[package]] -name = "futures" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876" -dependencies = [ - "futures-channel", - "futures-core", - "futures-executor", - "futures-io", - "futures-sink", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-channel" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" -dependencies = [ - "futures-core", - "futures-sink", -] - -[[package]] -name = "futures-core" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" - -[[package]] -name = "futures-executor" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" -dependencies = [ - "futures-core", - "futures-task", - "futures-util", -] - -[[package]] -name = "futures-io" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" - -[[package]] -name = "futures-macro" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "futures-sink" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7" - -[[package]] -name = "futures-task" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988" - -[[package]] -name = "futures-util" -version = "0.3.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" -dependencies = [ - "futures-channel", - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "pin-utils", - "slab", -] - -[[package]] -name = "generational-arena" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877e94aff08e743b651baaea359664321055749b398adff8740a7399af7796e7" -dependencies = [ - "cfg-if 1.0.4", -] - -[[package]] -name = "generic-array" -version = "0.12.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" -dependencies = [ - "typenum", -] - -[[package]] -name = "generic-array" -version = "0.14.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" -dependencies = [ - "cfg-if 1.0.4", - "js-sys", - "libc", - "wasi", - "wasm-bindgen", -] - -[[package]] -name = "getrandom" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" -dependencies = [ - "cfg-if 1.0.4", - "js-sys", - "libc", - "r-efi", - "wasip2", - "wasm-bindgen", -] - -[[package]] -name = "gimli" -version = "0.32.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" - -[[package]] -name = "glob" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280" - -[[package]] -name = "half" -version = "2.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" -dependencies = [ - "cfg-if 1.0.4", - "crunchy", - "zerocopy", -] - -[[package]] -name = "handlebars" -version = "5.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d08485b96a0e6393e9e4d1b8d48cf74ad6c063cd905eb33f42c1ce3f0377539b" -dependencies = [ - "log", - "pest", - "pest_derive", - "serde", - "serde_json", - "thiserror 1.0.69", -] - -[[package]] -name = "hashbrown" -version = "0.12.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" - -[[package]] -name = "hashbrown" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" - -[[package]] -name = "hashbrown" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d" - -[[package]] -name = "heck" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d621efb26863f0e9924c6ac577e8275e5e6b77455db64ffa6c65c904e9e132c" -dependencies = [ - "unicode-segmentation", -] - -[[package]] -name = "heck" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" - -[[package]] -name = "hermit-abi" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c" - -[[package]] -name = "hmac" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" -dependencies = [ - "digest 0.10.7", -] - -[[package]] -name = "hostname" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a56f203cd1c76362b69e3863fd987520ac36cf70a8c92627449b2f64a8cf7d65" -dependencies = [ - "cfg-if 1.0.4", - "libc", - "windows-link 0.1.3", -] - -[[package]] -name = "http" -version = "1.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565" -dependencies = [ - "bytes", - "fnv", - "itoa", -] - -[[package]] -name = "http-auth" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "150fa4a9462ef926824cf4519c84ed652ca8f4fbae34cb8af045b5cbcaf98822" -dependencies = [ - "memchr", -] - -[[package]] -name = "http-body" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" -dependencies = [ - "bytes", - "http", -] - -[[package]] -name = "http-body-util" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" -dependencies = [ - "bytes", - "futures-core", - "http", - "http-body", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" - -[[package]] -name = "hyper" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb3aa54a13a0dfe7fbe3a59e0c76093041720fdc77b110cc0fc260fafb4dc51e" -dependencies = [ - "atomic-waker", - "bytes", - "futures-channel", - "futures-core", - "http", - "http-body", - "httparse", - "itoa", - "pin-project-lite", - "pin-utils", - "smallvec", - "tokio", - "want", -] - -[[package]] -name = "hyper-rustls" -version = "0.27.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58" -dependencies = [ - "http", - "hyper", - "hyper-util", - "rustls", - "rustls-pki-types", - "tokio", - "tokio-rustls", - "tower-service", - "webpki-roots", -] - -[[package]] -name = "hyper-util" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c6995591a8f1380fcb4ba966a252a4b29188d51d2b89e3a252f5305be65aea8" -dependencies = [ - "base64 0.22.1", - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "http", - "http-body", - "hyper", - "ipnet", - "libc", - "percent-encoding", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.64" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "icu_collections" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f578a71f2bfaf7ceb30b519a645ae48024b45f9eecbe060a31a004d7b4ba9462" -dependencies = [ - "displaydoc", - "potential_utf", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c219b62bf5a06801012446193fdfcbd7970e876823aba4c62def2ce957dcb44" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33747cecc725eebb47ac503fab725e395d50cb7889ae490a1359f130611d4cc5" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6ce2d23e1b3c45624ba6a23e2c767e01c9680e0c0800b39c7abfff9565175d8" - -[[package]] -name = "icu_properties" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d70f9b6574c79f7a83ea5ce72cc88d271a3e77355c5f7748a107e751d8617fb" -dependencies = [ - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17fa55bf868e28e638ed132bcee1e5c21ba2c1e52c15e7c78b781858e7b54342" - -[[package]] -name = "icu_provider" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f64958e359123591ae1f17a27b5fc9ebdb50c98b04e0401146154de1d8fe3e44" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "im-rc" -version = "15.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af1955a75fa080c677d3972822ec4bad316169ab1cfc6c257a942c2265dbe5fe" -dependencies = [ - "bitmaps", - "rand_core 0.6.4", - "rand_xoshiro", - "sized-chunks", - "typenum", - "version_check", -] - -[[package]] -name = "indexmap" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99" -dependencies = [ - "autocfg", - "hashbrown 0.12.3", - "rustc-rayon 0.5.1", -] - -[[package]] -name = "indexmap" -version = "2.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6717a8d2a5a929a1a2eb43a12812498ed141a0bcfb7e8f7844fbdbe4303bba9f" -dependencies = [ - "equivalent", - "hashbrown 0.16.0", -] - -[[package]] -name = "inkwell" -version = "0.2.0" -source = "git+https://github.com/TheDan64/inkwell?branch=master#4030f764f1c889f36429ac02ef32e04fcfa8ce33" -dependencies = [ - "either", - "inkwell_internals", - "libc", - "llvm-sys", - "once_cell", - "parking_lot 0.12.5", -] - -[[package]] -name = "inkwell_internals" -version = "0.8.0" -source = "git+https://github.com/TheDan64/inkwell?branch=master#4030f764f1c889f36429ac02ef32e04fcfa8ce33" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "inotify" -version = "0.9.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8069d3ec154eb856955c1c0fbffefbf5f3c40a104ec912d4797314c1801abff" -dependencies = [ - "bitflags 1.3.2", - "inotify-sys", - "libc", -] - -[[package]] -name = "inotify" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fdd168d97690d0b8c412d6b6c10360277f4d7ee495c5d0d5d5fe0854923255cc" -dependencies = [ - "bitflags 1.3.2", - "inotify-sys", - "libc", -] - -[[package]] -name = "inotify-sys" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb" -dependencies = [ - "libc", -] - -[[package]] -name = "insta" -version = "1.43.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "46fdb647ebde000f43b5b53f773c30cf9b0cb4300453208713fa38b2c70935a0" -dependencies = [ - "console", - "once_cell", - "similar", -] - -[[package]] -name = "instant" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" -dependencies = [ - "cfg-if 1.0.4", -] - -[[package]] -name = "intl-memoizer" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "310da2e345f5eb861e7a07ee182262e94975051db9e4223e909ba90f392f163f" -dependencies = [ - "type-map", - "unic-langid", -] - -[[package]] -name = "intl_pluralrules" -version = "7.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "078ea7b7c29a2b4df841a7f6ac8775ff6074020c6776d48491ce2268e068f972" -dependencies = [ - "unic-langid", -] - -[[package]] -name = "inventory" -version = "0.3.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc61209c082fbeb19919bee74b176221b27223e27b65d781eb91af24eb1fb46e" -dependencies = [ - "rustversion", -] - -[[package]] -name = "ipnet" -version = "2.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" - -[[package]] -name = "iri-string" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc5ebe9c3a1a7a5127f920a418f7585e9e758e911d0466ed004f393b0e380b2" -dependencies = [ - "memchr", - "serde", -] - -[[package]] -name = "is-terminal" -version = "0.4.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46" -dependencies = [ - "hermit-abi", - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - -[[package]] -name = "itertools" -version = "0.10.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" - -[[package]] -name = "jiff" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be1f93b8b1eb69c77f24bbb0afdf66f54b632ee39af40ca21c4365a1d7347e49" -dependencies = [ - "jiff-static", - "log", - "portable-atomic", - "portable-atomic-util", - "serde", -] - -[[package]] -name = "jiff-static" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03343451ff899767262ec32146f6d559dd759fdadf42ff0e227c7c48f72594b4" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "jobserver" -version = "0.1.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33" -dependencies = [ - "getrandom 0.3.4", - "libc", -] - -[[package]] -name = "jod-thread" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b23360e99b8717f20aaa4598f5a6541efbe30630039fbc7706cf954a87947ae" - -[[package]] -name = "js-sys" -version = "0.3.82" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b011eec8cc36da2aab2d5cff675ec18454fad408585853910a202391cf9f8e65" -dependencies = [ - "once_cell", - "wasm-bindgen", -] - -[[package]] -name = "json-spanned-value" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb343fa4e3b1b22b344937deedac88da995abf139c2232cbeaa436c38380a210" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "jsonrpc-core" -version = "18.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14f7f76aef2d054868398427f6c54943cf3d1caa9a7ec7d0c38d69df97a965eb" -dependencies = [ - "futures", - "futures-executor", - "futures-util", - "log", - "serde", - "serde_derive", - "serde_json", -] - -[[package]] -name = "jsonrpc-stdio-server" -version = "18.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6878586767497326eb3d011bd6dbb583e9f008b11528f82fd47798ec46bb6c26" -dependencies = [ - "futures", - "jsonrpc-core", - "log", - "tokio", - "tokio-util 0.6.10", -] - -[[package]] -name = "jwt" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6204285f77fe7d9784db3fdc449ecce1a0114927a51d5a41c4c7a292011c015f" -dependencies = [ - "base64 0.13.1", - "crypto-common", - "digest 0.10.7", - "hmac", - "serde", - "serde_json", - "sha2 0.10.9", -] - -[[package]] -name = "kcl-language-server" -version = "0.11.2" -dependencies = [ - "anyhow", - "chrono", - "clap", - "compiler_base_session", - "crossbeam-channel", - "dashmap", - "env_logger", - "im-rc", - "insta", - "kclvm-ast", - "kclvm-config", - "kclvm-driver", - "kclvm-error", - "kclvm-parser", - "kclvm-primitives", - "kclvm-query", - "kclvm-sema", - "kclvm-span", - "kclvm-tools", - "kclvm-utils", - "kclvm-version", - "log", - "lsp-server", - "lsp-types", - "maplit", - "notify 7.0.0", - "parking_lot 0.12.5", - "proc_macro_crate", - "ra_ap_vfs", - "ra_ap_vfs-notify", - "ropey", - "rustc-hash 1.1.0", - "rustc_lexer", - "salsa", - "serde", - "serde_json", - "threadpool", - "tokio", - "tokio-test", -] - -[[package]] -name = "kclvm" -version = "0.11.2" -dependencies = [ - "kclvm-api", - "kclvm-ast", - "kclvm-cmd", - "kclvm-compiler", - "kclvm-config", - "kclvm-driver", - "kclvm-error", - "kclvm-evaluator", - "kclvm-loader", - "kclvm-parser", - "kclvm-primitives", - "kclvm-query", - "kclvm-runner", - "kclvm-runtime", - "kclvm-sema", - "kclvm-tools", - "kclvm-version", -] - -[[package]] -name = "kclvm-api" -version = "0.11.2" -dependencies = [ - "anyhow", - "criterion", - "futures", - "jsonrpc-stdio-server", - "kcl-language-server", - "kclvm-ast", - "kclvm-ast-pretty", - "kclvm-config", - "kclvm-driver", - "kclvm-error", - "kclvm-loader", - "kclvm-parser", - "kclvm-primitives", - "kclvm-query", - "kclvm-runner", - "kclvm-runtime", - "kclvm-sema", - "kclvm-tools", - "kclvm-utils", - "kclvm-version", - "maplit", - "once_cell", - "prost", - "prost-build", - "prost-types", - "prost-wkt", - "prost-wkt-build", - "protoc-bin-vendored", - "serde", - "serde_json", - "serde_yaml_ng", - "tempfile", - "tokio", -] - -[[package]] -name = "kclvm-ast" -version = "0.11.2" -dependencies = [ - "anyhow", - "compiler_base_span", - "kclvm-error", - "kclvm-parser", - "kclvm-span", - "kclvm-utils", - "serde", - "serde_json", - "thread_local", - "uuid", -] - -[[package]] -name = "kclvm-ast-pretty" -version = "0.11.2" -dependencies = [ - "compiler_base_macros", - "compiler_base_session", - "fancy-regex", - "kclvm-ast", - "kclvm-error", - "kclvm-parser", - "kclvm-primitives", - "pretty_assertions", -] - -[[package]] -name = "kclvm-cmd" -version = "0.11.2" -dependencies = [ - "anyhow", - "clap", - "compiler_base_session", - "kclvm-api", - "kclvm-config", - "kclvm-driver", - "kclvm-error", - "kclvm-parser", - "kclvm-runner", - "kclvm-runtime", - "kclvm-tools", - "kclvm-version", -] - -[[package]] -name = "kclvm-compiler" -version = "0.11.2" -dependencies = [ - "bit-set", - "bitflags 1.3.2", - "fancy-regex", - "inkwell", - "kclvm-ast", - "kclvm-error", - "kclvm-primitives", - "kclvm-runtime", - "kclvm-sema", - "once_cell", - "phf", - "time 0.2.27", - "unicode_names2", -] - -[[package]] -name = "kclvm-config" -version = "0.11.2" -dependencies = [ - "anyhow", - "chrono", - "dirs", - "glob", - "kclvm-ast", - "kclvm-utils", - "kclvm-version", - "md-5 0.8.0", - "pathdiff", - "regex", - "ron", - "serde", - "serde_json", - "serde_yaml_ng", - "toml", - "url", -] - -[[package]] -name = "kclvm-driver" -version = "0.11.2" -dependencies = [ - "anyhow", - "flate2", - "kclvm-ast", - "kclvm-config", - "kclvm-parser", - "kclvm-primitives", - "kclvm-runtime", - "kclvm-utils", - "oci-client", - "once_cell", - "parking_lot 0.12.5", - "serde", - "serde_json", - "tar", - "tokio", - "walkdir", -] - -[[package]] -name = "kclvm-error" -version = "0.11.2" -dependencies = [ - "annotate-snippets", - "anyhow", - "compiler_base_error", - "compiler_base_macros", - "compiler_base_session", - "compiler_base_span", - "kclvm-primitives", - "kclvm-runtime", - "kclvm-span", - "kclvm-utils", - "serde", - "serde_json", - "termize", - "thiserror 2.0.17", - "tracing", -] - -[[package]] -name = "kclvm-evaluator" -version = "0.11.2" -dependencies = [ - "anyhow", - "generational-arena", - "insta", - "kclvm-ast", - "kclvm-error", - "kclvm-loader", - "kclvm-parser", - "kclvm-primitives", - "kclvm-runtime", - "kclvm-sema", - "scopeguard", -] - -[[package]] -name = "kclvm-lexer" -version = "0.11.2" -dependencies = [ - "expect-test", - "kclvm-error", - "rustc_lexer", - "unic-emoji-char", -] - -[[package]] -name = "kclvm-loader" -version = "0.11.2" -dependencies = [ - "anyhow", - "insta", - "kclvm-ast", - "kclvm-ast-pretty", - "kclvm-error", - "kclvm-parser", - "kclvm-primitives", - "kclvm-query", - "kclvm-sema", - "kclvm-utils", - "maplit", -] - -[[package]] -name = "kclvm-macros" -version = "0.11.2" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", - "synstructure 0.12.6", -] - -[[package]] -name = "kclvm-parser" -version = "0.11.2" -dependencies = [ - "anyhow", - "bstr", - "compiler_base_error", - "compiler_base_macros", - "compiler_base_session", - "compiler_base_span", - "either", - "enquote", - "expect-test", - "glob", - "insta", - "kclvm-ast", - "kclvm-config", - "kclvm-error", - "kclvm-lexer", - "kclvm-primitives", - "kclvm-sema", - "kclvm-span", - "kclvm-utils", - "num-bigint", - "parking_lot 0.12.5", - "petgraph", - "regex", - "rustc_lexer", - "serde", - "serde_json", - "tracing", - "unicode_names2", - "walkdir", -] - -[[package]] -name = "kclvm-primitives" -version = "0.11.2" -dependencies = [ - "indexmap 2.12.0", - "rustc-hash 2.1.1", -] - -[[package]] -name = "kclvm-query" -version = "0.11.2" -dependencies = [ - "anyhow", - "compiler_base_macros", - "compiler_base_session", - "fancy-regex", - "insta", - "kclvm-ast", - "kclvm-ast-pretty", - "kclvm-error", - "kclvm-parser", - "kclvm-primitives", - "kclvm-sema", - "kclvm-utils", - "maplit", - "pretty_assertions", - "serde", - "serde_json", -] - -[[package]] -name = "kclvm-runner" -version = "0.11.2" -dependencies = [ - "anyhow", - "cc", - "chrono", - "compiler_base_macros", - "compiler_base_session", - "criterion", - "glob", - "kclvm-ast", - "kclvm-compiler", - "kclvm-config", - "kclvm-driver", - "kclvm-error", - "kclvm-evaluator", - "kclvm-parser", - "kclvm-primitives", - "kclvm-query", - "kclvm-runtime", - "kclvm-sema", - "kclvm-utils", - "kclvm-version", - "libc", - "libloading", - "once_cell", - "serde", - "serde_json", - "tempfile", - "threadpool", - "uuid", - "walkdir", -] - -[[package]] -name = "kclvm-runtime" -version = "0.11.2" -dependencies = [ - "anyhow", - "base32", - "base64 0.13.1", - "blake3", - "bstr", - "chrono", - "cidr", - "dns-lookup", - "encoding_rs", - "fancy-regex", - "generational-arena", - "glob", - "handlebars", - "hostname", - "itertools", - "kclvm-primitives", - "kclvm_runtime_internal_macros", - "lazy_static", - "libc", - "md5", - "num-integer", - "phf", - "regex", - "serde", - "serde_json", - "serde_yaml_ng", - "sha1", - "sha2 0.9.9", - "unic-ucd-bidi", - "unic-ucd-category", - "unicode-casing", - "uuid", - "walkdir", -] - -[[package]] -name = "kclvm-sema" -version = "0.11.2" -dependencies = [ - "anyhow", - "bit-set", - "bitflags 1.3.2", - "compiler_base_error", - "compiler_base_macros", - "compiler_base_session", - "compiler_base_span", - "criterion", - "fancy-regex", - "generational-arena", - "kclvm-ast", - "kclvm-ast-pretty", - "kclvm-error", - "kclvm-parser", - "kclvm-primitives", - "kclvm-runtime", - "kclvm-span", - "kclvm-utils", - "lazy_static", - "once_cell", - "parking_lot 0.12.5", - "petgraph", - "phf", - "regex", - "serde", - "serde_json", - "suggestions", - "unicode_names2", -] - -[[package]] -name = "kclvm-span" -version = "0.11.2" -dependencies = [ - "compiler_base_span", - "kclvm-macros", - "parking_lot 0.11.2", - "scoped-tls", -] - -[[package]] -name = "kclvm-tools" -version = "0.11.2" -dependencies = [ - "anyhow", - "compiler_base_session", - "compiler_base_span", - "criterion", - "fancy-regex", - "insta", - "json-spanned-value", - "kclvm-ast", - "kclvm-ast-pretty", - "kclvm-config", - "kclvm-driver", - "kclvm-error", - "kclvm-parser", - "kclvm-primitives", - "kclvm-query", - "kclvm-runner", - "kclvm-runtime", - "kclvm-sema", - "kclvm-utils", - "located_yaml", - "once_cell", - "pretty_assertions", - "regex", - "rustc_lexer", - "serde_json", - "serde_yaml_ng", - "walkdir", -] - -[[package]] -name = "kclvm-utils" -version = "0.11.2" -dependencies = [ - "anyhow", - "fslock", - "regex", -] - -[[package]] -name = "kclvm-version" -version = "0.11.2" -dependencies = [ - "vergen-gitcl", -] - -[[package]] -name = "kclvm_runtime_internal_macros" -version = "0.5.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "kqueue" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eac30106d7dce88daf4a3fcb4879ea939476d5074a9b7ddd0fb97fa4bed5596a" -dependencies = [ - "kqueue-sys", - "libc", -] - -[[package]] -name = "kqueue-sys" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed9625ffda8729b85e45cf04090035ac368927b8cebc34898e7c120f52e4838b" -dependencies = [ - "bitflags 1.3.2", - "libc", -] - -[[package]] -name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - -[[package]] -name = "libc" -version = "0.2.177" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" - -[[package]] -name = "libloading" -version = "0.7.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" -dependencies = [ - "cfg-if 1.0.4", - "winapi", -] - -[[package]] -name = "libredox" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "416f7e718bdb06000964960ffa43b4335ad4012ae8b99060261aa4a8088d5ccb" -dependencies = [ - "bitflags 2.10.0", - "libc", - "redox_syscall 0.5.18", -] - -[[package]] -name = "linked-hash-map" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" -dependencies = [ - "serde", -] - -[[package]] -name = "linux-raw-sys" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" - -[[package]] -name = "litemap" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" - -[[package]] -name = "llvm-sys" -version = "120.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624f2692f436769c7eb85a13eeca3f6fb9705a4b2bd0473ac9577c90f19e21ef" -dependencies = [ - "cc", - "lazy_static", - "libc", - "regex", - "semver 0.11.0", -] - -[[package]] -name = "located_yaml" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bc68ee6f87a1be7fdba1dcfd854528371aa84a8390279b5d7a99d5da82add76" -dependencies = [ - "linked-hash-map", - "serde", - "yaml-rust", -] - -[[package]] -name = "lock_api" -version = "0.4.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" -dependencies = [ - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" - -[[package]] -name = "lru-slab" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" - -[[package]] -name = "lsp-server" -version = "0.7.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9462c4dc73e17f971ec1f171d44bfffb72e65a130117233388a0ebc7ec5656f9" -dependencies = [ - "crossbeam-channel", - "log", - "serde", - "serde_derive", - "serde_json", -] - -[[package]] -name = "lsp-types" -version = "0.93.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9be6e9c7e2d18f651974370d7aff703f9513e0df6e464fd795660edc77e6ca51" -dependencies = [ - "bitflags 1.3.2", - "serde", - "serde_json", - "serde_repr", - "url", -] - -[[package]] -name = "maplit" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d" - -[[package]] -name = "matches" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5" - -[[package]] -name = "md-5" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a18af3dcaf2b0219366cdb4e2af65a6101457b415c3d1a5c71dd9c2b7c77b9c8" -dependencies = [ - "block-buffer 0.7.3", - "digest 0.8.1", - "opaque-debug 0.2.3", -] - -[[package]] -name = "md-5" -version = "0.10.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" -dependencies = [ - "cfg-if 1.0.4", - "digest 0.10.7", -] - -[[package]] -name = "md5" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" - -[[package]] -name = "memchr" -version = "2.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273" - -[[package]] -name = "memmap2" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "723e3ebdcdc5c023db1df315364573789f8857c11b631a2fdfad7c00f5c046b4" -dependencies = [ - "libc", -] - -[[package]] -name = "miniz_oxide" -version = "0.8.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" -dependencies = [ - "adler2", - "simd-adler32", -] - -[[package]] -name = "mio" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" -dependencies = [ - "libc", - "log", - "wasi", - "windows-sys 0.48.0", -] - -[[package]] -name = "mio" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873" -dependencies = [ - "libc", - "log", - "wasi", - "windows-sys 0.61.2", -] - -[[package]] -name = "miow" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ffbca2f655e33c08be35d87278e5b18b89550a37dbd598c20db92f6a471123" -dependencies = [ - "windows-sys 0.42.0", -] - -[[package]] -name = "multimap" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a" - -[[package]] -name = "notify" -version = "5.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "729f63e1ca555a43fe3efa4f3efdf4801c479da85b432242a7b726f353c88486" -dependencies = [ - "bitflags 1.3.2", - "crossbeam-channel", - "filetime", - "fsevent-sys", - "inotify 0.9.6", - "kqueue", - "libc", - "mio 0.8.11", - "walkdir", - "windows-sys 0.45.0", -] - -[[package]] -name = "notify" -version = "7.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c533b4c39709f9ba5005d8002048266593c1cfaf3c5f0739d5b8ab0c6c504009" -dependencies = [ - "bitflags 2.10.0", - "filetime", - "fsevent-sys", - "inotify 0.10.2", - "kqueue", - "libc", - "log", - "mio 1.1.0", - "notify-types", - "walkdir", - "windows-sys 0.52.0", -] - -[[package]] -name = "notify-types" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "585d3cb5e12e01aed9e8a1f70d5c6b5e86fe2a6e48fc8cd0b3e0b8df6f6eb174" -dependencies = [ - "instant", -] - -[[package]] -name = "num-bigint" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" -dependencies = [ - "num-integer", - "num-traits", -] - -[[package]] -name = "num-conv" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" - -[[package]] -name = "num-integer" -version = "0.1.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" -dependencies = [ - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_cpus" -version = "1.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "num_threads" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" -dependencies = [ - "libc", -] - -[[package]] -name = "object" -version = "0.37.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" -dependencies = [ - "memchr", -] - -[[package]] -name = "oci-client" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "560faeb9396a5bae11b141bed3cec8bf9242e5bfec17d0f48feeeab0f879ca35" -dependencies = [ - "bytes", - "chrono", - "futures-util", - "http", - "http-auth", - "jwt", - "lazy_static", - "olpc-cjson", - "regex", - "reqwest", - "serde", - "serde_json", - "sha2 0.10.9", - "thiserror 1.0.69", - "tokio", - "tracing", - "unicase", -] - -[[package]] -name = "olpc-cjson" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "696183c9b5fe81a7715d074fd632e8bd46f4ccc0231a3ed7fc580a80de5f7083" -dependencies = [ - "serde", - "serde_json", - "unicode-normalization", -] - -[[package]] -name = "once_cell" -version = "1.21.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" - -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - -[[package]] -name = "oorandom" -version = "11.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" - -[[package]] -name = "opaque-debug" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2839e79665f131bdb5782e51f2c6c9599c133c6098982a54c794358bf432529c" - -[[package]] -name = "opaque-debug" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" - -[[package]] -name = "option-ext" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" - -[[package]] -name = "parking_lot" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" -dependencies = [ - "instant", - "lock_api", - "parking_lot_core 0.8.6", -] - -[[package]] -name = "parking_lot" -version = "0.12.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" -dependencies = [ - "lock_api", - "parking_lot_core 0.9.12", -] - -[[package]] -name = "parking_lot_core" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc" -dependencies = [ - "cfg-if 1.0.4", - "instant", - "libc", - "redox_syscall 0.2.16", - "smallvec", - "winapi", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" -dependencies = [ - "cfg-if 1.0.4", - "libc", - "redox_syscall 0.5.18", - "smallvec", - "windows-link 0.2.1", -] - -[[package]] -name = "pathdiff" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3" - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "pest" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "989e7521a040efde50c3ab6bbadafbe15ab6dc042686926be59ac35d74607df4" -dependencies = [ - "memchr", - "ucd-trie", -] - -[[package]] -name = "pest_derive" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "187da9a3030dbafabbbfb20cb323b976dc7b7ce91fcd84f2f74d6e31d378e2de" -dependencies = [ - "pest", - "pest_generator", -] - -[[package]] -name = "pest_generator" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49b401d98f5757ebe97a26085998d6c0eecec4995cad6ab7fc30ffdf4b052843" -dependencies = [ - "pest", - "pest_meta", - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "pest_meta" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f27a2cfee9f9039c4d86faa5af122a0ac3851441a34865b8a043b46be0065a" -dependencies = [ - "pest", - "sha2 0.10.9", -] - -[[package]] -name = "petgraph" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4c5cc86750666a3ed20bdaf5ca2a0344f9c67674cae0515bec2da16fbaa47db" -dependencies = [ - "fixedbitset", - "indexmap 2.12.0", -] - -[[package]] -name = "phf" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2ac8b67553a7ca9457ce0e526948cad581819238f4a9d1ea74545851fa24f37" -dependencies = [ - "phf_macros", - "phf_shared", - "proc-macro-hack", -] - -[[package]] -name = "phf_generator" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43f3220d96e0080cc9ea234978ccd80d904eafb17be31bb0f76daaea6493082" -dependencies = [ - "phf_shared", - "rand 0.8.5", -] - -[[package]] -name = "phf_macros" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b706f5936eb50ed880ae3009395b43ed19db5bff2ebd459c95e7bf013a89ab86" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro-hack", - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "phf_shared" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a68318426de33640f02be62b4ae8eb1261be2efbc337b60c54d845bf4484e0d9" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" - -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - -[[package]] -name = "plotters" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747" -dependencies = [ - "num-traits", - "plotters-backend", - "plotters-svg", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "plotters-backend" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a" - -[[package]] -name = "plotters-svg" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670" -dependencies = [ - "plotters-backend", -] - -[[package]] -name = "portable-atomic" -version = "1.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483" - -[[package]] -name = "portable-atomic-util" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507" -dependencies = [ - "portable-atomic", -] - -[[package]] -name = "potential_utf" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" -dependencies = [ - "zerovec", -] - -[[package]] -name = "powerfmt" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" - -[[package]] -name = "ppv-lite86" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" -dependencies = [ - "zerocopy", -] - -[[package]] -name = "pretty_assertions" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" -dependencies = [ - "diff", - "yansi", -] - -[[package]] -name = "prettyplease" -version = "0.2.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" -dependencies = [ - "proc-macro2", - "syn 2.0.108", -] - -[[package]] -name = "proc-macro-hack" -version = "0.5.20+deprecated" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" - -[[package]] -name = "proc-macro2" -version = "1.0.103" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "proc_macro_crate" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "prost" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7231bd9b3d3d33c86b58adbac74b5ec0ad9f496b19d22801d773636feaa95f3d" -dependencies = [ - "bytes", - "prost-derive", -] - -[[package]] -name = "prost-build" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac6c3320f9abac597dcbc668774ef006702672474aad53c6d596b62e487b40b1" -dependencies = [ - "heck 0.4.1", - "itertools", - "log", - "multimap", - "once_cell", - "petgraph", - "prettyplease", - "prost", - "prost-types", - "regex", - "syn 2.0.108", - "tempfile", -] - -[[package]] -name = "prost-derive" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9120690fafc389a67ba3803df527d0ec9cbbc9cc45e4cc20b332996dfb672425" -dependencies = [ - "anyhow", - "itertools", - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "prost-types" -version = "0.14.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9b4db3d6da204ed77bb26ba83b6122a73aeb2e87e25fbf7ad2e84c4ccbf8f72" -dependencies = [ - "prost", -] - -[[package]] -name = "prost-wkt" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "655944d0ce015e71b3ec21279437e6a09e58433e50c7b0677901f3d5235e74f5" -dependencies = [ - "chrono", - "inventory", - "prost", - "serde", - "serde_derive", - "serde_json", - "typetag", -] - -[[package]] -name = "prost-wkt-build" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f869f1443fee474b785e935d92e1007f57443e485f51668ed41943fc01a321a2" -dependencies = [ - "heck 0.4.1", - "prost", - "prost-build", - "prost-types", - "quote", -] - -[[package]] -name = "protoc-bin-vendored" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1c381df33c98266b5f08186583660090a4ffa0889e76c7e9a5e175f645a67fa" -dependencies = [ - "protoc-bin-vendored-linux-aarch_64", - "protoc-bin-vendored-linux-ppcle_64", - "protoc-bin-vendored-linux-s390_64", - "protoc-bin-vendored-linux-x86_32", - "protoc-bin-vendored-linux-x86_64", - "protoc-bin-vendored-macos-aarch_64", - "protoc-bin-vendored-macos-x86_64", - "protoc-bin-vendored-win32", -] - -[[package]] -name = "protoc-bin-vendored-linux-aarch_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c350df4d49b5b9e3ca79f7e646fde2377b199e13cfa87320308397e1f37e1a4c" - -[[package]] -name = "protoc-bin-vendored-linux-ppcle_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a55a63e6c7244f19b5c6393f025017eb5d793fd5467823a099740a7a4222440c" - -[[package]] -name = "protoc-bin-vendored-linux-s390_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1dba5565db4288e935d5330a07c264a4ee8e4a5b4a4e6f4e83fad824cc32f3b0" - -[[package]] -name = "protoc-bin-vendored-linux-x86_32" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8854774b24ee28b7868cd71dccaae8e02a2365e67a4a87a6cd11ee6cdbdf9cf5" - -[[package]] -name = "protoc-bin-vendored-linux-x86_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b38b07546580df720fa464ce124c4b03630a6fb83e05c336fea2a241df7e5d78" - -[[package]] -name = "protoc-bin-vendored-macos-aarch_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89278a9926ce312e51f1d999fee8825d324d603213344a9a706daa009f1d8092" - -[[package]] -name = "protoc-bin-vendored-macos-x86_64" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81745feda7ccfb9471d7a4de888f0652e806d5795b61480605d4943176299756" - -[[package]] -name = "protoc-bin-vendored-win32" -version = "3.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3" - -[[package]] -name = "quinn" -version = "0.11.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" -dependencies = [ - "bytes", - "cfg_aliases", - "pin-project-lite", - "quinn-proto", - "quinn-udp", - "rustc-hash 2.1.1", - "rustls", - "socket2", - "thiserror 2.0.17", - "tokio", - "tracing", - "web-time", -] - -[[package]] -name = "quinn-proto" -version = "0.11.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31" -dependencies = [ - "bytes", - "getrandom 0.3.4", - "lru-slab", - "rand 0.9.2", - "ring", - "rustc-hash 2.1.1", - "rustls", - "rustls-pki-types", - "slab", - "thiserror 2.0.17", - "tinyvec", - "tracing", - "web-time", -] - -[[package]] -name = "quinn-udp" -version = "0.5.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" -dependencies = [ - "cfg_aliases", - "libc", - "once_cell", - "socket2", - "tracing", - "windows-sys 0.60.2", -] - -[[package]] -name = "quote" -version = "1.0.41" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce25767e7b499d1b604768e7cde645d14cc8584231ea6b295e9c9eb22c02e1d1" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "r-efi" -version = "5.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" - -[[package]] -name = "ra_ap_paths" -version = "0.0.149" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d780b450680460bd7ea3e2483dcf15a3ac0ce0ec028696caa342c577d65e5506" - -[[package]] -name = "ra_ap_stdx" -version = "0.0.149" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d776542bf771f4fdf40c21ced864bf213924d8a60d580c970715818471ebd74c" -dependencies = [ - "always-assert", - "libc", - "miow", - "winapi", -] - -[[package]] -name = "ra_ap_vfs" -version = "0.0.149" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8cd60adecd0947e1dd41a3077713381aa0cdcba6dc8777300d7d5b83b9fbe84" -dependencies = [ - "fst", - "indexmap 1.9.3", - "ra_ap_paths", - "ra_ap_stdx", - "rustc-hash 1.1.0", -] - -[[package]] -name = "ra_ap_vfs-notify" -version = "0.0.149" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a680f2dbd796844ebeaa2a4d01ae209f412ddc2981f6512ab8bc9b471156e6cd" -dependencies = [ - "crossbeam-channel", - "jod-thread", - "notify 5.2.0", - "ra_ap_paths", - "ra_ap_vfs", - "tracing", - "walkdir", -] - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha 0.3.1", - "rand_core 0.6.4", -] - -[[package]] -name = "rand" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" -dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.3", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.4", -] - -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.3", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.16", -] - -[[package]] -name = "rand_core" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" -dependencies = [ - "getrandom 0.3.4", -] - -[[package]] -name = "rand_xoshiro" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f97cdb2a36ed4183de61b2f824cc45c9f1037f28afe0a322e9fff4c108b5aaa" -dependencies = [ - "rand_core 0.6.4", -] - -[[package]] -name = "rayon" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f" -dependencies = [ - "either", - "rayon-core", -] - -[[package]] -name = "rayon-core" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", -] - -[[package]] -name = "redox_syscall" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" -dependencies = [ - "bitflags 1.3.2", -] - -[[package]] -name = "redox_syscall" -version = "0.5.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" -dependencies = [ - "bitflags 2.10.0", -] - -[[package]] -name = "redox_users" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" -dependencies = [ - "getrandom 0.2.16", - "libredox", - "thiserror 1.0.69", -] - -[[package]] -name = "regex" -version = "1.12.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata 0.4.13", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" - -[[package]] -name = "regex-automata" -version = "0.4.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58" - -[[package]] -name = "reqwest" -version = "0.12.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f" -dependencies = [ - "base64 0.22.1", - "bytes", - "futures-core", - "futures-util", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-util", - "js-sys", - "log", - "percent-encoding", - "pin-project-lite", - "quinn", - "rustls", - "rustls-pki-types", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tokio-rustls", - "tokio-util 0.7.16", - "tower", - "tower-http", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "wasm-streams", - "web-sys", - "webpki-roots", -] - -[[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" -dependencies = [ - "cc", - "cfg-if 1.0.4", - "getrandom 0.2.16", - "libc", - "untrusted", - "windows-sys 0.52.0", -] - -[[package]] -name = "ron" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88073939a61e5b7680558e6be56b419e208420c2adb92be54921fa6b72283f1a" -dependencies = [ - "base64 0.13.1", - "bitflags 1.3.2", - "serde", -] - -[[package]] -name = "ropey" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93411e420bcd1a75ddd1dc3caf18c23155eda2c090631a85af21ba19e97093b5" -dependencies = [ - "smallvec", - "str_indices", -] - -[[package]] -name = "rustc-demangle" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56f7d92ca342cea22a06f2121d944b4fd82af56988c270852495420f961d4ace" - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - -[[package]] -name = "rustc-hash" -version = "2.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" - -[[package]] -name = "rustc-rayon" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9974ab223660e61c1b4e7b43b827379df286736ca988308ce7e16f59f2d89246" -dependencies = [ - "crossbeam-deque", - "either", - "rustc-rayon-core 0.3.2", -] - -[[package]] -name = "rustc-rayon" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cd9fb077db982d7ceb42a90471e5a69a990b58f71e06f0d8340bb2cf35eb751" -dependencies = [ - "either", - "rustc-rayon-core 0.5.1", -] - -[[package]] -name = "rustc-rayon-core" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "564bfd27be8db888d0fa76aa4335e7851aaed0c2c11ad1e93aeb9349f6b88500" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", - "lazy_static", - "num_cpus", -] - -[[package]] -name = "rustc-rayon-core" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f42932dcd3bcbe484b38a3ccf79b7906fac41c02d408b5b1bac26da3416efdb" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", -] - -[[package]] -name = "rustc_data_structures" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a38bae9c6afa27015bcaa2869e03bb111ecf0d0e0edc2da559a91d4057174c9a" -dependencies = [ - "arrayvec", - "bitflags 1.3.2", - "cfg-if 0.1.10", - "ena", - "indexmap 1.9.3", - "jobserver", - "libc", - "memmap2", - "parking_lot 0.12.5", - "rustc-hash 1.1.0", - "rustc-rayon 0.3.2", - "rustc-rayon-core 0.3.2", - "stable_deref_trait", - "tempfile", - "tracing", - "winapi", -] - -[[package]] -name = "rustc_errors" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "00299b1841816d2c41129e6d4f86b0b446ee387e8203871c2551e1c405b1243c" -dependencies = [ - "termcolor", - "winapi", -] - -[[package]] -name = "rustc_lexer" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c86aae0c77166108c01305ee1a36a1e77289d7dc6ca0a3cd91ff4992de2d16a5" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "rustc_span" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "043e9cc06c53de1f6a125e41e4b915d23a130241610a114ad4fe4f654617eae4" -dependencies = [ - "cfg-if 0.1.10", - "md-5 0.10.6", - "rustc_data_structures", - "scoped-tls", - "sha-1", - "sha2 0.10.9", - "tracing", - "unicode-width", -] - -[[package]] -name = "rustc_version" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -dependencies = [ - "semver 0.9.0", -] - -[[package]] -name = "rustc_version" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" -dependencies = [ - "semver 1.0.27", -] - -[[package]] -name = "rustix" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" -dependencies = [ - "bitflags 2.10.0", - "errno", - "libc", - "linux-raw-sys", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls" -version = "0.23.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a9586e9ee2b4f8fab52a0048ca7334d7024eef48e2cb9407e3497bb7cab7fa7" -dependencies = [ - "once_cell", - "ring", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-pki-types" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94182ad936a0c91c324cd46c6511b9510ed16af436d7b5bab34beab0afd55f7a" -dependencies = [ - "web-time", - "zeroize", -] - -[[package]] -name = "rustls-webpki" -version = "0.103.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e10b3f4191e8a80e6b43eebabfac91e5dcecebb27a71f04e820c47ec41d314bf" -dependencies = [ - "ring", - "rustls-pki-types", - "untrusted", -] - -[[package]] -name = "rustversion" -version = "1.0.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" - -[[package]] -name = "ryu" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" - -[[package]] -name = "salsa" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b84d9f96071f3f3be0dc818eae3327625d8ebc95b58da37d6850724f31d3403" -dependencies = [ - "crossbeam-utils", - "indexmap 1.9.3", - "lock_api", - "log", - "oorandom", - "parking_lot 0.11.2", - "rustc-hash 1.1.0", - "salsa-macros", - "smallvec", -] - -[[package]] -name = "salsa-macros" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd3904a4ba0a9d0211816177fd34b04c7095443f8cdacd11175064fe541c8fe2" -dependencies = [ - "heck 0.3.3", - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "scoped-tls" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" - -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - -[[package]] -name = "self_cell" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e14e4d63b804dc0c7ec4a1e52bcb63f02c7ac94476755aa579edac21e01f915d" -dependencies = [ - "self_cell 1.2.1", -] - -[[package]] -name = "self_cell" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16c2f82143577edb4921b71ede051dac62ca3c16084e918bf7b40c96ae10eb33" - -[[package]] -name = "semver" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -dependencies = [ - "semver-parser 0.7.0", -] - -[[package]] -name = "semver" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f301af10236f6df4160f7c3f04eec6dbc70ace82d23326abad5edee88801c6b6" -dependencies = [ - "semver-parser 0.10.3", -] - -[[package]] -name = "semver" -version = "1.0.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" - -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" - -[[package]] -name = "semver-parser" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9900206b54a3527fdc7b8a938bffd94a568bac4f4aa8113b209df75a09c0dec2" -dependencies = [ - "pest", -] - -[[package]] -name = "serde" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "serde_json" -version = "1.0.145" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" -dependencies = [ - "itoa", - "memchr", - "ryu", - "serde", - "serde_core", -] - -[[package]] -name = "serde_repr" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_yaml_ng" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f" -dependencies = [ - "indexmap 2.12.0", - "itoa", - "ryu", - "serde", - "unsafe-libyaml", -] - -[[package]] -name = "sha-1" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5058ada175748e33390e40e872bd0fe59a19f265d0158daa551c5a88a76009c" -dependencies = [ - "cfg-if 1.0.4", - "cpufeatures", - "digest 0.10.7", -] - -[[package]] -name = "sha1" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" -dependencies = [ - "sha1_smol", -] - -[[package]] -name = "sha1_smol" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" - -[[package]] -name = "sha2" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if 1.0.4", - "cpufeatures", - "digest 0.9.0", - "opaque-debug 0.3.1", -] - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if 1.0.4", - "cpufeatures", - "digest 0.10.7", -] - -[[package]] -name = "shlex" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" - -[[package]] -name = "signal-hook-registry" -version = "1.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a4719bff48cee6b39d12c020eeb490953ad2443b7055bd0b21fca26bd8c28b" -dependencies = [ - "libc", -] - -[[package]] -name = "simd-adler32" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe" - -[[package]] -name = "similar" -version = "2.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" - -[[package]] -name = "siphasher" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" - -[[package]] -name = "sized-chunks" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16d69225bde7a69b235da73377861095455d298f2b970996eec25ddbb42b3d1e" -dependencies = [ - "bitmaps", - "typenum", -] - -[[package]] -name = "slab" -version = "0.4.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" - -[[package]] -name = "smallvec" -version = "1.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" - -[[package]] -name = "socket2" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881" -dependencies = [ - "libc", - "windows-sys 0.60.2", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "standback" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e113fb6f3de07a243d434a56ec6f186dfd51cb08448239fe7bcae73f87ff28ff" -dependencies = [ - "version_check", -] - -[[package]] -name = "stdweb" -version = "0.4.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d022496b16281348b52d0e30ae99e01a73d737b2f45d38fed4edf79f9325a1d5" -dependencies = [ - "discard", - "rustc_version 0.2.3", - "stdweb-derive", - "stdweb-internal-macros", - "stdweb-internal-runtime", - "wasm-bindgen", -] - -[[package]] -name = "stdweb-derive" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c87a60a40fccc84bef0652345bbbbbe20a605bf5d0ce81719fc476f5c03b50ef" -dependencies = [ - "proc-macro2", - "quote", - "serde", - "serde_derive", - "syn 1.0.109", -] - -[[package]] -name = "stdweb-internal-macros" -version = "0.2.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58fa5ff6ad0d98d1ffa8cb115892b6e69d67799f6763e162a1c9db421dc22e11" -dependencies = [ - "base-x", - "proc-macro2", - "quote", - "serde", - "serde_derive", - "serde_json", - "sha1", - "syn 1.0.109", -] - -[[package]] -name = "stdweb-internal-runtime" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "213701ba3370744dcd1a12960caa4843b3d68b4d1c0a5d575e0d65b2ee9d16c0" - -[[package]] -name = "str_indices" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d08889ec5408683408db66ad89e0e1f93dff55c73a4ccc71c427d5b277ee47e6" - -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - -[[package]] -name = "suggestions" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5441c382482e49aaac2c3ea9cbcd24290531246e879ee94af5dfc4b144f11e80" -dependencies = [ - "strsim 0.10.0", -] - -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "syn" -version = "2.0.108" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da58917d35242480a05c2897064da0a80589a2a0476c9a3f2fdc83b53502e917" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "sync_wrapper" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" -dependencies = [ - "futures-core", -] - -[[package]] -name = "synstructure" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" -dependencies = [ - "proc-macro2", - "quote", - "syn 1.0.109", - "unicode-xid", -] - -[[package]] -name = "synstructure" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "tar" -version = "0.4.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d863878d212c87a19c1a610eb53bb01fe12951c0501cf5a0d65f724914a667a" -dependencies = [ - "filetime", - "libc", - "xattr", -] - -[[package]] -name = "tempfile" -version = "3.23.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d31c77bdf42a745371d260a26ca7163f1e0924b64afa0b688e61b5a9fa02f16" -dependencies = [ - "fastrand", - "getrandom 0.3.4", - "once_cell", - "rustix", - "windows-sys 0.61.2", -] - -[[package]] -name = "termcolor" -version = "1.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "termize" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1706be6b564323ce7092f5f7e6b118a14c8ef7ed0e69c8c5329c914a9f101295" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "thiserror" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" -dependencies = [ - "thiserror-impl 1.0.69", -] - -[[package]] -name = "thiserror" -version = "2.0.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" -dependencies = [ - "thiserror-impl 2.0.17", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "thread_local" -version = "1.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" -dependencies = [ - "cfg-if 1.0.4", -] - -[[package]] -name = "threadpool" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d050e60b33d41c19108b32cea32164033a9013fe3b46cbd4457559bfbf77afaa" -dependencies = [ - "num_cpus", -] - -[[package]] -name = "time" -version = "0.2.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4752a97f8eebd6854ff91f1c1824cd6160626ac4bd44287f7f4ea2035a02a242" -dependencies = [ - "const_fn", - "libc", - "standback", - "stdweb", - "time-macros 0.1.1", - "version_check", - "winapi", -] - -[[package]] -name = "time" -version = "0.3.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e7d9e3bb61134e77bde20dd4825b97c010155709965fedf0f49bb138e52a9d" -dependencies = [ - "deranged", - "itoa", - "libc", - "num-conv", - "num_threads", - "powerfmt", - "serde", - "time-core", - "time-macros 0.2.24", -] - -[[package]] -name = "time-core" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40868e7c1d2f0b8d73e4a8c7f0ff63af4f6d19be117e90bd73eb1d62cf831c6b" - -[[package]] -name = "time-macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "957e9c6e26f12cb6d0dd7fc776bb67a706312e7299aed74c8dd5b17ebb27e2f1" -dependencies = [ - "proc-macro-hack", - "time-macros-impl", -] - -[[package]] -name = "time-macros" -version = "0.2.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "30cfb0125f12d9c277f35663a0a33f8c30190f4e4574868a330595412d34ebf3" -dependencies = [ - "num-conv", - "time-core", -] - -[[package]] -name = "time-macros-impl" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3c141a1b43194f3f56a1411225df8646c55781d5f26db825b3d98507eb482f" -dependencies = [ - "proc-macro-hack", - "proc-macro2", - "quote", - "standback", - "syn 1.0.109", -] - -[[package]] -name = "tinystr" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" -dependencies = [ - "displaydoc", - "serde_core", - "zerovec", -] - -[[package]] -name = "tinytemplate" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc" -dependencies = [ - "serde", - "serde_json", -] - -[[package]] -name = "tinyvec" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - -[[package]] -name = "tokio" -version = "1.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408" -dependencies = [ - "bytes", - "libc", - "mio 1.1.0", - "parking_lot 0.12.5", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys 0.61.2", -] - -[[package]] -name = "tokio-macros" -version = "2.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "tokio-rustls" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" -dependencies = [ - "rustls", - "tokio", -] - -[[package]] -name = "tokio-stream" -version = "0.1.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eca58d7bba4a75707817a2c44174253f9236b2d5fbd055602e9d5c07c139a047" -dependencies = [ - "futures-core", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "tokio-test" -version = "0.4.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2468baabc3311435b55dd935f702f42cd1b8abb7e754fb7dfb16bd36aa88f9f7" -dependencies = [ - "async-stream", - "bytes", - "futures-core", - "tokio", - "tokio-stream", -] - -[[package]] -name = "tokio-util" -version = "0.6.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36943ee01a6d67977dd3f84a5a1d2efeb4ada3a1ae771cadfaa535d9d9fc6507" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "log", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "tokio-util" -version = "0.7.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14307c986784f72ef81c89db7d9e28d6ac26d16213b109ea501696195e6e3ce5" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "toml" -version = "0.5.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" -dependencies = [ - "serde", -] - -[[package]] -name = "tower" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9" -dependencies = [ - "futures-core", - "futures-util", - "pin-project-lite", - "sync_wrapper", - "tokio", - "tower-layer", - "tower-service", -] - -[[package]] -name = "tower-http" -version = "0.6.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2" -dependencies = [ - "bitflags 2.10.0", - "bytes", - "futures-util", - "http", - "http-body", - "iri-string", - "pin-project-lite", - "tower", - "tower-layer", - "tower-service", -] - -[[package]] -name = "tower-layer" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" - -[[package]] -name = "tower-service" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" - -[[package]] -name = "tracing" -version = "0.1.41" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" -dependencies = [ - "log", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81383ab64e72a7a8b8e13130c49e3dab29def6d0c7d76a03087b3cf71c5c6903" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "tracing-core" -version = "0.1.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d12581f227e93f094d3af2ae690a574abb8a2b9b7a96e7cfe9647b2b617678" -dependencies = [ - "once_cell", -] - -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - -[[package]] -name = "type-map" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" -dependencies = [ - "rustc-hash 2.1.1", -] - -[[package]] -name = "typeid" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c" - -[[package]] -name = "typenum" -version = "1.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" - -[[package]] -name = "typetag" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be2212c8a9b9bcfca32024de14998494cf9a5dfa59ea1b829de98bac374b86bf" -dependencies = [ - "erased-serde", - "inventory", - "once_cell", - "serde", - "typetag-impl", -] - -[[package]] -name = "typetag-impl" -version = "0.2.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "27a7a9b72ba121f6f1f6c3632b85604cac41aedb5ddc70accbebb6cac83de846" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "ucd-trie" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971" - -[[package]] -name = "unic-char-property" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" -dependencies = [ - "unic-char-range", -] - -[[package]] -name = "unic-char-range" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" - -[[package]] -name = "unic-common" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" - -[[package]] -name = "unic-emoji-char" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b07221e68897210270a38bde4babb655869637af0f69407f96053a34f76494d" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-langid" -version = "0.9.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28ba52c9b05311f4f6e62d5d9d46f094bd6e84cb8df7b3ef952748d752a7d05" -dependencies = [ - "unic-langid-impl", - "unic-langid-macros", -] - -[[package]] -name = "unic-langid-impl" -version = "0.9.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dce1bf08044d4b7a94028c93786f8566047edc11110595914de93362559bc658" -dependencies = [ - "tinystr", -] - -[[package]] -name = "unic-langid-macros" -version = "0.9.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5957eb82e346d7add14182a3315a7e298f04e1ba4baac36f7f0dbfedba5fc25" -dependencies = [ - "proc-macro-hack", - "tinystr", - "unic-langid-impl", - "unic-langid-macros-impl", -] - -[[package]] -name = "unic-langid-macros-impl" -version = "0.9.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1249a628de3ad34b821ecb1001355bca3940bcb2f88558f1a8bd82e977f75b5" -dependencies = [ - "proc-macro-hack", - "quote", - "syn 2.0.108", - "unic-langid-impl", -] - -[[package]] -name = "unic-ucd-bidi" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1d568b51222484e1f8209ce48caa6b430bf352962b877d592c29ab31fb53d8c" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-category" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b8d4591f5fcfe1bd4453baaf803c40e1b1e69ff8455c47620440b46efef91c0" -dependencies = [ - "matches", - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-version" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" -dependencies = [ - "unic-common", -] - -[[package]] -name = "unicase" -version = "2.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" - -[[package]] -name = "unicode-casing" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "061dbb8cc7f108532b6087a0065eff575e892a4bcb503dc57323a197457cc202" - -[[package]] -name = "unicode-ident" -version = "1.0.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "462eeb75aeb73aea900253ce739c8e18a67423fadf006037cd3ff27e82748a06" - -[[package]] -name = "unicode-normalization" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5033c97c4262335cded6d6fc3e5c18ab755e1a3dc96376350f3d8e9f009ad956" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-segmentation" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6ccf251212114b54433ec949fd6a7841275f9ada20dddd2f29e9ceea4501493" - -[[package]] -name = "unicode-width" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af" - -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - -[[package]] -name = "unicode_names2" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87d6678d7916394abad0d4b19df4d3802e1fd84abd7d701f39b75ee71b9e8cf1" - -[[package]] -name = "unsafe-libyaml" -version = "0.2.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" - -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "url" -version = "2.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "uuid" -version = "1.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f87b8aa10b915a06587d0dec516c282ff295b475d94abf425d62b57710070a2" -dependencies = [ - "getrandom 0.3.4", - "js-sys", - "serde", - "wasm-bindgen", -] - -[[package]] -name = "vergen" -version = "9.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b2bf58be11fc9414104c6d3a2e464163db5ef74b12296bda593cac37b6e4777" -dependencies = [ - "anyhow", - "derive_builder", - "rustc_version 0.4.1", - "rustversion", - "vergen-lib", -] - -[[package]] -name = "vergen-gitcl" -version = "1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9dfc1de6eb2e08a4ddf152f1b179529638bedc0ea95e6d667c014506377aefe" -dependencies = [ - "anyhow", - "derive_builder", - "rustversion", - "time 0.3.44", - "vergen", - "vergen-lib", -] - -[[package]] -name = "vergen-lib" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b07e6010c0f3e59fcb164e0163834597da68d1f864e2b8ca49f74de01e9c166" -dependencies = [ - "anyhow", - "derive_builder", - "rustversion", -] - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "walkdir" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" -dependencies = [ - "same-file", - "winapi-util", -] - -[[package]] -name = "want" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" -dependencies = [ - "try-lock", -] - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasip2" -version = "1.0.1+wasi-0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7" -dependencies = [ - "wit-bindgen", -] - -[[package]] -name = "wasm-bindgen" -version = "0.2.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da95793dfc411fbbd93f5be7715b0578ec61fe87cb1a42b12eb625caa5c5ea60" -dependencies = [ - "cfg-if 1.0.4", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "551f88106c6d5e7ccc7cd9a16f312dd3b5d36ea8b4954304657d5dfba115d4a0" -dependencies = [ - "cfg-if 1.0.4", - "js-sys", - "once_cell", - "wasm-bindgen", - "web-sys", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04264334509e04a7bf8690f2384ef5265f05143a4bff3889ab7a3269adab59c2" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "420bc339d9f322e562942d52e115d57e950d12d88983a14c79b86859ee6c7ebc" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn 2.0.108", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.105" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76f218a38c84bcb33c25ec7059b07847d465ce0e0a76b995e134a45adcb6af76" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "wasm-streams" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" -dependencies = [ - "futures-util", - "js-sys", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - -[[package]] -name = "web-sys" -version = "0.3.82" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a1f95c0d03a47f4ae1f7a64643a6bb97465d9b740f0fa8f90ea33915c99a9a1" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "webpki-roots" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32b130c0d2d49f8b6889abc456e795e82525204f27c42cf767cf0d7734e089b8" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link 0.2.1", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "windows-link" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link 0.2.1", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link 0.2.1", -] - -[[package]] -name = "windows-sys" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - -[[package]] -name = "windows-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" -dependencies = [ - "windows-targets 0.42.2", -] - -[[package]] -name = "windows-sys" -version = "0.48.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" -dependencies = [ - "windows-targets 0.48.5", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.59.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" -dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link 0.2.1", -] - -[[package]] -name = "windows-targets" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - -[[package]] -name = "windows-targets" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" -dependencies = [ - "windows_aarch64_gnullvm 0.48.5", - "windows_aarch64_msvc 0.48.5", - "windows_i686_gnu 0.48.5", - "windows_i686_msvc 0.48.5", - "windows_x86_64_gnu 0.48.5", - "windows_x86_64_gnullvm 0.48.5", - "windows_x86_64_msvc 0.48.5", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link 0.2.1", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - -[[package]] -name = "windows_i686_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" - -[[package]] -name = "windows_i686_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - -[[package]] -name = "windows_i686_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" - -[[package]] -name = "windows_i686_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.48.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - -[[package]] -name = "wit-bindgen" -version = "0.46.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59" - -[[package]] -name = "writeable" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" - -[[package]] -name = "xattr" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" -dependencies = [ - "libc", - "rustix", -] - -[[package]] -name = "yaml-rust" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" -dependencies = [ - "linked-hash-map", -] - -[[package]] -name = "yansi" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" - -[[package]] -name = "yansi-term" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe5c30ade05e61656247b2e334a031dfd0cc466fadef865bdcdea8d537951bf1" -dependencies = [ - "winapi", -] - -[[package]] -name = "yoke" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", - "synstructure 0.13.2", -] - -[[package]] -name = "zerocopy" -version = "0.8.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c" -dependencies = [ - "zerocopy-derive", -] - -[[package]] -name = "zerocopy-derive" -version = "0.8.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] - -[[package]] -name = "zerofrom" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", - "synstructure 0.13.2", -] - -[[package]] -name = "zeroize" -version = "1.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" - -[[package]] -name = "zerotrie" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", -] - -[[package]] -name = "zerovec" -version = "0.11.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" -dependencies = [ - "serde", - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.108", -] diff --git a/kclvm/Cargo.toml b/kclvm/Cargo.toml deleted file mode 100644 index 5aae89d5b..000000000 --- a/kclvm/Cargo.toml +++ /dev/null @@ -1,68 +0,0 @@ -[package] -name = "kclvm" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[lib] -crate-type = ["cdylib", "staticlib"] -path = "src/lib.rs" -name = "kclvm_cli_cdylib" - -[dependencies] -kclvm-api = { path = "./api" } -kclvm-cmd = { path = "./cmd" } -kclvm-ast = { path = "./ast" } -kclvm-runner = { path = "./runner" } -kclvm-parser = { path = "./parser" } -kclvm-compiler = { path = "./compiler" } -kclvm-config = { path = "./config" } -kclvm-loader = { path = "./loader" } -kclvm-runtime = { path = "./runtime" } -kclvm-sema = { path = "./sema" } -kclvm-tools = { path = "./tools" } -kclvm-version = { path = "./version" } -kclvm-error = { path = "./error" } -kclvm-evaluator = { path = "./evaluator" } -kclvm-query = { path = "./query" } -kclvm-driver = { path = "./driver" } -kclvm-primitives = { path = "./primitives" } - -[profile.release] -rpath = true -panic = "unwind" -opt-level = "z" # Optimize for size. -lto = true - -[workspace] -members = [ - "primitives", - "api", - "cmd", - "ast", - "ast_pretty", - "compiler", - "config", - "error", - "lexer", - "macros", - "parser", - "runner", - "runtime", - "sema", - "span", - "tools", - "version", - "query", - "utils", - "tools/src/LSP", -] - -[features] -llvm = [ - "kclvm-compiler/llvm", - "kclvm-runner/llvm", - "kclvm-tools/llvm", - "kclvm-api/llvm", -] diff --git a/kclvm/README.md b/kclvm/README.md deleted file mode 100644 index bfee41bd5..000000000 --- a/kclvm/README.md +++ /dev/null @@ -1,56 +0,0 @@ -# KCLVM - -A high-performance implementation of KCL written in Rust that uses LLVM as the compiler backend. - -## Building and Testing - -Firstly, see [KCLVM CONTRIBUTING](../CONTRIBUTING.md) to build KCLVM. Secondly, we need to download the [Rust](https://www.rust-lang.org/), [SWIG](http://www.swig.org/), [LLVM 12](https://releases.llvm.org/download.html), and add the LLVM installation location to `LLVM_SYS_120_PREFIX` and the `$PATH`. - -```shell -export LLVM_SYS_120_PREFIX= -export PATH=/bin:$PATH -``` - -To build everything, run: - -```shell -make -``` - -After building, we can add the following command line parameters to use the KCL high-performance version: - -```shell -kclvm_cli run main.k -``` - -To test, run: - -```shell -make test -``` - -## Building and Testing in Docker - -1. `make -C .. sh-in-docker` -2. `make build` -3. `export PATH=$PATH:/root/kclvm/_build/dist/ubuntu/kclvm/bin` -4. `kcl ./samples/hello.k` -5. `cd kclvm && make test` - -## IDE - -You can choose any IDE you like for development, but we recommend a combination of [VS Code](https://code.visualstudio.com/) and the [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer) plugin. - -## Notes - -1. If you wanna start over, you `MUST` clean up all cached building files, such as `LLVM build files`, `kclvm/target`, etc. -2. If your updating-cargo-index is extremely slow, setup `~/.cargo/config` file. - -```toml -[source.crates-io] -registry = "https://github.com/rust-lang/crates.io-index" -replace-with = 'ustc' - -[source.ustc] -registry = "git://mirrors.ustc.edu.cn/crates.io-index" -``` diff --git a/kclvm/api/Cargo.toml b/kclvm/api/Cargo.toml deleted file mode 100644 index b64dfbdcd..000000000 --- a/kclvm/api/Cargo.toml +++ /dev/null @@ -1,51 +0,0 @@ -[package] -name = "kclvm-api" -version = "0.11.2" -edition = "2021" - -[dependencies] -futures = "0.3.28" -tempfile = "3.5.0" -maplit = "1.0.2" - -serde_json = "1.0" -serde_yaml_ng = "0.10.0" -anyhow = "1.0.70" -serde = { version = "1", features = ["derive"] } -once_cell = "1.5.2" - -prost = "0.14.1" -prost-wkt = "0.7.0" -prost-types = "0.14.1" - -kclvm-runner = { path = "../runner" } -kclvm-config = { path = "../config" } -kclvm-driver = { path = "../driver" } -kclvm-error = { path = "../error" } -kclvm-parser = { path = "../parser" } -kclvm-loader = { path = "../loader" } -kclvm-sema = { path = "../sema" } -kclvm-ast = { path = "../ast" } -kclvm-ast-pretty = { path = "../ast_pretty" } -kclvm-runtime = { path = "../runtime" } -kclvm-tools = { path = "../tools" } -kclvm-query = { path = "../query" } -kclvm-version = { path = "../version" } -kcl-language-server = { path = "../tools/src/LSP" } -kclvm-primitives = { path = "../primitives" } -kclvm-utils = { path = "../utils" } - -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] -jsonrpc-stdio-server = "18.0.0" -tokio = { version = "1.37.0", features = ["full"] } - -[dev-dependencies] -criterion = "0.5" - -[build-dependencies] -protoc-bin-vendored = "3.2.0" -prost-build = "0.14.1" -prost-wkt-build = "0.7.0" - -[features] -llvm = ["kclvm-runner/llvm"] diff --git a/kclvm/api/build.rs b/kclvm/api/build.rs deleted file mode 100644 index 7d1c39b77..000000000 --- a/kclvm/api/build.rs +++ /dev/null @@ -1,34 +0,0 @@ -use std::{env, path::PathBuf}; - -use prost_wkt_build::{FileDescriptorSet, Message}; - -/// According to the file kclvm/spec/gpyrpc/gpyrpc.proto, automatically generate -/// the corresponding rust source file to the directory src/model -fn main() { - if env::var("PROTOC").is_err() { - env::set_var( - "PROTOC", - protoc_bin_vendored::protoc_bin_path().unwrap().as_os_str(), - ); - } - - let out = PathBuf::from(env::var("OUT_DIR").unwrap()); - let descriptor_file = out.join("kclvm_service_descriptor.bin"); - - let mut prost_build = prost_build::Config::new(); - prost_build - .type_attribute(".", "#[derive(serde::Serialize,serde::Deserialize)]") - .field_attribute(".", "#[serde(default)]") - .extern_path(".google.protobuf.Any", "::prost_wkt_types::Any") - .extern_path(".google.protobuf.Timestamp", "::prost_wkt_types::Timestamp") - .extern_path(".google.protobuf.Value", "::prost_wkt_types::Value") - .file_descriptor_set_path(&descriptor_file) - .compile_protos(&["../spec/gpyrpc/gpyrpc.proto"], &["../spec/gpyrpc/"]) - .expect("Running prost build failed."); - - let descriptor_bytes = std::fs::read(descriptor_file).unwrap(); - - let descriptor = FileDescriptorSet::decode(&descriptor_bytes[..]).unwrap(); - - prost_wkt_build::add_serde(out, descriptor); -} diff --git a/kclvm/api/src/lib.rs b/kclvm/api/src/lib.rs deleted file mode 100644 index e9a825720..000000000 --- a/kclvm/api/src/lib.rs +++ /dev/null @@ -1,104 +0,0 @@ -//! # KCL Rust SDK -//! -//! ## How to Use -//! -//! ```no_check,no_run -//! cargo add --git https://github.com/kcl-lang/kcl kclvm_api -//! ``` -//! -//! Write the Code -//! -//! ```no_run -//! use kclvm_api::*; -//! use std::path::Path; -//! use anyhow::Result; -//! -//! fn main() -> Result<()> { -//! let api = API::default(); -//! let args = &ExecProgramArgs { -//! work_dir: Path::new(".").join("testdata").canonicalize().unwrap().display().to_string(), -//! k_filename_list: vec!["test.k".to_string()], -//! ..Default::default() -//! }; -//! let exec_result = api.exec_program(args)?; -//! assert_eq!(exec_result.yaml_result, "alice:\n age: 18"); -//! Ok(()) -//! } -//! ``` -#[cfg(test)] -pub mod capi_test; -pub mod service; - -pub mod gpyrpc { - include!(concat!(env!("OUT_DIR"), "/gpyrpc.rs")); -} - -pub use crate::gpyrpc::*; -use crate::service::capi::{kclvm_service_call_with_length, kclvm_service_new}; -use crate::service::service_impl::KclvmServiceImpl; -use anyhow::Result; -use std::ffi::{c_char, CString}; - -pub type API = KclvmServiceImpl; - -/// Call KCL API with the API name and argument protobuf bytes. -#[inline] -pub fn call<'a>(name: &'a [u8], args: &'a [u8]) -> Result> { - call_with_plugin_agent(name, args, 0) -} - -/// Call KCL API with the API name, argument protobuf bytes and the plugin agent pointer address. -pub fn call_with_plugin_agent<'a>( - name: &'a [u8], - args: &'a [u8], - plugin_agent: u64, -) -> Result> { - let mut result_len: usize = 0; - let result_ptr = { - let serv = kclvm_service_new(plugin_agent); - let args_len = args.len(); - let name = unsafe { CString::from_vec_unchecked(name.to_vec()) }; - let args = unsafe { CString::from_vec_unchecked(args.to_vec()) }; - kclvm_service_call_with_length( - serv, - name.as_ptr(), - args.as_ptr() as *const c_char, - args_len, - &mut result_len, - ) - }; - let result = unsafe { - let mut dest_data: Vec = Vec::with_capacity(result_len); - let dest_ptr: *mut u8 = dest_data.as_mut_ptr(); - std::ptr::copy_nonoverlapping(result_ptr as *const u8, dest_ptr, result_len); - dest_data.set_len(result_len); - dest_data - }; - - Ok(result) -} - -/// call_native is a universal KCL API interface that is consistent with the methods and parameters defined in Protobuf. -/// The first two parameters represent the name and length of the calling method, the middle two parameters represent -/// the Protobuf byte sequence and length of the calling parameter, and the return parameter is the byte sequence and -/// length of Protobuf. -#[no_mangle] -pub extern "C-unwind" fn call_native( - name_ptr: *const u8, - name_len: usize, - args_ptr: *const u8, - args_len: usize, - result_ptr: *mut u8, -) -> usize { - let name = unsafe { std::slice::from_raw_parts(name_ptr, name_len) }; - let args = unsafe { std::slice::from_raw_parts(args_ptr, args_len) }; - let res = call(name, args); - let result = match res { - Ok(res) => res, - Err(err) => err.to_string().into_bytes(), - }; - unsafe { - std::ptr::copy_nonoverlapping(result.as_ptr(), result_ptr, result.len()); - } - result.len() -} diff --git a/kclvm/api/src/service/capi.rs b/kclvm/api/src/service/capi.rs deleted file mode 100644 index 287cfb238..000000000 --- a/kclvm/api/src/service/capi.rs +++ /dev/null @@ -1,706 +0,0 @@ -use prost::Message; - -use crate::gpyrpc::*; -use crate::service::service_impl::KclvmServiceImpl; -use std::ffi::CString; -use std::os::raw::c_char; -use std::slice; - -#[allow(non_camel_case_types)] -type kclvm_service = KclvmServiceImpl; - -fn c_char_to_vec(args: *const c_char, args_len: usize) -> Vec { - if args.is_null() { - return Vec::new(); - } - // Create a slice from the raw pointer - let slice = unsafe { slice::from_raw_parts(args as *const u8, args_len) }; - // Convert slice to Vec - slice.to_vec() -} - -/// Create an instance of kclvm_service and return its pointer -#[no_mangle] -pub extern "C-unwind" fn kclvm_service_new(plugin_agent: u64) -> *mut kclvm_service { - let serv = kclvm_service { plugin_agent }; - Box::into_raw(Box::new(serv)) -} - -/// # Safety -/// -/// This function should not be called twice on the same ptr. -/// Delete KclvmService -#[no_mangle] -pub unsafe extern "C-unwind" fn kclvm_service_delete(serv: *mut kclvm_service) { - if !serv.is_null() { - unsafe { - drop(Box::from_raw(serv)); - } - } -} - -/// # Safety -/// -/// This function should not be called twice on the same ptr. -/// Free memory for string returned to the outside -#[no_mangle] -pub unsafe extern "C-unwind" fn kclvm_service_free_string(res: *mut c_char) { - if !res.is_null() { - unsafe { - let _ = CString::from_raw(res); - }; - } -} - -macro_rules! call { - ($serv:expr, $args:expr, $args_len:expr, $result_len:expr, $arg_name:ident, $serv_name:ident) => {{ - unsafe { - let serv_ref = &mut *$serv; - let args = c_char_to_vec($args, $args_len); - let args = args.as_slice(); - let args = $arg_name::decode(args).unwrap(); - let res = serv_ref.$serv_name(&args); - let result_byte = match res { - Ok(res) => res.encode_to_vec(), - Err(err) => format!("ERROR:{}", err.to_string()).into_bytes(), - }; - *$result_len = result_byte.len(); - CString::from_vec_unchecked(result_byte).into_raw() - } - }}; -} - -/// Call kclvm service by C API. **Note that it is not thread safe.** -/// -/// # Parameters -/// -/// `serv`: [*mut kclvm_service] -/// The pointer of &\[[KclvmServiceImpl]] -/// -/// `call`: [*const c_char] -/// The C str of the name of the called service, -/// with the format "KclvmService.{MethodName}" -/// -/// `args`: [*const c_char] -/// Arguments of the call serialized as protobuf byte sequence, -/// refer to kclvm/spec/gpyrpc/gpyrpc.proto for the specific definitions of arguments -/// -/// # Returns -/// -/// result: [*const c_char] -/// Result of the call serialized as protobuf byte sequence -#[no_mangle] -pub extern "C-unwind" fn kclvm_service_call( - serv: *mut kclvm_service, - name: *const c_char, - args: *const c_char, - args_len: usize, -) -> *const c_char { - let mut _result_len = 0; - kclvm_service_call_with_length(serv, name, args, args_len, &mut _result_len) -} - -/// Call kclvm service by C API. **Note that it is not thread safe.** -/// -/// # Parameters -/// -/// `serv`: [*mut kclvm_service] -/// The pointer of &\[[KclvmServiceImpl]] -/// -/// `call`: [*const c_char] -/// The C str of the name of the called service, -/// with the format "KclvmService.{MethodName}" -/// -/// `args`: [*const c_char] -/// Arguments of the call serialized as protobuf byte sequence, -/// refer to kclvm/spec/gpyrpc/gpyrpc.proto for the specific definitions of arguments -/// -/// # Returns -/// -/// result: [*const c_char] -/// Result of the call serialized as protobuf byte sequence -#[no_mangle] -pub extern "C-unwind" fn kclvm_service_call_with_length( - serv: *mut kclvm_service, - name: *const c_char, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - let result = std::panic::catch_unwind(|| { - let name = unsafe { std::ffi::CStr::from_ptr(name) }.to_str().unwrap(); - let call = kclvm_get_service_fn_ptr_by_name(name); - if call == 0 { - panic!("null fn ptr"); - } - let call = (&call as *const u64) as *const () - as *const fn( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, - ) -> *const c_char; - unsafe { (*call)(serv, args, args_len, result_len) } - }); - match result { - Ok(result) => result, - Err(panic_err) => { - let err_message = kclvm_error::err_to_str(panic_err); - - let c_string = std::ffi::CString::new(format!("ERROR:{}", err_message.as_str())) - .expect("CString::new failed"); - let ptr = c_string.into_raw(); - ptr as *const c_char - } - } -} - -pub(crate) fn kclvm_get_service_fn_ptr_by_name(name: &str) -> u64 { - match name { - "KclvmService.Ping" => ping as *const () as u64, - "KclvmService.GetVersion" => get_version as *const () as u64, - "KclvmService.ParseFile" => parse_file as *const () as u64, - "KclvmService.ParseProgram" => parse_program as *const () as u64, - "KclvmService.LoadPackage" => load_package as *const () as u64, - "KclvmService.ListOptions" => list_options as *const () as u64, - "KclvmService.ListVariables" => list_variables as *const () as u64, - "KclvmService.ExecProgram" => exec_program as *const () as u64, - #[cfg(feature = "llvm")] - "KclvmService.BuildProgram" => build_program as *const () as u64, - #[cfg(feature = "llvm")] - "KclvmService.ExecArtifact" => exec_artifact as *const () as u64, - "KclvmService.OverrideFile" => override_file as *const () as u64, - "KclvmService.GetSchemaTypeMapping" => get_schema_type_mapping as *const () as u64, - "KclvmService.GetSchemaTypeMappingUnderPath" => { - get_schema_type_mapping_under_path as *const () as u64 - } - "KclvmService.FormatCode" => format_code as *const () as u64, - "KclvmService.FormatPath" => format_path as *const () as u64, - "KclvmService.LintPath" => lint_path as *const () as u64, - "KclvmService.ValidateCode" => validate_code as *const () as u64, - "KclvmService.LoadSettingsFiles" => load_settings_files as *const () as u64, - "KclvmService.Rename" => rename as *const () as u64, - "KclvmService.RenameCode" => rename_code as *const () as u64, - "KclvmService.Test" => test as *const () as u64, - #[cfg(not(target_arch = "wasm32"))] - "KclvmService.UpdateDependencies" => update_dependencies as *const () as u64, - _ => panic!("unknown method name : {name}"), - } -} - -/// ping is used to test whether kclvm service is successfully imported -/// arguments and return results should be consistent -pub(crate) fn ping( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!(serv, args, args_len, result_len, PingArgs, ping) -} - -/// get_version is used to get kclvm service version -pub(crate) fn get_version( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - GetVersionArgs, - get_version - ) -} - -/// parse_file provides users with the ability to parse kcl single file -/// -/// # Parameters -/// -/// `serv`: [*mut kclvm_service] -/// The pointer of &\[[KclvmServiceImpl]] -/// -/// -/// `args`: [*const c_char] -/// the items and compile parameters selected by the user in the KCL CLI -/// serialized as protobuf byte sequence -/// -/// # Returns -/// -/// result: [*const c_char] -/// Result of the call serialized as protobuf byte sequence -pub(crate) fn parse_file( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!(serv, args, args_len, result_len, ParseFileArgs, parse_file) -} - -/// parse_program provides users with the ability to parse kcl program -/// -/// # Parameters -/// -/// `serv`: [*mut kclvm_service] -/// The pointer of &\[[KclvmServiceImpl]] -/// -/// -/// `args`: [*const c_char] -/// the items and compile parameters selected by the user in the KCL CLI -/// serialized as protobuf byte sequence -/// -/// # Returns -/// -/// result: [*const c_char] -/// Result of the call serialized as protobuf byte sequence -pub(crate) fn parse_program( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - ParseProgramArgs, - parse_program - ) -} - -/// load_package provides users with the ability to parse kcl program and sematic model -/// information including symbols, types, definitions, etc, -/// -/// # Parameters -/// -/// `serv`: [*mut kclvm_service] -/// The pointer of &\[[KclvmServiceImpl]] -/// -/// -/// `args`: [*const c_char] -/// the items and compile parameters selected by the user in the KCL CLI -/// serialized as protobuf byte sequence -/// -/// # Returns -/// -/// result: [*const c_char] -/// Result of the call serialized as protobuf byte sequence -pub(crate) fn load_package( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - LoadPackageArgs, - load_package - ) -} - -/// list_options provides users with the ability to parse kcl program and get all option -/// calling information. -/// -/// # Parameters -/// -/// `serv`: [*mut kclvm_service] -/// The pointer of &\[[KclvmServiceImpl]] -/// -/// -/// `args`: [*const c_char] -/// the items and compile parameters selected by the user in the KCL CLI -/// serialized as protobuf byte sequence -/// -/// # Returns -/// -/// result: [*const c_char] -/// Result of the call serialized as protobuf byte sequence -pub(crate) fn list_options( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - ParseProgramArgs, - list_options - ) -} - -/// list_variables provides users with the ability to parse kcl program and get all variables -/// calling information. -/// -/// # Parameters -/// -/// `serv`: [*mut kclvm_service] -/// The pointer of &\[[KclvmServiceImpl]] -/// -/// -/// `args`: [*const c_char] -/// the items and compile parameters selected by the user in the KCL CLI -/// serialized as protobuf byte sequence -/// -/// # Returns -/// -/// result: [*const c_char] -/// Result of the call serialized as protobuf byte sequence -pub(crate) fn list_variables( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - ListVariablesArgs, - list_variables - ) -} - -/// exec_program provides users with the ability to execute KCL code -/// -/// # Parameters -/// -/// `serv`: [*mut kclvm_service] -/// The pointer of &\[[KclvmServiceImpl]] -/// -/// -/// `args`: [*const c_char] -/// the items and compile parameters selected by the user in the KCL CLI -/// serialized as protobuf byte sequence -/// -/// # Returns -/// -/// result: [*const c_char] -/// Result of the call serialized as protobuf byte sequence -pub(crate) fn exec_program( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - ExecProgramArgs, - exec_program - ) -} - -/// build_program provides users with the ability to build the KCL program to an artifact. -/// -/// # Parameters -/// -/// `serv`: [*mut kclvm_service] -/// The pointer of &\[[KclvmServiceImpl]] -/// -/// -/// `args`: [*const c_char] -/// the items and compile parameters selected by the user in the KCL CLI -/// serialized as protobuf byte sequence -/// -/// # Returns -/// -/// result: [*const c_char] -/// Result of the call serialized as protobuf byte sequence -#[cfg(feature = "llvm")] -pub(crate) fn build_program( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - BuildProgramArgs, - build_program - ) -} - -/// build_program provides users with the ability to execute the KCL artifact. -/// -/// # Parameters -/// -/// `serv`: [*mut kclvm_service] -/// The pointer of &\[[KclvmServiceImpl]] -/// -/// -/// `args`: [*const c_char] -/// the items and compile parameters selected by the user in the KCL CLI -/// serialized as protobuf byte sequence -/// -/// # Returns -/// -/// result: [*const c_char] -/// Result of the call serialized as protobuf byte sequence -#[cfg(feature = "llvm")] -pub(crate) fn exec_artifact( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - ExecArtifactArgs, - exec_artifact - ) -} - -/// override_file enable users override existing KCL file with specific KCl code -/// -/// # Parameters -/// -/// `serv`: [*mut kclvm_service] -/// The pointer of &\[[KclvmServiceImpl]] -/// -/// -/// `args`: [*const c_char] -/// kcl file , override specs and import paths selected by the user in the KCL CLI -/// serialized as protobuf byte sequence -/// -/// # Returns -/// -/// result: [*const c_char] -/// Result of the call serialized as protobuf byte sequence -pub(crate) fn override_file( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - OverrideFileArgs, - override_file - ) -} - -/// Get schema types from a kcl file or code. -/// -/// # Parameters -/// file: [&str]. The kcl filename. -/// -/// code: [Option<&str>]. The kcl code string -/// -/// schema_name: [Option<&str>]. The schema name, when the schema name is empty, all schemas are returned. -pub(crate) fn get_schema_type_mapping( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - GetSchemaTypeMappingArgs, - get_schema_type_mapping - ) -} - -/// Get schema types under path -/// -/// # Parameters -/// file: [&str]. The kcl filename. -/// -/// code: [Option<&str>]. The kcl code string -/// -/// schema_name: [Option<&str>]. The schema name, when the schema name is empty, all schemas are returned. -pub(crate) fn get_schema_type_mapping_under_path( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - GetSchemaTypeMappingArgs, - get_schema_type_mapping_under_path - ) -} - -/// Service for formatting a code source and returns the formatted source and -/// whether the source is changed. -pub(crate) fn format_code( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - FormatCodeArgs, - format_code - ) -} - -/// Service for formatting kcl file or directory path contains kcl files and -/// returns the changed file paths. -pub(crate) fn format_path( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - FormatPathArgs, - format_path - ) -} - -/// Service for KCL Lint API, check a set of files, skips execute, -/// returns error message including errors and warnings. -pub(crate) fn lint_path( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!(serv, args, args_len, result_len, LintPathArgs, lint_path) -} - -/// Service for validating the data string using the schema code string, when the parameter -/// `schema` is omitted, use the first schema appeared in the kcl code. -pub(crate) fn validate_code( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - ValidateCodeArgs, - validate_code - ) -} - -/// Service for building setting file config from args. -pub(crate) fn load_settings_files( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - LoadSettingsFilesArgs, - load_settings_files - ) -} - -/// Service for renaming all the occurrences of the target symbol in the files. This API will rewrite files if they contain symbols to be renamed. -/// return the file paths got changed. -pub(crate) fn rename( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!(serv, args, args_len, result_len, RenameArgs, rename) -} - -/// Service for renaming all the occurrences of the target symbol in the code. This API won't rewrite files but return the modified code if any code has been changed. -/// return the changed code. -pub(crate) fn rename_code( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - RenameCodeArgs, - rename_code - ) -} - -/// Service for the testing tool. -pub(crate) fn test( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!(serv, args, args_len, result_len, TestArgs, test) -} - -#[cfg(not(target_arch = "wasm32"))] -/// Service for the dependencies updating -/// calling information. -/// -/// # Parameters -/// -/// `serv`: [*mut kclvm_service] -/// The pointer of &\[[KclvmServiceImpl]] -/// -/// -/// `args`: [*const c_char] -/// the items and compile parameters selected by the user in the KCL CLI -/// serialized as protobuf byte sequence -/// -/// # Returns -/// -/// result: [*const c_char] -/// Result of the call serialized as protobuf byte sequence -pub(crate) fn update_dependencies( - serv: *mut kclvm_service, - args: *const c_char, - args_len: usize, - result_len: *mut usize, -) -> *const c_char { - call!( - serv, - args, - args_len, - result_len, - UpdateDependenciesArgs, - update_dependencies - ) -} diff --git a/kclvm/api/src/service/into.rs b/kclvm/api/src/service/into.rs deleted file mode 100644 index fb179a43a..000000000 --- a/kclvm/api/src/service/into.rs +++ /dev/null @@ -1,138 +0,0 @@ -use crate::gpyrpc::{ - CliConfig, Error, KeyValuePair, LoadSettingsFilesResult, Message, Position, Scope, ScopeIndex, - Symbol, SymbolIndex, -}; -use crate::service::ty::kcl_ty_to_pb_ty; -use kclvm_config::settings::SettingsFile; -use kclvm_error::Diagnostic; -use kclvm_loader::{ScopeInfo, SymbolInfo}; -use kclvm_sema::core::{scope::ScopeRef, symbol::SymbolRef}; - -pub(crate) trait IntoLoadSettingsFiles { - /// Convert self into the LoadSettingsFiles structure. - fn into_load_settings_files(self, files: &[String]) -> LoadSettingsFilesResult; -} - -pub(crate) trait IntoError { - fn into_error(self) -> Error; -} - -pub(crate) trait IntoSymbolIndex { - fn into_symbol_index(self) -> SymbolIndex; -} - -pub(crate) trait IntoSymbol { - fn into_symbol(self) -> Symbol; -} - -pub(crate) trait IntoScope { - fn into_scope(self) -> Scope; -} - -pub(crate) trait IntoScopeIndex { - fn into_scope_index(self) -> ScopeIndex; -} - -impl IntoLoadSettingsFiles for SettingsFile { - fn into_load_settings_files(self, files: &[String]) -> LoadSettingsFilesResult { - LoadSettingsFilesResult { - kcl_cli_configs: self.kcl_cli_configs.map(|config| CliConfig { - files: files.to_vec(), - output: config.output.unwrap_or_default(), - overrides: config.overrides.unwrap_or_default(), - path_selector: config.path_selector.unwrap_or_default(), - strict_range_check: config.strict_range_check.unwrap_or_default(), - disable_none: config.disable_none.unwrap_or_default(), - verbose: config.verbose.unwrap_or_default() as i64, - debug: config.debug.unwrap_or_default(), - sort_keys: config.sort_keys.unwrap_or_default(), - show_hidden: config.show_hidden.unwrap_or_default(), - fast_eval: config.fast_eval.unwrap_or_default(), - include_schema_type_path: config.include_schema_type_path.unwrap_or_default(), - }), - kcl_options: match self.kcl_options { - Some(opts) => opts - .iter() - .map(|o| KeyValuePair { - key: o.key.to_string(), - value: o.value.to_string(), - }) - .collect(), - None => vec![], - }, - } - } -} - -impl IntoError for Diagnostic { - fn into_error(self) -> Error { - Error { - level: self.level.to_string(), - code: format!( - "{:?}", - self.code.unwrap_or(kclvm_error::DiagnosticId::Error( - kclvm_error::ErrorKind::InvalidSyntax, - )) - ), - messages: self - .messages - .iter() - .map(|m| Message { - msg: m.message.clone(), - pos: Some(Position { - filename: m.range.0.filename.clone(), - line: m.range.0.line as i64, - column: m.range.0.column.unwrap_or_default() as i64, - }), - }) - .collect(), - } - } -} - -impl IntoSymbolIndex for SymbolRef { - fn into_symbol_index(self) -> SymbolIndex { - let (index, generation) = self.get_id().into_raw_parts(); - SymbolIndex { - i: index as u64, - g: generation, - kind: format!("{:?}", self.get_kind()), - } - } -} - -impl IntoScopeIndex for ScopeRef { - fn into_scope_index(self) -> ScopeIndex { - let (index, generation) = self.get_id().into_raw_parts(); - ScopeIndex { - i: index as u64, - g: generation, - kind: format!("{:?}", self.get_kind()), - } - } -} - -impl IntoSymbol for SymbolInfo { - fn into_symbol(self) -> Symbol { - Symbol { - ty: Some(kcl_ty_to_pb_ty(&self.ty)), - name: self.name, - owner: self.owner.map(|o| o.into_symbol_index()), - def: self.def.map(|d| d.into_symbol_index()), - attrs: self.attrs.iter().map(|a| a.into_symbol_index()).collect(), - is_global: self.is_global, - } - } -} - -impl IntoScope for ScopeInfo { - fn into_scope(self) -> Scope { - Scope { - kind: format!("{:?}", self.kind), - parent: self.parent.map(|o| o.into_scope_index()), - owner: self.owner.map(|o| o.into_symbol_index()), - children: self.children.iter().map(|a| a.into_scope_index()).collect(), - defs: self.defs.iter().map(|a| a.into_symbol_index()).collect(), - } - } -} diff --git a/kclvm/api/src/service/jsonrpc.rs b/kclvm/api/src/service/jsonrpc.rs deleted file mode 100644 index 00f63c15f..000000000 --- a/kclvm/api/src/service/jsonrpc.rs +++ /dev/null @@ -1,284 +0,0 @@ -use crate::gpyrpc::*; -use crate::service::service_impl::KclvmServiceImpl; -use core::fmt::Display; -use jsonrpc_stdio_server::jsonrpc_core::{Error, ErrorCode, IoHandler, Params}; -use jsonrpc_stdio_server::ServerBuilder; -use serde::Serialize; -const KCLVM_SERVER_ERROR_CODE: i64 = 0x4B434C; // the ASCII code of "KCL" - -/// Start a json rpc server via Stdin/Stdout -#[tokio::main] -pub async fn start_stdio_server() -> Result<(), anyhow::Error> { - let mut io = IoHandler::default(); - // KclvmService - register_kclvm_service(&mut io); - // BuiltinService - register_builtin_service(&mut io); - let server = ServerBuilder::new(io).build(); - server.await; - Ok(()) -} - -macro_rules! catch { - ($serv:expr, $args:expr, $serv_name:ident) => {{ - let prev_hook = std::panic::take_hook(); - - // disable print panic info - std::panic::set_hook(Box::new(|_info| {})); - let result = std::panic::catch_unwind(|| to_json_result(&$serv.$serv_name(&$args))); - std::panic::set_hook(prev_hook); - match result { - Ok(result) => result, - Err(panic_err) => { - let err_message = kclvm_error::err_to_str(panic_err); - Err(Error { - code: ErrorCode::from(KCLVM_SERVER_ERROR_CODE), - message: err_message, - data: None, - }) - } - } - }}; -} - -/// Transform the [`Result`] into [`Result`] -#[inline] -fn to_json_result(val: &Result) -> Result -where - V: Serialize, - E: Display, -{ - match val { - Ok(val) => Ok(serde_json::to_value(val).unwrap()), - Err(err) => Err(Error { - code: ErrorCode::from(KCLVM_SERVER_ERROR_CODE), - message: err.to_string(), - data: None, - }), - } -} - -fn register_kclvm_service(io: &mut IoHandler) { - io.add_method("KclvmService.Ping", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: PingArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, ping)) - }); - io.add_method("KclvmService.GetVersion", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: GetVersionArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, get_version)) - }); - io.add_method("KclvmService.ParseFile", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: ParseFileArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, parse_file)) - }); - io.add_method("KclvmService.ParseProgram", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: ParseProgramArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, parse_program)) - }); - io.add_method("KclvmService.LoadPackage", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: LoadPackageArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, load_package)) - }); - io.add_method("KclvmService.ListOptions", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: ParseProgramArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, list_options)) - }); - io.add_method("KclvmService.ListVariables", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: ListVariablesArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, list_variables)) - }); - io.add_method("KclvmService.ExecProgram", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: ExecProgramArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, exec_program)) - }); - #[cfg(feature = "llvm")] - io.add_method("KclvmService.BuildProgram", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: BuildProgramArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, build_program)) - }); - #[cfg(feature = "llvm")] - io.add_method("KclvmService.ExecArtifact", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: ExecArtifactArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, exec_artifact)) - }); - io.add_method("KclvmService.OverrideFile", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: OverrideFileArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, override_file)) - }); - io.add_method("KclvmService.GetSchemaTypeMapping", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: GetSchemaTypeMappingArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, get_schema_type_mapping)) - }); - io.add_method( - "KclvmService.GetSchemaTypeMappingUnderPath", - |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: GetSchemaTypeMappingArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!( - kclvm_service_impl, - args, - get_schema_type_mapping_under_path - )) - }, - ); - io.add_method("KclvmService.FormatCode", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: FormatCodeArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, format_code)) - }); - io.add_method("KclvmService.FormatPath", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: FormatPathArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, format_path)) - }); - io.add_method("KclvmService.LintPath", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: LintPathArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, lint_path)) - }); - io.add_method("KclvmService.ValidateCode", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: ValidateCodeArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, validate_code)) - }); - io.add_method("KclvmService.LoadSettingsFiles", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: LoadSettingsFilesArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, load_settings_files)) - }); - io.add_method("KclvmService.Rename", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: RenameArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, rename)) - }); - io.add_method("KclvmService.RenameCode", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: RenameCodeArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, rename_code)) - }); - io.add_method("KclvmService.Test", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: TestArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, test)) - }); - io.add_method("KclvmService.UpdateDependencies", |params: Params| { - let kclvm_service_impl = KclvmServiceImpl::default(); - let args: UpdateDependenciesArgs = match params.parse() { - Ok(val) => val, - Err(err) => return futures::future::ready(Err(err)), - }; - futures::future::ready(catch!(kclvm_service_impl, args, update_dependencies)) - }); -} - -fn register_builtin_service(io: &mut IoHandler) { - io.add_sync_method("BuiltinService.Ping", |params: Params| { - let args: PingArgs = params.parse()?; - let result = PingResult { value: args.value }; - Ok(serde_json::to_value(result).unwrap()) - }); - io.add_sync_method("BuiltinService.ListMethod", |_params: Params| { - let result = ListMethodResult { - method_name_list: vec![ - "KclvmService.Ping".to_owned(), - "KclvmService.GetVersion".to_owned(), - "KclvmService.ParseFile".to_owned(), - "KclvmService.ParseProgram".to_owned(), - "KclvmService.ExecProgram".to_owned(), - "KclvmService.BuildProgram".to_owned(), - "KclvmService.ExecArtifact".to_owned(), - "KclvmService.OverrideFile".to_owned(), - "KclvmService.GetSchemaType".to_owned(), - "KclvmService.GetFullSchemaType".to_owned(), - "KclvmService.GetSchemaTypeMapping".to_owned(), - "KclvmService.FormatCode".to_owned(), - "KclvmService.FormatPath".to_owned(), - "KclvmService.LintPath".to_owned(), - "KclvmService.ValidateCode".to_owned(), - "KclvmService.LoadSettingsFiles".to_owned(), - "KclvmService.Rename".to_owned(), - "KclvmService.RenameCode".to_owned(), - "KclvmService.Test".to_owned(), - "KclvmService.UpdateDependencies".to_owned(), - "BuiltinService.Ping".to_owned(), - "BuiltinService.PingListMethod".to_owned(), - ], - }; - Ok(serde_json::to_value(result).unwrap()) - }); -} diff --git a/kclvm/api/src/service/mod.rs b/kclvm/api/src/service/mod.rs deleted file mode 100644 index 1cea8033c..000000000 --- a/kclvm/api/src/service/mod.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub mod capi; -pub(crate) mod into; -#[cfg(not(target_arch = "wasm32"))] -pub mod jsonrpc; -pub mod service_impl; -pub(crate) mod ty; -pub(crate) mod util; - -pub use service_impl::KclvmServiceImpl; diff --git a/kclvm/api/src/service/ty.rs b/kclvm/api/src/service/ty.rs deleted file mode 100644 index bb3149a64..000000000 --- a/kclvm/api/src/service/ty.rs +++ /dev/null @@ -1,121 +0,0 @@ -use crate::gpyrpc::{Decorator, Example, KclType}; -use kclvm_primitives::IndexSet; -use kclvm_sema::ty::{DictType, SchemaType, Type}; -use std::collections::HashMap; - -/// Convert the kcl sematic type to the kcl protobuf type. -pub(crate) fn kcl_ty_to_pb_ty(ty: &Type) -> KclType { - match &ty.kind { - kclvm_sema::ty::TypeKind::List(item_ty) => KclType { - r#type: "list".to_string(), - item: Some(Box::new(kcl_ty_to_pb_ty(item_ty))), - ..Default::default() - }, - kclvm_sema::ty::TypeKind::Dict(DictType { key_ty, val_ty, .. }) => KclType { - r#type: "dict".to_string(), - key: Some(Box::new(kcl_ty_to_pb_ty(key_ty))), - item: Some(Box::new(kcl_ty_to_pb_ty(val_ty))), - ..Default::default() - }, - kclvm_sema::ty::TypeKind::Union(types) => KclType { - r#type: "union".to_string(), - union_types: types.iter().map(|ty| kcl_ty_to_pb_ty(ty)).collect(), - ..Default::default() - }, - kclvm_sema::ty::TypeKind::Schema(schema_ty) => kcl_schema_ty_to_pb_ty(schema_ty), - _ => KclType { - r#type: ty.ty_str(), - ..Default::default() - }, - } -} - -/// Convert the kcl sematic type to the kcl protobuf type. -pub(crate) fn kcl_schema_ty_to_pb_ty(schema_ty: &SchemaType) -> KclType { - KclType { - r#type: "schema".to_string(), - schema_name: schema_ty.name.clone(), - schema_doc: schema_ty.doc.clone(), - examples: get_schema_ty_examples(schema_ty), - properties: get_schema_ty_attributes(schema_ty, &mut 1), - required: get_schema_ty_required_attributes(schema_ty), - decorators: schema_ty - .decorators - .iter() - .map(|d| Decorator { - name: d.name.clone(), - arguments: d.arguments.clone(), - keywords: d.keywords.clone(), - }) - .collect(), - filename: schema_ty.filename.clone(), - pkg_path: schema_ty.pkgpath.clone(), - description: schema_ty.doc.clone(), - base_schema: schema_ty - .base - .as_ref() - .map(|base| Box::new(kcl_schema_ty_to_pb_ty(&**base))), - ..Default::default() - } -} - -fn get_schema_ty_examples(schema_ty: &SchemaType) -> HashMap { - let mut examples = HashMap::new(); - for (key, example) in &schema_ty.examples { - let exa = Example { - summary: example.summary.clone(), - description: example.description.clone(), - value: example.value.clone(), - }; - examples.insert(key.clone(), exa); - } - examples -} - -fn get_schema_ty_attributes(schema_ty: &SchemaType, line: &mut i32) -> HashMap { - let mut base_type_mapping = if let Some(base) = &schema_ty.base { - get_schema_ty_attributes(base, line) - } else { - HashMap::new() - }; - let mut type_mapping = HashMap::new(); - for (key, attr) in &schema_ty.attrs { - let mut ty = kcl_ty_to_pb_ty(&attr.ty); - ty.line = *line; - ty.description = attr.doc.clone().unwrap_or_default(); - ty.decorators = attr - .decorators - .iter() - .map(|d| Decorator { - name: d.name.clone(), - arguments: d.arguments.clone(), - keywords: d.keywords.clone(), - }) - .collect(); - ty.default = attr.default.clone().unwrap_or_default(); - type_mapping.insert(key.to_string(), ty); - *line += 1 - } - for (k, ty) in type_mapping { - base_type_mapping.insert(k, ty); - } - base_type_mapping -} - -fn get_schema_ty_required_attributes(schema_ty: &SchemaType) -> Vec { - let base_attr_set = if let Some(base) = &schema_ty.base { - get_schema_ty_required_attributes(base) - } else { - Vec::new() - }; - let mut attr_set = IndexSet::new(); - for (key, attr) in &schema_ty.attrs { - if !attr.is_optional { - attr_set.insert(key.to_string()); - } - } - for k in base_attr_set { - attr_set.insert(k); - } - attr_set.iter().cloned().collect() -} diff --git a/kclvm/api/src/service/util.rs b/kclvm/api/src/service/util.rs deleted file mode 100644 index f74b5fa1f..000000000 --- a/kclvm/api/src/service/util.rs +++ /dev/null @@ -1,27 +0,0 @@ -use crate::gpyrpc::ExecProgramArgs; - -/// Transform the str with zero value into [`Option`] -#[inline] -pub(crate) fn transform_str_para(para: &str) -> Option { - if para.is_empty() { - None - } else { - Some(para.to_string()) - } -} - -#[inline] -pub(crate) fn transform_exec_para( - exec_args: &Option, - plugin_agent: u64, -) -> anyhow::Result { - let mut args = match exec_args { - Some(exec_args) => { - let args_json = serde_json::to_string(exec_args)?; - kclvm_runner::ExecProgramArgs::from_str(args_json.as_str()) - } - None => kclvm_runner::ExecProgramArgs::default(), - }; - args.plugin_agent = plugin_agent; - Ok(args) -} diff --git a/kclvm/ast/Cargo.lock b/kclvm/ast/Cargo.lock deleted file mode 100644 index dc0cb57cc..000000000 --- a/kclvm/ast/Cargo.lock +++ /dev/null @@ -1,1473 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "ahash" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" -dependencies = [ - "getrandom", - "once_cell", - "version_check", -] - -[[package]] -name = "aho-corasick" -version = "0.7.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" -dependencies = [ - "memchr", -] - -[[package]] -name = "annotate-snippets" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78ea013094e5ea606b1c05fe35f1dd7ea1eb1ea259908d040b25bd5ec677ee5" - -[[package]] -name = "arrayvec" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" - -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi", - "libc", - "winapi", -] - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "base64" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" - -[[package]] -name = "bit-set" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e11e16035ea35e4e5997b393eacbf6f63983188f7a2ad25bfb13465f5ad59de" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "generic-array", -] - -[[package]] -name = "block-buffer" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bstr" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" -dependencies = [ - "lazy_static", - "memchr", - "regex-automata", -] - -[[package]] -name = "cc" -version = "1.0.73" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "chrono" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" -dependencies = [ - "libc", - "num-integer", - "num-traits", - "time", - "winapi", -] - -[[package]] -name = "cpufeatures" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b" -dependencies = [ - "libc", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" -dependencies = [ - "cfg-if 1.0.0", - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1145cf131a2c6ba0615079ab6a638f7e1973ac9c2634fcbeaaad6114246efe8c" -dependencies = [ - "autocfg", - "cfg-if 1.0.0", - "crossbeam-utils", - "lazy_static", - "memoffset", - "scopeguard", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf124c720b7686e3c2663cf54062ab0f68a88af2fb6a030e87e30bf721fcb38" -dependencies = [ - "cfg-if 1.0.0", - "lazy_static", -] - -[[package]] -name = "crypto-common" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "digest" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" -dependencies = [ - "generic-array", -] - -[[package]] -name = "digest" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506" -dependencies = [ - "block-buffer 0.10.2", - "crypto-common", -] - -[[package]] -name = "either" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" - -[[package]] -name = "ena" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7402b94a93c24e742487327a7cd839dc9d36fec9de9fb25b09f2dae459f36c3" -dependencies = [ - "log", -] - -[[package]] -name = "enquote" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06c36cb11dbde389f4096111698d8b567c0720e3452fd5ac3e6b4e47e1939932" -dependencies = [ - "thiserror", -] - -[[package]] -name = "fancy-regex" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d6b8560a05112eb52f04b00e5d3790c0dd75d9d980eb8a122fb23b92a623ccf" -dependencies = [ - "bit-set", - "regex", -] - -[[package]] -name = "fastrand" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf" -dependencies = [ - "instant", -] - -[[package]] -name = "fixedbitset" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "279fb028e20b3c4c320317955b77c5e0c9701f05a1d309905d6fc702cdc5053e" - -[[package]] -name = "fslock" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04412b8935272e3a9bae6f48c7bfff74c2911f60525404edfdd28e49884c3bfb" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "fuchsia-cprng" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" - -[[package]] -name = "gcc" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2" - -[[package]] -name = "generic-array" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "wasi", -] - -[[package]] -name = "glob" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" - -[[package]] -name = "hashbrown" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" - -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - -[[package]] -name = "indexmap" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" -dependencies = [ - "autocfg", - "hashbrown", - "rustc-rayon", -] - -[[package]] -name = "instant" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "itertools" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" - -[[package]] -name = "jobserver" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af25a77299a7f711a01975c35a6a424eb6862092cc2d6c72c4ed6cbc56dfc1fa" -dependencies = [ - "libc", -] - -[[package]] -name = "json_minimal" -version = "0.1.3" - -[[package]] -name = "kclvm-ast" -version = "0.1.0" -dependencies = [ - "kclvm-parser", - "kclvm-span", - "rustc_span", - "serde", - "serde_json", -] - -[[package]] -name = "kclvm-config" -version = "0.1.0" -dependencies = [ - "ahash", - "chrono", - "fslock", - "glob", - "indexmap", - "kclvm-version", - "pathdiff", - "ron", - "rust-crypto", - "serde", - "serde_yaml", - "toml", -] - -[[package]] -name = "kclvm-error" -version = "0.1.0" -dependencies = [ - "annotate-snippets", - "atty", - "indexmap", - "kclvm-runtime", - "kclvm-span", - "rustc_span", - "termcolor", - "termize", - "tracing", -] - -[[package]] -name = "kclvm-lexer" -version = "0.1.0" -dependencies = [ - "kclvm-error", - "rustc_lexer", - "unic-emoji-char", -] - -[[package]] -name = "kclvm-macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "kclvm-parser" -version = "0.1.0" -dependencies = [ - "bstr", - "either", - "enquote", - "kclvm-ast", - "kclvm-config", - "kclvm-error", - "kclvm-lexer", - "kclvm-runtime", - "kclvm-sema", - "kclvm-span", - "num-bigint", - "rustc_data_structures", - "rustc_lexer", - "rustc_span", - "serde", - "serde_json", - "tracing", - "unicode_names2", -] - -[[package]] -name = "kclvm-runtime" -version = "0.1.0" -dependencies = [ - "ahash", - "base64", - "bstr", - "chrono", - "fancy-regex", - "indexmap", - "itertools", - "json_minimal", - "kclvm_runtime_internal_macros", - "libc", - "md5", - "num-integer", - "phf", - "regex", - "serde", - "serde_json", - "serde_yaml", - "sha1", - "sha2 0.9.9", - "unic-ucd-bidi", - "unic-ucd-category", - "unicode-casing", -] - -[[package]] -name = "kclvm-sema" -version = "0.1.0" -dependencies = [ - "ahash", - "bit-set", - "bitflags", - "fancy-regex", - "indexmap", - "kclvm-ast", - "kclvm-error", - "kclvm-runtime", - "kclvm-span", - "once_cell", - "petgraph", - "phf", - "unicode_names2", -] - -[[package]] -name = "kclvm-span" -version = "0.1.0" -dependencies = [ - "kclvm-macros", - "rustc_span", - "scoped-tls", -] - -[[package]] -name = "kclvm-version" -version = "0.1.0" - -[[package]] -name = "kclvm_runtime_internal_macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.124" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21a41fed9d98f27ab1c6d161da622a4fa35e8a54a8adc24bbf3ddd0ef70b0e50" - -[[package]] -name = "linked-hash-map" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3" - -[[package]] -name = "lock_api" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" -dependencies = [ - "autocfg", - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6389c490849ff5bc16be905ae24bc913a9c8892e19b2341dbc175e14c341c2b8" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "matches" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" - -[[package]] -name = "md-5" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "658646b21e0b72f7866c7038ab086d3d5e1cd6271f060fd37defb241949d0582" -dependencies = [ - "digest 0.10.3", -] - -[[package]] -name = "md5" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" - -[[package]] -name = "memchr" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" - -[[package]] -name = "memmap2" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "723e3ebdcdc5c023db1df315364573789f8857c11b631a2fdfad7c00f5c046b4" -dependencies = [ - "libc", -] - -[[package]] -name = "memoffset" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num-bigint" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f" -dependencies = [ - "autocfg", - "num-integer", - "num-traits", -] - -[[package]] -name = "num-integer" -version = "0.1.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" -dependencies = [ - "autocfg", - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_cpus" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "once_cell" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225" - -[[package]] -name = "opaque-debug" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" - -[[package]] -name = "parking_lot" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f5ec2493a61ac0506c0f4199f99070cbe83857b0337006a30f3e6719b8ef58" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "995f667a6c822200b0433ac218e05582f0e2efa1b922a3fd2fbaadc5f87bab37" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "redox_syscall", - "smallvec", - "windows-sys", -] - -[[package]] -name = "pathdiff" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" - -[[package]] -name = "petgraph" -version = "0.6.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6d5014253a1331579ce62aa67443b4a658c5e7dd03d4bc6d302b94474888143" -dependencies = [ - "fixedbitset", - "indexmap", -] - -[[package]] -name = "phf" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2ac8b67553a7ca9457ce0e526948cad581819238f4a9d1ea74545851fa24f37" -dependencies = [ - "phf_macros", - "phf_shared", - "proc-macro-hack", -] - -[[package]] -name = "phf_generator" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43f3220d96e0080cc9ea234978ccd80d904eafb17be31bb0f76daaea6493082" -dependencies = [ - "phf_shared", - "rand 0.8.5", -] - -[[package]] -name = "phf_macros" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b706f5936eb50ed880ae3009395b43ed19db5bff2ebd459c95e7bf013a89ab86" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro-hack", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "phf_shared" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a68318426de33640f02be62b4ae8eb1261be2efbc337b60c54d845bf4484e0d9" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e280fbe77cc62c91527259e9442153f4688736748d24660126286329742b4c6c" - -[[package]] -name = "ppv-lite86" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" - -[[package]] -name = "proc-macro-hack" -version = "0.5.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" - -[[package]] -name = "proc-macro2" -version = "1.0.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "psm" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "871372391786ccec00d3c5d3d6608905b3d4db263639cfe075d3b60a736d115a" -dependencies = [ - "cc", -] - -[[package]] -name = "quote" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rand" -version = "0.3.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64ac302d8f83c0c1974bf758f6b041c6c8ada916fbb44a609158ca8b064cc76c" -dependencies = [ - "libc", - "rand 0.4.6", -] - -[[package]] -name = "rand" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293" -dependencies = [ - "fuchsia-cprng", - "libc", - "rand_core 0.3.1", - "rdrand", - "winapi", -] - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha", - "rand_core 0.6.3", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.3", -] - -[[package]] -name = "rand_core" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" -dependencies = [ - "rand_core 0.4.2", -] - -[[package]] -name = "rand_core" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" - -[[package]] -name = "rand_core" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" -dependencies = [ - "getrandom", -] - -[[package]] -name = "rdrand" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" -dependencies = [ - "rand_core 0.3.1", -] - -[[package]] -name = "redox_syscall" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" -dependencies = [ - "bitflags", -] - -[[package]] -name = "regex" -version = "1.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83f127d94bdbcda4c8cc2e50f6f84f4b611f69c902699ca385a39c3a75f9ff1" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" - -[[package]] -name = "regex-syntax" -version = "0.6.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49b3de9ec5dc0a3417da371aab17d729997c15010e7fd24ff707773a33bddb64" - -[[package]] -name = "remove_dir_all" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" -dependencies = [ - "winapi", -] - -[[package]] -name = "ron" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b861ecaade43ac97886a512b360d01d66be9f41f3c61088b42cedf92e03d678" -dependencies = [ - "base64", - "bitflags", - "serde", -] - -[[package]] -name = "rust-crypto" -version = "0.2.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f76d05d3993fd5f4af9434e8e436db163a12a9d40e1a58a726f27a01dfd12a2a" -dependencies = [ - "gcc", - "libc", - "rand 0.3.23", - "rustc-serialize", - "time", -] - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - -[[package]] -name = "rustc-rayon" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9974ab223660e61c1b4e7b43b827379df286736ca988308ce7e16f59f2d89246" -dependencies = [ - "crossbeam-deque", - "either", - "rustc-rayon-core", -] - -[[package]] -name = "rustc-rayon-core" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "564bfd27be8db888d0fa76aa4335e7851aaed0c2c11ad1e93aeb9349f6b88500" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", - "lazy_static", - "num_cpus", -] - -[[package]] -name = "rustc-serialize" -version = "0.3.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda" - -[[package]] -name = "rustc_data_structures" -version = "0.0.0" -dependencies = [ - "arrayvec", - "bitflags", - "cfg-if 0.1.10", - "ena", - "indexmap", - "jobserver", - "libc", - "memmap2", - "parking_lot", - "rustc-hash", - "rustc-rayon", - "rustc-rayon-core", - "stable_deref_trait", - "stacker", - "tempfile", - "tracing", - "winapi", -] - -[[package]] -name = "rustc_lexer" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c86aae0c77166108c01305ee1a36a1e77289d7dc6ca0a3cd91ff4992de2d16a5" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "rustc_span" -version = "0.0.0" -dependencies = [ - "cfg-if 0.1.10", - "md-5", - "rustc_data_structures", - "scoped-tls", - "sha-1", - "sha2 0.10.2", - "tracing", - "unicode-width", -] - -[[package]] -name = "ryu" -version = "1.0.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" - -[[package]] -name = "scoped-tls" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" - -[[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - -[[package]] -name = "serde" -version = "1.0.136" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.136" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.79" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e8d9fa5c3b304765ce1fd9c4c8a3de2c8db365a5b91be52f186efc675681d95" -dependencies = [ - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_yaml" -version = "0.8.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707d15895415db6628332b737c838b88c598522e4dc70647e59b72312924aebc" -dependencies = [ - "indexmap", - "ryu", - "serde", - "yaml-rust", -] - -[[package]] -name = "sha-1" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.3", -] - -[[package]] -name = "sha1" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" -dependencies = [ - "sha1_smol", -] - -[[package]] -name = "sha1_smol" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" - -[[package]] -name = "sha2" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.9.0", - "opaque-debug", -] - -[[package]] -name = "sha2" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.3", -] - -[[package]] -name = "siphasher" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bd3e3206899af3f8b12af284fafc038cc1dc2b41d1b89dd17297221c5d225de" - -[[package]] -name = "smallvec" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83" - -[[package]] -name = "stable_deref_trait" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" - -[[package]] -name = "stacker" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90939d5171a4420b3ff5fbc8954d641e7377335454c259dcb80786f3f21dc9b4" -dependencies = [ - "cc", - "cfg-if 1.0.0", - "libc", - "psm", - "winapi", -] - -[[package]] -name = "syn" -version = "1.0.91" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "synstructure" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "unicode-xid", -] - -[[package]] -name = "tempfile" -version = "3.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" -dependencies = [ - "cfg-if 1.0.0", - "fastrand", - "libc", - "redox_syscall", - "remove_dir_all", - "winapi", -] - -[[package]] -name = "termcolor" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "termize" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1706be6b564323ce7092f5f7e6b118a14c8ef7ed0e69c8c5329c914a9f101295" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "thiserror" -version = "1.0.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "time" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" -dependencies = [ - "libc", - "wasi", - "winapi", -] - -[[package]] -name = "toml" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" -dependencies = [ - "serde", -] - -[[package]] -name = "tracing" -version = "0.1.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0ecdcb44a79f0fe9844f0c4f33a342cbcbb5117de8001e6ba0dc2351327d09" -dependencies = [ - "cfg-if 1.0.0", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e65ce065b4b5c53e73bb28912318cb8c9e9ad3921f1d669eb0e68b4c8143a2b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tracing-core" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f54c8ca710e81886d498c2fd3331b56c93aa248d49de2222ad2742247c60072f" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "typenum" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" - -[[package]] -name = "unic-char-property" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" -dependencies = [ - "unic-char-range", -] - -[[package]] -name = "unic-char-range" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" - -[[package]] -name = "unic-common" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" - -[[package]] -name = "unic-emoji-char" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b07221e68897210270a38bde4babb655869637af0f69407f96053a34f76494d" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-bidi" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1d568b51222484e1f8209ce48caa6b430bf352962b877d592c29ab31fb53d8c" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-category" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b8d4591f5fcfe1bd4453baaf803c40e1b1e69ff8455c47620440b46efef91c0" -dependencies = [ - "matches", - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-version" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" -dependencies = [ - "unic-common", -] - -[[package]] -name = "unicode-casing" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "623f59e6af2a98bdafeb93fa277ac8e1e40440973001ca15cf4ae1541cd16d56" - -[[package]] -name = "unicode-width" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" - -[[package]] -name = "unicode-xid" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" - -[[package]] -name = "unicode_names2" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87d6678d7916394abad0d4b19df4d3802e1fd84abd7d701f39b75ee71b9e8cf1" - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "wasi" -version = "0.10.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" -dependencies = [ - "winapi", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-sys" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5acdd78cb4ba54c0045ac14f62d8f94a03d10047904ae2a40afa1e99d8f70825" -dependencies = [ - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17cffbe740121affb56fad0fc0e421804adf0ae00891205213b5cecd30db881d" - -[[package]] -name = "windows_i686_gnu" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2564fde759adb79129d9b4f54be42b32c89970c18ebf93124ca8870a498688ed" - -[[package]] -name = "windows_i686_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cd9d32ba70453522332c14d38814bceeb747d80b3958676007acadd7e166956" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfce6deae227ee8d356d19effc141a509cc503dfd1f850622ec4b0f84428e1f4" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d19538ccc21819d01deaf88d6a17eae6596a12e9aafdbb97916fb49896d89de9" - -[[package]] -name = "yaml-rust" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" -dependencies = [ - "linked-hash-map", -] diff --git a/kclvm/ast/Cargo.toml b/kclvm/ast/Cargo.toml deleted file mode 100644 index e76842ecd..000000000 --- a/kclvm/ast/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "kclvm-ast" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -uuid = { version = "1.4.1", features = ["v4"] } -compiler_base_span = "0.1.2" -serde = { version = "1", features = ["derive"] } -serde_json = "1.0" - -kclvm-span = { path = "../span" } -kclvm-error = { path = "../error" } -thread_local = "1.1.7" -kclvm-utils = {path = "../utils"} -anyhow = "1.0" - -[dev-dependencies] -kclvm-parser = { path = "../parser" } diff --git a/kclvm/ast/src/config.rs b/kclvm/ast/src/config.rs deleted file mode 100644 index 510805add..000000000 --- a/kclvm/ast/src/config.rs +++ /dev/null @@ -1,34 +0,0 @@ -use crate::ast; - -/// Try get a config expr mut ref from a expr if the expr is a schema or a config. -/// If not, return [None]. -/// TODO: use [TryInto]? -/// -/// # Examples -/// -/// ``` -/// use kclvm_parser::parse_expr; -/// use kclvm_ast::ast; -/// use kclvm_ast::config::try_get_config_expr_mut; -/// -/// let mut expr = parse_expr(r#"{ -/// a: {b: {c = 1}} -/// } -/// "#).unwrap(); -/// assert!(matches!(try_get_config_expr_mut(&mut expr.node), Some(_))); -/// let mut expr = parse_expr(r#"1"#).unwrap(); -/// assert!(matches!(try_get_config_expr_mut(&mut expr.node), None)); -/// ``` -pub fn try_get_config_expr_mut(expr: &mut ast::Expr) -> Option<&mut ast::ConfigExpr> { - match expr { - ast::Expr::Schema(schema_expr) => { - if let ast::Expr::Config(config_expr) = &mut schema_expr.config.node { - Some(config_expr) - } else { - None - } - } - ast::Expr::Config(config_expr) => Some(config_expr), - _ => None, - } -} diff --git a/kclvm/ast/src/path.rs b/kclvm/ast/src/path.rs deleted file mode 100644 index 4d8b06654..000000000 --- a/kclvm/ast/src/path.rs +++ /dev/null @@ -1,170 +0,0 @@ -use crate::ast; - -/// Get config key path from the AST key node and convert string-based AST nodes including -/// `ast::Expr::Identifier` and `ast::Expr::StringLit` to strings. -/// -/// # Examples -/// -/// ``` -/// use kclvm_ast::ast; -/// use kclvm_ast::path::get_key_path; -/// -/// let ident = Some(Box::new(ast::Node::dummy_node(ast::Expr::Identifier(ast::Identifier { -/// names: vec![ast::Node::dummy_node("alice".to_string())], -/// pkgpath: "".to_string(), -/// ctx: ast::ExprContext::Load, -/// })))); -/// assert_eq!(get_key_path(&ident), "alice"); -/// let str_lit = Some(Box::new(ast::Node::dummy_node(ast::Expr::StringLit(ast::StringLit { -/// is_long_string: false, -/// raw_value: "\"Alice\"".to_string(), -/// value: "Alice".to_string(), -/// })))); -/// assert_eq!(get_key_path(&str_lit), "Alice"); -/// ``` -#[inline] -pub fn get_key_path(key: &Option>) -> String { - match key { - Some(key) => match &key.node { - ast::Expr::Identifier(identifier) => identifier.get_name(), - ast::Expr::StringLit(string_lit) => string_lit.value.clone(), - _ => "".to_string(), - }, - None => "".to_string(), - } -} - -/// Get config key parts from the AST key node and convert string-based AST nodes including -/// `ast::Expr::Identifier` and `ast::Expr::StringLit` to strings. -#[inline] -pub fn get_key_parts(key: &Option>) -> Vec<&str> { - match key { - Some(key) => match &key.node { - ast::Expr::Identifier(identifier) => { - identifier.names.iter().map(|v| v.node.as_str()).collect() - } - ast::Expr::StringLit(string_lit) => vec![string_lit.value.as_str()], - _ => vec![], - }, - None => vec![], - } -} - -/// Get assign target path from the AST key node and convert string-based AST nodes including -/// `ast::Expr::Identifier` and `ast::Expr::StringLit` to strings. -/// -/// # Examples -/// -/// ``` -/// use kclvm_ast::ast; -/// use kclvm_ast::path::get_target_path; -/// -/// let target = ast::Target { -/// name: ast::Node::dummy_node("alice".to_string()), -/// paths: vec![], -/// pkgpath: "".to_string(), -/// }; -/// assert_eq!(get_target_path(&target), "alice"); -/// ``` -#[inline] -pub fn get_target_path(key: &ast::Target) -> String { - let mut result = key.name.node.to_string(); - for path in &key.paths { - match path { - ast::MemberOrIndex::Member(member) => { - result.push('.'); - result.push_str(&member.node); - } - ast::MemberOrIndex::Index(index) => { - result.push('['); - match &index.node { - ast::Expr::Unary(unary_expr) => match &unary_expr.operand.node { - ast::Expr::NumberLit(number) => { - result.push_str(&unary_expr.op.symbol()); - result.push_str(&number.to_string()); - } - _ => { - result.push_str("..."); - } - }, - ast::Expr::NumberLit(number) => { - result.push_str(&number.to_string()); - } - ast::Expr::StringLit(string_lit) => { - result.push_str(&format!("{:?}", string_lit.value)); - } - _ => { - result.push_str("..."); - } - } - result.push(']'); - } - } - } - result -} - -/// Get all attribute paths recursively from a config expression AST node. -/// -/// # Examples -/// -/// ``` -/// use kclvm_parser::parse_expr; -/// use kclvm_ast::ast; -/// use kclvm_ast::path::get_attr_paths_from_config_expr; -/// -/// let expr = parse_expr(r#"{ -/// a: {b: {c = 1}} -/// } -/// "#).unwrap(); -/// if let ast::Expr::Config(config_expr) = &expr.node { -/// assert_eq!(get_attr_paths_from_config_expr(&config_expr), vec![ -/// "a".to_string(), -/// "a.b".to_string(), -/// "a.b.c".to_string(), -/// ]) -/// } else { -/// panic!("invalid config expr {:?}", expr) -/// } -/// ``` -pub fn get_attr_paths_from_config_expr(config: &ast::ConfigExpr) -> Vec { - let mut paths = vec![]; - for entry in &config.items { - let mut entry_paths = get_entry_paths(&entry.node); - paths.append(&mut entry_paths); - } - paths -} - -/// Get all attribute paths from a config entry. -fn get_entry_paths(entry: &ast::ConfigEntry) -> Vec { - let mut paths = vec![]; - let path = get_key_path(&entry.key); - if path.is_empty() || path.trim().is_empty() { - return paths; - } - paths.push(path.clone()); - let option_config_expr = match &entry.value.node { - ast::Expr::Schema(schema_expr) => { - if let ast::Expr::Config(config_expr) = &schema_expr.config.node { - Some(config_expr) - } else { - None - } - } - ast::Expr::Config(config_expr) => Some(config_expr), - _ => None, - }; - if let Some(config_expr) = option_config_expr { - let value_paths = get_attr_paths_from_config_expr(config_expr); - if !value_paths.is_empty() { - paths.append( - &mut value_paths - .iter() - .map(|value_path| format!("{}.{}", path, value_path)) - .collect::>(), - ); - } - } - paths -} diff --git a/kclvm/ast/src/tests.rs b/kclvm/ast/src/tests.rs deleted file mode 100644 index 71cad0033..000000000 --- a/kclvm/ast/src/tests.rs +++ /dev/null @@ -1,276 +0,0 @@ -use crate::node_ref; -use crate::walker::MutSelfMutWalker; -use crate::{ast, ast::*}; - -/// Construct an AssignStmt node with assign_value as value -fn build_assign_node(attr_name: &str, assign_value: NodeRef) -> NodeRef { - let target = node_ref!(Target { - name: Node::dummy_node(attr_name.to_string()), - paths: vec![], - pkgpath: "".to_string() - }); - - node_ref!(Stmt::Assign(AssignStmt { - value: assign_value, - targets: vec![target], - ty: None - })) -} - -fn get_dummy_assign_ast() -> ast::Node { - let filename = "main.k"; - let line = 1; - let column = 1; - let end_line = 1; - let end_column = 2; - ast::Node::new( - ast::AssignStmt { - targets: vec![Box::new(ast::Node::new( - ast::Target { - name: Node::dummy_node(String::from("a")), - paths: vec![], - pkgpath: "".to_string(), - }, - String::from(filename), - line, - column, - end_line, - end_column, - ))], - value: Box::new(ast::Node::new( - ast::Expr::StringLit(ast::StringLit { - is_long_string: false, - raw_value: String::from("s"), - value: String::from("s"), - }), - String::from(filename), - line, - column, - end_line, - end_column, - )), - ty: None, - }, - String::from(filename), - line, - column, - end_line, - end_column, - ) -} - -fn get_dummy_assign_binary_ast() -> ast::Node { - let filename = "main.k"; - let line = 1; - let column = 1; - let end_line = 1; - let end_column = 2; - ast::Node::new( - ast::AssignStmt { - targets: vec![Box::new(ast::Node::new( - ast::Target { - name: Node::dummy_node(String::from("a")), - paths: vec![], - pkgpath: "".to_string(), - }, - String::from(filename), - line, - column, - end_line, - end_column, - ))], - value: Box::new(ast::Node::new( - ast::Expr::Binary(ast::BinaryExpr { - op: ast::BinOp::Add, - left: Box::new(ast::Node::new( - ast::Expr::Identifier(ast::Identifier { - names: vec![Node::dummy_node(String::from("a"))], - pkgpath: String::from(filename), - ctx: ast::ExprContext::Load, - }), - String::from(filename), - line, - column, - end_line, - end_column, - )), - right: Box::new(ast::Node::new( - ast::Expr::Identifier(ast::Identifier { - names: vec![Node::dummy_node(String::from("a"))], - pkgpath: String::from(filename), - ctx: ast::ExprContext::Load, - }), - String::from(filename), - line, - column, - end_line, - end_column, - )), - }), - String::from(filename), - line, - column, - end_line, - end_column, - )), - ty: None, - }, - String::from(filename), - line, - column, - end_line, - end_column, - ) -} - -#[test] -fn test_ast_print_assign() { - let assign_stmt = get_dummy_assign_ast(); - println!("{:?}", assign_stmt); - let json_str = serde_json::to_string(&assign_stmt).unwrap(); - println!("{:?}", json_str); -} - -#[test] -fn test_ast_print_assign_binary() { - let assign_stmt = get_dummy_assign_binary_ast(); - println!("{:?}", assign_stmt); - let json_str = serde_json::to_string(&assign_stmt).unwrap(); - println!("{:?}", json_str); -} - -#[test] -fn test_mut_walker() { - pub struct VarMutSelfMutWalker; - impl<'ctx> MutSelfMutWalker<'ctx> for VarMutSelfMutWalker { - fn walk_target(&mut self, target: &'ctx mut ast::Target) { - if target.name.node == "a" { - target.name.node = "x".to_string(); - } - } - } - let mut assign_stmt = get_dummy_assign_ast(); - VarMutSelfMutWalker {}.walk_assign_stmt(&mut assign_stmt.node); - assert_eq!(assign_stmt.node.targets[0].node.name.node, "x") -} - -#[test] -fn test_try_from_for_stringlit() { - let str_lit = ast::StringLit::try_from("test_str".to_string()).unwrap(); - let json_str = serde_json::to_string(&str_lit).unwrap(); - - let str_expected = - r#"{"is_long_string":false,"raw_value":"\"test_str\"","value":"test_str"}"#.to_string(); - assert_eq!(str_expected, json_str); -} - -#[test] -fn test_try_from_for_nameconstant() { - let name_cons = ast::NameConstant::try_from(true).unwrap(); - let json_str = serde_json::to_string(&name_cons).unwrap(); - assert_eq!("\"True\"", json_str); - - let name_cons = ast::NameConstant::try_from(false).unwrap(); - let json_str = serde_json::to_string(&name_cons).unwrap(); - assert_eq!("\"False\"", json_str); -} - -#[test] -fn test_filter_schema_with_no_schema() { - let ast_mod = Module { - filename: "".to_string(), - doc: Some(node_ref!("".to_string())), - body: vec![], - comments: vec![], - }; - let schema_stmts = ast_mod.filter_schema_stmt_from_module(); - assert_eq!(schema_stmts.len(), 0); -} - -#[test] -fn test_filter_schema_with_one_schema() { - let mut ast_mod = Module { - filename: "".to_string(), - doc: Some(node_ref!("".to_string())), - body: vec![], - comments: vec![], - }; - let mut gen_schema_stmts = gen_schema_stmt(1); - ast_mod.body.append(&mut gen_schema_stmts); - let schema_stmts = ast_mod.filter_schema_stmt_from_module(); - assert_eq!(schema_stmts.len(), 1); - assert_eq!(schema_stmts[0].node.name.node, "schema_stmt_0".to_string()); -} - -#[test] -fn test_filter_schema_with_mult_schema() { - let mut ast_mod = Module { - filename: "".to_string(), - doc: Some(node_ref!("".to_string())), - body: vec![], - comments: vec![], - }; - let mut gen_schema_stmts = gen_schema_stmt(10); - ast_mod.body.append(&mut gen_schema_stmts); - let schema_stmts = ast_mod.filter_schema_stmt_from_module(); - assert_eq!(schema_stmts.len(), 10); - for i in 0..10 { - assert_eq!( - schema_stmts[i].node.name.node, - "schema_stmt_".to_string() + &i.to_string() - ) - } -} - -#[test] -fn test_build_assign_stmt() { - let test_expr = node_ref!(ast::Expr::Identifier(Identifier { - names: vec![ - Node::dummy_node("name1".to_string()), - Node::dummy_node("name2".to_string()) - ], - pkgpath: "test".to_string(), - ctx: ast::ExprContext::Load - })); - let assgin_stmt = build_assign_node("test_attr_name", test_expr); - - if let ast::Stmt::Assign(ref assign) = assgin_stmt.node { - if let ast::Expr::Identifier(ref iden) = &assign.value.node { - assert_eq!(iden.names.len(), 2); - assert_eq!(iden.names[0].node, "name1".to_string()); - assert_eq!(iden.names[1].node, "name2".to_string()); - assert_eq!(iden.pkgpath, "test".to_string()); - match iden.ctx { - ast::ExprContext::Load => {} - _ => { - assert!(false); - } - } - } else { - assert!(false); - } - } else { - assert!(false); - } -} - -fn gen_schema_stmt(count: i32) -> Vec> { - let mut schema_stmts = Vec::new(); - for c in 0..count { - schema_stmts.push(node_ref!(ast::Stmt::Schema(SchemaStmt { - doc: Some(node_ref!("".to_string())), - name: node_ref!("schema_stmt_".to_string() + &c.to_string()), - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: vec![], - body: vec![], - decorators: vec![], - checks: vec![], - index_signature: None - }))) - } - schema_stmts -} diff --git a/kclvm/ast_pretty/Cargo.toml b/kclvm/ast_pretty/Cargo.toml deleted file mode 100644 index 9a6b3728d..000000000 --- a/kclvm/ast_pretty/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "kclvm-ast-pretty" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -kclvm-error = { path = "../error" } -kclvm-ast = { path = "../ast" } -kclvm-primitives = { path = "../primitives" } - -fancy-regex = "0.7.1" -pretty_assertions = "1.3.0" -compiler_base_session = "0.1.3" -compiler_base_macros = "0.1.1" - -[dev-dependencies] -kclvm-parser = { path = "../parser" } diff --git a/kclvm/ast_pretty/src/lib.rs b/kclvm/ast_pretty/src/lib.rs deleted file mode 100644 index 18b95ce2d..000000000 --- a/kclvm/ast_pretty/src/lib.rs +++ /dev/null @@ -1,354 +0,0 @@ -use kclvm_ast::{ - ast::{self, Module}, - token::TokenKind, - walker::MutSelfTypedResultWalker, -}; -use kclvm_primitives::IndexMap; -use std::collections::VecDeque; -mod node; - -#[cfg(test)] -mod tests; - -pub const WHITESPACE: &str = " "; -pub const TAB: &str = "\t"; -pub const NEWLINE: &str = "\n"; - -#[derive(Debug, Clone)] -pub enum Indentation { - Indent = 0, - Dedent = 1, - Newline = 2, - IndentWithNewline = 3, - DedentWithNewline = 4, - Fill = 5, -} - -/// Printer config -#[derive(Debug)] -pub struct Config { - pub tab_len: usize, - pub indent_len: usize, - pub use_spaces: bool, - pub write_comments: bool, -} - -impl Default for Config { - fn default() -> Self { - Self { - tab_len: 4, - indent_len: 4, - use_spaces: true, - write_comments: true, - } - } -} - -#[derive(Copy, Clone)] -pub struct NoHook; - -impl PrinterHook for NoHook {} - -pub enum ASTNode<'p> { - Stmt(&'p ast::NodeRef), - Expr(&'p ast::NodeRef), -} - -pub trait PrinterHook { - fn pre(&self, _printer: &mut Printer<'_>, _node: ASTNode<'_>) {} - fn post(&self, _printer: &mut Printer<'_>, _node: ASTNode<'_>) {} -} - -pub struct Printer<'p> { - /// Output string buffer. - pub out: String, - pub indent: usize, - pub cfg: Config, - /// Print comments, - pub comments: VecDeque>, - pub import_spec: IndexMap, - pub hook: &'p (dyn PrinterHook + 'p), - /// Last AST expr/stmt line, default is 0. - last_ast_line: u64, - /// Stack of the current expression span (start_line, end_line). - expr_span_stack: Vec<(u64, u64)>, -} - -impl Default for Printer<'_> { - fn default() -> Self { - Self { - hook: &NoHook, - out: Default::default(), - indent: Default::default(), - cfg: Default::default(), - comments: Default::default(), - import_spec: Default::default(), - last_ast_line: Default::default(), - expr_span_stack: Default::default(), - } - } -} - -impl<'p> Printer<'p> { - pub fn new(cfg: Config, hook: &'p (dyn PrinterHook + 'p)) -> Self { - Self { - out: "".to_string(), - indent: 0, - cfg, - comments: VecDeque::default(), - import_spec: IndexMap::default(), - hook, - last_ast_line: 0, - expr_span_stack: Vec::default(), - } - } - - // -------------------------- - // Write functions - // -------------------------- - - /// Write a string - #[inline] - pub fn write(&mut self, text: &str) { - self.write_string(text); - } - - /// Write a string with newline. - #[inline] - pub fn writeln(&mut self, text: &str) { - self.write_string(text); - self.write_string(NEWLINE); - self.fill(""); - } - - /// Write a space. - #[inline] - pub fn write_space(&mut self) { - self.write_string(WHITESPACE); - } - - /// Fill a indent - pub fn fill(&mut self, text: &str) { - if self.cfg.use_spaces { - self.write(&format!( - "{}{}", - WHITESPACE.repeat(self.indent * self.cfg.indent_len), - text - )); - } else { - self.write(&format!("{}{}", TAB.repeat(self.indent), text)); - } - } - - /// Print string - #[inline] - pub fn write_string(&mut self, string: &str) { - self.out.push_str(string); - } - - pub fn write_indentation(&mut self, indentation: Indentation) { - match indentation { - Indentation::Indent => self.enter(), - Indentation::Dedent => self.leave(), - Indentation::Newline => self.write_newline(), - Indentation::IndentWithNewline => { - self.enter(); - self.write_newline() - } - Indentation::DedentWithNewline => { - self.leave(); - self.write_newline(); - } - Indentation::Fill => self.fill(""), - } - } - - #[inline] - pub fn write_newline(&mut self) { - self.writeln("") - } - - #[inline] - pub fn write_newline_without_fill(&mut self) { - self.write_string(NEWLINE); - } - - /// Print value - #[inline] - pub fn write_value(&mut self, value: T) { - self.write(&format!("{}", value)); - } - - /// Print ast token - #[inline] - pub fn write_token(&mut self, tok: TokenKind) { - let tok_str: String = tok.into(); - self.write_string(&tok_str); - } - - /// Print ast node - #[inline] - pub fn write_node(&mut self, node: ASTNode<'_>) { - match node { - ASTNode::Stmt(stmt) => self.stmt(stmt), - ASTNode::Expr(expr) => self.expr(expr), - } - } - - /// Print ast module. - #[inline] - pub fn write_module(&mut self, module: &ast::Module) { - self.walk_module(module); - while let Some(comment) = self.comments.pop_front() { - self.writeln(&comment.node.text); - self.fill(""); - } - } - - /// Wether has comments on ast node. - pub(crate) fn has_comments_on_node(&mut self, node: &ast::NodeRef) -> bool { - if !self.cfg.write_comments { - return false; - } - let mut index = None; - for (i, comment) in self.comments.iter().enumerate() { - if comment.line <= node.line { - index = Some(i); - } else { - break; - } - } - index.is_some() - } - - /// Print ast comments. - pub fn update_last_ast_line(&mut self, node: &ast::NodeRef) { - if node.line > self.last_ast_line { - self.last_ast_line = node.line; - } - } - - /// Print ast comments. - pub fn write_comments_before_node(&mut self, node: &ast::NodeRef) { - if !self.cfg.write_comments { - return; - } - if node.line > self.last_ast_line { - self.last_ast_line = node.line; - let mut index = None; - for (i, comment) in self.comments.iter().enumerate() { - if comment.line <= node.line { - index = Some(i); - } else { - break; - } - } - if let Some(index) = index { - let mut count = index as isize; - while count >= 0 { - match self.comments.pop_front() { - Some(comment) => { - self.writeln(&comment.node.text); - match self.comments.front() { - Some(next_comment) => { - if next_comment.line >= comment.line + 2 && count > 0 { - self.write_newline(); - } - } - None => {} - } - } - None => break, - } - count -= 1; - } - } - } - } - - pub fn write_comments_until_line(&mut self, line: u64) { - if !self.cfg.write_comments || line == 0 { - return; - } - - let mut comments_written = 0; - while let Some(comment) = self.comments.front() { - if comment.line == 0 || comment.line > line { - break; - } - - let comment = self.comments.pop_front().unwrap(); - - // Add newline before first comment if not already at line start - if comments_written == 0 && !self.out.ends_with('\n') { - self.write_newline_without_fill(); - } - - self.fill(""); - self.write(&comment.node.text); - self.write_newline_without_fill(); - - // Add extra newline if next comment is 2+ lines away - if let Some(next) = self.comments.front() { - if next.line >= comment.line + 2 && next.line <= line { - self.write_newline_without_fill(); - } - } - - self.last_ast_line = self.last_ast_line.max(comment.line); - comments_written += 1; - } - - // Remove trailing newline if we wrote any comments - if comments_written > 0 && self.out.ends_with('\n') { - self.out.pop(); - } - } - - // -------------------------- - // Indent and scope functions - // -------------------------- - - /// Enter with a indent - pub fn enter(&mut self) { - self.indent += 1; - } - - /// Leave with a dedent - pub fn leave(&mut self) { - self.indent -= 1; - } - - pub(crate) fn push_expr_span(&mut self, start_line: u64, end_line: u64) { - self.expr_span_stack.push((start_line, end_line)); - } - - pub(crate) fn pop_expr_span(&mut self) { - self.expr_span_stack.pop(); - } - - pub(crate) fn current_expr_end_line(&self) -> Option { - self.expr_span_stack.last().map(|(_, end_line)| *end_line) - } -} - -/// Print AST to string. The default format is according to the KCL code style defined here: https://kcl-lang.io/docs/reference/lang/spec/codestyle -pub fn print_ast_module(module: &Module) -> String { - let mut printer = Printer::default(); - printer.write_module(module); - printer.out -} - -/// Print AST to string -pub fn print_ast_node(node: ASTNode) -> String { - let mut printer = Printer::default(); - printer.write_node(node); - printer.out -} - -/// Print schema expression AST node to string. -pub fn print_schema_expr(schema_expr: &ast::SchemaExpr) -> String { - let mut printer = Printer::default(); - printer.walk_schema_expr(schema_expr); - printer.out -} diff --git a/kclvm/ast_pretty/src/node.rs b/kclvm/ast_pretty/src/node.rs deleted file mode 100644 index 5c1ff63ce..000000000 --- a/kclvm/ast_pretty/src/node.rs +++ /dev/null @@ -1,1022 +0,0 @@ -use std::collections::HashSet; - -use compiler_base_macros::bug; -use kclvm_ast::{ - ast::{self, CallExpr}, - token::{DelimToken, TokenKind}, - walker::MutSelfTypedResultWalker, -}; - -use super::{Indentation, Printer}; - -type ParameterType<'a> = ( - (&'a ast::NodeRef, Option), - &'a Option>, -); - -const COMMA_WHITESPACE: &str = ", "; -const IDENTIFIER_REGEX: &str = r#"^\$?[a-zA-Z_]\w*$"#; - -macro_rules! interleave { - ($inter: expr, $f: expr, $seq: expr) => { - if !$seq.is_empty() { - $f(&$seq[0]); - for s in &$seq[1..] { - $inter(); - $f(s); - } - } - }; -} - -impl<'p, 'ctx> MutSelfTypedResultWalker<'ctx> for Printer<'p> { - type Result = (); - - fn walk_module(&mut self, module: &'ctx ast::Module) -> Self::Result { - for comment in &module.comments { - self.comments.push_back(comment.clone()); - } - if let Some(doc) = &module.doc { - self.write(&doc.node); - self.write_newline(); - self.write_newline(); - } - - self.stmts(&module.body); - } - - fn walk_expr_stmt(&mut self, expr_stmt: &'ctx ast::ExprStmt) -> Self::Result { - interleave!( - || self.write(COMMA_WHITESPACE), - |expr| self.expr(expr), - expr_stmt.exprs - ); - self.write_newline_without_fill(); - } - - fn walk_unification_stmt( - &mut self, - unification_stmt: &'ctx ast::UnificationStmt, - ) -> Self::Result { - self.walk_identifier(&unification_stmt.target.node); - self.write(": "); - self.walk_schema_expr(&unification_stmt.value.node); - self.write_newline_without_fill(); - } - - fn walk_type_alias_stmt(&mut self, type_alias_stmt: &'ctx ast::TypeAliasStmt) -> Self::Result { - self.write("type"); - self.write_space(); - self.walk_identifier(&type_alias_stmt.type_name.node); - self.write(" = "); - self.write(&type_alias_stmt.type_value.node); - self.write_newline_without_fill(); - } - - fn walk_assign_stmt(&mut self, assign_stmt: &'ctx ast::AssignStmt) -> Self::Result { - for (i, target) in assign_stmt.targets.iter().enumerate() { - self.walk_target(&target.node); - if i == 0 { - if let Some(ty) = &assign_stmt.ty { - self.write(": "); - self.write(&ty.node.to_string()); - } - } - self.write(" = "); - } - self.expr(&assign_stmt.value); - self.write_newline_without_fill(); - } - - fn walk_aug_assign_stmt(&mut self, aug_assign_stmt: &'ctx ast::AugAssignStmt) -> Self::Result { - self.walk_target(&aug_assign_stmt.target.node); - self.write_space(); - self.write(aug_assign_stmt.op.symbol()); - self.write_space(); - self.expr(&aug_assign_stmt.value); - self.write_newline_without_fill(); - } - - fn walk_assert_stmt(&mut self, assert_stmt: &'ctx ast::AssertStmt) -> Self::Result { - self.write("assert "); - self.expr(&assert_stmt.test); - if let Some(if_cond) = &assert_stmt.if_cond { - self.write(" if "); - self.expr(if_cond); - } - if let Some(msg) = &assert_stmt.msg { - self.write(COMMA_WHITESPACE); - self.expr(msg); - } - self.write_newline_without_fill(); - } - - fn walk_if_stmt(&mut self, if_stmt: &'ctx ast::IfStmt) -> Self::Result { - self.write("if "); - self.expr(&if_stmt.cond); - self.write_token(TokenKind::Colon); - self.write_newline_without_fill(); - self.write_indentation(Indentation::Indent); - self.stmts(&if_stmt.body); - self.write_indentation(Indentation::Dedent); - - if !if_stmt.orelse.is_empty() { - // Check if orelse contains exactly one if statement - if if_stmt.orelse.len() == 1 { - if let ast::Stmt::If(elif_stmt) = &if_stmt.orelse[0].node { - // Nested if statements need to be considered, - // so `el` needs to be preceded by the current indentation. - self.fill("el"); - self.walk_if_stmt(elif_stmt); - } else { - self.fill("else:"); - self.write_newline_without_fill(); - self.write_indentation(Indentation::Indent); - self.stmts(&if_stmt.orelse); - self.write_indentation(Indentation::Dedent); - } - } else { - // Handle multiple else statements - self.fill("else:"); - self.write_newline_without_fill(); - self.write_indentation(Indentation::Indent); - self.stmts(&if_stmt.orelse); - self.write_indentation(Indentation::Dedent); - } - } else { - self.write_newline_without_fill(); - } - } - - fn walk_import_stmt(&mut self, import_stmt: &'ctx ast::ImportStmt) -> Self::Result { - self.write("import "); - // use `import_stmt.rawpath` to write the raw path - // otherwise, use `import_stmt.path` will replace `import .xxx` with `import xxx` - self.write(&import_stmt.rawpath); - if let Some(as_name) = &import_stmt.asname { - self.write(" as "); - self.write(&as_name.node); - } - self.write_newline_without_fill(); - } - - fn walk_schema_stmt(&mut self, schema_stmt: &'ctx ast::SchemaStmt) -> Self::Result { - interleave!( - || self.write_newline(), - |expr: &ast::NodeRef| { - self.write_comments_before_node(&expr); - self.write("@"); - self.walk_call_expr(&expr.node); - }, - schema_stmt.decorators - ); - if !schema_stmt.decorators.is_empty() { - self.write_newline(); - } - if schema_stmt.is_mixin { - self.write("mixin "); - } else if schema_stmt.is_protocol { - self.write("protocol "); - } else { - self.write("schema "); - } - self.write(&schema_stmt.name.node); - if let Some(args) = &schema_stmt.args { - self.write("["); - self.walk_arguments(&args.node); - self.write("]"); - } - if let Some(parent_name) = &schema_stmt.parent_name { - self.write("("); - self.walk_identifier(&parent_name.node); - self.write(")"); - } - if let Some(host_name) = &schema_stmt.for_host_name { - self.write(" for "); - self.walk_identifier(&host_name.node); - } - self.write_token(TokenKind::Colon); - self.write_newline_without_fill(); - self.write_indentation(Indentation::Indent); - - if let Some(doc) = &schema_stmt.doc { - self.fill(""); - self.write(&doc.node); - self.write_newline_without_fill(); - } - - if !schema_stmt.mixins.is_empty() { - self.fill(""); - self.write("mixin ["); - self.write_indentation(Indentation::IndentWithNewline); - interleave!( - || { - self.write(","); - self.write_newline(); - }, - |mixin_name: &ast::NodeRef| { - self.write_comments_before_node(&mixin_name); - self.walk_identifier(&mixin_name.node); - }, - schema_stmt.mixins - ); - self.write_indentation(Indentation::Dedent); - self.write_newline(); - self.write("]"); - self.write_newline_without_fill(); - } - if let Some(index_signature) = &schema_stmt.index_signature { - self.fill(""); - self.write_comments_before_node(index_signature); - self.write_token(TokenKind::OpenDelim(DelimToken::Bracket)); - if index_signature.node.any_other { - self.write_token(TokenKind::DotDotDot); - } - if let Some(key_name) = &index_signature.node.key_name { - self.write(&format!("{}: ", key_name.node)); - } - self.write(&index_signature.node.key_ty.node.to_string()); - self.write_token(TokenKind::CloseDelim(DelimToken::Bracket)); - self.write_token(TokenKind::Colon); - self.write_space(); - self.write(&index_signature.node.value_ty.node.to_string()); - if let Some(value) = &index_signature.node.value { - self.write(" = "); - self.expr(value); - } - self.write_newline_without_fill(); - } - self.stmts(&schema_stmt.body); - self.write_newline_without_fill(); - if !schema_stmt.checks.is_empty() { - self.fill("check:"); - // Schema check indent - self.write_indentation(Indentation::IndentWithNewline); - interleave!( - || self.write_newline(), - |check_expr: &ast::NodeRef| { - self.write_comments_before_node(&check_expr); - self.walk_check_expr(&check_expr.node); - }, - schema_stmt.checks - ); - self.write_newline_without_fill(); - // Schema check dedent - self.write_indentation(Indentation::Dedent); - self.write_newline_without_fill(); - } - // Schema Stmt dedent - self.write_indentation(Indentation::Dedent); - } - - fn walk_rule_stmt(&mut self, rule_stmt: &'ctx ast::RuleStmt) -> Self::Result { - interleave!( - || self.write_newline(), - |expr: &ast::NodeRef| { - self.write("@"); - self.walk_call_expr(&expr.node); - }, - rule_stmt.decorators - ); - if !rule_stmt.decorators.is_empty() { - self.write_newline(); - } - self.write("rule "); - self.write(&rule_stmt.name.node); - if let Some(args) = &rule_stmt.args { - self.write("["); - self.walk_arguments(&args.node); - self.write("]"); - } - if !rule_stmt.parent_rules.is_empty() { - self.write("("); - interleave!( - || self.write(COMMA_WHITESPACE), - |identifier: &ast::NodeRef| self.walk_identifier(&identifier.node), - rule_stmt.parent_rules - ); - self.write(")"); - } - if let Some(host_name) = &rule_stmt.for_host_name { - self.write(" for "); - self.walk_identifier(&host_name.node); - } - self.write_token(TokenKind::Colon); - // Rule Stmt indent - self.write_indentation(Indentation::IndentWithNewline); - if let Some(doc) = &rule_stmt.doc { - self.write(&doc.node); - self.write_newline(); - } - if !rule_stmt.checks.is_empty() { - interleave!( - || self.write_newline(), - |check_expr: &ast::NodeRef| { - self.write_comments_before_node(&check_expr); - self.walk_check_expr(&check_expr.node); - }, - rule_stmt.checks - ); - self.write_newline_without_fill(); - } - // Rule Stmt dedent - self.write_indentation(Indentation::Dedent); - } - - fn walk_quant_expr(&mut self, quant_expr: &'ctx ast::QuantExpr) -> Self::Result { - let in_one_line = self.last_ast_line > 0 && quant_expr.test.line == self.last_ast_line; - let quant_op_string: String = quant_expr.op.clone().into(); - self.write(&quant_op_string); - self.write_space(); - interleave!( - || self.write(COMMA_WHITESPACE), - |identifier: &ast::NodeRef| self.walk_identifier(&identifier.node), - quant_expr.variables - ); - self.write(" in "); - self.expr(&quant_expr.target); - self.write(" {"); - if !in_one_line { - self.write_indentation(Indentation::IndentWithNewline); - } - self.expr(&quant_expr.test); - if let Some(if_cond) = &quant_expr.if_cond { - self.write(" if "); - self.expr(if_cond); - } - if !in_one_line { - self.write_indentation(Indentation::DedentWithNewline) - } - self.write("}") - } - - fn walk_schema_attr(&mut self, schema_attr: &'ctx ast::SchemaAttr) -> Self::Result { - interleave!( - || self.write_newline(), - |expr: &ast::NodeRef| { - self.write_comments_before_node(&expr); - self.write("@"); - self.walk_call_expr(&expr.node) - }, - schema_attr.decorators - ); - if !schema_attr.decorators.is_empty() { - self.write_newline(); - } - // A schema string attribute needs quote. - if !schema_attr.is_ident_attr() { - self.write(&format!("{:?}", schema_attr.name.node)); - } else { - self.write_attribute(&schema_attr.name); - } - if schema_attr.is_optional { - self.write("?"); - } - self.write(": "); - self.write(&schema_attr.ty.node.to_string()); - if let Some(op) = &schema_attr.op { - let symbol = op.symbol(); - self.write_space(); - self.write(symbol); - self.write_space(); - } - if let Some(value) = &schema_attr.value { - self.expr(value); - } - self.write_newline_without_fill(); - } - - fn walk_if_expr(&mut self, if_expr: &'ctx ast::IfExpr) -> Self::Result { - self.expr(&if_expr.body); - self.write(" if "); - self.expr(&if_expr.cond); - self.write(" else "); - self.expr(&if_expr.orelse); - } - - fn walk_unary_expr(&mut self, unary_expr: &'ctx ast::UnaryExpr) -> Self::Result { - self.write(unary_expr.op.symbol()); - // Four forms: `+expr`, `-expr`, `~expr`, `not expr` - // `not expr` needs a space between `not` and `expr` - if matches!(unary_expr.op, ast::UnaryOp::Not) { - self.write_space(); - } - self.expr(&unary_expr.operand); - } - - fn walk_binary_expr(&mut self, binary_expr: &'ctx ast::BinaryExpr) -> Self::Result { - let symbol = binary_expr.op.symbol(); - self.expr(&binary_expr.left); - self.write_space(); - self.write(symbol); - self.write_space(); - self.expr(&binary_expr.right); - } - - fn walk_selector_expr(&mut self, selector_expr: &'ctx ast::SelectorExpr) -> Self::Result { - self.expr(&selector_expr.value); - self.write(if selector_expr.has_question { - "?." - } else { - "." - }); - self.walk_identifier(&selector_expr.attr.node); - } - - fn walk_call_expr(&mut self, call_expr: &'ctx ast::CallExpr) -> Self::Result { - self.expr(&call_expr.func); - self.write("("); - self.write_args_and_kwargs(&call_expr.args, &call_expr.keywords); - self.write(")"); - } - - fn walk_subscript(&mut self, subscript: &'ctx ast::Subscript) -> Self::Result { - self.expr(&subscript.value); - if subscript.has_question { - self.write("?"); - } - self.write("["); - if let Some(index) = &subscript.index { - self.expr(index); - } else { - if let Some(lower) = &subscript.lower { - self.expr(lower); - } - self.write_token(TokenKind::Colon); - if let Some(upper) = &subscript.upper { - self.expr(upper); - } - self.write_token(TokenKind::Colon); - if let Some(step) = &subscript.step { - self.expr(step); - } - } - self.write("]"); - } - - fn walk_paren_expr(&mut self, paren_expr: &'ctx ast::ParenExpr) -> Self::Result { - self.write_token(TokenKind::OpenDelim(DelimToken::Paren)); - self.expr(&paren_expr.expr); - self.write_token(TokenKind::CloseDelim(DelimToken::Paren)); - } - - fn walk_list_expr(&mut self, list_expr: &'ctx ast::ListExpr) -> Self::Result { - let mut line_set = list_expr - .elts - .iter() - .map(|e| e.line) - .filter(|l| *l > 0) - .collect::>(); - if self.last_ast_line > 0 { - line_set.insert(self.last_ast_line); - } - // There are comments in the configuration block. - let has_comment = !list_expr.elts.is_empty() - && list_expr - .elts - .iter() - .map(|e| self.has_comments_on_node(e)) - .all(|r| r); - // When there are comments in the configuration block, print them as multiline configurations. - let mut in_one_line = line_set.len() <= 1 && !has_comment; - if let Some(elt) = list_expr.elts.first() { - if let ast::Expr::ListIfItem(_) = &elt.node { - in_one_line = false; - } - } - self.write_token(TokenKind::OpenDelim(DelimToken::Bracket)); - if !in_one_line { - self.write_indentation(Indentation::IndentWithNewline); - } - interleave!( - || if in_one_line { - self.write(COMMA_WHITESPACE); - } else { - self.write_newline(); - }, - |elt| { - self.write_comments_before_node(elt); - self.expr(elt); - }, - list_expr.elts - ); - if !in_one_line { - if let Some(end_line) = self.current_expr_end_line() { - self.write_comments_until_line(end_line.saturating_sub(1)); - } - self.write_indentation(Indentation::DedentWithNewline); - } - self.write_token(TokenKind::CloseDelim(DelimToken::Bracket)); - } - - fn walk_list_comp(&mut self, list_comp: &'ctx ast::ListComp) -> Self::Result { - self.write_token(TokenKind::OpenDelim(DelimToken::Bracket)); - self.expr(&list_comp.elt); - for gen in &list_comp.generators { - self.walk_comp_clause(&gen.node); - } - self.write_token(TokenKind::CloseDelim(DelimToken::Bracket)); - } - - fn walk_list_if_item_expr( - &mut self, - list_if_item_expr: &'ctx ast::ListIfItemExpr, - ) -> Self::Result { - self.write("if "); - self.expr(&list_if_item_expr.if_cond); - self.write(":"); - self.write_indentation(Indentation::IndentWithNewline); - interleave!( - || self.write_newline(), - |expr| { - self.write_comments_before_node(expr); - self.expr(expr); - }, - list_if_item_expr.exprs - ); - self.write_indentation(Indentation::Dedent); - if let Some(orelse) = &list_if_item_expr.orelse { - self.write_newline(); - match &orelse.node { - ast::Expr::List(list_expr) => { - self.write("else:"); - self.write_indentation(Indentation::IndentWithNewline); - interleave!( - || self.write_newline(), - |expr| { - self.write_comments_before_node(expr); - self.expr(expr); - }, - list_expr.elts - ); - self.write_indentation(Indentation::Dedent); - } - ast::Expr::ListIfItem(_) => { - self.write("el"); - self.expr(orelse); - } - _ => bug!("Invalid list if expr orelse node {:?}", orelse.node), - } - } - } - - fn walk_starred_expr(&mut self, starred_expr: &'ctx ast::StarredExpr) -> Self::Result { - self.write("*"); - self.expr(&starred_expr.value) - } - - fn walk_dict_comp(&mut self, dict_comp: &'ctx ast::DictComp) -> Self::Result { - self.write_token(TokenKind::OpenDelim(DelimToken::Brace)); - self.expr(match &dict_comp.entry.key { - Some(key) => key, - None => bug!("Invalid dict comp key"), - }); - if !matches!(dict_comp.entry.operation, ast::ConfigEntryOperation::Union) { - self.write_space(); - } - self.write(dict_comp.entry.operation.symbol()); - self.write_space(); - self.expr(&dict_comp.entry.value); - for gen in &dict_comp.generators { - self.walk_comp_clause(&gen.node); - } - self.write_token(TokenKind::CloseDelim(DelimToken::Brace)); - } - - fn walk_config_if_entry_expr( - &mut self, - config_if_entry_expr: &'ctx ast::ConfigIfEntryExpr, - ) -> Self::Result { - self.write("if "); - self.expr(&config_if_entry_expr.if_cond); - self.write_token(TokenKind::Colon); - self.write_indentation(Indentation::IndentWithNewline); - interleave!( - || self.write_newline(), - |entry: &ast::NodeRef| self.write_entry(entry), - config_if_entry_expr.items - ); - self.write_indentation(Indentation::Dedent); - if let Some(orelse) = &config_if_entry_expr.orelse { - self.write_newline(); - match &orelse.node { - ast::Expr::Config(config_expr) => { - self.write("else:"); - self.write_indentation(Indentation::IndentWithNewline); - interleave!( - || self.write_newline(), - |entry: &ast::NodeRef| self.write_entry(entry), - config_expr.items - ); - self.write_indentation(Indentation::Dedent); - } - ast::Expr::ConfigIfEntry(_) => { - self.write("el"); - self.expr(orelse); - } - _ => bug!("Invalid config if expr orelse node {:?}", orelse.node), - } - } - } - - fn walk_comp_clause(&mut self, comp_clause: &'ctx ast::CompClause) -> Self::Result { - self.write(" for "); - interleave!( - || self.write(COMMA_WHITESPACE), - |target: &ast::NodeRef| self.walk_identifier(&target.node), - comp_clause.targets - ); - self.write(" in "); - self.expr(&comp_clause.iter); - for if_clause in &comp_clause.ifs { - self.write(" if "); - self.expr(if_clause); - } - } - - fn walk_schema_expr(&mut self, schema_expr: &'ctx ast::SchemaExpr) -> Self::Result { - self.walk_identifier(&schema_expr.name.node); - if !schema_expr.args.is_empty() || !schema_expr.kwargs.is_empty() { - self.write_token(TokenKind::OpenDelim(DelimToken::Paren)); - self.write_args_and_kwargs(&schema_expr.args, &schema_expr.kwargs); - self.write_token(TokenKind::CloseDelim(DelimToken::Paren)); - } - self.write_space(); - self.expr(&schema_expr.config) - } - - fn walk_config_expr(&mut self, config_expr: &'ctx ast::ConfigExpr) -> Self::Result { - let mut line_set: HashSet = config_expr - .items - .iter() - .map(|item| item.line) - .filter(|l| *l > 0) - .collect(); - if self.last_ast_line > 0 { - line_set.insert(self.last_ast_line); - } - // There are comments in the configuration block. - let has_comment = !config_expr.items.is_empty() - && config_expr - .items - .iter() - .map(|item| self.has_comments_on_node(item)) - .all(|r| r); - // When there are comments in the configuration block, print them as multiline configurations. - let mut in_one_line = line_set.len() <= 1 && !has_comment; - // When there are complex configuration blocks in the configuration block, print them as multiline configurations. - if config_expr.items.len() == 1 && in_one_line { - if let Some(item) = config_expr.items.first() { - if matches!( - &item.node.value.node, - ast::Expr::ConfigIfEntry(_) | ast::Expr::Config(_) | ast::Expr::Schema(_) - ) { - in_one_line = false; - } - } - } - self.write_token(TokenKind::OpenDelim(DelimToken::Brace)); - if !config_expr.items.is_empty() { - if !in_one_line { - self.write_indentation(Indentation::IndentWithNewline); - } - interleave!( - || if in_one_line { - self.write(COMMA_WHITESPACE); - } else { - self.write_newline(); - }, - |entry: &ast::NodeRef| self.write_entry(entry), - config_expr.items - ); - if !in_one_line { - if let Some(end_line) = self.current_expr_end_line() { - self.write_comments_until_line(end_line.saturating_sub(1)); - } - self.write_indentation(Indentation::DedentWithNewline); - } - } - self.write_token(TokenKind::CloseDelim(DelimToken::Brace)); - } - - fn walk_check_expr(&mut self, check_expr: &'ctx ast::CheckExpr) -> Self::Result { - self.expr(&check_expr.test); - if let Some(if_cond) = &check_expr.if_cond { - self.write(" if "); - self.expr(if_cond); - } - if let Some(msg) = &check_expr.msg { - self.write(COMMA_WHITESPACE); - self.expr(msg); - } - } - - fn walk_lambda_expr(&mut self, lambda_expr: &'ctx ast::LambdaExpr) -> Self::Result { - self.write("lambda"); - if let Some(args) = &lambda_expr.args { - self.write_space(); - self.walk_arguments(&args.node); - } - if let Some(ty_str) = &lambda_expr.return_ty { - self.write_space(); - self.write_token(TokenKind::RArrow); - self.write_space(); - self.write(&ty_str.node.to_string()); - } - self.write_space(); - self.write_token(TokenKind::OpenDelim(DelimToken::Brace)); - self.write_newline_without_fill(); - self.write_indentation(Indentation::Indent); - - // lambda body - self.stmts(&lambda_expr.body); - - self.write_indentation(Indentation::Dedent); - self.fill(""); - self.write_token(TokenKind::CloseDelim(DelimToken::Brace)); - } - - fn walk_keyword(&mut self, keyword: &'ctx ast::Keyword) -> Self::Result { - self.walk_identifier(&keyword.arg.node); - if let Some(value) = &keyword.value { - self.write("="); - self.expr(value); - } - } - - fn walk_arguments(&mut self, arguments: &'ctx ast::Arguments) -> Self::Result { - let parameter_zip_list: Vec> = arguments - .args - .iter() - .zip( - arguments - .ty_list - .iter() - .map(|ty| ty.clone().map(|n| n.node.to_string())), - ) - .zip(arguments.defaults.iter()) - .collect(); - interleave!( - || self.write(COMMA_WHITESPACE), - |para: &ParameterType<'_>| { - let ((arg, ty_str), default) = para; - self.walk_identifier(&arg.node); - if let Some(ty_str) = ty_str { - self.write(&format!(": {}", ty_str)); - } - if let Some(default) = default { - self.write(" = "); - self.expr(default); - } - }, - parameter_zip_list - ); - } - - fn walk_compare(&mut self, compare: &'ctx ast::Compare) -> Self::Result { - self.expr(&compare.left); - for (op, expr) in compare.ops.iter().zip(compare.comparators.iter()) { - self.write_space(); - self.write(op.symbol()); - self.write_space(); - self.expr(expr); - } - } - - #[inline] - fn walk_identifier(&mut self, identifier: &'ctx ast::Identifier) -> Self::Result { - self.write(&identifier.get_name()); - } - - #[inline] - fn walk_target(&mut self, target: &'ctx ast::Target) -> Self::Result { - self.write(target.get_name()); - for path in &target.paths { - match path { - ast::MemberOrIndex::Member(member) => { - self.write("."); - self.write(&member.node) - } - ast::MemberOrIndex::Index(index) => { - self.write("["); - self.walk_expr(&index.node); - self.write("]"); - } - } - } - } - - fn walk_number_lit(&mut self, number_lit: &'ctx ast::NumberLit) -> Self::Result { - match &number_lit.value { - ast::NumberLitValue::Int(int_val) => self.write(&int_val.to_string()), - ast::NumberLitValue::Float(float_val) => self.write(&float_val.to_string()), - } - // Number suffix e.g., 1Gi - if let Some(binary_suffix) = &number_lit.binary_suffix { - self.write(&binary_suffix.value()) - } - } - - fn walk_string_lit(&mut self, string_lit: &'ctx ast::StringLit) -> Self::Result { - if !string_lit.raw_value.is_empty() { - self.write(&string_lit.raw_value) - } else { - self.write(&if string_lit.is_long_string { - format!("\"\"\"{}\"\"\"", string_lit.value.replace('\"', "\\\"")) - } else { - format!("\"{}\"", string_lit.value.replace('\"', "\\\"")) - }); - } - } - - #[inline] - fn walk_name_constant_lit( - &mut self, - name_constant_lit: &'ctx ast::NameConstantLit, - ) -> Self::Result { - self.write(name_constant_lit.value.symbol()); - } - - fn walk_joined_string(&mut self, joined_string: &'ctx ast::JoinedString) -> Self::Result { - if !joined_string.raw_value.is_empty() { - self.write(&joined_string.raw_value) - } else { - let quote_str = if joined_string.is_long_string { - "\"\"\"" - } else { - "\"" - }; - self.write(quote_str); - for value in &joined_string.values { - match &value.node { - ast::Expr::StringLit(string_lit) => { - self.write(&string_lit.value.replace('\"', "\\\"")); - } - _ => self.expr(value), - } - } - self.write(quote_str); - } - } - - fn walk_formatted_value(&mut self, formatted_value: &'ctx ast::FormattedValue) -> Self::Result { - self.write("${"); - self.expr(&formatted_value.value); - if let Some(spec) = &formatted_value.format_spec { - self.write(&format!(": {}", spec)); - } - self.write("}"); - } - - fn walk_comment(&mut self, comment: &'ctx ast::Comment) -> Self::Result { - self.writeln(&comment.text); - self.fill(""); - } - - fn walk_missing_expr(&mut self, _missing_expr: &'ctx ast::MissingExpr) -> Self::Result { - // Nothing to do - } -} - -impl<'p> Printer<'p> { - pub fn write_args_and_kwargs( - &mut self, - args: &[ast::NodeRef], - kwargs: &[ast::NodeRef], - ) { - interleave!(|| self.write(COMMA_WHITESPACE), |arg| self.expr(arg), args); - if !args.is_empty() && !kwargs.is_empty() { - self.write(COMMA_WHITESPACE); - } - interleave!( - || self.write(COMMA_WHITESPACE), - |kwarg: &ast::NodeRef| self.walk_keyword(&kwarg.node), - kwargs - ); - } - - pub fn write_entry(&mut self, item: &ast::NodeRef) { - match &item.node.key { - Some(key) => { - let print_right_brace_count = self.write_config_key(key); - if !matches!(item.node.operation, ast::ConfigEntryOperation::Union) { - self.write_space(); - } - self.write(item.node.operation.symbol()); - self.write_space(); - self.expr(&item.node.value); - self.write(&"}".repeat(print_right_brace_count)); - } - None => { - self.write_comments_before_node(&item); - if !matches!(&item.node.value.node, ast::Expr::ConfigIfEntry(_)) { - self.write("**"); - } - self.expr(&item.node.value) - } - }; - } - - fn write_config_key(&mut self, key: &ast::NodeRef) -> usize { - match &key.node { - ast::Expr::Identifier(identifier) => { - self.hook.pre(self, super::ASTNode::Expr(key)); - self.write_comments_before_node(key); - // Judge contains string or dot identifier, e.g., "x-y-z" and "a.b.c" - let names = &identifier.names; - - let re = fancy_regex::Regex::new(IDENTIFIER_REGEX).unwrap(); - let need_right_brace = !names.iter().all(|n| re.is_match(&n.node).unwrap_or(false)); - let count = if need_right_brace { - self.write( - &names - .iter() - .map(|n| format!("{:?}", n.node)) - .collect::>() - .join(": {"), - ); - names.len() - 1 - } else { - self.expr(key); - 0 - }; - self.hook.post(self, super::ASTNode::Expr(key)); - count - } - _ => { - self.write_comments_before_node(key); - self.expr(key); - 0 - } - } - } - - fn write_attribute(&mut self, attr: &ast::NodeRef) { - let re = fancy_regex::Regex::new(IDENTIFIER_REGEX).unwrap(); - let need_quote = !re.is_match(&attr.node).unwrap(); - if need_quote { - self.write(&format!("{:?}", attr.node)); - } else { - self.write(&attr.node); - }; - } -} - -impl<'p> Printer<'p> { - // ------------------------------ - // Expr and Stmt walker functions - // ------------------------------ - - pub fn expr(&mut self, expr: &ast::NodeRef) { - self.push_expr_span(expr.line, expr.end_line); - self.hook.pre(self, super::ASTNode::Expr(expr)); - self.update_last_ast_line(expr); - self.walk_expr(&expr.node); - self.hook.post(self, super::ASTNode::Expr(expr)); - self.pop_expr_span(); - } - - pub fn stmt(&mut self, stmt: &ast::NodeRef) { - self.hook.pre(self, super::ASTNode::Stmt(stmt)); - self.fill(""); - self.write_comments_before_node(stmt); - self.walk_stmt(&stmt.node); - self.hook.post(self, super::ASTNode::Stmt(stmt)); - } - - pub fn exprs(&mut self, exprs: &[ast::NodeRef]) { - for expr in exprs { - self.expr(expr); - } - } - - pub fn stmts(&mut self, stmts: &[ast::NodeRef]) { - // Hold the prev statement pointer. - let mut prev_stmt: Option<&ast::NodeRef> = None; - for stmt in stmts { - let import_stmt_alter = match (prev_stmt.map(|s| &s.node).as_ref(), &stmt.node) { - (Some(ast::Stmt::Import(_)), ast::Stmt::Import(_)) => false, - (Some(ast::Stmt::Import(_)), _) => true, - _ => false, - }; - // Do not format out user-reserved blank lines: which does not mean that to preserve all user-written blank lines. - // For situations where there are more than two blank lines, we only keep one blank line. - let need_newline = if let Some(prev_stmt) = prev_stmt { - if stmt.line > prev_stmt.end_line + 2 { - true - } else if stmt.line == prev_stmt.end_line + 2 { - stmt.line > 0 && !self.has_comments_on_node(stmt) - } else { - false - } - } else { - false - }; - if import_stmt_alter || need_newline { - self.write_newline_without_fill(); - } - self.stmt(stmt); - prev_stmt = Some(stmt); - } - } -} diff --git a/kclvm/ast_pretty/src/tests.rs b/kclvm/ast_pretty/src/tests.rs deleted file mode 100644 index 5ef2f2494..000000000 --- a/kclvm/ast_pretty/src/tests.rs +++ /dev/null @@ -1,65 +0,0 @@ -use std::path::{Path, PathBuf}; - -use super::print_ast_module; -use kclvm_parser::parse_file_force_errors; -use pretty_assertions::assert_eq; - -const FILE_INPUT_SUFFIX: &str = ".input"; -const FILE_OUTPUT_SUFFIX: &str = ".output"; -const TEST_CASES: &[&str] = &[ - "arguments", - "empty", - "if_stmt", - "import", - "unary", - "codelayout", - "collection_if", - "comment", - "index_sign", - "joined_str", - "lambda", - "orelse", - "quant", - "rule", - "str", - "type_alias", - "unification", -]; - -fn read_data(data_name: &str) -> (String, String) { - let mut filename = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - filename.push( - Path::new("src") - .join("test_data") - .join(format!("{}{}", data_name, FILE_INPUT_SUFFIX)) - .display() - .to_string(), - ); - - let module = parse_file_force_errors(filename.to_str().unwrap(), None); - - let mut filename_expect = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - filename_expect.push( - Path::new("src") - .join("test_data") - .join(format!("{}{}", data_name, FILE_OUTPUT_SUFFIX)) - .display() - .to_string(), - ); - ( - print_ast_module(&module.unwrap()), - std::fs::read_to_string(filename_expect.to_str().unwrap()).unwrap(), - ) -} - -#[test] -fn test_ast_printer() { - for case in TEST_CASES { - let (data_input, data_output) = read_data(case); - - #[cfg(target_os = "windows")] - let data_output = data_output.replace("\r\n", "\n"); - - assert_eq!(data_input, data_output, "Test failed on {}", case); - } -} diff --git a/kclvm/cmd/Cargo.toml b/kclvm/cmd/Cargo.toml deleted file mode 100644 index e3186a38b..000000000 --- a/kclvm/cmd/Cargo.toml +++ /dev/null @@ -1,19 +0,0 @@ -[package] -name = "kclvm-cmd" -version = "0.11.2" -edition = "2021" - -[dependencies] -anyhow = "1.0" -clap = "4.3.0" -compiler_base_session = "0.1.3" - -kclvm-api = {path = "../api"} -kclvm-parser = {path = "../parser"} -kclvm-runner = {path = "../runner"} -kclvm-config = {path = "../config"} -kclvm-driver = {path = "../driver"} -kclvm-runtime = {path = "../runtime"} -kclvm-tools = {path = "../tools"} -kclvm-error = {path = "../error"} -kclvm-version = {path = "../version"} diff --git a/kclvm/cmd/src/lib.rs b/kclvm/cmd/src/lib.rs deleted file mode 100644 index e85ade250..000000000 --- a/kclvm/cmd/src/lib.rs +++ /dev/null @@ -1,64 +0,0 @@ -//! The `kclvm` command-line interface. - -#[macro_use] -extern crate clap; - -pub mod run; -pub mod settings; -pub(crate) mod util; - -#[cfg(test)] -mod tests; - -use clap::{ArgAction, Command}; - -use std::io; - -use anyhow::Result; -use run::run_command; - -/// Run the KCL main command. -pub fn main(args: &[&str]) -> Result<()> { - let matches = app().arg_required_else_help(true).get_matches_from(args); - // Sub commands - match matches.subcommand() { - Some(("run", sub_matches)) => run_command(sub_matches, &mut io::stdout()), - Some(("version", _)) => { - println!("{}", kclvm_version::get_version_info()); - Ok(()) - } - #[cfg(not(target_arch = "wasm32"))] - Some(("server", _)) => kclvm_api::service::jsonrpc::start_stdio_server(), - _ => Ok(()), - } -} - -/// Get the CLI application including a run command and -/// a gPRC server command to interacting with external systems. -pub fn app() -> Command { - Command::new("kclvm_cli") - .version(kclvm_version::VERSION) - .about("KCL main CLI.") - .subcommand( - Command::new("run") - .about("run") - .arg(arg!([input] ... "Specify the input files to run").num_args(0..)) - .arg(arg!(output: -o --output "Specify the YAML output file path")) - .arg(arg!(setting: -Y --setting ... "Specify the input setting file").num_args(1..)) - .arg(arg!(verbose: -v --verbose "Print test information verbosely").action(ArgAction::Count)) - .arg(arg!(disable_none: -n --disable_none "Disable dumping None values")) - .arg(arg!(strict_range_check: -r --strict_range_check "Do perform strict numeric range checks")) - .arg(arg!(debug: -d --debug "Run in debug mode (for developers only)")) - .arg(arg!(sort_keys: -k --sort_keys "Sort result keys")) - .arg(arg!(show_hidden: -H --show_hidden "Display hidden attributes")) - .arg(arg!(fast_eval: -K --fast_eval "Use the fast evaluation mode")) - .arg(arg!(arguments: -D --argument ... "Specify the top-level argument").num_args(1..)) - .arg(arg!(path_selector: -S --path_selector ... "Specify the path selector").num_args(1..)) - .arg(arg!(overrides: -O --overrides ... "Specify the configuration override path and value").num_args(1..)) - .arg(arg!(target: --target "Specify the target type")) - .arg(arg!(recursive: -R --recursive "Compile the files directory recursively")) - .arg(arg!(package_map: -E --external ... "Mapping of package name and path where the package is located").num_args(1..)), - ) - .subcommand(Command::new("server").about("Start a rpc server for APIs")) - .subcommand(Command::new("version").about("Show the KCL version")) -} diff --git a/kclvm/cmd/src/settings.rs b/kclvm/cmd/src/settings.rs deleted file mode 100644 index cbdd6aa73..000000000 --- a/kclvm/cmd/src/settings.rs +++ /dev/null @@ -1,73 +0,0 @@ -use crate::util::*; -use anyhow::Result; -use clap::ArgMatches; -use kclvm_config::settings::{build_settings_pathbuf, Config, SettingsFile, SettingsPathBuf}; -use kclvm_driver::arguments::parse_key_value_pair; -use kclvm_error::Handler; -use kclvm_runtime::PanicInfo; - -/// Build settings from arg matches. -pub(crate) fn must_build_settings(matches: &ArgMatches) -> SettingsPathBuf { - match build_settings(matches) { - Ok(settings) => settings, - Err(err) => { - // New an error handler. - let mut handler = Handler::default(); - handler - .add_panic_info(&PanicInfo { - message: err.to_string(), - ..Default::default() - }) - .abort_if_any_errors(); - SettingsPathBuf::default() - } - } -} - -/// Build settings from arg matches. -pub(crate) fn build_settings(matches: &ArgMatches) -> Result { - let files: Vec<&str> = match matches.get_many::("input") { - Some(files) => files.into_iter().map(|f| f.as_str()).collect::>(), - None => vec![], - }; - - let setting_files = matches - .get_many::("setting") - .map(|files| files.into_iter().map(|f| f.as_str()).collect::>()); - - let arguments = strings_from_matches(matches, "arguments"); - - let package_maps = hashmaps_from_matches(matches, "package_map").transpose()?; - - build_settings_pathbuf( - files.as_slice(), - setting_files, - Some(SettingsFile { - kcl_cli_configs: Some(Config { - output: matches.get_one::("output").map(|v| v.to_string()), - overrides: strings_from_matches(matches, "overrides"), - path_selector: strings_from_matches(matches, "path_selector"), - strict_range_check: bool_from_matches(matches, "strict_range_check"), - disable_none: bool_from_matches(matches, "disable_none"), - verbose: u32_from_matches(matches, "verbose"), - debug: bool_from_matches(matches, "debug"), - sort_keys: bool_from_matches(matches, "sort_keys"), - show_hidden: bool_from_matches(matches, "show_hidden"), - fast_eval: bool_from_matches(matches, "fast_eval"), - package_maps, - ..Default::default() - }), - kcl_options: if arguments.is_some() { - let mut key_value_pairs = vec![]; - if let Some(arguments) = arguments { - for arg in arguments { - key_value_pairs.push(parse_key_value_pair(&arg)?); - } - } - Some(key_value_pairs) - } else { - None - }, - }), - ) -} diff --git a/kclvm/cmd/src/tests.rs b/kclvm/cmd/src/tests.rs deleted file mode 100644 index 016b04876..000000000 --- a/kclvm/cmd/src/tests.rs +++ /dev/null @@ -1,589 +0,0 @@ -use std::{ - env, - fs::{self, remove_file}, - path::{Path, PathBuf}, - sync::Arc, -}; - -use kclvm_config::modfile::KCL_PKG_PATH; -use kclvm_parser::ParseSession; -use kclvm_runner::{exec_program, MapErrorResult}; - -use crate::{ - app, - run::run_command, - settings::{build_settings, must_build_settings}, - util::hashmaps_from_matches, -}; - -#[cfg(unix)] -use std::os::unix::fs::symlink; -#[cfg(windows)] -use std::os::windows::fs::symlink_file as symlink; - -const ROOT_CMD: &str = "kclvm_cli"; - -#[test] -fn test_build_settings() { - let work_dir = work_dir(); - let matches = app().get_matches_from(settings_arguments(work_dir.join("kcl.yaml"))); - let matches = matches.subcommand_matches("run").unwrap(); - let s = build_settings(matches).unwrap(); - // Testing work directory - assert_eq!(s.path().as_ref().unwrap().to_str(), work_dir.to_str()); - // Testing CLI configs - assert_eq!( - s.settings().kcl_cli_configs.as_ref().unwrap().files, - Some(vec!["hello.k".to_string()]) - ); - assert_eq!( - s.settings().kcl_cli_configs.as_ref().unwrap().disable_none, - Some(true) - ); - assert_eq!( - s.settings() - .kcl_cli_configs - .as_ref() - .unwrap() - .strict_range_check, - Some(true) - ); - assert_eq!( - s.settings().kcl_cli_configs.as_ref().unwrap().overrides, - Some(vec!["c.a=1".to_string(), "c.b=1".to_string(),]) - ); - assert_eq!( - s.settings().kcl_cli_configs.as_ref().unwrap().path_selector, - Some(vec!["a.b.c".to_string()]) - ); - assert_eq!(s.settings().input(), vec!["hello.k".to_string()]); -} - -#[test] -fn test_build_settings_fail() { - let matches = app().get_matches_from(settings_arguments(work_dir().join("error_kcl.yaml"))); - let matches = matches.subcommand_matches("run").unwrap(); - assert!(build_settings(matches).is_err()); -} - -fn work_dir() -> std::path::PathBuf { - std::path::Path::new(".") - .join("src") - .join("test_data") - .join("settings") -} - -fn settings_arguments(path: std::path::PathBuf) -> Vec { - vec![ - ROOT_CMD.to_string(), - "run".to_string(), - "-Y".to_string(), - path.to_str().unwrap().to_string(), - "-r".to_string(), - "-O".to_string(), - "c.a=1".to_string(), - "-O".to_string(), - "c.b=1".to_string(), - "-S".to_string(), - "a.b.c".to_string(), - ] -} - -#[test] -fn test_external_cmd() { - let matches = app().get_matches_from(&[ROOT_CMD, "run", "-E", "test_name=test_path"]); - let matches = matches.subcommand_matches("run").unwrap(); - let pair = hashmaps_from_matches(matches, "package_map") - .unwrap() - .unwrap(); - assert_eq!(pair.len(), 1); - assert!(pair.contains_key("test_name")); - assert_eq!(pair.get("test_name").unwrap(), "test_path"); -} - -#[test] -fn test_version_cmd() { - let matches = app().get_matches_from(&[ROOT_CMD, "version"]); - assert!(matches.subcommand_matches("version").is_some()) -} - -#[test] -fn test_multi_external_cmd() { - let matches = app().get_matches_from(&[ - ROOT_CMD, - "run", - "-E", - "test_name=test_path", - "-E", - "test_name1=test_path1", - ]); - let matches = matches.subcommand_matches("run").unwrap(); - let pair = hashmaps_from_matches(matches, "package_map") - .unwrap() - .unwrap(); - - assert_eq!(pair.len(), 2); - assert!(pair.contains_key("test_name")); - assert!(pair.contains_key("test_name1")); - assert_eq!(pair.get("test_name").unwrap(), "test_path"); - assert_eq!(pair.get("test_name1").unwrap(), "test_path1"); -} - -#[test] -fn test_multi_external_with_same_key_cmd() { - let matches = app().get_matches_from(&[ - ROOT_CMD, - "run", - "-E", - "test_name=test_path", - "-E", - "test_name=test_path1", - ]); - let matches = matches.subcommand_matches("run").unwrap(); - let pair = hashmaps_from_matches(matches, "package_map") - .unwrap() - .unwrap(); - assert_eq!(pair.len(), 1); - assert!(pair.contains_key("test_name")); - assert_eq!(pair.get("test_name").unwrap(), "test_path1"); -} - -#[test] -fn test_external_cmd_invalid() { - let invalid_cases: [&str; 5] = [ - "test_nametest_path", - "test_name=test_path=test_suffix", - "=test_path", - "test_name=", - "=test_name=test_path=", - ]; - for case in invalid_cases { - let matches = app().get_matches_from(&[ROOT_CMD, "run", "-E", case]); - let matches = matches.subcommand_matches("run").unwrap(); - match hashmaps_from_matches(matches, "package_map").unwrap() { - Ok(_) => { - panic!("unreachable code.") - } - Err(err) => { - assert!(format!("{:?}", err).contains("Invalid value for top level arguments")); - } - }; - } -} - -#[test] -#[cfg(not(windows))] -// All the unit test cases in [`test_run_command`] can not be executed concurrently. -fn test_run_command() { - test_run_command_with_import(); - test_run_command_with_konfig(); - test_load_cache_with_different_pkg(); - test_kcl_path_is_sym_link(); - test_compile_two_kcl_mod(); - test_main_pkg_not_found(); - test_multi_mod_file(); - test_instances_with_yaml(); - test_plugin_not_found(); - test_error_message_fuzz_matched(); - test_error_message_fuzz_unmatched(); - test_keyword_argument_error_message(); -} - -fn test_run_command_with_import() { - let vendor_path = PathBuf::from("./src/test_data/cases/vendor"); - - let test_cases = vec!["import_1"]; - let test_case_root = PathBuf::from("./src/test_data/cases") - .canonicalize() - .unwrap(); - - for test_case in test_cases { - check_run_command_with_env( - test_case_root.join(test_case), - vendor_path.canonicalize().unwrap().display().to_string(), - ); - } -} - -fn test_run_command_with_konfig() { - let vendor_path = PathBuf::from("../../test/integration"); - - let test_cases = vec!["import_konfig_1"]; - let test_case_root = PathBuf::from("./src/test_data/cases") - .canonicalize() - .unwrap(); - - for test_case in test_cases { - check_run_command_with_env( - test_case_root.join(test_case), - vendor_path.canonicalize().unwrap().display().to_string(), - ); - } -} - -fn test_load_cache_with_different_pkg() { - let main_path = PathBuf::from("./src/test_data/cache/main/main.k"); - let main_v1_path = PathBuf::from("./src/test_data/cache/main/main.k.v1"); - let main_v2_path = PathBuf::from("./src/test_data/cache/main/main.k.v2"); - let kcl1_v1_path = PathBuf::from("./src/test_data/cache/v1/kcl1"); - let kcl1_v2_path = PathBuf::from("./src/test_data/cache/v2/kcl1"); - - // Copy the content from main.k.v1 to main.k - fs::copy(main_v1_path, &main_path).unwrap(); - let matches = app().get_matches_from(&[ - ROOT_CMD, - "run", - main_path.to_str().unwrap(), - "-E", - format!("kcl1={}", kcl1_v1_path.display()).as_str(), - ]); - - let matches = matches.subcommand_matches("run").unwrap(); - let mut buf = Vec::new(); - run_command(matches, &mut buf).unwrap(); - assert_eq!( - String::from_utf8(buf).unwrap(), - "The_first_kcl_program: 1\n" - ); - - // Copy the content from main.k.v2 to main.k - fs::copy(main_v2_path, &main_path).unwrap(); - let matches = app().get_matches_from(&[ - ROOT_CMD, - "run", - main_path.to_str().unwrap(), - "-E", - format!("kcl1={}", kcl1_v2_path.display()).as_str(), - ]); - - let matches = matches.subcommand_matches("run").unwrap(); - let mut buf = Vec::new(); - run_command(matches, &mut buf).unwrap(); - assert_eq!( - String::from_utf8(buf).unwrap(), - "The_first_kcl_program: 1\nkcl1_schema:\n name: kcl1\n" - ); -} - -/// rust crate [`gag`]: https://crates.io/crates/gag -/// allows redirecting stderr or stdout either to a file or to nothing, -/// but it only works on unix systems. -/// After [`gag`] can better support windows in the future, it may be considered to test the `println!`. -fn check_run_command_with_env(test_case_path: PathBuf, kcl_pkg_path_env: String) { - env::set_var(KCL_PKG_PATH, kcl_pkg_path_env); - - let test_case_expect_file = test_case_path.join("stdout").display().to_string(); - let expect = fs::read_to_string(test_case_expect_file).expect("Unable to read file"); - - let matches = app().arg_required_else_help(true).get_matches_from(&[ - ROOT_CMD, - "run", - &test_case_path.join("main.k").display().to_string(), - ]); - - let mut buf = Vec::new(); - run_command(matches.subcommand_matches("run").unwrap(), &mut buf).unwrap(); - - #[cfg(target_os = "windows")] - let expect = expect.replace("\r\n", "\n"); - assert_eq!(String::from_utf8(buf).unwrap(), expect); -} - -fn test_kcl_path_is_sym_link() { - let origin = "./src/test_data/sym_link/origin"; - let link = "./src/test_data/sym_link/sym_link"; - - let origin_k_file_path = PathBuf::from(origin).join("a.k"); - let origin_matches = app().arg_required_else_help(true).get_matches_from(&[ - ROOT_CMD, - "run", - origin_k_file_path.to_str().unwrap(), - ]); - - let mut origin_res = Vec::new(); - run_command( - origin_matches.subcommand_matches("run").unwrap(), - &mut origin_res, - ) - .unwrap(); - - // Create a symlink - symlink( - PathBuf::from(origin).canonicalize().unwrap(), - Path::new(link), - ) - .unwrap(); - - let sym_link_k_file_path = PathBuf::from(link).join("a.k"); - let mut sym_link_res = Vec::new(); - let sym_link_matches = app().arg_required_else_help(true).get_matches_from(&[ - ROOT_CMD, - "run", - sym_link_k_file_path.to_str().unwrap(), - ]); - run_command( - sym_link_matches.subcommand_matches("run").unwrap(), - &mut sym_link_res, - ) - .unwrap(); - - // compare the result from origin kcl path and symlink kcl path. - assert_eq!( - String::from_utf8(sym_link_res), - String::from_utf8(origin_res) - ); - - // clean up the symlink - remove_file(link).unwrap(); -} - -fn test_compile_two_kcl_mod() { - let test_case_path = PathBuf::from("./src/test_data/multimod"); - - let matches = app().arg_required_else_help(true).get_matches_from(&[ - ROOT_CMD, - "run", - &test_case_path.join("kcl1/main.k").display().to_string(), - "${kcl2:KCL_MOD}/main.k", - "-E", - &format!("kcl2={}", test_case_path.join("kcl2").display().to_string()), - ]); - - let mut buf = Vec::new(); - run_command(matches.subcommand_matches("run").unwrap(), &mut buf).unwrap(); - - assert_eq!( - "kcl1: hello 1\nkcl2: hello 2\n", - String::from_utf8(buf).unwrap() - ); - - let matches = app().arg_required_else_help(true).get_matches_from(&[ - ROOT_CMD, - "run", - &test_case_path.join("kcl2/main.k").display().to_string(), - "${kcl1:KCL_MOD}/main.k", - "-E", - &format!("kcl1={}", test_case_path.join("kcl1").display().to_string()), - ]); - - let mut buf = Vec::new(); - run_command(matches.subcommand_matches("run").unwrap(), &mut buf).unwrap(); - - assert_eq!( - "kcl2: hello 2\nkcl1: hello 1\n", - String::from_utf8(buf).unwrap() - ); - - let matches = app().arg_required_else_help(true).get_matches_from(&[ - ROOT_CMD, - "run", - &test_case_path.join("kcl3/main.k").display().to_string(), - "${kcl4:KCL_MOD}/main.k", - "-E", - &format!( - "kcl4={}", - test_case_path - .join("kcl3") - .join("kcl4") - .display() - .to_string() - ), - ]); - - let mut buf = Vec::new(); - run_command(matches.subcommand_matches("run").unwrap(), &mut buf).unwrap(); - - assert_eq!( - "k3: Hello World 3\nk4: Hello World 4\n", - String::from_utf8(buf).unwrap() - ); - - let matches = app().arg_required_else_help(true).get_matches_from(&[ - ROOT_CMD, - "run", - &test_case_path - .join("kcl3/kcl4/main.k") - .display() - .to_string(), - "${kcl3:KCL_MOD}/main.k", - "-E", - &format!("kcl3={}", test_case_path.join("kcl3").display().to_string()), - ]); - - let mut buf = Vec::new(); - run_command(matches.subcommand_matches("run").unwrap(), &mut buf).unwrap(); - - assert_eq!( - "k4: Hello World 4\nk3: Hello World 3\n", - String::from_utf8(buf).unwrap() - ); -} - -fn test_instances_with_yaml() { - let test_cases = [ - "test_inst_1", - "test_inst_2", - "test_inst_3", - "test_inst_4", - "test_inst_5", - "test_inst_6", - "test_inst_7", - "test_inst_8", - "test_inst_9", - "test_inst_10", - "test_inst_11/test_inst_111", - ]; - - for case in &test_cases { - let expected = format!("{}/expected", case); - let case_yaml = format!("{}/kcl.yaml", case); - test_instances(&case_yaml, &expected); - } -} - -fn test_instances(kcl_yaml_path: &str, expected_file_path: &str) { - let test_case_path = PathBuf::from("./src/test_data/instances"); - let matches = app().arg_required_else_help(true).get_matches_from(&[ - ROOT_CMD, - "run", - "-Y", - &test_case_path.join(kcl_yaml_path).display().to_string(), - ]); - - let mut buf = Vec::new(); - run_command(matches.subcommand_matches("run").unwrap(), &mut buf).unwrap(); - let expect = fs::read_to_string( - test_case_path - .join(expected_file_path) - .display() - .to_string(), - ) - .unwrap(); - - assert_eq!( - expect.replace("\r\n", "\n"), - String::from_utf8(buf).unwrap() - ); -} - -fn test_main_pkg_not_found() { - let test_case_path = PathBuf::from("./src/test_data/multimod"); - - let matches = app().arg_required_else_help(true).get_matches_from(&[ - ROOT_CMD, - "run", - "${kcl3:KCL_MOD}/main.k", - "-E", - &format!("kcl3={}", test_case_path.join("kcl3").display().to_string()), - ]); - let settings = must_build_settings(matches.subcommand_matches("run").unwrap()); - let sess = Arc::new(ParseSession::default()); - match exec_program(sess.clone(), &settings.try_into().unwrap()) - .map_err_to_result() - .map_err(|e| e.to_string()) - { - Ok(_) => panic!("unreachable code."), - Err(msg) => assert_eq!( - msg, - "Cannot find the kcl file, please check the file path ${kcl3:KCL_MOD}/main.k" - ), - } -} - -fn test_multi_mod_file() { - let test_case_path = PathBuf::from("./src/test_data/multimod"); - - let matches = app().arg_required_else_help(true).get_matches_from(&[ - ROOT_CMD, - "run", - &test_case_path.join("kcl1").display().to_string(), - &test_case_path.join("kcl2").display().to_string(), - ]); - let settings = must_build_settings(matches.subcommand_matches("run").unwrap()); - let sess = Arc::new(ParseSession::default()); - match exec_program(sess.clone(), &settings.try_into().unwrap()) { - Ok(res) => { - assert_eq!(res.yaml_result, "kcl1: hello 1\nkcl2: hello 2"); - assert_eq!( - res.json_result, - "{\"kcl1\": \"hello 1\", \"kcl2\": \"hello 2\"}" - ); - } - Err(_) => panic!("unreachable code."), - } -} - -fn test_plugin_not_found() { - let test_case_path = PathBuf::from("./src/test_data/plugin/plugin_not_found"); - let matches = app().arg_required_else_help(true).get_matches_from(&[ - ROOT_CMD, - "run", - test_case_path.as_path().display().to_string().as_str(), - ]); - let settings = must_build_settings(matches.subcommand_matches("run").unwrap()); - let sess = Arc::new(ParseSession::default()); - match exec_program(sess.clone(), &settings.try_into().unwrap()).map_err_to_result().map_err(|e|e.to_string()) { - Ok(_) => panic!("unreachable code."), - Err(msg) => assert!(msg.contains("the plugin package `kcl_plugin.not_exist` is not found, please confirm if plugin mode is enabled")), - } -} - -fn test_error_message_fuzz_matched() { - let test_case_path = PathBuf::from("./src/test_data/fuzz_match/main.k"); - let matches = app().arg_required_else_help(true).get_matches_from(&[ - ROOT_CMD, - "run", - &test_case_path.canonicalize().unwrap().display().to_string(), - ]); - let settings = must_build_settings(matches.subcommand_matches("run").unwrap()); - let sess = Arc::new(ParseSession::default()); - match exec_program(sess.clone(), &settings.try_into().unwrap()) - .map_err_to_result() - .map_err(|e| e.to_string()) - { - Ok(_) => panic!("unreachable code."), - Err(msg) => { - assert!(msg.contains("attribute 'a' not found in 'Person', did you mean '[\"aa\"]'?")) - } - } -} - -fn test_error_message_fuzz_unmatched() { - let test_case_path = PathBuf::from("./src/test_data/fuzz_match/main_unmatched.k"); - let matches = app().arg_required_else_help(true).get_matches_from(&[ - ROOT_CMD, - "run", - &test_case_path.canonicalize().unwrap().display().to_string(), - ]); - let settings = must_build_settings(matches.subcommand_matches("run").unwrap()); - let sess = Arc::new(ParseSession::default()); - match exec_program(sess.clone(), &settings.try_into().unwrap()) - .map_err_to_result() - .map_err(|e| e.to_string()) - { - Ok(_) => panic!("unreachable code."), - Err(msg) => { - assert!(msg.contains("attribute 'a' not found in 'Person'")) - } - } -} - -fn test_keyword_argument_error_message() { - let test_case_path = PathBuf::from("./src/test_data/failed/keyword_argument_error.k"); - let matches = app().arg_required_else_help(true).get_matches_from(&[ - ROOT_CMD, - "run", - &test_case_path.canonicalize().unwrap().display().to_string(), - ]); - let settings = must_build_settings(matches.subcommand_matches("run").unwrap()); - let sess = Arc::new(ParseSession::default()); - match exec_program(sess.clone(), &settings.try_into().unwrap()) - .map_err_to_result() - .map_err(|e| e.to_string()) - { - Ok(_) => panic!("unreachable code."), - Err(msg) => { - assert!(msg.contains("keyword argument 'ID' not found")); - } - } -} diff --git a/kclvm/compiler/Cargo.toml b/kclvm/compiler/Cargo.toml deleted file mode 100644 index 7efb23558..000000000 --- a/kclvm/compiler/Cargo.toml +++ /dev/null @@ -1,24 +0,0 @@ -[package] -name = "kclvm-compiler" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -inkwell = { git = "https://github.com/TheDan64/inkwell", branch = "master", optional = true } -time = "0.2.23" -phf = { version = "0.9", features = ["macros"] } -bit-set = "0.5.0" -bitflags = "1.2.1" -once_cell = "1.5.2" -fancy-regex = "0.7.1" -unicode_names2 = "0.4" -kclvm-ast = { path = "../ast" } -kclvm-sema = { path = "../sema" } -kclvm-runtime = { path = "../runtime" } -kclvm-error = { path = "../error" } -kclvm-primitives = { path = "../primitives" } - -[features] -llvm = ["inkwell/target-webassembly", "inkwell/llvm12-0"] diff --git a/kclvm/compiler/src/codegen/llvm/backtrack.rs b/kclvm/compiler/src/codegen/llvm/backtrack.rs deleted file mode 100644 index 937ea29dc..000000000 --- a/kclvm/compiler/src/codegen/llvm/backtrack.rs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. - -use super::context::LLVMCodeGenContext; -use crate::codegen::llvm::context::BacktrackKind; -use crate::codegen::traits::BuilderMethods; -use inkwell::values::BasicValueEnum; - -impl<'ctx> LLVMCodeGenContext<'ctx> { - pub(crate) fn update_backtrack_meta( - &self, - name: &str, - schema_value: BasicValueEnum<'ctx>, - ) -> bool { - if let Some(backtrack_meta) = self.backtrack_meta.borrow_mut().as_mut() { - if name == backtrack_meta.target { - backtrack_meta.count += 1; - if backtrack_meta.count >= backtrack_meta.level { - backtrack_meta.stop = true; - self.ret(schema_value); - return true; - } - } - } - false - } - - #[inline] - pub(crate) fn is_backtrack_only_if(&self) -> bool { - if let Some(backtrack_meta) = self.backtrack_meta.borrow_mut().as_ref() { - matches!(backtrack_meta.kind, BacktrackKind::If) - } else { - false - } - } - - #[inline] - pub(crate) fn is_backtrack_only_or_else(&self) -> bool { - if let Some(backtrack_meta) = self.backtrack_meta.borrow_mut().as_ref() { - matches!(backtrack_meta.kind, BacktrackKind::OrElse) - } else { - false - } - } -} diff --git a/kclvm/compiler/src/codegen/llvm/context.rs b/kclvm/compiler/src/codegen/llvm/context.rs deleted file mode 100644 index 72f867466..000000000 --- a/kclvm/compiler/src/codegen/llvm/context.rs +++ /dev/null @@ -1,2592 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. - -use inkwell::basic_block::BasicBlock; -use inkwell::builder::Builder; -use inkwell::context::Context; -use inkwell::memory_buffer::MemoryBuffer; -use inkwell::module::{Linkage, Module}; -use inkwell::support::LLVMString; -use inkwell::targets::{CodeModel, FileType, RelocMode}; -use inkwell::types::{BasicMetadataTypeEnum, BasicType, BasicTypeEnum, FunctionType}; -use inkwell::values::{ - BasicMetadataValueEnum, BasicValueEnum, FunctionValue, IntValue, PointerValue, -}; -use inkwell::{AddressSpace, IntPredicate}; -use kclvm_primitives::{IndexMap, IndexSet}; -use phf::{phf_map, Map}; -use std::cell::RefCell; -use std::collections::{HashMap, HashSet}; -use std::error::Error; -use std::path::Path; -use std::rc::Rc; -use std::str; - -use kclvm_ast::ast; -use kclvm_ast::walker::TypedResultWalker; -use kclvm_error::*; -use kclvm_runtime::{ApiFunc, MAIN_PKG_PATH, PKG_PATH_PREFIX}; -use kclvm_sema::builtin; -use kclvm_sema::pkgpath_without_prefix; -use kclvm_sema::plugin; - -use crate::codegen::abi::Align; -use crate::codegen::llvm::utils; -use crate::codegen::OBJECT_FILE_SUFFIX; -use crate::codegen::{error as kcl_error, EmitOptions}; -use crate::codegen::{ - traits::*, ENTRY_NAME, GLOBAL_VAL_ALIGNMENT, MODULE_NAME, PKG_INIT_FUNCTION_SUFFIX, -}; -use crate::codegen::{CodeGenContext, GLOBAL_LEVEL}; -use crate::value; - -/// SCALAR_KEY denotes the temp scalar key for the global variable json plan process. -const SCALAR_KEY: &str = ""; -/// Float type string width mapping -pub const FLOAT_TYPE_WIDTH_MAPPING: Map<&str, usize> = phf_map! { - "half" => 16, - "float" => 32, - "double" => 64, - "x86_fp80" => 80, - "ppc_fp128" => 128, - "fp128" => 128, -}; - -/// The compiler function result -pub type CompileResult<'a> = Result, kcl_error::KCLError>; - -/// The compiler scope. -#[derive(Debug, Default)] -pub struct Scope<'ctx> { - /// Scalars denotes the expression statement values without attribute. - pub(crate) scalars: RefCell>>, - /// schema_scalar_idx denotes whether a schema exists in the scalar list. - pub(crate) schema_scalar_idx: RefCell, - /// Scope normal variables - pub(crate) variables: RefCell>>, - /// Scope normal initialized variables - pub(crate) uninitialized: RefCell>, - /// Potential arguments in the current scope, such as schema/lambda arguments. - pub(crate) arguments: RefCell>, -} - -/// Setter kind. -/// - If it is a normal kind, traverse all statements in the setter. -/// - If it is an if type, only traverse the if statement in the if stmt, skipping the else stmt. -/// - If it is an orelse type, only traverse the else statement, and make conditional judgments based on the inverse of the if stmt's cond. -#[derive(Default, Debug, Clone, PartialEq)] -pub enum BacktrackKind { - #[default] - Normal, - If, - OrElse, -} - -/// Schema or Global internal order independent computation backtracking meta information. -pub struct BacktrackMeta { - pub target: String, - pub level: usize, - pub count: usize, - pub stop: bool, - pub kind: BacktrackKind, -} - -/// The LLVM code generator -pub struct LLVMCodeGenContext<'ctx> { - pub context: &'ctx Context, - pub module: Module<'ctx>, - pub builder: Builder<'ctx>, - pub program: &'ctx ast::Program, - pub functions: RefCell>>>, - pub imported: RefCell>, - pub setter_keys: RefCell>, - pub schema_stack: RefCell>, - pub lambda_stack: RefCell>, - pub schema_expr_stack: RefCell>, - pub pkgpath_stack: RefCell>, - pub filename_stack: RefCell>, - /// Package scope to store variable pointers. - pub pkg_scopes: RefCell>>>>, - /// Local variables in the loop. - pub local_vars: RefCell>, - /// The names of possible assignment objects for the current instruction. - pub target_vars: RefCell>, - /// Global string caches - pub global_strings: RefCell>>>, - /// Global variable pointers cross different packages. - pub global_vars: RefCell>>>, - /// The line number of the source file corresponding to the current instruction - pub current_line: RefCell, - /// Error handler to store compile errors. - pub handler: RefCell, - /// Schema attr backtrack meta - pub backtrack_meta: RefCell>, - /// Import names mapping - pub import_names: IndexMap>, - /// No link mode - pub no_link: bool, - /// Program modules according to AST modules - pub modules: RefCell>>>, - /// Program workdir - pub workdir: String, -} - -/// LLVM module with debug info builder and compile unit. -pub struct DebugModule<'ctx> { - pub inner: Module<'ctx>, -} - -impl<'ctx> CodeGenObject for BasicValueEnum<'ctx> {} - -impl<'ctx> CodeGenObject for BasicTypeEnum<'ctx> {} - -impl<'ctx> BackendTypes for LLVMCodeGenContext<'ctx> { - type Value = BasicValueEnum<'ctx>; - type Type = BasicTypeEnum<'ctx>; - type BasicBlock = BasicBlock<'ctx>; - type Function = FunctionValue<'ctx>; - type FunctionLet = FunctionType<'ctx>; -} - -impl<'ctx> BuilderMethods for LLVMCodeGenContext<'ctx> { - /// SSA append a basic block named `name`. - #[inline] - fn append_block(&self, name: &str) -> Self::BasicBlock { - let cur_func = self.current_function(); - self.context.append_basic_block(cur_func, name) - } - /// SSA switch to the block. - #[inline] - fn switch_to_block(&self, block: Self::BasicBlock) { - self.builder.position_at_end(block); - } - /// SSA alloca instruction. - #[inline] - fn alloca(&self, ty: Self::Type, name: &str, _align: Option) -> Self::Value { - self.builder.build_alloca(ty, name).into() - } - /// SSA array alloca instruction. - #[inline] - fn array_alloca( - &self, - ty: Self::Type, - len: Self::Value, - name: &str, - _align: Align, - ) -> Self::Value { - self.builder - .build_array_alloca(ty, len.into_int_value(), name) - .into() - } - /// SSA ret instruction. - #[inline] - fn ret_void(&self) { - self.builder.build_return(None); - } - /// SSA ret instruction with returned value. - #[inline] - fn ret(&self, v: Self::Value) { - self.builder.build_return(Some(&v)); - } - /// SSA br instruction. - #[inline] - fn br(&self, dest: Self::BasicBlock) { - self.builder.build_unconditional_branch(dest); - } - /// SSA cond br instruction. - #[inline] - fn cond_br(&self, cond: Self::Value, then_bb: Self::BasicBlock, else_bb: Self::BasicBlock) { - self.builder - .build_conditional_branch(cond.into_int_value(), then_bb, else_bb); - } - /// SSA select instruction. - #[inline] - fn select( - &self, - cond: Self::Value, - then_val: Self::Value, - else_val: Self::Value, - ) -> Self::Value { - self.builder - .build_select(cond.into_int_value(), then_val, else_val, "") - } - /// SSA va arg instruction. - #[inline] - fn va_arg(&self, list: Self::Value, ty: Self::Type) -> Self::Value { - self.builder.build_va_arg(list.into_pointer_value(), ty, "") - } - /// SSA extract element instruction. - #[inline] - fn extract_element(&self, vec: Self::Value, idx: Self::Value) -> Self::Value { - self.builder - .build_extract_element(vec.into_vector_value(), idx.into_int_value(), "") - } - /// SSA extract value instruction. - #[inline] - fn extract_value(&self, agg_val: Self::Value, idx: u32) -> Self::Value { - self.builder - .build_extract_value(agg_val.into_array_value(), idx, "") - .expect(kcl_error::INTERNAL_ERROR_MSG) - } - /// SSA insert value instruction. - #[inline] - fn insert_value(&self, agg_val: Self::Value, elt: Self::Value, idx: u32) -> Self::Value { - self.builder - .build_insert_value(agg_val.into_array_value(), elt, idx, "") - .expect(kcl_error::INTERNAL_ERROR_MSG) - .into_array_value() - .into() - } - /// SSA function invoke instruction. - #[inline] - fn invoke( - &self, - _ty: Self::Type, - fn_value: Self::Function, - args: &[Self::Value], - then: Self::BasicBlock, - catch: Self::BasicBlock, - ) -> Self::Value { - self.builder - .build_invoke(fn_value, args, then, catch, "") - .try_as_basic_value() - .expect_left(kcl_error::INTERNAL_ERROR_MSG) - } - /// SSA function call instruction. - #[inline] - fn call(&self, _ty: Self::Type, fn_value: Self::Function, args: &[Self::Value]) -> Self::Value { - let args: Vec = args.iter().map(|arg| (*arg).into()).collect(); - self.builder - .build_call(fn_value, &args, "") - .try_as_basic_value() - .left() - .expect(kcl_error::FUNCTION_RETURN_VALUE_NOT_FOUND_MSG) - } - /// SSA load instruction. - #[inline] - fn load(&self, ptr: Self::Value, name: &str) -> Self::Value { - self.builder.build_load(ptr.into_pointer_value(), name) - } - /// SSA store instruction. - #[inline] - fn store(&self, ptr: Self::Value, val: Self::Value) { - self.builder.build_store(ptr.into_pointer_value(), val); - } - /// SSA gep instruction. - #[inline] - fn gep(&self, _ty: Self::Type, ptr: Self::Value, indices: &[Self::Value]) -> Self::Value { - let ordered_indexes: Vec = indices.iter().map(|v| v.into_int_value()).collect(); - unsafe { - self.builder - .build_gep(ptr.into_pointer_value(), &ordered_indexes, "") - .into() - } - } - /// SSA inbounds gep instruction. - #[inline] - fn inbounds_gep( - &self, - _ty: Self::Type, - ptr: Self::Value, - indices: &[Self::Value], - ) -> Self::Value { - let ordered_indexes: Vec = indices.iter().map(|v| v.into_int_value()).collect(); - unsafe { - self.builder - .build_in_bounds_gep(ptr.into_pointer_value(), &ordered_indexes, "") - .into() - } - } - /// SSA struct gep instruction. - #[inline] - fn struct_gep(&self, _ty: Self::Type, ptr: Self::Value, idx: u32) -> Self::Value { - self.builder - .build_struct_gep(ptr.into_pointer_value(), idx, "") - .expect(kcl_error::INTERNAL_ERROR_MSG) - .into() - } - /// SSA cast pointer to int. - #[inline] - fn ptr_to_int(&self, val: Self::Value, dest_ty: Self::Type) -> Self::Value { - self.builder - .build_ptr_to_int(val.into_pointer_value(), dest_ty.into_int_type(), "") - .into() - } - /// SSA cast int to pointer. - #[inline] - fn int_to_ptr(&self, val: Self::Value, dest_ty: Self::Type) -> Self::Value { - self.builder - .build_int_to_ptr(val.into_int_value(), dest_ty.into_pointer_type(), "") - .into() - } - /// SSA bit cast. - #[inline] - fn bit_cast(&self, val: Self::Value, dest_ty: Self::Type) -> Self::Value { - self.builder.build_bitcast(val, dest_ty, "") - } - /// SSA int cast. - #[inline] - fn int_cast(&self, val: Self::Value, dest_ty: Self::Type, _is_signed: bool) -> Self::Value { - self.builder - .build_int_cast(val.into_int_value(), dest_ty.into_int_type(), "") - .into() - } - /// SSA pointer cast. - #[inline] - fn ptr_cast(&self, val: Self::Value, dest_ty: Self::Type) -> Self::Value { - self.builder - .build_pointer_cast(val.into_pointer_value(), dest_ty.into_pointer_type(), "") - .into() - } - /// Lookup a known function named `name`. - fn lookup_function(&self, name: &str) -> Self::Function { - if self.no_link { - let pkgpath = self.current_pkgpath(); - let modules = self.modules.borrow(); - let msg = format!("pkgpath {} is not found", pkgpath); - let module = &modules.get(&pkgpath).expect(&msg).borrow().inner; - if let Some(function) = module.get_function(name) { - function - } else { - let function = self - .module - .get_function(name) - .unwrap_or_else(|| panic!("known function {} not found", name)); - let fn_type = function.get_type(); - module.add_function(name, fn_type, Some(Linkage::External)) - } - } else { - self.module - .get_function(name) - .unwrap_or_else(|| panic!("known function {} not found", name)) - } - } - /// Add a function named `name`. - fn add_function(&self, name: &str) -> Self::Function { - let fn_ty = self.function_type(); - if self.no_link { - let pkgpath = self.current_pkgpath(); - let msg = format!("pkgpath {} is not found", pkgpath); - let modules = self.modules.borrow_mut(); - let module = &modules.get(&pkgpath).expect(&msg).borrow_mut().inner; - module.add_function(name, fn_ty, None) - } else { - self.module.add_function(name, fn_ty, None) - } - } - - /// Add a setter function named `name`. - fn add_setter_function(&self, name: &str) -> Self::Function { - let fn_ty = self.setter_func_type(); - if self.no_link { - let pkgpath = self.current_pkgpath(); - let msg = format!("pkgpath {} is not found", pkgpath); - let modules = self.modules.borrow_mut(); - let module = modules.get(&pkgpath).expect(&msg).borrow_mut(); - module.inner.add_function(name, fn_ty, None) - } else { - self.module.add_function(name, fn_ty, None) - } - } -} - -/* Value methods */ - -impl<'ctx> ValueMethods for LLVMCodeGenContext<'ctx> { - /// Construct a 64-bit int value using i64 - fn int_value(&self, v: i64) -> Self::Value { - let i64_type = self.context.i64_type(); - self.build_call( - &ApiFunc::kclvm_value_Int.name(), - &[ - self.current_runtime_ctx_ptr(), - i64_type.const_int(v as u64, false).into(), - ], - ) - } - - /// Construct a 64-bit float value using f64 - fn float_value(&self, v: f64) -> Self::Value { - let f64_type = self.context.f64_type(); - self.build_call( - &ApiFunc::kclvm_value_Float.name(), - &[ - self.current_runtime_ctx_ptr(), - f64_type.const_float(v).into(), - ], - ) - } - - /// Construct a string value using &str - fn string_value(&self, v: &str) -> Self::Value { - let string_ptr_value = self.native_global_string(v, ""); - self.build_call( - &ApiFunc::kclvm_value_Str.name(), - &[self.current_runtime_ctx_ptr(), string_ptr_value.into()], - ) - } - - /// Construct a bool value - fn bool_value(&self, v: bool) -> Self::Value { - let i8_type = self.context.i8_type(); - self.build_call( - &ApiFunc::kclvm_value_Bool.name(), - &[ - self.current_runtime_ctx_ptr(), - i8_type.const_int(v as u64, false).into(), - ], - ) - } - - /// Construct a None value - fn none_value(&self) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_None.name(), - &[self.current_runtime_ctx_ptr()], - ) - } - - /// Construct a Undefined value - fn undefined_value(&self) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_Undefined.name(), - &[self.current_runtime_ctx_ptr()], - ) - } - - /// Construct a empty kcl list value - fn list_value(&self) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_List.name(), - &[self.current_runtime_ctx_ptr()], - ) - } - - /// Construct a list value with `n` elements - fn list_values(&self, values: &[Self::Value]) -> Self::Value { - let mut args = vec![self.current_runtime_ctx_ptr()]; - for value in values { - args.push(*value); - } - self.build_call( - &format!("{}{}", ApiFunc::kclvm_value_List.name(), values.len()), - args.as_slice(), - ) - } - - /// Construct a empty kcl dict value. - fn dict_value(&self) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_Dict.name(), - &[self.current_runtime_ctx_ptr()], - ) - } - - /// Construct a unit value - fn unit_value(&self, v: f64, raw: i64, unit: &str) -> Self::Value { - let f64_type = self.context.f64_type(); - let i64_type = self.context.i64_type(); - let unit_native_str = self.native_global_string(unit, ""); - self.build_call( - &ApiFunc::kclvm_value_Unit.name(), - &[ - self.current_runtime_ctx_ptr(), - f64_type.const_float(v).into(), - i64_type.const_int(raw as u64, false).into(), - unit_native_str.into(), - ], - ) - } - /// Construct a function value using a native function. - fn function_value(&self, function: FunctionValue<'ctx>) -> Self::Value { - let func_name = function.get_name().to_str().unwrap(); - let func_name_ptr = self.native_global_string(func_name, func_name).into(); - let lambda_fn_ptr = self.builder.build_bitcast( - function.as_global_value().as_pointer_value(), - self.context.i64_type().ptr_type(AddressSpace::default()), - "", - ); - self.build_call( - &ApiFunc::kclvm_value_Function_using_ptr.name(), - &[self.current_runtime_ctx_ptr(), lambda_fn_ptr, func_name_ptr], - ) - } - /// Construct a closure function value with the closure variable. - fn closure_value(&self, function: FunctionValue<'ctx>, closure: Self::Value) -> Self::Value { - let func_name = function.get_name().to_str().unwrap(); - let func_name_ptr = self.native_global_string(func_name, func_name).into(); - // Convert the function to a i64 pointer to store it into the function value. - let fn_ptr = self.builder.build_bitcast( - function.as_global_value().as_pointer_value(), - self.context.i64_type().ptr_type(AddressSpace::default()), - "", - ); - self.build_call( - &ApiFunc::kclvm_value_Function.name(), - &[ - self.current_runtime_ctx_ptr(), - fn_ptr, - closure, - func_name_ptr, - self.native_i8_zero().into(), - ], - ) - } - /// Construct a schema function value using native functions. - fn struct_function_value( - &self, - functions: &[FunctionValue<'ctx>], - attr_functions: &HashMap>>, - runtime_type: &str, - ) -> Self::Value { - if functions.is_empty() { - return self.none_value(); - } - // Convert the function to a i64 pointer to store it into the function value. - let schema_body_fn_ptr = self.builder.build_bitcast( - functions[0].as_global_value().as_pointer_value(), - self.context.i64_type().ptr_type(AddressSpace::default()), - "", - ); - // Convert the function to a i64 pointer to store it into the function value. - let check_block_fn_ptr = if functions.len() > 1 { - self.builder.build_bitcast( - functions[1].as_global_value().as_pointer_value(), - self.context.i64_type().ptr_type(AddressSpace::default()), - "", - ) - } else { - self.context - .i64_type() - .ptr_type(AddressSpace::default()) - .const_zero() - .into() - }; - let runtime_type_native_str = self.native_global_string_value(runtime_type); - let attr_map = self.dict_value(); - for attr in attr_functions.keys() { - self.dict_insert_override_item(attr_map, attr, self.undefined_value()) - } - self.builder - .build_call( - self.lookup_function(&ApiFunc::kclvm_value_schema_function.name()), - &[ - self.current_runtime_ctx_ptr().into(), - schema_body_fn_ptr.into(), - check_block_fn_ptr.into(), - attr_map.into(), - runtime_type_native_str.into(), - ], - runtime_type, - ) - .try_as_basic_value() - .left() - .expect(kcl_error::FUNCTION_RETURN_VALUE_NOT_FOUND_MSG) - } - /// Construct a builtin function value using the function name. - fn builtin_function_value(&self, function_name: &str) -> Self::Value { - let mut function = self - .module - .get_function(function_name) - .unwrap_or_else(|| panic!("global function {} not found", function_name)); - if self.no_link { - let pkgpath = self.current_pkgpath(); - let modules = self.modules.borrow_mut(); - let msg = format!("pkgpath {} is not found", pkgpath); - let module = &modules.get(&pkgpath).expect(&msg).borrow_mut().inner; - let fn_type = function.get_type(); - function = module.add_function(function_name, fn_type, Some(Linkage::External)); - } - self.function_value(function) - } - /// Get a global value pointer named `name`. - fn global_value_ptr(&self, name: &str) -> Self::Value { - let tpe = self.value_ptr_type(); - // Builtin function value is a global one - let global_var = if self.no_link { - let pkgpath = self.current_pkgpath(); - let msg = format!("pkgpath {} is not found", pkgpath); - let modules = self.modules.borrow_mut(); - let module = &modules.get(&pkgpath).expect(&msg).borrow_mut().inner; - module.add_global(tpe, Some(AddressSpace::default()), name) - } else { - self.module - .add_global(tpe, Some(AddressSpace::default()), name) - }; - global_var.set_alignment(GLOBAL_VAL_ALIGNMENT); - global_var.set_initializer(&tpe.const_zero()); - global_var.as_pointer_value().into() - } - /// Get the global runtime context pointer. - fn current_runtime_ctx_ptr(&self) -> Self::Value { - self.builder - .get_insert_block() - .unwrap() - .get_parent() - .unwrap() - .get_first_param() - .expect(kcl_error::CONTEXT_VAR_NOT_FOUND_MSG) - } - /// Get the global evaluation scope pointer. - fn current_scope_ptr(&self) -> Self::Value { - self.builder - .get_insert_block() - .unwrap() - .get_parent() - .unwrap() - .get_nth_param(1) - .expect(kcl_error::CONTEXT_VAR_NOT_FOUND_MSG) - } -} - -impl<'ctx> ValueCalculationMethods for LLVMCodeGenContext<'ctx> { - /// lhs + rhs - fn add(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_op_add.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs - rhs - fn sub(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_op_sub.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs * rhs - fn mul(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_op_mul.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs / rhs - fn div(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_op_div.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs // rhs - fn floor_div(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_op_floor_div.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs % rhs - fn r#mod(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_op_mod.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs ** rhs - fn pow(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_op_pow.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs << rhs - fn bit_lshift(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_op_bit_lshift.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs >> rhs - fn bit_rshift(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_op_bit_rshift.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs & rhs - fn bit_and(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_op_bit_and.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs | rhs - fn bit_or(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_op_bit_or.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs ^ rhs - fn bit_xor(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_op_bit_xor.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs and rhs - fn logic_and(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_logic_and.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs or rhs - fn logic_or(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_logic_or.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs == rhs - fn cmp_equal_to(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_cmp_equal_to.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs != rhs - fn cmp_not_equal_to(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_cmp_not_equal_to.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs > rhs - fn cmp_greater_than(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_cmp_greater_than.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs >= rhs - fn cmp_greater_than_or_equal(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_cmp_greater_than_or_equal.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs < rhs - fn cmp_less_than(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_cmp_less_than.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs <= rhs - fn cmp_less_than_or_equal(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_cmp_less_than_or_equal.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs as rhs - fn r#as(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_as.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs is rhs - fn is(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_is.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs is not rhs - fn is_not(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_is_not.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs in rhs - fn r#in(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_in.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } - /// lhs not in rhs - fn not_in(&self, lhs: Self::Value, rhs: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_not_in.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ) - } -} - -impl<'ctx> DerivedValueCalculationMethods for LLVMCodeGenContext<'ctx> { - /// Value subscript a[b] - #[inline] - fn value_subscript(&self, value: Self::Value, item: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_subscr.name(), - &[self.current_runtime_ctx_ptr(), value, item], - ) - } - /// Value is truth function, return i1 value. - fn value_is_truthy(&self, value: Self::Value) -> Self::Value { - let is_truth = self - .build_call(&ApiFunc::kclvm_value_is_truthy.name(), &[value]) - .into_int_value(); - self.builder - .build_int_compare(IntPredicate::NE, is_truth, self.native_i8_zero(), "") - .into() - } - /// Value deep copy - #[inline] - fn value_deep_copy(&self, value: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_deep_copy.name(), - &[self.current_runtime_ctx_ptr(), value], - ) - } - /// value_union unions two collection elements. - #[inline] - fn value_union(&self, lhs: Self::Value, rhs: Self::Value) { - self.build_void_call( - &ApiFunc::kclvm_value_union.name(), - &[self.current_runtime_ctx_ptr(), lhs, rhs], - ); - } - // List get the item using the index. - #[inline] - fn list_get(&self, list: Self::Value, index: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_list_get.name(), - &[self.current_runtime_ctx_ptr(), list, index], - ) - } - // List set the item using the index. - #[inline] - fn list_set(&self, list: Self::Value, index: Self::Value, value: Self::Value) { - self.build_void_call(&ApiFunc::kclvm_list_set.name(), &[list, index, value]) - } - // List slice. - #[inline] - fn list_slice( - &self, - list: Self::Value, - start: Self::Value, - stop: Self::Value, - step: Self::Value, - ) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_value_slice.name(), - &[self.current_runtime_ctx_ptr(), list, start, stop, step], - ) - } - /// Append a item into the list. - #[inline] - fn list_append(&self, list: Self::Value, item: Self::Value) { - self.build_void_call(&ApiFunc::kclvm_list_append.name(), &[list, item]) - } - /// Append a list item and unpack it into the list. - #[inline] - fn list_append_unpack(&self, list: Self::Value, item: Self::Value) { - self.build_void_call(&ApiFunc::kclvm_list_append_unpack.name(), &[list, item]); - } - /// Runtime list value pop - #[inline] - fn list_pop(&self, list: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_list_pop.name(), - &[self.current_runtime_ctx_ptr(), list], - ) - } - /// Runtime list pop the first value - #[inline] - fn list_pop_first(&self, list: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_list_pop_first.name(), - &[self.current_runtime_ctx_ptr(), list], - ) - } - /// List clear value. - #[inline] - fn list_clear(&self, list: Self::Value) { - self.build_void_call(&ApiFunc::kclvm_list_clear.name(), &[list]) - } - /// Return number of occurrences of the list value. - #[inline] - fn list_count(&self, list: Self::Value, item: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_list_count.name(), - &[self.current_runtime_ctx_ptr(), list, item], - ) - } - /// Return first index of the list value. Panic if the value is not present. - #[inline] - fn list_find(&self, list: Self::Value, item: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_list_find.name(), - &[self.current_runtime_ctx_ptr(), list, item], - ) - } - /// Insert object before index of the list value. - #[inline] - fn list_insert(&self, list: Self::Value, index: Self::Value, value: Self::Value) { - self.build_void_call(&ApiFunc::kclvm_list_insert.name(), &[list, index, value]) - } - /// List length. - #[inline] - fn list_len(&self, list: Self::Value) -> Self::Value { - self.build_call(&ApiFunc::kclvm_list_len.name(), &[list]) - } - /// Dict get the value of the key. - #[inline] - fn dict_get(&self, dict: Self::Value, key: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_dict_get_value.name(), - &[self.current_runtime_ctx_ptr(), dict, key], - ) - } - /// Dict set the value of the key. - #[inline] - fn dict_set(&self, dict: Self::Value, key: Self::Value, value: Self::Value) { - self.build_void_call( - &ApiFunc::kclvm_dict_set_value.name(), - &[self.current_runtime_ctx_ptr(), dict, key, value], - ) - } - /// Return all dict keys. - #[inline] - fn dict_keys(&self, dict: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_dict_keys.name(), - &[self.current_runtime_ctx_ptr(), dict], - ) - } - /// Return all dict values. - #[inline] - fn dict_values(&self, dict: Self::Value) -> Self::Value { - self.build_call( - &ApiFunc::kclvm_dict_values.name(), - &[self.current_runtime_ctx_ptr(), dict], - ) - } - /// Dict clear value. - #[inline] - fn dict_clear(&self, dict: Self::Value) { - self.build_void_call( - &ApiFunc::kclvm_dict_insert_value.name(), - &[self.current_runtime_ctx_ptr(), dict], - ) - } - /// Dict pop the value of the key. - #[inline] - fn dict_pop(&self, dict: Self::Value, key: Self::Value) -> Self::Value { - self.build_call(&ApiFunc::kclvm_dict_remove.name(), &[dict, key]) - } - /// Dict length. - #[inline] - fn dict_len(&self, dict: Self::Value) -> Self::Value { - self.build_call(&ApiFunc::kclvm_dict_len.name(), &[dict]) - } - /// Insert a dict entry including key, value, op and insert_index into the dict, - /// and the type of key is `&str` - #[inline] - fn dict_insert( - &self, - dict: Self::Value, - key: &str, - value: Self::Value, - op: i32, - insert_index: Option, - ) { - let name = self.native_global_string(key, "").into(); - let op = self.native_int_value(op); - let has_insert_index = insert_index.is_some(); - let has_insert_index = self.native_i8_value(if has_insert_index { 1 } else { 0 }); - let insert_index = self.native_int_value(insert_index.unwrap_or(-1)); - self.build_void_call( - &ApiFunc::kclvm_dict_insert.name(), - &[ - self.current_runtime_ctx_ptr(), - dict, - name, - value, - op, - insert_index, - has_insert_index, - ], - ); - } - - /// Insert a dict entry including key, value, op and insert_index into the dict. - /// and the type of key is `Self::Value` - #[inline] - fn dict_insert_with_key_value( - &self, - dict: Self::Value, - key: Self::Value, - value: Self::Value, - op: i32, - insert_index: Option, - ) { - let op = self.native_int_value(op); - let has_insert_index = insert_index.is_some(); - let has_insert_index = self.native_i8_value(if has_insert_index { 1 } else { 0 }); - let insert_index = self.native_int_value(insert_index.unwrap_or(-1)); - self.build_void_call( - &ApiFunc::kclvm_dict_insert_value.name(), - &[ - self.current_runtime_ctx_ptr(), - dict, - key, - value, - op, - insert_index, - has_insert_index, - ], - ); - } -} - -impl<'ctx> ValueCodeGen for LLVMCodeGenContext<'ctx> {} - -/* Type methods */ - -impl<'ctx> BaseTypeMethods for LLVMCodeGenContext<'ctx> { - /// Native i8 type - fn i8_type(&self) -> Self::Type { - self.context.i8_type().into() - } - /// Native i16 type - fn i16_type(&self) -> Self::Type { - self.context.i16_type().into() - } - /// Native i32 type - fn i32_type(&self) -> Self::Type { - self.context.i32_type().into() - } - /// Native i64 type - fn i64_type(&self) -> Self::Type { - self.context.i64_type().into() - } - /// Native i128 type - fn i128_type(&self) -> Self::Type { - self.context.i128_type().into() - } - /// Native f32 type - fn f32_type(&self) -> Self::Type { - self.context.f32_type().into() - } - /// Native f64 type - fn f64_type(&self) -> Self::Type { - self.context.f64_type().into() - } - /// Native struct type. - #[inline] - fn struct_type(&self, els: &[Self::Type], packed: bool) -> Self::Type { - self.context.struct_type(els, packed).into() - } - /// Native pointer type of `ty`. - #[inline] - fn ptr_type_to(&self, ty: Self::Type) -> Self::Type { - self.ptr_type_to_ext(ty, crate::codegen::abi::AddressSpace::DATA) - } - /// Native pointer type of `ty` with the address space. - #[inline] - fn ptr_type_to_ext( - &self, - ty: Self::Type, - address_space: crate::codegen::abi::AddressSpace, - ) -> Self::Type { - let address_space = - AddressSpace::try_from(address_space.0).expect(kcl_error::INTERNAL_ERROR_MSG); - let ptr_type = match ty { - BasicTypeEnum::ArrayType(a) => a.ptr_type(address_space), - BasicTypeEnum::FloatType(f) => f.ptr_type(address_space), - BasicTypeEnum::IntType(i) => i.ptr_type(address_space), - BasicTypeEnum::PointerType(p) => p.ptr_type(address_space), - BasicTypeEnum::StructType(s) => s.ptr_type(address_space), - BasicTypeEnum::VectorType(v) => v.ptr_type(address_space), - }; - ptr_type.into() - } - /// Native array element type. - #[inline] - fn element_type(&self, ty: Self::Type) -> Self::Type { - match ty { - BasicTypeEnum::ArrayType(a) => a.get_element_type(), - BasicTypeEnum::VectorType(v) => v.get_element_type(), - other => panic!("element_type called on unsupported type {:?}", other), - } - } - /// Returns the number of elements in `self` if it is a LLVM vector type. - #[inline] - fn vector_length(&self, ty: Self::Type) -> usize { - ty.into_vector_type().get_size() as usize - } - /// Retrieves the bit width of the float type `self`. - #[inline] - fn float_width(&self, ty: Self::Type) -> usize { - let ty_str = format!("{:?}", ty.into_float_type()); - for (float_ty, float_width) in FLOAT_TYPE_WIDTH_MAPPING.into_iter() { - if ty_str.contains(float_ty) { - return *float_width; - } - } - panic!("float_width called on unsupported type {:?}", ty); - } - /// Retrieves the bit width of the integer type `self`. - #[inline] - fn int_width(&self, ty: Self::Type) -> usize { - ty.into_int_type().get_bit_width() as usize - } - /// Get the value type. - #[inline] - fn val_type(&self, v: Self::Value) -> Self::Type { - v.get_type() - } - /// Native function type - #[inline] - fn function_let(&self, args: &[Self::Type], ret: Self::Type) -> Self::FunctionLet { - let args: Vec = args.iter().map(|arg| (*arg).into()).collect(); - ret.fn_type(&args, false) - } -} - -impl<'ctx> DerivedTypeMethods for LLVMCodeGenContext<'ctx> { - /// Lookup type by the type name. - #[inline] - fn get_intrinsic_type(&self, name: &str) -> Self::Type { - self.module - .get_struct_type(name) - .expect(kcl_error::VALUE_TYPE_NOT_FOUND_MSG) - .into() - } -} - -impl<'ctx> TypeCodeGen for LLVMCodeGenContext<'ctx> {} - -impl<'ctx> ProgramCodeGen for LLVMCodeGenContext<'ctx> { - /// Current package path - #[inline] - fn current_pkgpath(&self) -> String { - self.pkgpath_stack - .borrow_mut() - .last() - .expect(kcl_error::INTERNAL_ERROR_MSG) - .to_string() - } - - /// Current filename - #[inline] - fn current_filename(&self) -> String { - self.filename_stack - .borrow_mut() - .last() - .expect(kcl_error::INTERNAL_ERROR_MSG) - .to_string() - } - /// Init a scope named `pkgpath` with all builtin functions - fn init_scope(&self, pkgpath: &str) { - { - let mut pkg_scopes = self.pkg_scopes.borrow_mut(); - if pkg_scopes.contains_key(pkgpath) { - return; - } - let scopes = vec![Rc::new(Scope::default())]; - pkg_scopes.insert(String::from(pkgpath), scopes); - } - let msg = format!("pkgpath {} is not found", pkgpath); - // Init all global types including schema and rule - let module_list: &Vec = if self.program.pkgs.contains_key(pkgpath) { - self.program.pkgs.get(pkgpath).expect(&msg) - } else if pkgpath.starts_with(kclvm_runtime::PKG_PATH_PREFIX) - && self.program.pkgs.contains_key(&pkgpath[1..]) - { - self.program - .pkgs - .get(&pkgpath[1..]) - .expect(kcl_error::INTERNAL_ERROR_MSG) - } else { - panic!("pkgpath {} not found", pkgpath); - }; - for module in module_list { - for stmt in &module.body { - let name = match &stmt.node { - ast::Stmt::Schema(schema_stmt) => schema_stmt.name.node.clone(), - ast::Stmt::Rule(rule_stmt) => rule_stmt.name.node.clone(), - _ => "".to_string(), - }; - if !name.is_empty() { - let name = name.as_str(); - let var_name = format!("${}.${}", pkgpath_without_prefix!(pkgpath), name); - let global_var_ptr = self.new_global_kcl_value_ptr(&var_name); - self.add_variable(name, global_var_ptr); - } - } - } - // Init all builtin functions - for symbol in builtin::BUILTIN_FUNCTION_NAMES { - let function_name = - format!("{}_{}", builtin::KCL_BUILTIN_FUNCTION_MANGLE_PREFIX, symbol); - let function_value = self.builtin_function_value(function_name.as_str()); - let builtin_function_name = format!( - "{}_{}_{}", - builtin::BUILTIN_FUNCTION_PREFIX, - pkgpath_without_prefix!(pkgpath), - function_name - ); - let global_var_ptr = self.new_global_kcl_value_ptr(&builtin_function_name); - self.builder.build_store(global_var_ptr, function_value); - self.add_variable(symbol, global_var_ptr); - } - self.enter_scope(); - } - - /// Get the scope level - fn scope_level(&self) -> usize { - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get(¤t_pkgpath).expect(&msg); - // Sub the builtin global scope - scopes.len() - 1 - } - - /// Enter scope - fn enter_scope(&self) { - let current_pkgpath = self.current_pkgpath(); - let mut pkg_scopes = self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); - let scope = Rc::new(Scope::default()); - scopes.push(scope); - } - - /// Leave scope - fn leave_scope(&self) { - let current_pkgpath = self.current_pkgpath(); - let mut pkg_scopes = self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); - scopes.pop(); - } -} - -impl<'ctx> CodeGenContext for LLVMCodeGenContext<'ctx> { - /// Generate LLVM IR of ast module. - fn emit(&self, opt: &EmitOptions) -> Result<(), Box> { - self.emit_code(opt) - } -} - -impl<'ctx> LLVMCodeGenContext<'ctx> { - /// New aa LLVMCodeGenContext using the LLVM Context and AST Program - pub fn new( - context: &'ctx Context, - module: Module<'ctx>, - program: &'ctx ast::Program, - import_names: IndexMap>, - no_link: bool, - workdir: String, - ) -> LLVMCodeGenContext<'ctx> { - LLVMCodeGenContext { - context, - module, - builder: context.create_builder(), - program, - pkg_scopes: RefCell::new(HashMap::new()), - functions: RefCell::new(vec![]), - imported: RefCell::new(HashSet::new()), - local_vars: RefCell::new(HashSet::new()), - setter_keys: RefCell::new(HashSet::new()), - schema_stack: RefCell::new(vec![]), - // 1 denotes the top global main function lambda and 0 denotes the builtin scope. - // Any user-defined lambda scope greater than 1. - lambda_stack: RefCell::new(vec![GLOBAL_LEVEL]), - schema_expr_stack: RefCell::new(vec![]), - pkgpath_stack: RefCell::new(vec![String::from(MAIN_PKG_PATH)]), - filename_stack: RefCell::new(vec![String::from("")]), - target_vars: RefCell::new(vec![String::from("")]), - global_strings: RefCell::new(IndexMap::default()), - global_vars: RefCell::new(IndexMap::default()), - current_line: RefCell::new(0), - handler: RefCell::new(Handler::default()), - backtrack_meta: RefCell::new(None), - import_names, - no_link, - modules: RefCell::new(HashMap::new()), - workdir, - } - } - - /// Generate LLVM IR of ast module. - pub(crate) fn emit_code( - self: &LLVMCodeGenContext<'ctx>, - opt: &EmitOptions, - ) -> Result<(), Box> { - let tpe = self.value_ptr_type().into_pointer_type(); - let void_type = self.context.void_type(); - let context_ptr_type = self.context_ptr_type(); - let scope_ptr_type = self.scope_ptr_type(); - let fn_type = tpe.fn_type(&[context_ptr_type.into(), scope_ptr_type.into()], false); - let void_fn_type = - void_type.fn_type(&[context_ptr_type.into(), scope_ptr_type.into()], false); - let has_main_pkg = self.program.pkgs.contains_key(MAIN_PKG_PATH); - let function = if self.no_link { - let mut modules = self.modules.borrow_mut(); - let (pkgpath, function_name) = if has_main_pkg { - (MAIN_PKG_PATH.to_string(), MODULE_NAME.to_string()) - } else { - assert!(self.program.pkgs.len() == 1); - let pkgpath = format!( - "{}{}", - kclvm_runtime::PKG_PATH_PREFIX, - self.program - .pkgs - .keys() - .next() - .expect(kcl_error::INTERNAL_ERROR_MSG) - ); - ( - pkgpath.clone(), - format!( - "${}.{}", - pkgpath_without_prefix!(pkgpath), - PKG_INIT_FUNCTION_SUFFIX - ), - ) - }; - let module = self.context.create_module(pkgpath.as_str()); - let function = module.add_function( - // Function name - function_name.as_str(), - // Function type - if has_main_pkg { fn_type } else { void_fn_type }, - None, - ); - modules.insert( - pkgpath.to_string(), - RefCell::new(self.create_debug_module(module)), - ); - function - } else { - self.module.add_function( - // Function name - MODULE_NAME, - // Function type - fn_type, - None, - ) - }; - self.push_function(function); - // Add a block named entry into the function - let basic_block = self.append_block(ENTRY_NAME); - // Set position to the basic block - self.builder.position_at_end(basic_block); - // Get the runtime context - let ctx_value = function - .get_first_param() - .expect(kcl_error::INTERNAL_ERROR_MSG); - if self.no_link && !has_main_pkg { - for pkgpath in self.program.pkgs.keys() { - let pkgpath = format!("{}{}", kclvm_runtime::PKG_PATH_PREFIX, pkgpath); - self.push_pkgpath(&pkgpath); - } - } - if !self.import_names.is_empty() { - let import_names = self.dict_value(); - for (k, v) in &self.import_names { - let map = self.dict_value(); - for (pkgname, pkgpath) in v { - self.dict_insert_override_item( - map, - pkgname, - self.string_value(&format!("@{}", pkgpath)), - ); - } - self.dict_insert_override_item(import_names, k, map); - } - self.build_void_call( - &ApiFunc::kclvm_context_set_import_names.name(), - &[ctx_value, import_names], - ); - } - // Main package - if self.no_link && !has_main_pkg { - // When compiling a pkgpath separately, only one pkgpath is required in the AST Program - assert!(self.program.pkgs.len() == 1); - // pkgs may not contains main pkg in no link mode - for (pkgpath, modules) in &self.program.pkgs { - let pkgpath = format!("{}{}", kclvm_runtime::PKG_PATH_PREFIX, pkgpath); - self.push_pkgpath(&pkgpath); - // Init all builtin functions. - self.init_scope(pkgpath.as_str()); - self.compile_ast_modules(modules); - } - self.ret_void(); - } else { - // Set the kcl module path to the runtime context only in the main package. - self.build_void_call( - &ApiFunc::kclvm_context_set_kcl_modpath.name(), - &[ - self.current_runtime_ctx_ptr(), - self.native_global_string_value(&self.program.root), - ], - ); - // Set the kcl workdir to the runtime context - self.build_void_call( - &ApiFunc::kclvm_context_set_kcl_workdir.name(), - &[ - self.current_runtime_ctx_ptr(), - self.native_global_string_value(&self.workdir), - ], - ); - // Init scope and all builtin functions - self.init_scope(MAIN_PKG_PATH); - let main_pkg_modules = self - .program - .pkgs - .get(MAIN_PKG_PATH) - .expect(kcl_error::INTERNAL_ERROR_MSG); - self.compile_ast_modules(main_pkg_modules); - // Get the JSON string including all global variables - let json_str_value = self.globals_to_json_str(); - // Build a return in the current block - self.pop_function(); - self.builder - .build_return(Some(&json_str_value.into_pointer_value())); - } - if let Some(path_str) = &opt.emit_path { - let path = std::path::Path::new(&path_str); - if opt.no_link { - let modules = self.modules.borrow_mut(); - for (index, (_, module)) in modules.iter().enumerate() { - let path = if modules.len() == 1 { - format!("{}{}", path_str, OBJECT_FILE_SUFFIX) - } else { - format!("{}_{}{}", path_str, index, OBJECT_FILE_SUFFIX) - }; - let path = std::path::Path::new(&path); - // Build LLVM module to a `.o` object file. - self.build_object_file(&module.borrow().inner, path)?; - } - } else { - // Build LLVM module to a `.o` object file. - self.build_object_file(&self.module, path)?; - } - } - Ok(()) - } - - /// Build LLVM module to a `.o` object file. - /// - /// TODO: WASM and cross platform build. - fn build_object_file( - self: &LLVMCodeGenContext<'ctx>, - module: &Module, - path: &Path, - ) -> Result<(), LLVMString> { - let triple = inkwell::targets::TargetMachine::get_default_triple(); - let target = inkwell::targets::Target::from_triple(&triple)?; - // Convert LLVM module to ll file. - module.print_to_file(path)?; - let buf = MemoryBuffer::create_from_file(path)?; - let module = self.context.create_module_from_ir(buf)?; - // Read ll file and use target machine to generate native object file. - let target_machine = target - .create_target_machine( - &triple, - "", - "", - // We do not enable any optimization, so that - // the sum of compile time and run time is as small as possible - inkwell::OptimizationLevel::None, - RelocMode::PIC, - CodeModel::Default, - ) - .expect(kcl_error::CODE_GEN_ERROR_MSG); - target_machine.write_to_file(&module, FileType::Object, path) - } -} - -impl<'ctx> LLVMCodeGenContext<'ctx> { - /// Get compiler default ok result - #[inline] - pub fn ok_result(&self) -> CompileResult<'ctx> { - let i32_type = self.context.i32_type(); - Ok(i32_type.const_int(0u64, false).into()) - } - - /// Build a void function call - #[inline] - pub fn build_void_call(&self, name: &str, args: &[BasicValueEnum]) { - let args: Vec = args.iter().map(|arg| (*arg).into()).collect(); - self.builder - .build_call(self.lookup_function(name), &args, ""); - } - - /// Build a function call with the return value - #[inline] - pub fn build_call(&self, name: &str, args: &[BasicValueEnum<'ctx>]) -> BasicValueEnum<'ctx> { - let args: Vec = args.iter().map(|arg| (*arg).into()).collect(); - self.builder - .build_call(self.lookup_function(name), &args, "") - .try_as_basic_value() - .left() - .expect(kcl_error::FUNCTION_RETURN_VALUE_NOT_FOUND_MSG) - } - - /// Creates global string in the llvm module with initializer - pub fn native_global_string(&self, value: &str, name: &str) -> PointerValue<'ctx> { - let mut global_string_maps = self.global_strings.borrow_mut(); - let pkgpath = self.current_pkgpath(); - let str_name = format!("${}_{}_str", pkgpath_without_prefix!(pkgpath), name); - if !global_string_maps.contains_key(&pkgpath) { - global_string_maps.insert(pkgpath.clone(), IndexMap::default()); - } - let msg = format!("pkgpath {} is not found", pkgpath); - let global_strings = global_string_maps.get_mut(&pkgpath).expect(&msg); - if let Some(ptr) = global_strings.get(value) { - *ptr - } else { - let gv = unsafe { self.builder.build_global_string(value, &str_name) }; - let ptr = self - .ptr_cast( - gv.as_pointer_value().into(), - self.ptr_type_to(self.i8_type()), - ) - .into_pointer_value(); - global_strings.insert(value.to_string(), ptr); - ptr - } - } - - /// Creates global string value in the llvm module with initializer - pub fn native_global_string_value(&self, value: &str) -> BasicValueEnum<'ctx> { - let pkgpath = self.current_pkgpath(); - let str_name = format!("${}_str", pkgpath_without_prefix!(pkgpath)); - self.native_global_string(value, &str_name).into() - } - - /// Get LLVM i8 zero value - pub fn native_i8_zero(&self) -> IntValue<'ctx> { - let i8_type = self.context.i8_type(); - i8_type.const_int(0u64, false) - } - - /// Get LLVM i8 zero value - pub fn native_i8(&self, v: i8) -> IntValue<'ctx> { - let i8_type = self.context.i8_type(); - i8_type.const_int(v as u64, false) - } - - /// Get LLVM i8 zero value - pub fn native_i8_value(&self, v: i8) -> BasicValueEnum<'ctx> { - let i8_type = self.context.i8_type(); - i8_type.const_int(v as u64, false).into() - } - - /// Construct a LLVM int value using i32 - pub fn native_int_value(&self, v: i32) -> BasicValueEnum<'ctx> { - let i32_type = self.context.i32_type(); - i32_type.const_int(v as u64, false).into() - } - - /// Construct a global value pointer named `name` - pub fn new_global_kcl_value_ptr(&self, name: &str) -> PointerValue<'ctx> { - let tpe = self.value_ptr_type(); - // Builtin function value is a global one - let global_var = if self.no_link { - let pkgpath = self.current_pkgpath(); - let msg = format!("pkgpath {} is not found", pkgpath); - let modules = self.modules.borrow_mut(); - let module = &modules.get(&pkgpath).expect(&msg).borrow_mut().inner; - module.add_global(tpe, Some(AddressSpace::default()), name) - } else { - self.module - .add_global(tpe, Some(AddressSpace::default()), name) - }; - global_var.set_alignment(GLOBAL_VAL_ALIGNMENT); - global_var.set_initializer(&tpe.const_zero()); - global_var.as_pointer_value() - } - - /// Append a scalar value into the scope. - pub fn add_scalar(&self, scalar: BasicValueEnum<'ctx>, is_schema: bool) { - let current_pkgpath = self.current_pkgpath(); - let mut pkg_scopes = self.pkg_scopes.borrow_mut(); - let scopes = pkg_scopes - .get_mut(¤t_pkgpath) - .unwrap_or_else(|| panic!("pkgpath {} is not found", current_pkgpath)); - if let Some(last) = scopes.last_mut() { - let mut scalars = last.scalars.borrow_mut(); - // TODO: To avoid conflicts, only the last schema scalar expressions are allowed. - let mut schema_scalar_idx = last.schema_scalar_idx.borrow_mut(); - if is_schema { - // Remove the last schema scalar. - if *schema_scalar_idx < scalars.len() { - scalars.remove(*schema_scalar_idx); - } - // Override the last schema scalar. - scalars.push(scalar); - *schema_scalar_idx = scalars.len() - 1; - } else { - scalars.push(scalar); - } - } - } - - /// Append a variable into the scope - pub fn add_variable(&self, name: &str, pointer: PointerValue<'ctx>) { - let current_pkgpath = self.current_pkgpath(); - let mut pkg_scopes = self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); - if let Some(last) = scopes.last_mut() { - let mut variables = last.variables.borrow_mut(); - if !variables.contains_key(name) { - variables.insert(name.to_string(), pointer); - } - } - } - - /// Store the argument named `name` in the current scope. - pub(crate) fn store_argument_in_current_scope(&self, name: &str) { - // Find argument name in the scope - let current_pkgpath = self.current_pkgpath(); - let mut pkg_scopes = self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); - let index = scopes.len() - 1; - let mut arguments_mut = scopes[index].arguments.borrow_mut(); - arguments_mut.insert(name.to_string()); - } - - /// Store the variable named `name` with `value` from the current scope, return false when not found - pub fn store_variable_in_current_scope(&self, name: &str, value: BasicValueEnum<'ctx>) -> bool { - // Find argument name in the scope - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = self.pkg_scopes.borrow(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get(¤t_pkgpath).expect(&msg); - let index = scopes.len() - 1; - let variables = scopes[index].variables.borrow(); - if let Some(var) = variables.get(&name.to_string()) { - self.builder.build_store(*var, value); - return true; - } - false - } - - /// Store the variable named `name` with `value` from the scope, return false when not found - pub fn store_variable(&self, name: &str, value: BasicValueEnum<'ctx>) -> bool { - // Find argument name in the scope - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = self.pkg_scopes.borrow(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get(¤t_pkgpath).expect(&msg); - for i in 0..scopes.len() { - let index = scopes.len() - i - 1; - let variables = scopes[index].variables.borrow(); - if let Some(var) = variables.get(&name.to_string()) { - self.builder.build_store(*var, value); - return true; - } - } - false - } - - /// Resolve variable in scope, return false when not found. - #[inline] - pub fn resolve_variable(&self, name: &str) -> bool { - self.resolve_variable_level(name).is_some() - } - - /// Resolve variable level in scope, return None when not found. - pub fn resolve_variable_level(&self, name: &str) -> Option { - // Find argument name in the scope - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = self.pkg_scopes.borrow(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get(¤t_pkgpath).expect(&msg); - let mut level = None; - for i in 0..scopes.len() { - let index = scopes.len() - i - 1; - let variables = scopes[index].variables.borrow(); - let arguments = scopes[index].arguments.borrow(); - if variables.get(name).is_some() { - level = Some(index); - break; - } - if arguments.contains(name) { - level = Some(index); - break; - } - } - level - } - - /// Append a variable or update the existed closure variable within the current scope. - pub fn add_or_update_local_variable_within_scope( - &self, - name: &str, - value: Option>, - ) { - let current_pkgpath = self.current_pkgpath(); - let mut pkg_scopes = self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); - let index = scopes.len() - 1; - if let Some(scope) = scopes.last_mut() { - let mut variables_mut = scope.variables.borrow_mut(); - let mut uninitialized = scope.uninitialized.borrow_mut(); - if value.is_none() { - uninitialized.insert(name.to_string()); - } else { - uninitialized.remove(name); - } - match variables_mut.get(&name.to_string()) { - // If the local variable is found, store the new value for the variable. - // We cannot update rule/lambda/schema arguments because they are read-only. - Some(ptr) if index > GLOBAL_LEVEL => { - if let Some(value) = value { - self.builder.build_store(*ptr, value); - } - } - _ => { - let ptr = self.builder.build_alloca(self.value_ptr_type(), name); - if let Some(value) = value { - self.builder.build_store(ptr, value); - } - // Store the value for the variable and add the variable into the current scope. - variables_mut.insert(name.to_string(), ptr); - } - }; - } - } - - /// Append a variable or update the existed variable - pub fn add_or_update_global_variable( - &self, - name: &str, - value: BasicValueEnum<'ctx>, - save_scope: bool, - ) { - // Find argument name in the scope - let current_pkgpath = self.current_pkgpath(); - let mut pkg_scopes = self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); - let mut existed = false; - if let Some(last) = scopes.last_mut() { - let variables = last.variables.borrow(); - if let Some(var) = variables.get(&name.to_string()) { - self.builder.build_store(*var, value); - if save_scope { - self.build_void_call( - &ApiFunc::kclvm_scope_set.name(), - &[ - self.current_runtime_ctx_ptr(), - self.current_scope_ptr(), - self.native_global_string(¤t_pkgpath, "").into(), - self.native_global_string(name, "").into(), - value, - ], - ); - } - existed = true; - } - } - if !existed { - if let Some(last) = scopes.last_mut() { - let mut variables = last.variables.borrow_mut(); - let pkgpath = self.current_pkgpath(); - let var_name = format!("${}.${}", pkgpath_without_prefix!(pkgpath), name); - let pointer = self.new_global_kcl_value_ptr(&var_name); - self.builder.build_store(pointer, value); - if save_scope { - self.build_void_call( - &ApiFunc::kclvm_scope_set.name(), - &[ - self.current_runtime_ctx_ptr(), - self.current_scope_ptr(), - self.native_global_string(¤t_pkgpath, "").into(), - self.native_global_string(name, "").into(), - value, - ], - ); - } - if !variables.contains_key(name) { - variables.insert(name.to_string(), pointer); - } - } - } - } - - /// Get the variable value named `name` from the scope, return Err when not found - pub fn get_variable(&self, name: &str) -> CompileResult<'ctx> { - let current_pkgpath = self.current_pkgpath(); - self.get_variable_in_pkgpath(name, ¤t_pkgpath) - } - - /// Get the variable value named `name` from the scope, return Err when not found - pub fn get_variable_in_schema(&self, name: &str) -> CompileResult<'ctx> { - let schema_value = self - .get_variable(value::SCHEMA_SELF_NAME) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let cal_map = self - .get_variable(value::SCHEMA_CAL_MAP) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let string_ptr_value = self.native_global_string(name, "").into(); - let cal_map_has_key = self - .build_call( - &ApiFunc::kclvm_dict_has_value.name(), - &[cal_map, string_ptr_value], - ) - .into_int_value(); - let schema_has_key = self - .build_call( - &ApiFunc::kclvm_dict_has_value.name(), - &[schema_value, string_ptr_value], - ) - .into_int_value(); - // has_key = cal_map_has_key or schema_has_key - let has_key = self - .builder - .build_int_add(cal_map_has_key, schema_has_key, ""); - let has_key = - self.builder - .build_int_compare(IntPredicate::NE, has_key, self.native_i8_zero(), ""); - let then_block = self.append_block(""); - let else_block = self.append_block(""); - let end_block = self.append_block(""); - self.builder - .build_conditional_branch(has_key, then_block, else_block); - self.builder.position_at_end(then_block); - let target_attr = self - .target_vars - .borrow() - .last() - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone(); - let target_attr = self.native_global_string_value(&target_attr); - let config_attr_value = { - let config = self - .get_variable(value::SCHEMA_CONFIG_NAME) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let config_meta = self - .get_variable(value::SCHEMA_CONFIG_META_NAME) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let backtrack_level_map = self - .get_variable(value::BACKTRACK_LEVEL_MAP) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let backtrack_cache = self - .get_variable(value::BACKTRACK_CACHE) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let args = self - .get_variable(value::SCHEMA_ARGS) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let kwargs = self - .get_variable(value::SCHEMA_KWARGS) - .expect(kcl_error::INTERNAL_ERROR_MSG); - self.build_call( - &ApiFunc::kclvm_schema_get_value.name(), - &[ - self.current_runtime_ctx_ptr(), - schema_value, - string_ptr_value, - config, - config_meta, - cal_map, - target_attr, - backtrack_level_map, - backtrack_cache, - args, - kwargs, - ], - ) - }; - self.br(end_block); - self.builder.position_at_end(else_block); - let current_pkgpath = self.current_pkgpath(); - let result = self.get_variable_in_pkgpath(name, ¤t_pkgpath); - let value = match result { - Ok(v) => v, - Err(_) => self.undefined_value(), - }; - self.br(end_block); - self.builder.position_at_end(end_block); - let tpe = self.value_ptr_type(); - let phi = self.builder.build_phi(tpe, ""); - phi.add_incoming(&[(&value, else_block), (&config_attr_value, then_block)]); - let value = phi.as_basic_value(); - Ok(value) - } - - /// Get the variable value named `name` from the scope named `pkgpath`, return Err when not found - pub fn get_variable_in_pkgpath(&self, name: &str, pkgpath: &str) -> CompileResult<'ctx> { - let pkg_scopes = self.pkg_scopes.borrow(); - let pkgpath = - if !pkgpath.starts_with(kclvm_runtime::PKG_PATH_PREFIX) && pkgpath != MAIN_PKG_PATH { - format!("{}{}", kclvm_runtime::PKG_PATH_PREFIX, pkgpath) - } else { - pkgpath.to_string() - }; - let mut result = Err(kcl_error::KCLError { - message: format!("name '{}' is not defined", name), - ty: kcl_error::KCLErrorType::Compile, - }); - let is_in_schema = self.is_in_schema(); - // System module - if builtin::STANDARD_SYSTEM_MODULE_NAMES_WITH_AT.contains(&pkgpath.as_str()) { - let pkgpath = &pkgpath[1..]; - let mangle_func_name = format!( - "{}{}_{}", - builtin::KCL_SYSTEM_MODULE_MANGLE_PREFIX, - pkgpath_without_prefix!(pkgpath), - name - ); - let value = if pkgpath == builtin::system_module::UNITS - && builtin::system_module::UNITS_FIELD_NAMES.contains(&name) - { - let value_float: f64 = kclvm_runtime::f64_unit_value(name); - let value_int: u64 = kclvm_runtime::u64_unit_value(name); - if value_int != 1 { - self.int_value(value_int as i64) - } else { - self.float_value(value_float) - } - } else { - let function = self.lookup_function(&mangle_func_name); - // Convert the function to a i64 pointer to store it into the function value. - let lambda_fn_ptr = self.builder.build_bitcast( - function.as_global_value().as_pointer_value(), - self.context.i64_type().ptr_type(AddressSpace::default()), - "", - ); - let func_name = function.get_name().to_str().unwrap(); - let func_name_ptr = self.native_global_string(func_name, func_name).into(); - let none_value = self.none_value(); - self.build_call( - &ApiFunc::kclvm_value_Function.name(), - &[ - self.current_runtime_ctx_ptr(), - lambda_fn_ptr, - none_value, - func_name_ptr, - self.native_i8_zero().into(), - ], - ) - }; - Ok(value) - } - // Plugin pkgpath - else if pkgpath.starts_with(plugin::PLUGIN_PREFIX_WITH_AT) { - let null_fn_ptr = self - .context - .i64_type() - .ptr_type(AddressSpace::default()) - .const_zero() - .into(); - let name = format!("{}.{}", &pkgpath[1..], name); - let name = self.native_global_string(&name, "").into(); - let none_value = self.none_value(); - return Ok(self.build_call( - &ApiFunc::kclvm_value_Function.name(), - &[ - self.current_runtime_ctx_ptr(), - null_fn_ptr, - none_value, - name, - self.native_i8(1).into(), - ], - )); - // User pkgpath - } else { - // Global or local variables. - let scopes = pkg_scopes - .get(&pkgpath) - .unwrap_or_else(|| panic!("package {} is not found", pkgpath)); - // Scopes 0 is builtin scope, Scopes 1 is the global scope, Scopes 2~ are the local scopes - let scopes_len = scopes.len(); - for i in 0..scopes_len { - let index = scopes_len - i - 1; - let variables = scopes[index].variables.borrow(); - // Skip uninitialized pointer value, which may cause NPE. - let uninitialized = scopes[index].uninitialized.borrow(); - if let Some(var) = variables.get(&name.to_string()) { - // Closure vars, 2 denotes the builtin scope and the global scope, here is a closure scope. - let value = if i >= 1 && i < scopes_len - 2 { - let last_lambda_scope = self.last_lambda_scope(); - // Local scope variable - if index >= last_lambda_scope { - self.builder.build_load(*var, name) - } else { - // Outer lambda closure - let variables = scopes[last_lambda_scope].variables.borrow(); - let ptr = variables.get(value::LAMBDA_CLOSURE); - // Lambda closure - match ptr { - Some(ptr) => { - let closure_map = self.builder.build_load(*ptr, ""); - let string_ptr_value = - self.native_global_string(name, "").into(); - // Not a closure, maybe a local variable - self.build_call( - &ApiFunc::kclvm_dict_get_value.name(), - &[ - self.current_runtime_ctx_ptr(), - closure_map, - string_ptr_value, - ], - ) - } - None => self.builder.build_load(*var, name), - } - } - } else { - // Not a local schema attribute or a global type. - let key = format!("{}.{name}", pkgpath_without_prefix!(pkgpath)); - let is_in_lambda = self.is_in_lambda(); - if !is_in_schema - && !is_in_lambda - && index <= GLOBAL_LEVEL - && !self.local_vars.borrow().contains(name) - && self.setter_keys.borrow().contains(&key) - { - let target = self - .target_vars - .borrow_mut() - .last() - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone(); - self.build_call( - &ApiFunc::kclvm_scope_get.name(), - &[ - // Runtime context ptr - self.current_runtime_ctx_ptr(), - // Scope ptr - self.current_scope_ptr(), - // Package path - self.native_global_string(&pkgpath, "").into(), - // Attribute name - self.native_global_string(name, "").into(), - // Target - self.native_global_string(&target, "").into(), - // Default - self.builder.build_load(*var, name), - ], - ) - } else { - if uninitialized.contains(name) { - continue; - } - self.builder.build_load(*var, name) - } - }; - result = Ok(value); - break; - } - } - match result { - Ok(_) => result, - Err(ref err) => { - if !is_in_schema { - let mut handler = self.handler.borrow_mut(); - let pos = Position { - filename: self.current_filename(), - line: *self.current_line.borrow(), - column: None, - }; - handler.add_compile_error(&err.message, (pos.clone(), pos)); - handler.abort_if_any_errors() - } - result - } - } - } - } - - /// Get the variable value named `name` from the scope named `pkgpath`, return Err when not found - pub fn get_external_variable_in_pkgpath( - &self, - name: &str, - pkgpath: &str, - ) -> CompileResult<'ctx> { - let ext_pkgpath = if !pkgpath.starts_with(kclvm_runtime::PKG_PATH_PREFIX) - && pkgpath != kclvm_runtime::MAIN_PKG_PATH - { - format!("{}{}", kclvm_runtime::PKG_PATH_PREFIX, pkgpath) - } else { - pkgpath.to_string() - }; - // System module or plugin module - if builtin::STANDARD_SYSTEM_MODULE_NAMES_WITH_AT.contains(&ext_pkgpath.as_str()) - || ext_pkgpath.starts_with(plugin::PLUGIN_PREFIX_WITH_AT) - { - return self.get_variable_in_pkgpath(name, pkgpath); - } - // User module external variable - let external_var_name = format!("${}.${}", pkgpath_without_prefix!(ext_pkgpath), name); - let current_pkgpath = self.current_pkgpath(); - let modules = self.modules.borrow(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let module = &modules.get(¤t_pkgpath).expect(&msg).borrow().inner; - let tpe = self.value_ptr_type(); - let mut global_var_maps = self.global_vars.borrow_mut(); - let pkgpath = self.current_pkgpath(); - if !global_var_maps.contains_key(&pkgpath) { - global_var_maps.insert(pkgpath.clone(), IndexMap::default()); - } - // Add or update a external variable - let global_vars = global_var_maps.get_mut(&pkgpath).expect(&msg); - let ptr = if let Some(ptr) = global_vars.get(external_var_name.as_str()) { - *ptr - } else { - let global_var = - module.add_global(tpe, Some(AddressSpace::default()), &external_var_name); - global_var.set_alignment(GLOBAL_VAL_ALIGNMENT); - global_var.set_linkage(Linkage::External); - let ptr = global_var.as_pointer_value(); - global_vars.insert(external_var_name, ptr); - ptr - }; - let value = self.builder.build_load(ptr, ""); - Ok(value) - } - - /// Get closure map in the current inner scope. - pub(crate) fn get_current_inner_scope_variable_map(&self) -> BasicValueEnum<'ctx> { - let var_map = { - let last_lambda_scope = self.last_lambda_scope(); - // Get variable map in the current scope. - let pkgpath = self.current_pkgpath(); - let pkgpath = if !pkgpath.starts_with(PKG_PATH_PREFIX) && pkgpath != MAIN_PKG_PATH { - format!("{}{}", PKG_PATH_PREFIX, pkgpath) - } else { - pkgpath - }; - let pkg_scopes = self.pkg_scopes.borrow(); - let scopes = pkg_scopes - .get(&pkgpath) - .unwrap_or_else(|| panic!("package {} is not found", pkgpath)); - let current_scope = scopes.len() - 1; - // Get last closure map. - let var_map = if current_scope >= last_lambda_scope && last_lambda_scope > 0 { - let variables = scopes[last_lambda_scope].variables.borrow(); - let ptr = variables.get(value::LAMBDA_CLOSURE); - let var_map = match ptr { - Some(ptr) => self.builder.build_load(*ptr, ""), - None => self.dict_value(), - }; - // Get variable map including schema in the current scope. - for i in last_lambda_scope..current_scope + 1 { - let variables = scopes - .get(i) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .variables - .borrow(); - for (key, ptr) in &*variables { - if key != value::LAMBDA_CLOSURE { - let value = self.builder.build_load(*ptr, ""); - self.dict_insert_override_item(var_map, key.as_str(), value); - } - } - } - var_map - } else { - self.dict_value() - }; - var_map - }; - // Capture schema `self` closure. - if self.is_in_schema() { - for schema_closure_name in value::SCHEMA_VARIABLE_LIST { - let value = self - .get_variable(schema_closure_name) - .expect(kcl_error::INTERNAL_ERROR_MSG); - self.dict_insert_override_item(var_map, schema_closure_name, value); - } - } - var_map - } - - #[inline] - pub(crate) fn push_pkgpath(&self, pkgpath: &str) { - self.pkgpath_stack.borrow_mut().push(pkgpath.to_string()); - utils::update_ctx_pkgpath(self, pkgpath); - } - - #[inline] - pub(crate) fn pop_pkgpath(&self) { - if let Some(pkgpath) = self.pkgpath_stack.borrow_mut().pop() { - utils::update_ctx_pkgpath(self, &pkgpath); - } - } - - /// Load value from name. - pub fn load_value(&self, pkgpath: &str, names: &[&str]) -> CompileResult<'ctx> { - if names.is_empty() { - return Err(kcl_error::KCLError { - message: "error: read value from empty name".to_string(), - ty: kcl_error::KCLErrorType::Compile, - }); - } - let name = names[0]; - if names.len() == 1 { - self.load_name(name) - } else { - let mut value = if pkgpath.is_empty() { - self.load_name(name) - } else { - self.ok_result() - } - .expect(kcl_error::INTERNAL_ERROR_MSG); - for i in 0..names.len() - 1 { - let attr = names[i + 1]; - if i == 0 && !pkgpath.is_empty() { - value = if self.no_link { - self.get_external_variable_in_pkgpath(attr, pkgpath) - } else { - self.get_variable_in_pkgpath(attr, pkgpath) - } - .expect(kcl_error::INTERNAL_ERROR_MSG) - } else { - let attr = self.native_global_string(attr, "").into(); - value = self.build_call( - &ApiFunc::kclvm_value_load_attr.name(), - &[self.current_runtime_ctx_ptr(), value, attr], - ); - } - } - Ok(value) - } - } - - /// Load global or local value from name. - pub fn load_name(&self, name: &str) -> CompileResult<'ctx> { - match ( - self.is_in_schema(), - self.is_in_lambda(), - self.is_local_var(name), - ) { - // Get from local or global scope - (false, _, _) | (_, _, true) => self.get_variable(name), - // Get variable from the current schema scope. - (true, false, false) => self.get_variable_in_schema(name), - // Get from local scope including lambda arguments, lambda variables, - // loop variables or global variables. - (true, true, _) => - // Get from local scope including lambda arguments, lambda variables, - // loop variables or global variables. - { - match self.resolve_variable_level(name) { - // Closure variable or local variables - Some(level) if level > GLOBAL_LEVEL => { - let ctx_stack = self.ctx_stack.borrow(); - let mut result = self.undefined_value(); - let mut found = false; - for i in 0..ctx_stack.len() { - let index = ctx_stack.len() - i - 1; - match &ctx_stack[index] { - crate::LambdaOrSchemaEvalContext::Schema(_) => { - let res = self.get_variable_in_schema_or_rule(name); - - if !res.is_undefined() { - result = res; - found = true; - break; - } - } - crate::LambdaOrSchemaEvalContext::Lambda(_) => { - let current_pkgpath = self.current_pkgpath(); - let res = self.get_variable_in_pkgpath_from_last_scope( - name, - ¤t_pkgpath, - ); - if !res.is_undefined() { - result = res; - found = true; - break; - } - } - } - } - if found { - result - } else { - // Not found variable in the scope, maybe lambda closures captured in other package scopes. - self.last_lambda_ctx() - .map(|ctx| ctx.closure.get(name).cloned().unwrap_or(result.clone())) - .unwrap_or(result) - } - } - // Schema closure or global variables - _ => self.get_variable_in_schema_or_rule(name), - } - } - } - } - - /// Load value from assignment target. - pub fn load_target(&self, target: &'ctx ast::Target) -> CompileResult<'ctx> { - let mut value = self.load_name(target.get_name())?; - for path in &target.paths { - value = self.load_target_path(value, path)?; - } - Ok(value) - } - - /// Load value from assignment target path. - pub fn load_target_path( - &self, - value: BasicValueEnum<'ctx>, - path: &'ctx ast::MemberOrIndex, - ) -> CompileResult<'ctx> { - Ok(match path { - ast::MemberOrIndex::Member(member) => { - let attr = &member.node; - let attr = self.native_global_string(attr, "").into(); - self.build_call( - &ApiFunc::kclvm_value_load_attr.name(), - &[self.current_runtime_ctx_ptr(), value, attr], - ) - } - ast::MemberOrIndex::Index(index) => { - let index = self.walk_expr(index)?; - self.build_call( - &ApiFunc::kclvm_value_subscr.name(), - &[self.current_runtime_ctx_ptr(), value, index], - ) - } - }) - } - - pub fn store_target_path( - &self, - value: BasicValueEnum<'ctx>, - path: &'ctx ast::MemberOrIndex, - right_value: BasicValueEnum<'ctx>, - ) -> CompileResult<'ctx> { - match path { - ast::MemberOrIndex::Member(member) => { - let attr = &member.node; - let attr = self.native_global_string(attr, "").into(); - self.build_void_call( - &ApiFunc::kclvm_dict_set_value.name(), - &[self.current_runtime_ctx_ptr(), value, attr, right_value], - ); - } - ast::MemberOrIndex::Index(index) => { - let index = self.walk_expr(index)?; - self.build_void_call( - &ApiFunc::kclvm_value_subscr_set.name(), - &[self.current_runtime_ctx_ptr(), value, index, right_value], - ); - } - } - self.ok_result() - } - - /// Push a lambda definition scope into the lambda stack - #[inline] - pub fn push_lambda(&self, scope: usize) { - self.lambda_stack.borrow_mut().push(scope); - } - - /// Pop a lambda definition scope. - #[inline] - pub fn pop_lambda(&self) { - self.lambda_stack.borrow_mut().pop(); - } - - #[inline] - pub fn is_in_lambda(&self) -> bool { - *self - .lambda_stack - .borrow() - .last() - .expect(kcl_error::INTERNAL_ERROR_MSG) - > GLOBAL_LEVEL - } - - #[inline] - pub fn last_lambda_scope(&self) -> usize { - *self - .lambda_stack - .borrow() - .last() - .expect(kcl_error::INTERNAL_ERROR_MSG) - } - - #[inline] - pub fn is_in_schema(&self) -> bool { - self.schema_stack.borrow().len() > 0 - } - - #[inline] - pub fn is_in_schema_expr(&self) -> bool { - self.schema_expr_stack.borrow().len() > 0 - } - - #[inline] - pub fn is_local_var(&self, name: &str) -> bool { - self.local_vars.borrow().contains(name) - } - - /// Push a function call frame into the function stack - #[inline] - pub fn push_function(&self, function: FunctionValue<'ctx>) { - self.functions.borrow_mut().push(Rc::new(function)); - } - - /// Pop a function from the function stack - #[inline] - pub fn pop_function(&self) { - self.functions.borrow_mut().pop(); - } - - /// Get the current function - #[inline] - pub fn current_function(&self) -> FunctionValue<'ctx> { - **self - .functions - .borrow() - .last() - .expect(kcl_error::INTERNAL_ERROR_MSG) - } - - /// Plan globals to a json string - pub fn globals_to_json_str(&self) -> BasicValueEnum<'ctx> { - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = self.pkg_scopes.borrow(); - let scopes = pkg_scopes - .get(¤t_pkgpath) - .unwrap_or_else(|| panic!("pkgpath {} is not found", current_pkgpath)); - // The global scope. - let scope = scopes.last().expect(kcl_error::INTERNAL_ERROR_MSG); - let scalars = scope.scalars.borrow(); - let globals = scope.variables.borrow(); - // Construct a plan object. - let global_dict = self.dict_value(); - // Plan empty dict result. - if scalars.is_empty() && globals.is_empty() { - return self.build_call( - &ApiFunc::kclvm_value_plan_to_json.name(), - &[self.current_runtime_ctx_ptr(), global_dict], - ); - } - // Deal scalars - for scalar in scalars.iter() { - self.dict_safe_insert(global_dict, SCALAR_KEY, *scalar, 0, None); - } - // Deal global variables - for (name, ptr) in globals.iter() { - let value = self.builder.build_load(*ptr, ""); - let value_dict = self.dict_value(); - self.dict_safe_insert(value_dict, name.as_str(), value, 0, None); - self.dict_safe_insert(global_dict, SCALAR_KEY, value_dict, 0, None); - } - // Plan result to json string. - self.build_call( - &ApiFunc::kclvm_value_plan_to_json.name(), - &[ - self.current_runtime_ctx_ptr(), - self.dict_get( - global_dict, - self.native_global_string(SCALAR_KEY, "").into(), - ), - ], - ) - } - - /// Insert a dict entry including key, value, op and insert_index into the dict. - #[inline] - fn dict_safe_insert( - &self, - dict: BasicValueEnum<'ctx>, - key: &str, - value: BasicValueEnum<'ctx>, - op: i32, - insert_index: Option, - ) { - let name = self.native_global_string(key, "").into(); - let op = self.native_int_value(op); - let has_insert_index = insert_index.is_some(); - let has_insert_index = self.native_i8_value(if has_insert_index { 1 } else { 0 }); - let insert_index = self.native_int_value(insert_index.unwrap_or(-1)); - self.build_void_call( - &ApiFunc::kclvm_dict_safe_insert.name(), - &[ - self.current_runtime_ctx_ptr(), - dict, - name, - value, - op, - insert_index, - has_insert_index, - ], - ); - } - - /// Merge a dict entry including key, value, op and insert_index into the dict - /// without the idempotent check. - #[inline] - pub fn dict_merge( - &self, - dict: BasicValueEnum<'ctx>, - key: &str, - value: BasicValueEnum<'ctx>, - op: i32, - insert_index: Option, - ) { - let name = self.native_global_string(key, "").into(); - let op = self.native_int_value(op); - let has_insert_index = insert_index.is_some(); - let has_insert_index = self.native_i8_value(if has_insert_index { 1 } else { 0 }); - let insert_index = self.native_int_value(insert_index.unwrap_or(-1)); - self.build_void_call( - &ApiFunc::kclvm_dict_merge.name(), - &[ - self.current_runtime_ctx_ptr(), - dict, - name, - value, - op, - insert_index, - has_insert_index, - ], - ); - } - - /// default_dict(list) insert a key-value pair, and the value is a int pointer - #[inline] - pub fn default_collection_insert_int_pointer( - &self, - dict: BasicValueEnum<'ctx>, - key: &str, - value: BasicValueEnum<'ctx>, - ) { - let name = self.native_global_string(key, "").into(); - self.build_void_call( - ApiFunc::kclvm_default_collection_insert_int_pointer - .name() - .as_str(), - &[dict, name, value], - ); - } - - /// default_dict(list) insert a key-value pair - #[inline] - pub fn default_collection_insert_value( - &self, - dict: BasicValueEnum<'ctx>, - key: &str, - value: BasicValueEnum<'ctx>, - ) { - let name = self.native_global_string(key, "").into(); - self.build_void_call( - ApiFunc::kclvm_default_collection_insert_value - .name() - .as_str(), - &[dict, name, value], - ); - } -} diff --git a/kclvm/compiler/src/codegen/llvm/emit.rs b/kclvm/compiler/src/codegen/llvm/emit.rs deleted file mode 100644 index 395bd52e0..000000000 --- a/kclvm/compiler/src/codegen/llvm/emit.rs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. - -use inkwell::module::Module; -use inkwell::{context::Context, memory_buffer::MemoryBuffer}; -use kclvm_ast::ast; -use kclvm_primitives::IndexMap; -use once_cell::sync::OnceCell; -use std::error; - -use crate::codegen::{EmitOptions, MODULE_NAME}; - -use super::context::LLVMCodeGenContext; - -static LLVM_INIT: OnceCell<()> = OnceCell::new(); -static RUNTIME_LLVM_BC: &[u8] = include_bytes!("../../../../runtime/src/_kclvm.bc"); - -/// Load runtime libraries and parse it to a module. -fn load_runtime(context: &'_ Context) -> Module<'_> { - let memory = MemoryBuffer::create_from_memory_range(RUNTIME_LLVM_BC, MODULE_NAME); - Module::parse_bitcode_from_buffer(&memory, context).unwrap() -} - -/// Generate LLVM IR of KCL ast module. -pub fn emit_code( - program: &ast::Program, - workdir: String, - import_names: IndexMap>, - opts: &EmitOptions, -) -> Result<(), Box> { - // Init LLVM targets - LLVM_INIT.get_or_init(|| { - #[cfg(target_os = "linux")] - inkwell::targets::Target::initialize_x86(&Default::default()); - #[cfg(all(target_os = "linux", target_arch = "aarch64"))] - inkwell::targets::Target::initialize_aarch64(&Default::default()); - #[cfg(target_arch = "wasm32")] - inkwell::targets::Target::initialize_webassembly(&Default::default()); - #[cfg(not(any(target_os = "linux", target_arch = "wasm32")))] - inkwell::targets::Target::initialize_all(&Default::default()); - }); - // Create a LLVM context - let context = Context::create(); - // Create a LLVM module using an exist LLVM bitcode file - let module = if let Some(path) = &opts.from_path { - Module::parse_bitcode_from_path(std::path::Path::new(path), &context).unwrap() - } else { - load_runtime(&context) - }; - // Create a KCL LLVM code generator using the KCL AST and the LLVM module - let ctx = LLVMCodeGenContext::new( - &context, - module, - program, - import_names, - opts.no_link, - workdir, - ); - // Generate user KCL code LLVM IR - crate::codegen::emit_code_with(ctx, opts) -} diff --git a/kclvm/compiler/src/codegen/llvm/metadata.rs b/kclvm/compiler/src/codegen/llvm/metadata.rs deleted file mode 100644 index 1aadda9ed..000000000 --- a/kclvm/compiler/src/codegen/llvm/metadata.rs +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. - -use super::context::{DebugModule, LLVMCodeGenContext}; -use inkwell::module::Module; - -impl<'ctx> LLVMCodeGenContext<'ctx> { - pub(crate) fn create_debug_module(&self, module: Module<'ctx>) -> DebugModule<'ctx> { - DebugModule { inner: module } - } -} diff --git a/kclvm/compiler/src/codegen/llvm/mod.rs b/kclvm/compiler/src/codegen/llvm/mod.rs deleted file mode 100644 index 3b800239b..000000000 --- a/kclvm/compiler/src/codegen/llvm/mod.rs +++ /dev/null @@ -1,17 +0,0 @@ -//! The goal of this module is to translate KCL Program into LLVM IR code, where each AST corresponding to KCL -//! pkgpath corresponds to a module of LLVM. They share a global symbol table and LLVM context. Different LLVM -//! module modules pass extern and declare keys. Declare and call them in words, and finally use clang to link -//! them together. -//! -//! Copyright The KCL Authors. All rights reserved. - -mod backtrack; -mod context; -mod emit; -mod metadata; -mod module; -mod node; -mod schema; -mod utils; - -pub use emit::emit_code; diff --git a/kclvm/compiler/src/codegen/llvm/module.rs b/kclvm/compiler/src/codegen/llvm/module.rs deleted file mode 100644 index 751c01a00..000000000 --- a/kclvm/compiler/src/codegen/llvm/module.rs +++ /dev/null @@ -1,411 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. - -use inkwell::values::FunctionValue; -use inkwell::AddressSpace; -use kclvm_ast::ast; -use kclvm_ast::walker::TypedResultWalker; -use kclvm_primitives::IndexMap; -use kclvm_runtime::ApiFunc; -use kclvm_sema::pkgpath_without_prefix; - -use super::context::{BacktrackMeta, LLVMCodeGenContext}; -use crate::codegen::llvm::context::BacktrackKind; -use crate::codegen::traits::{BuilderMethods, ProgramCodeGen, ValueMethods}; -use crate::codegen::{error as kcl_error, ENTRY_NAME}; -use crate::value; -use std::str; - -impl<'ctx> LLVMCodeGenContext<'ctx> { - pub fn compile_module_import_and_types(&self, module: &'ctx ast::Module) { - for stmt in &module.body { - match &stmt.node { - ast::Stmt::Import(import_stmt) => { - self.walk_import_stmt(import_stmt) - .expect(kcl_error::COMPILE_ERROR_MSG); - } - ast::Stmt::Schema(schema_stmt) => { - // Pre define global types with undefined values - self.predefine_global_types(&schema_stmt.name.node); - self.walk_schema_stmt(schema_stmt) - .expect(kcl_error::COMPILE_ERROR_MSG); - } - ast::Stmt::Rule(rule_stmt) => { - // Pre define global types with undefined values - self.predefine_global_types(&rule_stmt.name.node); - self.walk_rule_stmt(rule_stmt) - .expect(kcl_error::COMPILE_ERROR_MSG); - } - _ => {} - }; - } - // Pre define global variables with setter functions. - self.predefine_global_setters(module); - } - - pub fn predefine_global_types(&self, name: &str) { - // Store or add the variable in the scope - let function = self.undefined_value(); - if !self.store_variable(name, function) { - let global_var_ptr = self.new_global_kcl_value_ptr(""); - self.builder.build_store(global_var_ptr, function); - self.add_variable(name, global_var_ptr); - } - } - - /// Predefine all global variables. - #[inline] - pub(crate) fn predefine_global_vars(&self, module: &'ctx ast::Module) { - self.emit_global_vars(&module.body); - } - - /// Predefine all global variables. - pub fn predefine_global_setters(&self, module: &'ctx ast::Module) { - // New a function block to the global setter construction process. - let global_setter_block = self.append_block(""); - self.br(global_setter_block); - self.builder.position_at_end(global_setter_block); - let mut place_holder_map: IndexMap>> = IndexMap::new(); - let mut body_map: IndexMap, BacktrackKind)>> = - IndexMap::new(); - let pkgpath = &self.current_pkgpath(); - // Setter function name format: "$set..$" - self.emit_global_setters( - &module.body, - &pkgpath, - false, - &mut place_holder_map, - &mut body_map, - &mut vec![], - ); - // Build global attribute backtrack functions. - { - for (k, functions) in &place_holder_map { - if k == kclvm_runtime::CAL_MAP_INDEX_SIGNATURE { - continue; - } - let stmt_list = body_map.get(k).expect(kcl_error::INTERNAL_ERROR_MSG); - let mut if_level = 0; - for (attr_func, (stmt, kind)) in functions.iter().zip(stmt_list) { - let function = *attr_func; - let name = function - .get_name() - .to_str() - .expect(kcl_error::INTERNAL_ERROR_MSG); - // Get attribute function from the module. - let function = self.lookup_function(name); - self.push_function(function); - let attr_block = self.append_block(ENTRY_NAME); - self.builder.position_at_end(attr_block); - // Backtrack meta begin - if matches!(&stmt.node, ast::Stmt::If(..)) { - if_level += 1; - *self.backtrack_meta.borrow_mut() = Some(BacktrackMeta { - target: k.clone(), - level: if_level, - count: 0, - stop: false, - kind: kind.clone(), - }); - } else { - if_level = 0; - } - let result = self.walk_stmt(stmt).expect(kcl_error::COMPILE_ERROR_MSG); - // Backtrack meta end - if matches!(&stmt.node, ast::Stmt::If(..)) { - *self.backtrack_meta.borrow_mut() = None - } - // Build return - self.builder.build_return(Some(&result)); - // Position at global main function block - self.builder.position_at_end(global_setter_block); - self.pop_function(); - } - } - } - } - - fn emit_global_vars(&self, body: &'ctx [Box>]) { - for stmt in body { - match &stmt.node { - ast::Stmt::Unification(unification_stmt) => { - let names = &unification_stmt.target.node.names; - if names.len() == 1 { - self.add_or_update_global_variable( - &names[0].node, - self.undefined_value(), - false, - ); - } - } - ast::Stmt::Assign(assign_stmt) => { - for target in &assign_stmt.targets { - self.add_or_update_global_variable( - target.node.get_name(), - self.undefined_value(), - false, - ); - } - } - ast::Stmt::If(if_stmt) => { - self.emit_global_vars(&if_stmt.body); - self.emit_global_vars(&if_stmt.orelse); - } - _ => {} - } - } - } - - pub(crate) fn emit_config_if_entry_expr_vars( - &self, - config_if_entry_expr: &'ctx ast::ConfigIfEntryExpr, - ) { - self.emit_config_entries_vars(&config_if_entry_expr.items); - if let Some(orelse) = &config_if_entry_expr.orelse { - // Config expr or config if entry expr. - if let ast::Expr::Config(config_expr) = &orelse.node { - self.emit_config_entries_vars(&config_expr.items); - } else if let ast::Expr::ConfigIfEntry(config_if_entry_expr) = &orelse.node { - self.emit_config_if_entry_expr_vars(config_if_entry_expr); - } - } - } - - pub(crate) fn emit_config_entries_vars(&self, items: &'ctx [ast::NodeRef]) { - for item in items { - if let ast::Expr::ConfigIfEntry(config_if_entry_expr) = &item.node.value.node { - self.emit_config_if_entry_expr_vars(config_if_entry_expr); - } - if let Some(key) = &item.node.key { - let optional_name = match &key.node { - ast::Expr::Identifier(identifier) => Some(identifier.names[0].node.clone()), - ast::Expr::StringLit(string_lit) => Some(string_lit.value.clone()), - ast::Expr::Subscript(subscript) => { - let mut name = None; - if let ast::Expr::Identifier(identifier) = &subscript.value.node { - if let Some(index_node) = &subscript.index { - if let ast::Expr::NumberLit(number) = &index_node.node { - if let ast::NumberLitValue::Int(_) = number.value { - name = Some(identifier.names[0].node.clone()) - } - } - } - } - name - } - _ => None, - }; - if let Some(name) = &optional_name { - self.add_or_update_local_variable_within_scope(name, None); - } - } - } - } - - /// Compile AST Modules, which requires traversing three times. - /// 1. scan all possible global variables and allocate undefined values to global pointers. - /// 2. build all user-defined schema/rule types. - /// 3. generate all LLVM IR codes for the third time. - pub(crate) fn compile_ast_modules(&self, modules: &'ctx [ast::Module]) { - // Scan global variables - for ast_module in modules { - { - self.filename_stack - .borrow_mut() - .push(ast_module.filename.clone()); - } - // Pre define global variables with undefined values - self.predefine_global_vars(ast_module); - { - self.filename_stack.borrow_mut().pop(); - } - } - // Scan global types - for ast_module in modules { - { - self.filename_stack - .borrow_mut() - .push(ast_module.filename.clone()); - } - self.compile_module_import_and_types(ast_module); - { - self.filename_stack.borrow_mut().pop(); - } - } - // Compile the ast module in the pkgpath. - for ast_module in modules { - { - self.filename_stack - .borrow_mut() - .push(ast_module.filename.clone()); - } - self.walk_module(ast_module) - .expect(kcl_error::COMPILE_ERROR_MSG); - { - self.filename_stack.borrow_mut().pop(); - } - } - } - - /// Emit setter functions for global variables. - pub(crate) fn emit_global_setters( - &self, - body: &'ctx [Box>], - pkgpath: &str, - is_in_if: bool, - place_holder_map: &mut IndexMap>>, - body_map: &mut IndexMap, BacktrackKind)>>, - in_if_names: &mut Vec, - ) { - let add_stmt = |name: &str, - stmt: &'ctx ast::Node, - kind: BacktrackKind, - place_holder_map: &mut IndexMap>>, - body_map: &mut IndexMap< - String, - Vec<(&'ctx ast::Node, BacktrackKind)>, - >| { - // The function form e.g., $set.__main__.a(&Context, &LazyScope, &ValueRef, &ValueRef) - let var_key = format!("{}.{name}", pkgpath_without_prefix!(pkgpath)); - let function = - self.add_setter_function(&format!("{}.{}", value::GLOBAL_SETTER, var_key)); - let lambda_fn_ptr = self.builder.build_bitcast( - function.as_global_value().as_pointer_value(), - self.context.i64_type().ptr_type(AddressSpace::default()), - "", - ); - if !place_holder_map.contains_key(name) { - place_holder_map.insert(name.to_string(), vec![]); - } - let name_vec = place_holder_map - .get_mut(name) - .expect(kcl_error::INTERNAL_ERROR_MSG); - name_vec.push(function); - self.build_void_call( - &ApiFunc::kclvm_scope_add_setter.name(), - &[ - self.current_runtime_ctx_ptr(), - self.current_scope_ptr(), - self.native_global_string(pkgpath, "").into(), - self.native_global_string(name, "").into(), - lambda_fn_ptr, - ], - ); - let key = format!("{}.{name}", pkgpath_without_prefix!(pkgpath)); - self.setter_keys.borrow_mut().insert(key); - if !body_map.contains_key(name) { - body_map.insert(name.to_string(), vec![]); - } - let body_vec = body_map.get_mut(name).expect(kcl_error::INTERNAL_ERROR_MSG); - body_vec.push((stmt, kind)); - }; - for stmt in body { - match &stmt.node { - ast::Stmt::Unification(unification_stmt) => { - let name = &unification_stmt.target.node.names[0].node; - if is_in_if { - in_if_names.push(name.to_string()); - } else { - add_stmt( - name, - stmt, - BacktrackKind::Normal, - place_holder_map, - body_map, - ); - } - } - ast::Stmt::Assign(assign_stmt) => { - for target in &assign_stmt.targets { - let name = &target.node.name.node; - if is_in_if { - in_if_names.push(name.to_string()); - } else { - add_stmt( - name, - stmt, - BacktrackKind::Normal, - place_holder_map, - body_map, - ); - } - } - } - ast::Stmt::AugAssign(aug_assign_stmt) => { - let target = &aug_assign_stmt.target; - let name = &target.node.name.node; - if is_in_if { - in_if_names.push(name.to_string()); - } else { - add_stmt( - name, - stmt, - BacktrackKind::Normal, - place_holder_map, - body_map, - ); - } - } - ast::Stmt::If(if_stmt) => { - let mut names: Vec = vec![]; - self.emit_global_setters( - &if_stmt.body, - pkgpath, - true, - place_holder_map, - body_map, - &mut names, - ); - if is_in_if { - for name in &names { - in_if_names.push(name.to_string()); - } - } else { - for name in &names { - add_stmt(name, stmt, BacktrackKind::If, place_holder_map, body_map); - } - } - names.clear(); - self.emit_global_setters( - &if_stmt.orelse, - pkgpath, - true, - place_holder_map, - body_map, - &mut names, - ); - if is_in_if { - for name in &names { - in_if_names.push(name.to_string()); - } - } else { - for name in &names { - add_stmt( - name, - stmt, - BacktrackKind::OrElse, - place_holder_map, - body_map, - ); - } - } - names.clear(); - } - ast::Stmt::SchemaAttr(schema_attr) => { - let name = schema_attr.name.node.as_str(); - if is_in_if { - in_if_names.push(name.to_string()); - } else { - add_stmt( - name, - stmt, - BacktrackKind::Normal, - place_holder_map, - body_map, - ); - } - } - _ => {} - } - } - } -} diff --git a/kclvm/compiler/src/codegen/llvm/node.rs b/kclvm/compiler/src/codegen/llvm/node.rs deleted file mode 100644 index a8bdf4d7a..000000000 --- a/kclvm/compiler/src/codegen/llvm/node.rs +++ /dev/null @@ -1,3046 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. - -use std::cell::RefCell; -use std::collections::HashMap; -use std::convert::TryFrom; - -use inkwell::basic_block::BasicBlock; -use inkwell::module::Linkage; -use inkwell::values::{BasicValueEnum, CallableValue, FunctionValue}; -use inkwell::{AddressSpace, IntPredicate}; -use kclvm_ast::ast::{self, CallExpr, ConfigEntry, NodeRef}; -use kclvm_ast::walker::TypedResultWalker; -use kclvm_runtime::{ApiFunc, PKG_PATH_PREFIX}; -use kclvm_sema::pkgpath_without_prefix; -use kclvm_sema::ty::{ANY_TYPE_STR, STR_TYPE_STR}; - -use crate::check_backtrack_stop; -use crate::codegen::error as kcl_error; -use crate::codegen::llvm::context::BacktrackKind; -use crate::codegen::llvm::context::BacktrackMeta; -use crate::codegen::llvm::utils; -use crate::codegen::traits::*; -use crate::codegen::{ENTRY_NAME, GLOBAL_LEVEL, INNER_LEVEL, PKG_INIT_FUNCTION_SUFFIX}; - -use super::context::{CompileResult, LLVMCodeGenContext}; -use crate::value; -use kclvm_sema::builtin; -use kclvm_sema::plugin; - -/// Impl TypedResultWalker for LLVMCodeGenContext to visit AST nodes to emit LLVM IR. -impl<'ctx> TypedResultWalker<'ctx> for LLVMCodeGenContext<'ctx> { - type Result = CompileResult<'ctx>; - - /* - * Stmt - */ - - fn walk_stmt(&self, stmt: &'ctx ast::Node) -> Self::Result { - check_backtrack_stop!(self); - utils::update_ctx_filename(self, stmt); - utils::update_ctx_line_col(self, stmt); - utils::reset_target_vars(self); - match &stmt.node { - ast::Stmt::TypeAlias(type_alias) => self.walk_type_alias_stmt(type_alias), - ast::Stmt::Expr(expr_stmt) => self.walk_expr_stmt(expr_stmt), - ast::Stmt::Unification(unification_stmt) => { - self.walk_unification_stmt(unification_stmt) - } - ast::Stmt::Assign(assign_stmt) => self.walk_assign_stmt(assign_stmt), - ast::Stmt::AugAssign(aug_assign_stmt) => self.walk_aug_assign_stmt(aug_assign_stmt), - ast::Stmt::Assert(assert_stmt) => self.walk_assert_stmt(assert_stmt), - ast::Stmt::If(if_stmt) => self.walk_if_stmt(if_stmt), - ast::Stmt::Import(import_stmt) => self.walk_import_stmt(import_stmt), - ast::Stmt::SchemaAttr(schema_attr) => self.walk_schema_attr(schema_attr), - ast::Stmt::Schema(schema_stmt) => self.walk_schema_stmt(schema_stmt), - ast::Stmt::Rule(rule_stmt) => self.walk_rule_stmt(rule_stmt), - } - } - - fn walk_expr_stmt(&self, expr_stmt: &'ctx ast::ExprStmt) -> Self::Result { - check_backtrack_stop!(self); - let mut result = self.ok_result(); - for expr in &expr_stmt.exprs { - let scalar = self.walk_expr(expr)?; - // Only non-call expressions are allowed to emit values because of the function void return type. - if !matches!(expr.node, ast::Expr::Call(_)) { - self.add_scalar(scalar, matches!(expr.node, ast::Expr::Schema(_))); - } - result = Ok(scalar); - } - result - } - - fn walk_unification_stmt(&self, unification_stmt: &'ctx ast::UnificationStmt) -> Self::Result { - check_backtrack_stop!(self); - self.local_vars.borrow_mut().clear(); - let name = &unification_stmt.target.node.names[0].node; - self.target_vars.borrow_mut().push(name.clone()); - // The right value of the unification_stmt is a schema_expr. - let value = self - .walk_schema_expr(&unification_stmt.value.node) - .expect(kcl_error::COMPILE_ERROR_MSG); - if self.scope_level() == GLOBAL_LEVEL || self.is_in_lambda() { - if self.resolve_variable(name) { - let org_value = self - .walk_identifier_with_ctx( - &unification_stmt.target.node, - &ast::ExprContext::Load, - None, - ) - .expect(kcl_error::COMPILE_ERROR_MSG); - let fn_name = ApiFunc::kclvm_value_op_aug_bit_or; - let value = self.build_call( - &fn_name.name(), - &[self.current_runtime_ctx_ptr(), org_value, value], - ); - // Store the identifier value - self.walk_identifier_with_ctx( - &unification_stmt.target.node, - &ast::ExprContext::Store, - Some(value), - ) - .expect(kcl_error::COMPILE_ERROR_MSG); - return Ok(value); - } else { - self.walk_identifier_with_ctx( - &unification_stmt.target.node, - &unification_stmt.target.node.ctx, - Some(value), - ) - .expect(kcl_error::COMPILE_ERROR_MSG); - return Ok(value); - } - // Local variables including schema/rule/lambda - } else if self.is_in_schema() { - // Load the identifier value - let org_value = self - .walk_identifier_with_ctx( - &unification_stmt.target.node, - &ast::ExprContext::Load, - None, - ) - .expect(kcl_error::COMPILE_ERROR_MSG); - let fn_name = ApiFunc::kclvm_value_op_bit_or; - let value = self.build_call( - &fn_name.name(), - &[self.current_runtime_ctx_ptr(), org_value, value], - ); - // Store the identifier value - self.walk_identifier_with_ctx( - &unification_stmt.target.node, - &ast::ExprContext::Store, - Some(value), - ) - .expect(kcl_error::COMPILE_ERROR_MSG); - return Ok(value); - } - Ok(value) - } - - fn walk_type_alias_stmt(&self, _type_alias_stmt: &'ctx ast::TypeAliasStmt) -> Self::Result { - // Nothing to do, because all type aliases have been replaced at compile time - self.ok_result() - } - - fn walk_assign_stmt(&self, assign_stmt: &'ctx ast::AssignStmt) -> Self::Result { - check_backtrack_stop!(self); - self.local_vars.borrow_mut().clear(); - // Set target vars. - for name in &assign_stmt.targets { - self.target_vars - .borrow_mut() - .push(name.node.name.node.clone()); - } - // Load the right value - let mut value = self - .walk_expr(&assign_stmt.value) - .expect(kcl_error::COMPILE_ERROR_MSG); - if let Some(ty) = &assign_stmt.ty { - let type_annotation = self.native_global_string_value(&ty.node.to_string()); - let is_in_schema = self.is_in_schema() || self.is_in_schema_expr(); - value = self.build_call( - &ApiFunc::kclvm_convert_collection_value.name(), - &[ - self.current_runtime_ctx_ptr(), - value, - type_annotation, - self.bool_value(is_in_schema), - ], - ); - } - if assign_stmt.targets.len() == 1 { - // Store the single target - let name = &assign_stmt.targets[0]; - self.walk_target_with_value(&name.node, value) - .expect(kcl_error::COMPILE_ERROR_MSG); - } else { - // Store multiple targets - for name in &assign_stmt.targets { - let value = self.value_deep_copy(value); - self.walk_target_with_value(&name.node, value) - .expect(kcl_error::COMPILE_ERROR_MSG); - } - } - Ok(value) - } - - fn walk_aug_assign_stmt(&self, aug_assign_stmt: &'ctx ast::AugAssignStmt) -> Self::Result { - check_backtrack_stop!(self); - self.target_vars - .borrow_mut() - .push(aug_assign_stmt.target.node.name.node.clone()); - // Load the right value - let right_value = self - .walk_expr(&aug_assign_stmt.value) - .expect(kcl_error::COMPILE_ERROR_MSG); - // Load the value - let org_value = self - .load_target(&aug_assign_stmt.target.node) - .expect(kcl_error::COMPILE_ERROR_MSG); - let fn_name = match aug_assign_stmt.op { - ast::AugOp::Add => ApiFunc::kclvm_value_op_aug_add, - ast::AugOp::Sub => ApiFunc::kclvm_value_op_aug_sub, - ast::AugOp::Mul => ApiFunc::kclvm_value_op_aug_mul, - ast::AugOp::Div => ApiFunc::kclvm_value_op_aug_div, - ast::AugOp::Mod => ApiFunc::kclvm_value_op_aug_mod, - ast::AugOp::Pow => ApiFunc::kclvm_value_op_aug_pow, - ast::AugOp::LShift => ApiFunc::kclvm_value_op_aug_bit_lshift, - ast::AugOp::RShift => ApiFunc::kclvm_value_op_aug_bit_rshift, - ast::AugOp::BitOr => ApiFunc::kclvm_value_op_bit_or, - ast::AugOp::BitXor => ApiFunc::kclvm_value_op_aug_bit_xor, - ast::AugOp::BitAnd => ApiFunc::kclvm_value_op_aug_bit_and, - ast::AugOp::FloorDiv => ApiFunc::kclvm_value_op_aug_floor_div, - ast::AugOp::Assign => { - return Err(kcl_error::KCLError::new(kcl_error::INVALID_OPERATOR_MSG)); - } - }; - let value = self.build_call( - &fn_name.name(), - &[self.current_runtime_ctx_ptr(), org_value, right_value], - ); - // Store the target value - self.walk_target_with_value(&aug_assign_stmt.target.node, value) - .expect(kcl_error::COMPILE_ERROR_MSG); - Ok(value) - } - - fn walk_assert_stmt(&self, assert_stmt: &'ctx ast::AssertStmt) -> Self::Result { - check_backtrack_stop!(self); - let start_block = self.append_block(""); - let end_block = self.append_block(""); - if let Some(if_cond) = &assert_stmt.if_cond { - let if_value = self.walk_expr(if_cond).expect(kcl_error::COMPILE_ERROR_MSG); - let is_truth = self.value_is_truthy(if_value); - self.cond_br(is_truth, start_block, end_block); - } else { - self.br(start_block); - } - self.builder.position_at_end(start_block); - let assert_result = self - .walk_expr(&assert_stmt.test) - .expect(kcl_error::COMPILE_ERROR_MSG); - // Assert statement error message. - let msg = { - if let Some(msg) = &assert_stmt.msg { - self.walk_expr(msg).expect(kcl_error::COMPILE_ERROR_MSG) - } else { - self.string_value("") - } - }; - self.build_void_call( - &ApiFunc::kclvm_assert.name(), - &[self.current_runtime_ctx_ptr(), assert_result, msg], - ); - self.br(end_block); - self.builder.position_at_end(end_block); - Ok(self.undefined_value()) - } - - fn walk_if_stmt(&self, if_stmt: &'ctx ast::IfStmt) -> Self::Result { - check_backtrack_stop!(self); - let cond = self.walk_expr(&if_stmt.cond)?; - let then_block = self.append_block(""); - let else_block = self.append_block(""); - let end_block = self.append_block(""); - let is_truth = self.value_is_truthy(cond); - self.cond_br(is_truth, then_block, else_block); - self.builder.position_at_end(then_block); - // Is backtrack only orelse stmt? - if self.is_backtrack_only_or_else() { - self.ok_result()?; - self.br(end_block); - self.builder.position_at_end(else_block); - self.walk_stmts(&if_stmt.orelse)?; - self.br(end_block); - self.builder.position_at_end(end_block); - return Ok(self.none_value()); - } - // Is backtrack only if stmt? - if self.is_backtrack_only_if() { - self.walk_stmts(&if_stmt.body)?; - self.br(end_block); - self.builder.position_at_end(else_block); - self.ok_result()?; - self.br(end_block); - self.builder.position_at_end(end_block); - return Ok(self.none_value()); - } - // Normal full if stmt. - self.walk_stmts(&if_stmt.body)?; - self.br(end_block); - self.builder.position_at_end(else_block); - self.walk_stmts(&if_stmt.orelse)?; - self.br(end_block); - self.builder.position_at_end(end_block); - Ok(self.none_value()) - } - - fn walk_import_stmt(&self, import_stmt: &'ctx ast::ImportStmt) -> Self::Result { - check_backtrack_stop!(self); - let pkgpath = import_stmt.path.node.as_str(); - // Check if it has already been generated, there is no need to generate code - // for duplicate import statements. - { - let imported = self.imported.borrow_mut(); - if imported.contains(pkgpath) { - return self.ok_result(); - } - // Deref the borrow mut - } - // Standard or plugin modules. - if builtin::STANDARD_SYSTEM_MODULES.contains(&pkgpath) - || pkgpath.starts_with(plugin::PLUGIN_MODULE_PREFIX) - { - // Nothing to do on the builtin system module import because the check has been done. - return self.ok_result(); - } else { - let pkgpath = format!("{}{}", PKG_PATH_PREFIX, import_stmt.path.node); - self.push_pkgpath(&pkgpath); - let has_pkgpath = self.program.pkgs.contains_key(&import_stmt.path.node); - let func_before_block = if self.no_link { - if has_pkgpath { - let func_before_block = self.append_block(""); - self.br(func_before_block); - let mut modules = self.modules.borrow_mut(); - let name = pkgpath.clone(); - let module = self.context.create_module(&name); - let module_name = format!( - "${}.{}", - pkgpath_without_prefix!(pkgpath), - PKG_INIT_FUNCTION_SUFFIX - ); - let tpe = self.context.void_type(); - let fn_type = tpe.fn_type( - &[self.context_ptr_type().into(), self.scope_ptr_type().into()], - false, - ); - let function = module.add_function( - // Function name - &module_name, - // Function type - fn_type, - None, - ); - // Add a block named entry into the function - let basic_block = self.context.append_basic_block(function, ENTRY_NAME); - self.builder.position_at_end(basic_block); - self.push_function(function); - modules.insert(name, RefCell::new(self.create_debug_module(module))); - Some(func_before_block) - } else { - None - } - } else { - None - }; - if has_pkgpath { - // Init all builtin functions. - self.init_scope(pkgpath.as_str()); - self.compile_ast_modules( - self.program - .pkgs - .get(&import_stmt.path.node) - .expect(kcl_error::INTERNAL_ERROR_MSG), - ); - } - self.pop_pkgpath(); - if self.no_link { - let name = format!( - "${}.{}", - pkgpath_without_prefix!(pkgpath), - PKG_INIT_FUNCTION_SUFFIX - ); - let function = { - let pkgpath = self.current_pkgpath(); - let modules = self.modules.borrow_mut(); - let msg = format!("pkgpath {} is not found", pkgpath); - let module = &modules.get(&pkgpath).expect(&msg).borrow_mut().inner; - if has_pkgpath { - self.ret_void(); - self.pop_function(); - self.builder.position_at_end( - func_before_block.expect(kcl_error::INTERNAL_ERROR_MSG), - ); - } - let tpe = self.context.void_type(); - let fn_type = tpe.fn_type( - &[self.context_ptr_type().into(), self.scope_ptr_type().into()], - false, - ); - module.add_function(&name, fn_type, Some(Linkage::External)) - }; - let ctx = self.current_runtime_ctx_ptr(); - let scope = self.current_scope_ptr(); - let pkgpath_value = self.native_global_string_value(&name); - let is_imported = self - .build_call( - &ApiFunc::kclvm_context_pkgpath_is_imported.name(), - &[self.current_runtime_ctx_ptr(), pkgpath_value], - ) - .into_int_value(); - let is_not_imported = self.builder.build_int_compare( - IntPredicate::EQ, - is_imported, - self.native_i8_zero(), - "", - ); - let then_block = self.append_block(""); - let else_block = self.append_block(""); - self.builder - .build_conditional_branch(is_not_imported, then_block, else_block); - self.builder.position_at_end(then_block); - self.builder - .build_call(function, &[ctx.into(), scope.into()], ""); - self.br(else_block); - self.builder.position_at_end(else_block); - } - }; - { - let mut imported = self.imported.borrow_mut(); - (*imported).insert(pkgpath.to_string()); - // Deref the borrow mut - } - self.ok_result() - } - - fn walk_schema_stmt(&self, schema_stmt: &'ctx ast::SchemaStmt) -> Self::Result { - check_backtrack_stop!(self); - let func_before_block = self.append_block(""); - self.br(func_before_block); - let value_ptr_type = self.value_ptr_type(); - let schema_name = &schema_stmt.name.node; - let schema_pkgpath = &self.current_pkgpath(); - let filename = &self.current_filename(); - let runtime_type = kclvm_runtime::schema_runtime_type(schema_name, schema_pkgpath); - // Build schema body function - let function = self.add_function(&format!( - "{}.{}", - value::SCHEMA_NAME, - pkgpath_without_prefix!(runtime_type) - )); - // Build the schema check function. - let check_function = self.add_function(&format!( - "{}.{}", - value::SCHEMA_CHECK_BLOCK_NAME, - pkgpath_without_prefix!(runtime_type), - )); - let mut place_holder_map: HashMap>> = HashMap::new(); - let mut body_map: HashMap, BacktrackKind)>> = - HashMap::new(); - // Enter the function - self.push_function(function); - // Lambda function body - let block = self.append_block(ENTRY_NAME); - self.builder.position_at_end(block); - self.build_void_call( - &ApiFunc::kclvm_context_set_kcl_filename.name(), - &[ - self.current_runtime_ctx_ptr(), - self.native_global_string_value(filename), - ], - ); - utils::update_ctx_pkgpath(self, schema_pkgpath); - let args = function - .get_nth_param(1) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let kwargs = function - .get_nth_param(2) - .expect(kcl_error::INTERNAL_ERROR_MSG); - self.enter_scope(); - let add_variable = |name: &str, value: BasicValueEnum| { - let var = self.builder.build_alloca(value_ptr_type, name); - self.builder.build_store(var, value); - self.add_variable(name, var); - }; - // Schema function closures - let instance_pkgpath = self.list_pop(args); - let record_instance = self.list_pop(args); - let backtrack_cache = self.list_pop(args); - let backtrack_level_map = self.list_pop(args); - let cal_map = self.list_pop(args); - let attr_optional_mapping = self.list_pop(args); - let schema_value = self.list_pop(args); - let schema_config = self.list_pop(args); - let schema_config_meta = self.list_pop(args); - let is_sub_schema = self.list_pop(args); - add_variable(value::BACKTRACK_CACHE, backtrack_cache); - add_variable(value::BACKTRACK_LEVEL_MAP, backtrack_level_map); - add_variable(value::SCHEMA_CAL_MAP, cal_map); - add_variable(value::SCHEMA_CONFIG_NAME, schema_config); - add_variable(value::SCHEMA_CONFIG_META_NAME, schema_config_meta); - add_variable(value::SCHEMA_ARGS, args); - add_variable(value::SCHEMA_KWARGS, kwargs); - add_variable(value::SCHEMA_RUNTIME_TYPE, self.string_value(&runtime_type)); - self.walk_arguments(&schema_stmt.args, args, kwargs); - let schema = value::SchemaType::new( - schema_name, - schema_pkgpath, - &runtime_type, - schema_stmt.is_mixin, - ); - let schema_value = if let Some(parent_name) = &schema_stmt.parent_name { - let base_constructor_func = self - .walk_identifier_with_ctx(&parent_name.node, &ast::ExprContext::Load, None) - .expect(kcl_error::COMPILE_ERROR_MSG); - // Schema function closures - let list_value = self.list_values(&[ - // is_sub_schema - self.bool_value(false), - schema_config_meta, - schema_config, - schema_value, - attr_optional_mapping, - cal_map, - backtrack_level_map, - backtrack_cache, - record_instance, - instance_pkgpath, - ]); - let dict_value = self.dict_value(); - let func_ptr = self.build_call( - &ApiFunc::kclvm_value_function_ptr.name(), - &[base_constructor_func], - ); - let fn_ty = self.function_type().ptr_type(AddressSpace::default()); - let func_ptr_cast = self.builder.build_bitcast(func_ptr, fn_ty, ""); - self.builder - .build_call( - CallableValue::try_from(func_ptr_cast.into_pointer_value()) - .expect(kcl_error::INTERNAL_ERROR_MSG), - &[ - self.current_runtime_ctx_ptr().into(), - list_value.into(), - dict_value.into(), - ], - "", - ) - .try_as_basic_value() - .left() - .expect(kcl_error::FUNCTION_RETURN_VALUE_NOT_FOUND_MSG) - } else { - schema_value - }; - if schema_stmt.parent_name.is_some() { - self.build_void_call( - &ApiFunc::kclvm_context_set_kcl_filename.name(), - &[ - self.current_runtime_ctx_ptr(), - self.native_global_string_value(filename), - ], - ); - } - self.schema_stack.borrow_mut().push(schema); - add_variable(value::SCHEMA_SELF_NAME, schema_value); - self.emit_left_identifiers( - &schema_stmt.body, - &schema_stmt.index_signature, - cal_map, - &runtime_type, - false, - &mut place_holder_map, - &mut body_map, - &mut vec![], - ); - let do_run_i1 = self.value_is_truthy(record_instance); - let do_run_block = self.append_block(""); - let end_run_block = self.append_block(""); - self.cond_br(do_run_i1, do_run_block, end_run_block); - self.builder.position_at_end(do_run_block); - // Run schema compiled function - for stmt in &schema_stmt.body { - self.walk_stmt(stmt).expect(kcl_error::COMPILE_ERROR_MSG); - } - // Schema decorators check - for decorator in &schema_stmt.decorators { - self.walk_decorator_with_name(&decorator.node, Some(schema_name), true) - .expect(kcl_error::COMPILE_ERROR_MSG); - } - // Append schema default settings, args, kwargs and runtime type. - self.build_void_call( - &ApiFunc::kclvm_schema_default_settings.name(), - &[ - schema_value, - schema_config, - args, - kwargs, - self.native_global_string_value(&runtime_type), - ], - ); - self.br(end_run_block); - self.builder.position_at_end(end_run_block); - // Schema mixin - for mixin in &schema_stmt.mixins { - let mixin_func = self - .walk_identifier_with_ctx(&mixin.node, &ast::ExprContext::Load, None) - .expect(kcl_error::COMPILE_ERROR_MSG); - // Schema function closures - let list_value = self.list_values(&[ - // is_sub_schema - self.bool_value(false), - schema_config_meta, - schema_config, - schema_value, - attr_optional_mapping, - cal_map, - backtrack_level_map, - backtrack_cache, - record_instance, - instance_pkgpath, - ]); - let dict_value = self.dict_value(); - let func_ptr = - self.build_call(&ApiFunc::kclvm_value_function_ptr.name(), &[mixin_func]); - let fn_ty = self.function_type().ptr_type(AddressSpace::default()); - let func_ptr_cast = self.builder.build_bitcast(func_ptr, fn_ty, ""); - self.builder.build_call( - CallableValue::try_from(func_ptr_cast.into_pointer_value()) - .expect(kcl_error::INTERNAL_ERROR_MSG), - &[ - self.current_runtime_ctx_ptr().into(), - list_value.into(), - dict_value.into(), - ], - "", - ); - self.build_void_call( - &ApiFunc::kclvm_context_set_kcl_filename.name(), - &[ - self.current_runtime_ctx_ptr(), - self.native_global_string_value(filename), - ], - ); - } - // Schema Attribute optional check - for stmt in &schema_stmt.body { - if let ast::Stmt::SchemaAttr(schema_attr) = &stmt.node { - self.dict_insert_override_item( - attr_optional_mapping, - schema_attr.name.node.as_str(), - self.bool_value(schema_attr.is_optional), - ) - } - } - let is_sub_schema_i1 = self.value_is_truthy(is_sub_schema); - let do_check_block = self.append_block(""); - let end_check_block = self.append_block(""); - self.cond_br(is_sub_schema_i1, do_check_block, end_check_block); - self.builder.position_at_end(do_check_block); - let schema_name_native_str = self.native_global_string_value(&schema_stmt.name.node); - let schema_pkgpath_native_str = self.native_global_string_value(&self.current_pkgpath()); - { - let index_sign_key_name = if let Some(index_signature) = &schema_stmt.index_signature { - if let Some(key_name) = &index_signature.node.key_name { - key_name - } else { - "" - } - } else { - "" - }; - let list_value = self.value_deep_copy(args); - let dict_value = self.value_deep_copy(kwargs); - // Schema check function closure - self.list_append(list_value, schema_config_meta); - self.list_append(list_value, schema_config); - self.list_append(list_value, schema_value); - self.list_append(list_value, cal_map); - self.list_append(list_value, backtrack_level_map); - self.list_append(list_value, backtrack_cache); - if index_sign_key_name.is_empty() { - // Call schema check block function - self.builder.build_call( - check_function, - &[ - self.current_runtime_ctx_ptr().into(), - list_value.into(), - dict_value.into(), - ], - "", - ); - } else { - // Call schema check block function with index sign attribute name loop set - let check_lambda_fn_ptr = self.builder.build_bitcast( - check_function.as_global_value().as_pointer_value(), - self.context.i64_type().ptr_type(AddressSpace::default()), - "", - ); - let attr_name = self.native_global_string_value(index_sign_key_name); - self.build_void_call( - ApiFunc::kclvm_schema_do_check_with_index_sign_attr - .name() - .as_str(), - &[ - self.current_runtime_ctx_ptr(), - list_value, - dict_value, - check_lambda_fn_ptr, - attr_name, - ], - ); - } - } - self.br(end_check_block); - self.builder.position_at_end(end_check_block); - // Build a schema value and record instance - let schema_value = self.build_call( - &ApiFunc::kclvm_value_schema_with_config.name(), - &[ - self.current_runtime_ctx_ptr(), - schema_value, - schema_config, - schema_config_meta, - schema_name_native_str, - schema_pkgpath_native_str, - is_sub_schema, - record_instance, - instance_pkgpath, - attr_optional_mapping, - args, - kwargs, - ], - ); - // Schema constructor function returns a schema - self.builder.build_return(Some(&schema_value)); - // Exist the function - self.builder.position_at_end(func_before_block); - // Build schema check function - { - self.push_function(check_function); - let check_block = self.append_block(ENTRY_NAME); - self.builder.position_at_end(check_block); - let args = function - .get_nth_param(1) - .expect(kcl_error::INTERNAL_ERROR_MSG); - // Schema check function closure - let backtrack_cache = self.list_pop(args); - let backtrack_level_map = self.list_pop(args); - let cal_map = self.list_pop(args); - let schema_value = self.list_pop(args); - let schema_config = self.list_pop(args); - let schema_config_meta = self.list_pop(args); - add_variable(value::BACKTRACK_CACHE, backtrack_cache); - add_variable(value::BACKTRACK_LEVEL_MAP, backtrack_level_map); - add_variable(value::SCHEMA_CAL_MAP, cal_map); - add_variable(value::SCHEMA_CONFIG_NAME, schema_config); - add_variable(value::SCHEMA_CONFIG_META_NAME, schema_config_meta); - add_variable(value::SCHEMA_SELF_NAME, schema_value); - add_variable(value::SCHEMA_ARGS, args); - add_variable(value::SCHEMA_KWARGS, kwargs); - add_variable(value::SCHEMA_RUNTIME_TYPE, self.string_value(&runtime_type)); - let schema = self - .schema_stack - .borrow_mut() - .pop() - .expect(kcl_error::INTERNAL_ERROR_MSG); - self.walk_arguments(&schema_stmt.args, args, kwargs); - self.schema_stack.borrow_mut().push(schema); - // Schema runtime index signature and relaxed check - if let Some(index_signature) = &schema_stmt.index_signature { - let index_sign_value = if let Some(value) = &index_signature.node.value { - self.walk_expr(value).expect(kcl_error::COMPILE_ERROR_MSG) - } else { - self.undefined_value() - }; - let key_name_str_ptr = if let Some(key_name) = &index_signature.node.key_name { - self.native_global_string(key_name.as_str(), "") - } else { - self.native_global_string("", "") - }; - self.build_void_call( - &ApiFunc::kclvm_schema_value_check.name(), - &[ - self.current_runtime_ctx_ptr(), - schema_value, - schema_config, - schema_config_meta, - schema_name_native_str, - index_sign_value, - key_name_str_ptr.into(), - self.native_global_string( - index_signature.node.key_ty.node.to_string().as_str(), - "", - ) - .into(), - self.native_global_string( - index_signature.node.value_ty.node.to_string().as_str(), - "", - ) - .into(), - self.native_i8(index_signature.node.any_other as i8).into(), - ], - ); - } else { - self.build_void_call( - &ApiFunc::kclvm_schema_value_check.name(), - &[ - self.current_runtime_ctx_ptr(), - schema_value, - schema_config, - schema_config_meta, - schema_name_native_str, - self.none_value(), - self.native_global_string("", "").into(), - self.native_global_string("", "").into(), - self.native_global_string("", "").into(), - self.native_i8(0).into(), - ], - ); - } - // Call base check function - if let Some(parent_name) = &schema_stmt.parent_name { - let base_constructor_func = self - .walk_identifier_with_ctx(&parent_name.node, &ast::ExprContext::Load, None) - .expect(kcl_error::COMPILE_ERROR_MSG); - let func_ptr = self.build_call( - &ApiFunc::kclvm_value_check_function_ptr.name(), - &[base_constructor_func], - ); - let fn_ty = self.function_type().ptr_type(AddressSpace::default()); - let func_ptr_cast = self.builder.build_bitcast(func_ptr, fn_ty, ""); - // Schema check function closure - let list_value = self.list_values(&[ - schema_config_meta, - schema_config, - schema_value, - cal_map, - backtrack_level_map, - backtrack_cache, - ]); - let dict_value = self.dict_value(); - self.builder.build_call( - CallableValue::try_from(func_ptr_cast.into_pointer_value()) - .expect(kcl_error::INTERNAL_ERROR_MSG), - &[ - self.current_runtime_ctx_ptr().into(), - list_value.into(), - dict_value.into(), - ], - "", - ); - self.build_void_call( - &ApiFunc::kclvm_context_set_kcl_filename.name(), - &[ - self.current_runtime_ctx_ptr(), - self.native_global_string_value(filename), - ], - ); - } - // Call self check function - for check_expr in &schema_stmt.checks { - self.walk_check_expr(&check_expr.node) - .expect(kcl_error::COMPILE_ERROR_MSG); - } - // Call mixin check functions - for mixin in &schema_stmt.mixins { - let mixin_func = self - .walk_identifier_with_ctx(&mixin.node, &ast::ExprContext::Load, None) - .expect(kcl_error::COMPILE_ERROR_MSG); - let func_ptr = self.build_call( - &ApiFunc::kclvm_value_check_function_ptr.name(), - &[mixin_func], - ); - let fn_ty = self.function_type().ptr_type(AddressSpace::default()); - let func_ptr_cast = self.builder.build_bitcast(func_ptr, fn_ty, ""); - // Schema check function closure - let list_value = self.list_values(&[ - schema_config_meta, - schema_config, - schema_value, - cal_map, - backtrack_level_map, - backtrack_cache, - ]); - let dict_value = self.dict_value(); - self.builder.build_call( - CallableValue::try_from(func_ptr_cast.into_pointer_value()) - .expect(kcl_error::INTERNAL_ERROR_MSG), - &[ - self.current_runtime_ctx_ptr().into(), - list_value.into(), - dict_value.into(), - ], - "", - ); - self.build_void_call( - &ApiFunc::kclvm_context_set_kcl_filename.name(), - &[ - self.current_runtime_ctx_ptr(), - self.native_global_string_value(filename), - ], - ); - } - self.builder.build_return(Some(&schema_value)); - self.builder.position_at_end(func_before_block); - self.pop_function(); - } - // Build schema attr backtrack functions - { - for (k, functions) in &place_holder_map { - if k == kclvm_runtime::CAL_MAP_INDEX_SIGNATURE { - continue; - } - let stmt_list = body_map.get(k).expect(kcl_error::INTERNAL_ERROR_MSG); - let mut if_level = 0; - for (attr_func, (stmt, kind)) in functions.iter().zip(stmt_list) { - let function = *attr_func; - let name = function - .get_name() - .to_str() - .expect(kcl_error::INTERNAL_ERROR_MSG); - // Get schema attr function from the module - let function = self.lookup_function(name); - self.push_function(function); - self.enter_scope(); - let attr_block = self.append_block(ENTRY_NAME); - self.builder.position_at_end(attr_block); - let args = function - .get_nth_param(1) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let kwargs = function - .get_nth_param(2) - .expect(kcl_error::INTERNAL_ERROR_MSG); - // Schema attr function closure - let backtrack_cache = self.list_pop(args); - let backtrack_level_map = self.list_pop(args); - let cal_map = self.list_pop(args); - let schema_value = self.list_pop(args); - let schema_config = self.list_pop(args); - let schema_config_meta = self.list_pop(args); - // Store magic variable - add_variable(value::BACKTRACK_CACHE, backtrack_cache); - add_variable(value::BACKTRACK_LEVEL_MAP, backtrack_level_map); - add_variable(value::SCHEMA_CAL_MAP, cal_map); - add_variable(value::SCHEMA_CONFIG_NAME, schema_config); - add_variable(value::SCHEMA_CONFIG_META_NAME, schema_config_meta); - add_variable(value::SCHEMA_SELF_NAME, schema_value); - add_variable(value::SCHEMA_ARGS, args); - add_variable(value::SCHEMA_KWARGS, kwargs); - add_variable(value::SCHEMA_RUNTIME_TYPE, self.string_value(&runtime_type)); - self.build_void_call( - &ApiFunc::kclvm_context_set_kcl_filename.name(), - &[ - self.current_runtime_ctx_ptr(), - self.native_global_string_value(filename), - ], - ); - let schema = self - .schema_stack - .borrow_mut() - .pop() - .expect(kcl_error::INTERNAL_ERROR_MSG); - self.walk_arguments(&schema_stmt.args, args, kwargs); - self.schema_stack.borrow_mut().push(schema); - // Backtrack meta begin - if matches!(&stmt.node, ast::Stmt::If(..)) { - if_level += 1; - *self.backtrack_meta.borrow_mut() = Some(BacktrackMeta { - target: k.clone(), - level: if_level, - count: 0, - stop: false, - kind: kind.clone(), - }); - } else { - if_level = 0; - } - self.walk_stmt(stmt).expect(kcl_error::COMPILE_ERROR_MSG); - // Backtrack meta end - if matches!(&stmt.node, ast::Stmt::If(..)) { - *self.backtrack_meta.borrow_mut() = None - } - // Build return - self.builder.build_return(Some(&schema_value)); - // Position at global main function block - self.builder.position_at_end(func_before_block); - self.leave_scope(); - self.pop_function(); - } - } - } - let function = self.struct_function_value( - &[function, check_function], - &place_holder_map, - &runtime_type, - ); - self.leave_scope(); - self.pop_function(); - self.schema_stack.borrow_mut().pop(); - // Store or add the variable in the scope - if !self.store_variable(schema_name, function) { - let global_var_ptr = self.new_global_kcl_value_ptr(""); - self.builder.build_store(global_var_ptr, function); - self.add_variable(schema_name, global_var_ptr); - } - Ok(function) - } - - fn walk_rule_stmt(&self, rule_stmt: &'ctx ast::RuleStmt) -> Self::Result { - check_backtrack_stop!(self); - let func_before_block = self.append_block(""); - self.br(func_before_block); - let value_ptr_type = self.value_ptr_type(); - let name = &rule_stmt.name.node; - let pkgpath = &self.current_pkgpath(); - let filename = &self.current_filename(); - let runtime_type = kclvm_runtime::schema_runtime_type(name, pkgpath); - // Build schema body function - let function = self.add_function(&format!( - "{}.{}", - value::SCHEMA_NAME, - pkgpath_without_prefix!(runtime_type) - )); - // Build the schema check function. - let check_function = self.add_function(&format!( - "{}.{}", - value::SCHEMA_CHECK_BLOCK_NAME, - pkgpath_without_prefix!(runtime_type), - )); - // Enter the function - self.push_function(function); - // Lambda function body - let block = self.append_block(ENTRY_NAME); - self.builder.position_at_end(block); - self.build_void_call( - &ApiFunc::kclvm_context_set_kcl_filename.name(), - &[ - self.current_runtime_ctx_ptr(), - self.native_global_string_value(filename), - ], - ); - let args = function - .get_nth_param(1) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let kwargs = function - .get_nth_param(2) - .expect(kcl_error::INTERNAL_ERROR_MSG); - self.enter_scope(); - // Schema function closures - let instance_pkgpath = self.list_pop(args); - let record_instance = self.list_pop(args); - let backtrack_cache = self.list_pop(args); - let backtrack_level_map = self.list_pop(args); - let cal_map = self.list_pop(args); - let attr_optional_mapping = self.list_pop(args); - let schema_value = self.list_pop(args); - let schema_config = self.list_pop(args); - let schema_config_meta = self.list_pop(args); - let is_sub_schema = self.list_pop(args); - let add_variable = |name: &str, value: BasicValueEnum| { - let var = self.builder.build_alloca(value_ptr_type, name); - self.builder.build_store(var, value); - self.add_variable(name, var); - }; - add_variable(value::BACKTRACK_CACHE, backtrack_cache); - add_variable(value::BACKTRACK_LEVEL_MAP, backtrack_level_map); - add_variable(value::SCHEMA_CAL_MAP, cal_map); - add_variable(value::SCHEMA_CONFIG_NAME, schema_config); - add_variable(value::SCHEMA_CONFIG_META_NAME, schema_config_meta); - add_variable(value::SCHEMA_ARGS, args); - add_variable(value::SCHEMA_KWARGS, kwargs); - add_variable(value::SCHEMA_RUNTIME_TYPE, self.string_value(&runtime_type)); - self.walk_arguments(&rule_stmt.args, args, kwargs); - let schema = value::SchemaType::new(name, pkgpath, &runtime_type, false); - self.schema_stack.borrow_mut().push(schema); - add_variable(value::SCHEMA_SELF_NAME, schema_value); - // construct for protocol - let schema_value = if let Some(for_host_name) = &rule_stmt.for_host_name { - let base_constructor_func = self - .walk_identifier_with_ctx(&for_host_name.node, &ast::ExprContext::Load, None) - .expect(kcl_error::COMPILE_ERROR_MSG); - // Schema function closures - let list_value = self.list_values(&[ - // is_sub_schema - self.bool_value(false), - schema_config_meta, - schema_config, - schema_value, - attr_optional_mapping, - cal_map, - backtrack_level_map, - backtrack_cache, - record_instance, - instance_pkgpath, - ]); - let dict_value = self.dict_value(); - let func_ptr = self.build_call( - &ApiFunc::kclvm_value_function_ptr.name(), - &[base_constructor_func], - ); - let fn_ty = self.function_type().ptr_type(AddressSpace::default()); - let func_ptr_cast = self.builder.build_bitcast(func_ptr, fn_ty, ""); - let schema_value = self - .builder - .build_call( - CallableValue::try_from(func_ptr_cast.into_pointer_value()) - .expect(kcl_error::INTERNAL_ERROR_MSG), - &[ - self.current_runtime_ctx_ptr().into(), - list_value.into(), - dict_value.into(), - ], - "", - ) - .try_as_basic_value() - .left() - .expect(kcl_error::FUNCTION_RETURN_VALUE_NOT_FOUND_MSG); - let protocol_name_native_str = - self.native_global_string_value(&for_host_name.node.get_name()); - self.build_void_call( - &ApiFunc::kclvm_schema_value_check.name(), - &[ - self.current_runtime_ctx_ptr(), - schema_value, - schema_config, - schema_config_meta, - protocol_name_native_str, - self.undefined_value(), - self.native_global_string("", "").into(), - self.native_global_string(STR_TYPE_STR, "").into(), - self.native_global_string(ANY_TYPE_STR, "").into(), - self.native_i8(1).into(), - ], - ); - schema_value - } else { - schema_value - }; - let do_run_i1 = self.value_is_truthy(record_instance); - let do_run_block = self.append_block(""); - let end_run_block = self.append_block(""); - self.cond_br(do_run_i1, do_run_block, end_run_block); - self.builder.position_at_end(do_run_block); - // Rule decorators check - for decorator in &rule_stmt.decorators { - self.walk_decorator_with_name(&decorator.node, Some(name), true) - .expect(kcl_error::INTERNAL_ERROR_MSG); - } - self.br(end_run_block); - self.builder.position_at_end(end_run_block); - let is_sub_schema_i1 = self.value_is_truthy(is_sub_schema); - let do_check_block = self.append_block(""); - let end_check_block = self.append_block(""); - self.cond_br(is_sub_schema_i1, do_check_block, end_check_block); - self.builder.position_at_end(do_check_block); - { - // Schema check function closure - let list_value = self.list_values(&[ - schema_config_meta, - schema_config, - schema_value, - cal_map, - backtrack_level_map, - backtrack_cache, - ]); - let dict_value = self.dict_value(); - // Call schema check block function - self.builder.build_call( - check_function, - &[ - self.current_runtime_ctx_ptr().into(), - list_value.into(), - dict_value.into(), - ], - "", - ); - } - self.br(end_check_block); - self.builder.position_at_end(end_check_block); - // Rule constructor function returns a rule - self.builder.build_return(Some(&schema_value)); - // Exist the function - self.builder.position_at_end(func_before_block); - // Build rule check function - { - self.push_function(check_function); - let check_block = self.append_block(ENTRY_NAME); - self.builder.position_at_end(check_block); - let args = function - .get_nth_param(1) - .expect(kcl_error::INTERNAL_ERROR_MSG); - // Schema check function closure - let backtrack_cache = self.list_pop(args); - let backtrack_level_map = self.list_pop(args); - let cal_map = self.list_pop(args); - let schema_value = self.list_pop(args); - let schema_config = self.list_pop(args); - let schema_config_meta = self.list_pop(args); - add_variable(value::BACKTRACK_CACHE, backtrack_cache); - add_variable(value::BACKTRACK_LEVEL_MAP, backtrack_level_map); - add_variable(value::SCHEMA_CAL_MAP, cal_map); - add_variable(value::SCHEMA_CONFIG_NAME, schema_config); - add_variable(value::SCHEMA_CONFIG_META_NAME, schema_config_meta); - add_variable(value::SCHEMA_SELF_NAME, schema_value); - add_variable(value::SCHEMA_ARGS, args); - add_variable(value::SCHEMA_KWARGS, kwargs); - add_variable(value::SCHEMA_RUNTIME_TYPE, self.string_value(&runtime_type)); - let schema = self - .schema_stack - .borrow_mut() - .pop() - .expect(kcl_error::INTERNAL_ERROR_MSG); - self.walk_arguments(&rule_stmt.args, args, kwargs); - self.schema_stack.borrow_mut().push(schema); - // Call base check function - for parent_name in &rule_stmt.parent_rules { - let base_constructor_func = self - .walk_identifier_with_ctx(&parent_name.node, &ast::ExprContext::Load, None) - .expect(kcl_error::COMPILE_ERROR_MSG); - let func_ptr = self.build_call( - &ApiFunc::kclvm_value_check_function_ptr.name(), - &[base_constructor_func], - ); - let fn_ty = self.function_type().ptr_type(AddressSpace::default()); - let func_ptr_cast = self.builder.build_bitcast(func_ptr, fn_ty, ""); - // Schema check function closure - let list_value = self.list_values(&[ - schema_config_meta, - schema_config, - schema_value, - cal_map, - backtrack_level_map, - backtrack_cache, - ]); - let dict_value = self.dict_value(); - self.builder.build_call( - CallableValue::try_from(func_ptr_cast.into_pointer_value()) - .expect(kcl_error::INTERNAL_ERROR_MSG), - &[ - self.current_runtime_ctx_ptr().into(), - list_value.into(), - dict_value.into(), - ], - "", - ); - } - // Call self rule check expressions - for check_expr in &rule_stmt.checks { - self.walk_check_expr(&check_expr.node) - .expect(kcl_error::COMPILE_ERROR_MSG); - } - self.builder.build_return(Some(&schema_value)); - self.builder.position_at_end(func_before_block); - self.pop_function(); - } - let function = - self.struct_function_value(&[function, check_function], &HashMap::new(), &runtime_type); - self.leave_scope(); - self.pop_function(); - self.schema_stack.borrow_mut().pop(); - // Store or add the variable in the scope - if !self.store_variable(name, function) { - let global_var_ptr = self.new_global_kcl_value_ptr(&runtime_type); - self.builder.build_store(global_var_ptr, function); - self.add_variable(name, global_var_ptr); - } - Ok(function) - } - - /* - * Expr - */ - - fn walk_expr(&self, expr: &'ctx ast::Node) -> Self::Result { - check_backtrack_stop!(self); - utils::update_ctx_filename(self, expr); - utils::update_ctx_line_col(self, expr); - match &expr.node { - ast::Expr::Target(target) => self.walk_target(target), - ast::Expr::Identifier(identifier) => self.walk_identifier(identifier), - ast::Expr::Unary(unary_expr) => self.walk_unary_expr(unary_expr), - ast::Expr::Binary(binary_expr) => self.walk_binary_expr(binary_expr), - ast::Expr::If(if_expr) => self.walk_if_expr(if_expr), - ast::Expr::Selector(selector_expr) => self.walk_selector_expr(selector_expr), - ast::Expr::Call(call_expr) => self.walk_call_expr(call_expr), - ast::Expr::Paren(paren_expr) => self.walk_paren_expr(paren_expr), - ast::Expr::Quant(quant_expr) => self.walk_quant_expr(quant_expr), - ast::Expr::List(list_expr) => self.walk_list_expr(list_expr), - ast::Expr::ListIfItem(list_if_item_expr) => { - self.walk_list_if_item_expr(list_if_item_expr) - } - ast::Expr::ListComp(list_comp) => self.walk_list_comp(list_comp), - ast::Expr::Starred(starred_expr) => self.walk_starred_expr(starred_expr), - ast::Expr::DictComp(dict_comp) => self.walk_dict_comp(dict_comp), - ast::Expr::ConfigIfEntry(config_if_entry_expr) => { - self.walk_config_if_entry_expr(config_if_entry_expr) - } - ast::Expr::CompClause(comp_clause) => self.walk_comp_clause(comp_clause), - ast::Expr::Schema(schema_expr) => self.walk_schema_expr(schema_expr), - ast::Expr::Config(config_expr) => self.walk_config_expr(config_expr), - ast::Expr::Check(check) => self.walk_check_expr(check), - ast::Expr::Lambda(lambda) => self.walk_lambda_expr(lambda), - ast::Expr::Subscript(subscript) => self.walk_subscript(subscript), - ast::Expr::Keyword(keyword) => self.walk_keyword(keyword), - ast::Expr::Arguments(..) => self.ok_result(), - ast::Expr::Compare(compare) => self.walk_compare(compare), - ast::Expr::NumberLit(number_lit) => self.walk_number_lit(number_lit), - ast::Expr::StringLit(string_lit) => self.walk_string_lit(string_lit), - ast::Expr::NameConstantLit(name_constant_lit) => { - self.walk_name_constant_lit(name_constant_lit) - } - ast::Expr::JoinedString(joined_string) => self.walk_joined_string(joined_string), - ast::Expr::FormattedValue(formatted_value) => { - self.walk_formatted_value(formatted_value) - } - ast::Expr::Missing(missing_expr) => self.walk_missing_expr(missing_expr), - } - } - - fn walk_quant_expr(&self, quant_expr: &'ctx ast::QuantExpr) -> Self::Result { - check_backtrack_stop!(self); - let result = match quant_expr.op { - ast::QuantOperation::All => self.bool_value(true), - ast::QuantOperation::Any => self.bool_value(false), - ast::QuantOperation::Map => self.list_value(), - ast::QuantOperation::Filter => self.value_deep_copy( - self.walk_expr(&quant_expr.target) - .expect(kcl_error::COMPILE_ERROR_MSG), - ), - }; - // Blocks - let start_block = self.append_block(""); - let next_value_block = self.append_block(""); - let continue_block = self.append_block(""); - let end_for_block = self.append_block(""); - let all_break_block = self.append_block(""); - let any_break_block = self.append_block(""); - let result_block = self.append_block(""); - // Iterator - let iter_host_value = if let ast::QuantOperation::Filter = quant_expr.op { - self.value_deep_copy(result) - } else { - self.walk_expr(&quant_expr.target) - .expect(kcl_error::COMPILE_ERROR_MSG) - }; - let iter_value = self.build_call(&ApiFunc::kclvm_value_iter.name(), &[iter_host_value]); - self.br(start_block); - self.builder.position_at_end(start_block); - self.enter_scope(); - let is_end = self - .build_call(&ApiFunc::kclvm_iterator_is_end.name(), &[iter_value]) - .into_int_value(); - let is_end = - self.builder - .build_int_compare(IntPredicate::NE, is_end, self.native_i8_zero(), ""); - self.builder - .build_conditional_branch(is_end, end_for_block, next_value_block); - self.builder.position_at_end(next_value_block); - let next_value = self.build_call( - &ApiFunc::kclvm_iterator_next_value.name(), - &[iter_value, iter_host_value], - ); - let key = self.build_call(&ApiFunc::kclvm_iterator_cur_key.name(), &[iter_value]); - let variables = &quant_expr.variables; - { - let mut local_vars = self.local_vars.borrow_mut(); - for v in variables { - let name = &v.node.names[0].node; - local_vars.insert(name.clone()); - } - } - if variables.len() == 1 { - // Store the target - self.walk_identifier_with_ctx( - &variables.first().expect(kcl_error::INTERNAL_ERROR_MSG).node, - &ast::ExprContext::Store, - Some(next_value), - ) - .expect(kcl_error::COMPILE_ERROR_MSG); - } else if variables.len() == 2 { - let value = self.build_call(&ApiFunc::kclvm_iterator_cur_value.name(), &[iter_value]); - // Store the target - self.walk_identifier_with_ctx( - &variables.first().expect(kcl_error::INTERNAL_ERROR_MSG).node, - &ast::ExprContext::Store, - Some(key), - ) - .expect(kcl_error::COMPILE_ERROR_MSG); - self.walk_identifier_with_ctx( - &variables.get(1).expect(kcl_error::INTERNAL_ERROR_MSG).node, - &ast::ExprContext::Store, - Some(value), - ) - .expect(kcl_error::COMPILE_ERROR_MSG); - } else { - panic!( - "the number of loop variables is {}, which can only be 1 or 2", - variables.len() - ) - } - if let Some(if_expr) = &quant_expr.if_cond { - let if_truth = self.walk_expr(if_expr).expect(kcl_error::COMPILE_ERROR_MSG); - let is_truth = self.value_is_truthy(if_truth); - self.cond_br(is_truth, continue_block, start_block); - } else { - self.br(continue_block); - } - self.builder.position_at_end(continue_block); - // Body block - let test = &quant_expr.test; - let value = self.walk_expr(test).expect(kcl_error::COMPILE_ERROR_MSG); - let is_truth = self.value_is_truthy(value); - match quant_expr.op { - ast::QuantOperation::All => { - self.cond_br(is_truth, start_block, all_break_block); - } - ast::QuantOperation::Any => { - self.cond_br(is_truth, any_break_block, start_block); - } - ast::QuantOperation::Filter => { - let then_block = self.append_block(""); - self.cond_br(is_truth, start_block, then_block); - self.builder.position_at_end(then_block); - self.build_void_call( - &ApiFunc::kclvm_value_remove_item.name(), - &[result, next_value], - ); - self.br(start_block); - } - ast::QuantOperation::Map => { - self.list_append(result, value); - self.br(start_block); - } - } - self.builder.position_at_end(all_break_block); - let all_false_value = self.bool_value(false); - self.br(result_block); - self.builder.position_at_end(any_break_block); - let any_true_value = self.bool_value(true); - self.br(result_block); - self.builder.position_at_end(end_for_block); - let tpe = self.value_ptr_type(); - let ptr = self.builder.build_alloca(tpe, ""); - self.builder.build_store(ptr, result); - let value = self.builder.build_load(ptr, ""); - self.br(result_block); - self.builder.position_at_end(result_block); - let phi = self.builder.build_phi(tpe, ""); - phi.add_incoming(&[ - (&all_false_value, all_break_block), - (&any_true_value, any_break_block), - (&value, end_for_block), - ]); - self.leave_scope(); - self.local_vars.borrow_mut().clear(); - self.build_void_call(&ApiFunc::kclvm_iterator_delete.name(), &[iter_value]); - Ok(phi.as_basic_value()) - } - - fn walk_schema_attr(&self, schema_attr: &'ctx ast::SchemaAttr) -> Self::Result { - check_backtrack_stop!(self); - self.local_vars.borrow_mut().clear(); - let name = schema_attr.name.node.as_str(); - self.target_vars.borrow_mut().push(name.to_string()); - for decorator in &schema_attr.decorators { - self.walk_decorator_with_name(&decorator.node, Some(name), false) - .expect(kcl_error::COMPILE_ERROR_MSG); - } - let config_value = self - .get_variable(value::SCHEMA_CONFIG_NAME) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let schema_value = self - .get_variable(value::SCHEMA_SELF_NAME) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let string_ptr_value = self.native_global_string(name, "").into(); - let type_str_ptr_value = self - .native_global_string(&schema_attr.ty.node.to_string(), "") - .into(); - self.build_void_call( - &ApiFunc::kclvm_config_attr_map.name(), - &[schema_value, string_ptr_value, type_str_ptr_value], - ); - let has_key = self - .build_call( - &ApiFunc::kclvm_dict_has_value.name(), - &[config_value, string_ptr_value], - ) - .into_int_value(); - let has_key = - self.builder - .build_int_compare(IntPredicate::NE, has_key, self.native_i8_zero(), ""); - let then_block = self.append_block(""); - let else_block = self.append_block(""); - let end_block = self.append_block(""); - self.builder - .build_conditional_branch(has_key, then_block, else_block); - self.builder.position_at_end(then_block); - let config_attr_value = self.build_call( - &ApiFunc::kclvm_dict_get_entry.name(), - &[ - self.current_runtime_ctx_ptr(), - config_value, - string_ptr_value, - ], - ); - // If the attribute operator is not `=`, eval the schema attribute value. - // if is_not_override: - let is_override_attr = self - .build_call( - &ApiFunc::kclvm_dict_is_override_attr.name(), - &[config_value, string_ptr_value], - ) - .into_int_value(); - let is_not_override_attr = self.builder.build_int_compare( - IntPredicate::EQ, - is_override_attr, - self.native_i8_zero(), - "", - ); - let is_not_override_then_block = self.append_block(""); - let is_not_override_else_block = self.append_block(""); - self.builder.build_conditional_branch( - is_not_override_attr, - is_not_override_then_block, - is_not_override_else_block, - ); - self.builder.position_at_end(is_not_override_then_block); - let value = match &schema_attr.value { - Some(value) => self.walk_expr(value).expect(kcl_error::COMPILE_ERROR_MSG), - None => self.undefined_value(), - }; - if let Some(op) = &schema_attr.op { - match op { - // Union - ast::AugOp::BitOr => { - let org_value = self.build_call( - &ApiFunc::kclvm_dict_get_value.name(), - &[ - self.current_runtime_ctx_ptr(), - schema_value, - string_ptr_value, - ], - ); - let fn_name = ApiFunc::kclvm_value_op_bit_or; - let value = self.build_call( - &fn_name.name(), - &[self.current_runtime_ctx_ptr(), org_value, value], - ); - self.dict_merge(schema_value, name, value, 1, None); - } - // Assign - _ => self.dict_merge(schema_value, name, value, 1, None), - } - } - self.br(is_not_override_else_block); - self.builder.position_at_end(is_not_override_else_block); - self.value_union(schema_value, config_attr_value); - let cal_map = self - .get_variable(value::SCHEMA_CAL_MAP) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let backtrack_cache = self - .get_variable(value::BACKTRACK_CACHE) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let runtime_type = self - .get_variable(value::SCHEMA_RUNTIME_TYPE) - .expect(kcl_error::INTERNAL_ERROR_MSG); - self.build_void_call( - &ApiFunc::kclvm_schema_backtrack_cache.name(), - &[ - self.current_runtime_ctx_ptr(), - schema_value, - backtrack_cache, - cal_map, - string_ptr_value, - runtime_type, - ], - ); - // Update backtrack meta - if self.update_backtrack_meta(name, schema_value) { - return Ok(schema_value); - } - self.br(end_block); - self.builder.position_at_end(else_block); - // Lazy eval for the schema attribute. - let value = match &schema_attr.value { - Some(value) => self.walk_expr(value).expect(kcl_error::COMPILE_ERROR_MSG), - None => self.undefined_value(), - }; - if let Some(op) = &schema_attr.op { - match op { - // Union - ast::AugOp::BitOr => { - let org_value = self.build_call( - &ApiFunc::kclvm_dict_get_value.name(), - &[ - self.current_runtime_ctx_ptr(), - schema_value, - string_ptr_value, - ], - ); - let fn_name = ApiFunc::kclvm_value_op_bit_or; - let value = self.build_call( - &fn_name.name(), - &[self.current_runtime_ctx_ptr(), org_value, value], - ); - self.dict_merge(schema_value, name, value, 1, None); - } - // Assign - _ => self.dict_merge(schema_value, name, value, 1, None), - } - } - self.br(end_block); - self.builder.position_at_end(end_block); - Ok(schema_value) - } - - fn walk_if_expr(&self, if_expr: &'ctx ast::IfExpr) -> Self::Result { - check_backtrack_stop!(self); - let cond = self - .walk_expr(&if_expr.cond) - .expect(kcl_error::COMPILE_ERROR_MSG); - let then_block = self.append_block(""); - let else_block = self.append_block(""); - let end_block = self.append_block(""); - let is_truth = self.value_is_truthy(cond); - let tpe = self.value_ptr_type(); - self.cond_br(is_truth, then_block, else_block); - self.builder.position_at_end(then_block); - let then_value = self - .walk_expr(&if_expr.body) - .expect(kcl_error::COMPILE_ERROR_MSG); - let then_block = self.append_block(""); - self.br(then_block); - self.builder.position_at_end(then_block); - let ptr = self.builder.build_alloca(tpe, ""); - self.builder.build_store(ptr, then_value); - let then_value = self.builder.build_load(ptr, ""); - self.br(end_block); - self.builder.position_at_end(else_block); - let else_value = self - .walk_expr(&if_expr.orelse) - .expect(kcl_error::COMPILE_ERROR_MSG); - let else_block = self.append_block(""); - self.br(else_block); - self.builder.position_at_end(else_block); - let ptr = self.alloca(tpe, "", None).into_pointer_value(); - self.builder.build_store(ptr, else_value); - let else_value = self.builder.build_load(ptr, ""); - self.br(end_block); - self.builder.position_at_end(end_block); - let phi = self.builder.build_phi(tpe, ""); - phi.add_incoming(&[(&then_value, then_block), (&else_value, else_block)]); - Ok(phi.as_basic_value()) - } - - fn walk_unary_expr(&self, unary_expr: &'ctx ast::UnaryExpr) -> Self::Result { - check_backtrack_stop!(self); - let value = self - .walk_expr(&unary_expr.operand) - .expect(kcl_error::COMPILE_ERROR_MSG); - let fn_name = match unary_expr.op { - ast::UnaryOp::UAdd => ApiFunc::kclvm_value_unary_plus, - ast::UnaryOp::USub => ApiFunc::kclvm_value_unary_minus, - ast::UnaryOp::Invert => ApiFunc::kclvm_value_unary_not, - ast::UnaryOp::Not => ApiFunc::kclvm_value_unary_l_not, - }; - Ok(self.build_call(&fn_name.name(), &[self.current_runtime_ctx_ptr(), value])) - } - - fn walk_binary_expr(&self, binary_expr: &'ctx ast::BinaryExpr) -> Self::Result { - check_backtrack_stop!(self); - let is_logic_op = matches!(binary_expr.op, ast::BinOp::And | ast::BinOp::Or); - let is_membership_as_op = matches!(binary_expr.op, ast::BinOp::As); - if !is_logic_op { - let left_value = self - .walk_expr(&binary_expr.left) - .expect(kcl_error::COMPILE_ERROR_MSG); - let right_value = if is_membership_as_op { - match &binary_expr.right.node { - ast::Expr::Identifier(id) => { - let name = id.get_names().join("."); - self.string_value(&name) - } - _ => self.none_value(), - } - } else { - self.walk_expr(&binary_expr.right) - .expect(kcl_error::COMPILE_ERROR_MSG) - }; - let value = match binary_expr.op { - ast::BinOp::Add => self.add(left_value, right_value), - ast::BinOp::Sub => self.sub(left_value, right_value), - ast::BinOp::Mul => self.mul(left_value, right_value), - ast::BinOp::Div => self.div(left_value, right_value), - ast::BinOp::FloorDiv => self.floor_div(left_value, right_value), - ast::BinOp::Mod => self.r#mod(left_value, right_value), - ast::BinOp::Pow => self.pow(left_value, right_value), - ast::BinOp::LShift => self.bit_lshift(left_value, right_value), - ast::BinOp::RShift => self.bit_rshift(left_value, right_value), - ast::BinOp::BitAnd => self.bit_and(left_value, right_value), - ast::BinOp::BitOr => self.bit_or(left_value, right_value), - ast::BinOp::BitXor => self.bit_xor(left_value, right_value), - ast::BinOp::And => self.logic_and(left_value, right_value), - ast::BinOp::Or => self.logic_or(left_value, right_value), - ast::BinOp::As => self.r#as(left_value, right_value), - }; - Ok(value) - } else { - let jump_if_false = matches!(binary_expr.op, ast::BinOp::And); - let start_block = self.append_block(""); - let value_block = self.append_block(""); - let end_block = self.append_block(""); - let left_value = self - .walk_expr(&binary_expr.left) - .expect(kcl_error::COMPILE_ERROR_MSG); - self.br(start_block); - self.builder.position_at_end(start_block); - let is_truth = self.value_is_truthy(left_value); - let tpe = self.value_ptr_type(); - if jump_if_false { - // Jump if false on logic and - self.cond_br(is_truth, value_block, end_block); - } else { - // Jump if true on logic or - self.cond_br(is_truth, end_block, value_block); - }; - self.builder.position_at_end(value_block); - let right_value = self - .walk_expr(&binary_expr.right) - .expect(kcl_error::COMPILE_ERROR_MSG); - let value_block = self.append_block(""); - self.br(value_block); - self.builder.position_at_end(value_block); - let ptr = self.builder.build_alloca(tpe, ""); - self.builder.build_store(ptr, right_value); - let right_value = self.builder.build_load(ptr, ""); - self.br(end_block); - self.builder.position_at_end(end_block); - let phi = self.builder.build_phi(tpe, ""); - phi.add_incoming(&[(&left_value, start_block), (&right_value, value_block)]); - Ok(phi.as_basic_value()) - } - } - - fn walk_selector_expr(&self, selector_expr: &'ctx ast::SelectorExpr) -> Self::Result { - check_backtrack_stop!(self); - let mut value = self - .walk_expr(&selector_expr.value) - .expect(kcl_error::COMPILE_ERROR_MSG); - let string_ptr_value = self - .native_global_string(selector_expr.attr.node.names[0].node.as_str(), "") - .into(); - let fn_name = if selector_expr.has_question { - &ApiFunc::kclvm_value_load_attr_option - } else { - &ApiFunc::kclvm_value_load_attr - }; - value = self.build_call( - &fn_name.name(), - &[self.current_runtime_ctx_ptr(), value, string_ptr_value], - ); - for name in &selector_expr.attr.node.names[1..] { - let string_ptr_value = self.native_global_string(&name.node, "").into(); - value = self.build_call( - &ApiFunc::kclvm_value_load_attr.name(), - &[self.current_runtime_ctx_ptr(), value, string_ptr_value], - ); - } - Ok(value) - } - - fn walk_call_expr(&self, call_expr: &'ctx ast::CallExpr) -> Self::Result { - check_backtrack_stop!(self); - let func = self - .walk_expr(&call_expr.func) - .expect(kcl_error::COMPILE_ERROR_MSG); - // args - let list_value = self.list_value(); - for arg in &call_expr.args { - let value = self.walk_expr(arg).expect(kcl_error::COMPILE_ERROR_MSG); - self.list_append(list_value, value); - } - let dict_value = self.dict_value(); - // kwargs - for keyword in &call_expr.keywords { - let name = &keyword.node.arg.node.names[0]; - let value = if let Some(value) = &keyword.node.value { - self.walk_expr(value).expect(kcl_error::COMPILE_ERROR_MSG) - } else { - self.none_value() - }; - self.dict_insert(dict_value, name.node.as_str(), value, 0, None); - } - let pkgpath = self.native_global_string_value(&self.current_pkgpath()); - let is_in_schema = self.is_in_schema() || self.is_in_schema_expr(); - Ok(self.build_call( - &ApiFunc::kclvm_value_function_invoke.name(), - &[ - func, - self.current_runtime_ctx_ptr(), - list_value, - dict_value, - pkgpath, - self.bool_value(is_in_schema), - ], - )) - } - - fn walk_subscript(&self, subscript: &'ctx ast::Subscript) -> Self::Result { - check_backtrack_stop!(self); - let mut value = self - .walk_expr(&subscript.value) - .expect(kcl_error::COMPILE_ERROR_MSG); - if let Some(index) = &subscript.index { - // index - let index = self.walk_expr(index).expect(kcl_error::COMPILE_ERROR_MSG); - let fn_name = if subscript.has_question { - &ApiFunc::kclvm_value_subscr_option - } else { - &ApiFunc::kclvm_value_subscr - }; - value = self.build_call( - &fn_name.name(), - &[self.current_runtime_ctx_ptr(), value, index], - ); - } else { - let lower = { - if let Some(lower) = &subscript.lower { - self.walk_expr(lower).expect(kcl_error::COMPILE_ERROR_MSG) - } else { - self.none_value() - } - }; - let upper = { - if let Some(upper) = &subscript.upper { - self.walk_expr(upper).expect(kcl_error::COMPILE_ERROR_MSG) - } else { - self.none_value() - } - }; - let step = { - if let Some(step) = &subscript.step { - self.walk_expr(step).expect(kcl_error::COMPILE_ERROR_MSG) - } else { - self.none_value() - } - }; - let fn_name = if subscript.has_question { - &ApiFunc::kclvm_value_slice_option - } else { - &ApiFunc::kclvm_value_slice - }; - value = self.build_call( - &fn_name.name(), - &[self.current_runtime_ctx_ptr(), value, lower, upper, step], - ); - } - Ok(value) - } - - fn walk_paren_expr(&self, paren_expr: &'ctx ast::ParenExpr) -> Self::Result { - check_backtrack_stop!(self); - self.walk_expr(&paren_expr.expr) - } - - fn walk_list_expr(&self, list_expr: &'ctx ast::ListExpr) -> Self::Result { - check_backtrack_stop!(self); - let list_value = self.list_value(); - for item in &list_expr.elts { - let value = self.walk_expr(item).expect(kcl_error::COMPILE_ERROR_MSG); - let fn_name = match &item.node { - ast::Expr::Starred(_) | ast::Expr::ListIfItem(_) => { - ApiFunc::kclvm_list_append_unpack - } - _ => ApiFunc::kclvm_list_append, - }; - self.build_void_call(&fn_name.name(), &[list_value, value]); - } - Ok(list_value) - } - - fn walk_list_if_item_expr(&self, list_if_item_expr: &'ctx ast::ListIfItemExpr) -> Self::Result { - check_backtrack_stop!(self); - let cond = self - .walk_expr(&list_if_item_expr.if_cond) - .expect(kcl_error::COMPILE_ERROR_MSG); - let then_block = self.append_block(""); - let else_block = self.append_block(""); - let end_block = self.append_block(""); - let is_truth = self.value_is_truthy(cond); - let tpe = self.value_ptr_type(); - self.cond_br(is_truth, then_block, else_block); - self.builder.position_at_end(then_block); - let then_value = self.list_value(); - for expr in &list_if_item_expr.exprs { - let value = self.walk_expr(expr).expect(kcl_error::COMPILE_ERROR_MSG); - match &expr.node { - ast::Expr::Starred(_) | ast::Expr::ListIfItem(_) => { - self.list_append_unpack(then_value, value) - } - _ => self.list_append(then_value, value), - }; - } - let then_block = self.append_block(""); - self.br(then_block); - self.builder.position_at_end(then_block); - let ptr = self.builder.build_alloca(tpe, ""); - self.builder.build_store(ptr, then_value); - let then_value = self.builder.build_load(ptr, ""); - self.br(end_block); - self.builder.position_at_end(else_block); - let else_value = if let Some(orelse) = &list_if_item_expr.orelse { - self.walk_expr(orelse).expect(kcl_error::COMPILE_ERROR_MSG) - } else { - self.none_value() - }; - let else_block = self.append_block(""); - self.br(else_block); - self.builder.position_at_end(else_block); - let ptr = self.builder.build_alloca(tpe, ""); - self.builder.build_store(ptr, else_value); - let else_value = self.builder.build_load(ptr, ""); - self.br(end_block); - self.builder.position_at_end(end_block); - let phi = self.builder.build_phi(tpe, ""); - phi.add_incoming(&[(&then_value, then_block), (&else_value, else_block)]); - Ok(phi.as_basic_value()) - } - - fn walk_starred_expr(&self, starred_expr: &'ctx ast::StarredExpr) -> Self::Result { - check_backtrack_stop!(self); - self.walk_expr(&starred_expr.value) - } - - fn walk_list_comp(&self, list_comp: &'ctx ast::ListComp) -> Self::Result { - check_backtrack_stop!(self); - let collection_value = self.list_value(); - self.enter_scope(); - self.walk_generator( - &list_comp.generators, - &list_comp.elt, - None, - None, - 0, - collection_value, - ast::CompType::List, - ); - self.leave_scope(); - let tpe = self.value_ptr_type(); - let ptr = self.builder.build_alloca(tpe, ""); - self.builder.build_store(ptr, collection_value); - let value = self.builder.build_load(ptr, ""); - Ok(value) - } - - fn walk_dict_comp(&self, dict_comp: &'ctx ast::DictComp) -> Self::Result { - check_backtrack_stop!(self); - let collection_value = self.dict_value(); - self.enter_scope(); - let key = dict_comp - .entry - .key - .as_ref() - .expect(kcl_error::INTERNAL_ERROR_MSG); - self.walk_generator( - &dict_comp.generators, - key, - Some(&dict_comp.entry.value), - Some(&dict_comp.entry.operation), - 0, - collection_value, - ast::CompType::Dict, - ); - self.leave_scope(); - Ok(collection_value) - } - - fn walk_config_if_entry_expr( - &self, - config_if_entry_expr: &'ctx ast::ConfigIfEntryExpr, - ) -> Self::Result { - check_backtrack_stop!(self); - let cond = self - .walk_expr(&config_if_entry_expr.if_cond) - .expect(kcl_error::COMPILE_ERROR_MSG); - let then_block = self.append_block(""); - let else_block = self.append_block(""); - let end_block = self.append_block(""); - let is_truth = self.value_is_truthy(cond); - self.emit_config_if_entry_expr_vars(config_if_entry_expr); - let tpe = self.value_ptr_type(); - self.cond_br(is_truth, then_block, else_block); - self.builder.position_at_end(then_block); - let then_value = self.walk_config_entries(&config_if_entry_expr.items)?; - let then_block = self.append_block(""); - self.br(then_block); - self.builder.position_at_end(then_block); - let ptr = self.builder.build_alloca(tpe, ""); - self.builder.build_store(ptr, then_value); - let then_value = self.builder.build_load(ptr, ""); - self.br(end_block); - self.builder.position_at_end(else_block); - let else_value = if let Some(orelse) = &config_if_entry_expr.orelse { - // Config expr or config if entry expr. - if let ast::Expr::Config(config_expr) = &orelse.node { - self.walk_config_entries(&config_expr.items) - .expect(kcl_error::COMPILE_ERROR_MSG) - } else { - self.walk_expr(orelse).expect(kcl_error::COMPILE_ERROR_MSG) - } - } else { - self.none_value() - }; - let else_block = self.append_block(""); - self.br(else_block); - self.builder.position_at_end(else_block); - let ptr = self.builder.build_alloca(tpe, ""); - self.builder.build_store(ptr, else_value); - let else_value = self.builder.build_load(ptr, ""); - self.br(end_block); - self.builder.position_at_end(end_block); - let phi = self.builder.build_phi(tpe, ""); - phi.add_incoming(&[(&then_value, then_block), (&else_value, else_block)]); - Ok(phi.as_basic_value()) - } - - fn walk_comp_clause(&self, _comp_clause: &'ctx ast::CompClause) -> Self::Result { - // Nothing to do on this AST node - self.ok_result() - } - - fn walk_schema_expr(&self, schema_expr: &'ctx ast::SchemaExpr) -> Self::Result { - check_backtrack_stop!(self); - // Check the required attributes only when the values of all attributes - // in the final schema are solved. - let is_in_schema = self.is_in_schema() || self.is_in_schema_expr(); - { - self.schema_expr_stack.borrow_mut().push(()); - } - let config_value = self - .walk_expr(&schema_expr.config) - .expect(kcl_error::COMPILE_ERROR_MSG); - let schema_type = self - .walk_identifier_with_ctx(&schema_expr.name.node, &schema_expr.name.node.ctx, None) - .expect(kcl_error::COMPILE_ERROR_MSG); - let config_expr = match &schema_expr.config.node { - ast::Expr::Config(config_expr) => config_expr, - _ => panic!("invalid schema config expr"), - }; - let config_meta = self.get_schema_config_meta(Some(&schema_expr.name), config_expr); - let list_value = self.list_value(); - for arg in &schema_expr.args { - let value = self.walk_expr(arg).expect(kcl_error::COMPILE_ERROR_MSG); - self.list_append(list_value, value); - } - let dict_value = self.dict_value(); - for keyword in &schema_expr.kwargs { - let name = &keyword.node.arg.node.names[0]; - let value = if let Some(value) = &keyword.node.value { - self.walk_expr(value).expect(kcl_error::COMPILE_ERROR_MSG) - } else { - self.none_value() - }; - self.dict_insert(dict_value, name.node.as_str(), value, 0, None); - } - let pkgpath = self.native_global_string_value(&self.current_pkgpath()); - let schema = self.build_call( - &ApiFunc::kclvm_schema_value_new.name(), - &[ - self.current_runtime_ctx_ptr(), - list_value, - dict_value, - schema_type, - config_value, - config_meta, - pkgpath, - ], - ); - if !is_in_schema { - self.build_void_call( - &ApiFunc::kclvm_schema_optional_check.name(), - &[self.current_runtime_ctx_ptr(), schema], - ); - } - utils::update_ctx_filename(self, &schema_expr.config); - { - self.schema_expr_stack.borrow_mut().pop(); - } - Ok(schema) - } - - fn walk_config_expr(&self, config_expr: &'ctx ast::ConfigExpr) -> Self::Result { - check_backtrack_stop!(self); - self.enter_scope(); - let result = self.walk_config_entries(&config_expr.items); - self.leave_scope(); - result - } - - fn walk_check_expr(&self, check_expr: &'ctx ast::CheckExpr) -> Self::Result { - check_backtrack_stop!(self); - let start_block = self.append_block(""); - let end_block = self.append_block(""); - if let Some(if_cond) = &check_expr.if_cond { - let if_value = self.walk_expr(if_cond).expect(kcl_error::COMPILE_ERROR_MSG); - let is_truth = self.value_is_truthy(if_value); - self.cond_br(is_truth, start_block, end_block); - } else { - self.br(start_block); - } - self.builder.position_at_end(start_block); - let check_result = self - .walk_expr(&check_expr.test) - .expect(kcl_error::COMPILE_ERROR_MSG); - let msg = { - if let Some(msg) = &check_expr.msg { - self.walk_expr(msg).expect(kcl_error::COMPILE_ERROR_MSG) - } else { - self.string_value("") - } - }; - let schema_config_meta = self - .get_variable(value::SCHEMA_CONFIG_META_NAME) - .expect(kcl_error::COMPILE_ERROR_MSG); - utils::update_ctx_current_line(self); - self.build_void_call( - &ApiFunc::kclvm_schema_assert.name(), - &[ - self.current_runtime_ctx_ptr(), - check_result, - msg, - schema_config_meta, - ], - ); - self.br(end_block); - self.builder.position_at_end(end_block); - self.ok_result() - } - - fn walk_lambda_expr(&self, lambda_expr: &'ctx ast::LambdaExpr) -> Self::Result { - check_backtrack_stop!(self); - let pkgpath = &self.current_pkgpath(); - // Higher-order lambda requires capturing the current lambda closure variable - // as well as the closure of a more external scope. - let last_closure_map = self.get_current_inner_scope_variable_map(); - let func_before_block = self.append_block(""); - self.br(func_before_block); - // Use "pkgpath"+"kclvm_lambda" to name 'function' to prevent conflicts between lambdas with the same name in different packages - let function = self.add_function(&format!( - "{}.{}", - pkgpath_without_prefix!(pkgpath), - value::LAMBDA_NAME - )); - // Enter the function - self.push_function(function); - // Push the current lambda scope level in the lambda stack. - self.push_lambda(self.scope_level() + 1); - // Lambda function body - let block = self.context.append_basic_block(function, ENTRY_NAME); - self.builder.position_at_end(block); - let args = function - .get_nth_param(1) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let kwargs = function - .get_nth_param(2) - .expect(kcl_error::INTERNAL_ERROR_MSG); - self.enter_scope(); - let closure_map = self.list_pop_first(args); - let tpe = self.value_ptr_type(); - let var = self.builder.build_alloca(tpe, value::LAMBDA_CLOSURE); - self.builder.build_store(var, closure_map); - self.add_variable(value::LAMBDA_CLOSURE, var); - if self.is_in_schema() { - for schema_closure_name in value::SCHEMA_VARIABLE_LIST { - let string_ptr_value = self.native_global_string(schema_closure_name, "").into(); - let schema_value = self.build_call( - &ApiFunc::kclvm_dict_get_value.name(), - &[ - self.current_runtime_ctx_ptr(), - closure_map, - string_ptr_value, - ], - ); - let value_ptr_type = self.value_ptr_type(); - let var = self - .builder - .build_alloca(value_ptr_type, schema_closure_name); - self.builder.build_store(var, schema_value); - self.add_variable(schema_closure_name, var); - } - } - self.walk_arguments(&lambda_expr.args, args, kwargs); - let mut val = self - .walk_stmts(&lambda_expr.body) - .expect(kcl_error::COMPILE_ERROR_MSG); - if let Some(ty) = &lambda_expr.return_ty { - let type_annotation = self.native_global_string_value(&ty.node.to_string()); - val = self.build_call( - &ApiFunc::kclvm_convert_collection_value.name(), - &[ - self.current_runtime_ctx_ptr(), - val, - type_annotation, - self.bool_value(false), - ], - ); - } - self.builder.build_return(Some(&val)); - // Exist the function - self.builder.position_at_end(func_before_block); - let closure = self.list_value(); - // Use closure map in the last scope to construct current closure map. - // The default value of the closure map is `{}`. - self.list_append(closure, last_closure_map); - let function = self.closure_value(function, closure); - self.leave_scope(); - self.pop_function(); - self.pop_lambda(); - Ok(function) - } - - fn walk_keyword(&self, _keyword: &'ctx ast::Keyword) -> Self::Result { - // Nothing to do - self.ok_result() - } - - fn walk_arguments(&self, _arguments: &'ctx ast::Arguments) -> Self::Result { - // Nothing to do - self.ok_result() - } - - fn walk_compare(&self, compare: &'ctx ast::Compare) -> Self::Result { - check_backtrack_stop!(self); - let mut left_value = self - .walk_expr(&compare.left) - .expect(kcl_error::COMPILE_ERROR_MSG); - if compare.comparators.len() > 1 { - let tpe = self.value_ptr_type(); - let mut next_block = self.append_block(""); - let end_block = self.append_block(""); - self.br(next_block); - self.builder.position_at_end(next_block); - let mut values_blocks: Vec<(BasicValueEnum, BasicBlock)> = vec![]; - for (i, op) in compare.ops.iter().enumerate() { - let has_next = i < (compare.ops.len() - 1); - let right_value = self - .walk_expr(&compare.comparators[i]) - .expect(kcl_error::COMPILE_ERROR_MSG); - let fn_name = match op { - ast::CmpOp::Eq => ApiFunc::kclvm_value_cmp_equal_to, - ast::CmpOp::NotEq => ApiFunc::kclvm_value_cmp_not_equal_to, - ast::CmpOp::Gt => ApiFunc::kclvm_value_cmp_greater_than, - ast::CmpOp::GtE => ApiFunc::kclvm_value_cmp_greater_than_or_equal, - ast::CmpOp::Lt => ApiFunc::kclvm_value_cmp_less_than, - ast::CmpOp::LtE => ApiFunc::kclvm_value_cmp_less_than_or_equal, - ast::CmpOp::Is => ApiFunc::kclvm_value_is, - ast::CmpOp::IsNot => ApiFunc::kclvm_value_is_not, - ast::CmpOp::Not => ApiFunc::kclvm_value_is_not, - ast::CmpOp::NotIn => ApiFunc::kclvm_value_not_in, - ast::CmpOp::In => ApiFunc::kclvm_value_in, - }; - let result_value = self.build_call( - &fn_name.name(), - &[self.current_runtime_ctx_ptr(), left_value, right_value], - ); - let is_truth = self.value_is_truthy(result_value); - left_value = right_value; - // Get next value using a store/load temp block - let next_value_block = self.append_block(""); - self.br(next_value_block); - self.builder.position_at_end(next_value_block); - let ptr = self.builder.build_alloca(tpe, ""); - self.builder.build_store(ptr, result_value); - let result_value = self.builder.build_load(ptr, ""); - // Append a value-block pair in the vec - values_blocks.push((result_value, next_value_block)); - if has_next { - next_block = self.append_block(""); - self.cond_br(is_truth, next_block, end_block); - self.builder.position_at_end(next_block); - } else { - self.br(end_block); - } - } - self.builder.position_at_end(end_block); - let phi = self.builder.build_phi(tpe, ""); - for (value, block) in values_blocks { - phi.add_incoming(&[(&value, block)]); - } - Ok(phi.as_basic_value()) - } else { - let right_value = self - .walk_expr(&compare.comparators[0]) - .expect(kcl_error::COMPILE_ERROR_MSG); - let fn_name = match &compare.ops[0] { - ast::CmpOp::Eq => ApiFunc::kclvm_value_cmp_equal_to, - ast::CmpOp::NotEq => ApiFunc::kclvm_value_cmp_not_equal_to, - ast::CmpOp::Gt => ApiFunc::kclvm_value_cmp_greater_than, - ast::CmpOp::GtE => ApiFunc::kclvm_value_cmp_greater_than_or_equal, - ast::CmpOp::Lt => ApiFunc::kclvm_value_cmp_less_than, - ast::CmpOp::LtE => ApiFunc::kclvm_value_cmp_less_than_or_equal, - ast::CmpOp::Is => ApiFunc::kclvm_value_is, - ast::CmpOp::IsNot => ApiFunc::kclvm_value_is_not, - ast::CmpOp::Not => ApiFunc::kclvm_value_is_not, - ast::CmpOp::NotIn => ApiFunc::kclvm_value_not_in, - ast::CmpOp::In => ApiFunc::kclvm_value_in, - }; - left_value = self.build_call( - &fn_name.name(), - &[self.current_runtime_ctx_ptr(), left_value, right_value], - ); - Ok(left_value) - } - } - - fn walk_identifier(&self, identifier: &'ctx ast::Identifier) -> Self::Result { - check_backtrack_stop!(self); - self.walk_identifier_with_ctx(identifier, &identifier.ctx, None) - } - - #[inline] - fn walk_target(&self, target: &'ctx ast::Target) -> Self::Result { - check_backtrack_stop!(self); - self.load_target(target) - } - - fn walk_number_lit(&self, number_lit: &'ctx ast::NumberLit) -> Self::Result { - check_backtrack_stop!(self); - match number_lit.value { - ast::NumberLitValue::Int(int_value) => match &number_lit.binary_suffix { - Some(binary_suffix) => { - let unit = binary_suffix.value(); - let value = kclvm_runtime::cal_num(int_value, unit.as_str()); - Ok(self.unit_value(value, int_value, &unit)) - } - None => Ok(self.int_value(int_value)), - }, - ast::NumberLitValue::Float(float_value) => Ok(self.float_value(float_value)), - } - } - - fn walk_string_lit(&self, string_lit: &'ctx ast::StringLit) -> Self::Result { - check_backtrack_stop!(self); - let string_ptr_value = self - .native_global_string(string_lit.value.as_str(), "") - .into(); - Ok(self.build_call( - &ApiFunc::kclvm_value_Str.name(), - &[self.current_runtime_ctx_ptr(), string_ptr_value], - )) - } - - fn walk_name_constant_lit( - &self, - name_constant_lit: &'ctx ast::NameConstantLit, - ) -> Self::Result { - check_backtrack_stop!(self); - match name_constant_lit.value { - ast::NameConstant::True => Ok(self.bool_value(true)), - ast::NameConstant::False => Ok(self.bool_value(false)), - ast::NameConstant::None => Ok(self.none_value()), - ast::NameConstant::Undefined => Ok(self.undefined_value()), - } - } - - fn walk_joined_string(&self, joined_string: &'ctx ast::JoinedString) -> Self::Result { - check_backtrack_stop!(self); - let mut result_value = self.string_value(""); - for value in &joined_string.values { - let value = &value.node; - let value = match value { - ast::Expr::FormattedValue(formatted_value) => self - .walk_formatted_value(formatted_value) - .expect(kcl_error::INTERNAL_ERROR_MSG), - ast::Expr::StringLit(string_lit) => self - .walk_string_lit(string_lit) - .expect(kcl_error::INTERNAL_ERROR_MSG), - _ => panic!("{}", kcl_error::INVALID_JOINED_STR_MSG), - }; - result_value = self.build_call( - &ApiFunc::kclvm_value_op_add.name(), - &[self.current_runtime_ctx_ptr(), result_value, value], - ); - } - Ok(result_value) - } - - fn walk_formatted_value(&self, formatted_value: &'ctx ast::FormattedValue) -> Self::Result { - check_backtrack_stop!(self); - let formatted_expr_value = self - .walk_expr(&formatted_value.value) - .expect(kcl_error::COMPILE_ERROR_MSG); - let mut fn_name = ApiFunc::kclvm_value_to_str_value; - if let Some(spec) = &formatted_value.format_spec { - fn_name = match spec.to_lowercase().as_str() { - "#json" => ApiFunc::kclvm_value_to_json_value, - "#yaml" => ApiFunc::kclvm_value_to_yaml_value, - _ => panic!("{}", kcl_error::INVALID_STR_INTERPOLATION_SPEC_MSG), - }; - } - Ok(self.build_call( - &fn_name.name(), - &[self.current_runtime_ctx_ptr(), formatted_expr_value], - )) - } - - fn walk_comment(&self, _comment: &'ctx ast::Comment) -> Self::Result { - // Nothing to do - self.ok_result() - } - - fn walk_missing_expr(&self, _missing_expr: &'ctx ast::MissingExpr) -> Self::Result { - Err(kcl_error::KCLError::new( - "compile error: missing expression", - )) - } - - fn walk_module(&self, module: &'ctx ast::Module) -> Self::Result { - check_backtrack_stop!(self); - // Compile all statements of the module except all import statements - self.walk_stmts_except_import(&module.body) - } -} - -impl<'ctx> LLVMCodeGenContext<'ctx> { - pub fn walk_stmts_except_import( - &self, - stmts: &'ctx [Box>], - ) -> CompileResult<'ctx> { - check_backtrack_stop!(self); - let mut result = self.ok_result(); - for stmt in stmts { - if !matches!(&stmt.node, ast::Stmt::Import(..)) { - result = self.walk_stmt(stmt); - } - } - result - } - - pub fn walk_stmts(&self, stmts: &'ctx [Box>]) -> CompileResult<'ctx> { - check_backtrack_stop!(self); - // Empty statements return None value - let mut result = Ok(self.none_value()); - for stmt in stmts { - result = self.walk_stmt(stmt); - } - result - } - - pub fn walk_target_with_value( - &self, - target: &'ctx ast::Target, - right_value: BasicValueEnum<'ctx>, - ) -> CompileResult<'ctx> { - check_backtrack_stop!(self); - let is_in_schema = self.is_in_schema(); - if target.paths.is_empty() { - let name = target.get_name(); - let tpe = self.value_ptr_type(); - // Global variables - if self.scope_level() == GLOBAL_LEVEL { - self.add_or_update_global_variable(name, right_value, true); - // Lambda local variables. - } else if self.is_in_lambda() { - let value = right_value; - // If variable exists in the scope and update it, if not, add it to the scope. - if !self.store_variable_in_current_scope(name, value) { - let cur_bb = self.builder.get_insert_block().unwrap(); - let lambda_func = cur_bb.get_parent().unwrap(); - let entry_bb = lambda_func.get_first_basic_block().unwrap(); - match entry_bb.get_first_instruction() { - Some(inst) => self.builder.position_before(&inst), - None => self.builder.position_at_end(entry_bb), - }; - let var = self.builder.build_alloca(tpe, name); - let undefined_val = self.undefined_value(); - self.builder.build_store(var, undefined_val); - self.add_variable(name, var); - self.builder.position_at_end(cur_bb); - self.store_variable(name, value); - } - } else { - let is_local_var = self.is_local_var(name); - let value = right_value; - // Store schema attribute - if is_in_schema { - let schema_value = self.get_variable(value::SCHEMA_SELF_NAME)?; - // Schema config - let config_value = self.get_variable(value::SCHEMA_CONFIG_NAME)?; - // If is in the backtrack, return the schema value. - if self.update_schema_scope_value(schema_value, config_value, name, Some(value)) - { - return Ok(schema_value); - } - } - // Store loop variable - if is_local_var || !is_in_schema { - let var = self.builder.build_alloca(tpe, name); - self.builder.build_store(var, value); - self.add_variable(name, var); - } - } - } else { - let name = target.get_name(); - // In KCL, we cannot modify global variables in other packages, - // so pkgpath is empty here. - let mut value = self - .load_value("", &[name]) - .expect(kcl_error::INTERNAL_ERROR_MSG); - // Convert `store a.b.c = 1` -> `%t = load &a; %t = load_attr %t %b; store_attr %t %c with 1` - for (i, path) in target.paths.iter().enumerate() { - let ctx = if i < target.paths.len() - 1 { - ast::ExprContext::Load - } else { - ast::ExprContext::Store - }; - match ctx { - ast::ExprContext::Load => { - value = self.load_target_path(value, path)?; - } - ast::ExprContext::Store => { - self.store_target_path(value, path, right_value)?; - - let is_local_var = self.is_local_var(name); - let is_in_lambda = self.is_in_lambda(); - // Set config value for the schema attribute if the attribute is in the schema and - // it is not a local variable in the lambda function. - if self.scope_level() >= INNER_LEVEL - && is_in_schema - && !is_in_lambda - && !is_local_var - { - let schema_value = self.get_variable(value::SCHEMA_SELF_NAME)?; - let config_value = self.get_variable(value::SCHEMA_CONFIG_NAME)?; - if self.update_schema_scope_value( - schema_value, - config_value, - name, - None, - ) { - return Ok(schema_value); - } - } - } - } - } - } - Ok(right_value) - } - - pub fn walk_identifier_with_ctx( - &self, - identifier: &'ctx ast::Identifier, - identifier_ctx: &ast::ExprContext, - right_value: Option>, - ) -> CompileResult<'ctx> { - check_backtrack_stop!(self); - let is_in_schema = self.is_in_schema(); - match identifier_ctx { - // Store a.b.c = 1 - ast::ExprContext::Store => { - if identifier.names.len() == 1 { - let name = identifier.names[0].node.as_str(); - let tpe = self.value_ptr_type(); - // Global variables - if self.scope_level() == GLOBAL_LEVEL { - self.add_or_update_global_variable( - name, - right_value.expect(kcl_error::INTERNAL_ERROR_MSG), - true, - ); - // Lambda local variables. - } else if self.is_in_lambda() { - let value = right_value.expect(kcl_error::INTERNAL_ERROR_MSG); - // If variable exists in the scope and update it, if not, add it to the scope. - if !self.store_variable_in_current_scope(name, value) { - let cur_bb = self.builder.get_insert_block().unwrap(); - let lambda_func = cur_bb.get_parent().unwrap(); - let entry_bb = lambda_func.get_first_basic_block().unwrap(); - match entry_bb.get_first_instruction() { - Some(inst) => self.builder.position_before(&inst), - None => self.builder.position_at_end(entry_bb), - }; - let var = self.builder.build_alloca(tpe, name); - let undefined_val = self.undefined_value(); - self.builder.build_store(var, undefined_val); - self.add_variable(name, var); - self.builder.position_at_end(cur_bb); - self.store_variable(name, value); - } - } else { - let is_local_var = self.is_local_var(name); - let value = right_value.expect(kcl_error::INTERNAL_ERROR_MSG); - // Store schema attribute - if is_in_schema { - let schema_value = self - .get_variable(value::SCHEMA_SELF_NAME) - .expect(kcl_error::INTERNAL_ERROR_MSG); - // Schema config - let config_value = self - .get_variable(value::SCHEMA_CONFIG_NAME) - .expect(kcl_error::INTERNAL_ERROR_MSG); - // If is in the backtrack, return the schema value. - if self.update_schema_scope_value( - schema_value, - config_value, - name, - Some(value), - ) { - return Ok(schema_value); - } - } - // Store loop variable - if is_local_var || !is_in_schema { - let var = self.builder.build_alloca(tpe, name); - self.builder.build_store(var, value); - self.add_variable(name, var); - } - } - } else { - let names = &identifier.names; - let name = names[0].node.as_str(); - // In KCL, we cannot modify global variables in other packages, - // so pkgpath is empty here. - let mut value = self - .load_value("", &[name]) - .expect(kcl_error::INTERNAL_ERROR_MSG); - // Convert `store a.b.c = 1` -> `%t = load &a; %t = load_attr %t %b; store_attr %t %c with 1` - for i in 0..names.len() - 1 { - let attr = names[i + 1].node.as_str(); - let ctx = if matches!(identifier_ctx, ast::ExprContext::Store) - && i != names.len() - 2 - && names.len() > 2 - { - &ast::ExprContext::Load - } else { - identifier_ctx - }; - match ctx { - ast::ExprContext::Load => { - let attr = self.native_global_string(attr, "").into(); - value = self.build_call( - &ApiFunc::kclvm_value_load_attr.name(), - &[self.current_runtime_ctx_ptr(), value, attr], - ); - } - ast::ExprContext::Store => { - let attr = self.native_global_string(attr, "").into(); - self.build_void_call( - &ApiFunc::kclvm_dict_set_value.name(), - &[ - self.current_runtime_ctx_ptr(), - value, - attr, - right_value.expect(kcl_error::INTERNAL_ERROR_MSG), - ], - ); - - let is_local_var = self.is_local_var(name); - let is_in_lambda = self.is_in_lambda(); - // Set config value for the schema attribute if the attribute is in the schema and - // it is not a local variable in the lambda function. - if self.scope_level() >= INNER_LEVEL - && is_in_schema - && !is_in_lambda - && !is_local_var - { - let schema_value = self - .get_variable(value::SCHEMA_SELF_NAME) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let config_value = self - .get_variable(value::SCHEMA_CONFIG_NAME) - .expect(kcl_error::INTERNAL_ERROR_MSG); - if self.update_schema_scope_value( - schema_value, - config_value, - name, - None, - ) { - return Ok(schema_value); - } - } - } - } - } - } - Ok(right_value.expect(kcl_error::INTERNAL_ERROR_MSG)) - } - // Load .a.b.c - ast::ExprContext::Load => self.load_value( - &identifier.pkgpath, - &identifier - .names - .iter() - .map(|n| n.node.as_str()) - .collect::>(), - ), - } - } - - pub fn walk_decorator_with_name( - &self, - decorator: &'ctx CallExpr, - attr_name: Option<&str>, - is_schema_target: bool, - ) -> CompileResult<'ctx> { - check_backtrack_stop!(self); - let list_value = self.list_value(); - let dict_value = self.dict_value(); - let schema_config_meta = self - .get_variable(value::SCHEMA_CONFIG_META_NAME) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let schema_config_value = self - .get_variable(value::SCHEMA_CONFIG_NAME) - .expect(kcl_error::INTERNAL_ERROR_MSG); - for arg in &decorator.args { - let value = self.walk_expr(arg).expect(kcl_error::COMPILE_ERROR_MSG); - self.list_append(list_value, value); - } - for keyword in &decorator.keywords { - let name = &keyword.node.arg.node.names[0]; - let value = if let Some(value) = &keyword.node.value { - self.walk_expr(value).expect(kcl_error::COMPILE_ERROR_MSG) - } else { - self.none_value() - }; - self.dict_insert(dict_value, name.node.as_str(), value, 0, None); - } - let name = match &decorator.func.node { - ast::Expr::Identifier(ident) if ident.names.len() == 1 => ident.names[0].clone(), - _ => panic!("invalid decorator name, expect single identifier"), - }; - let attr_name = if let Some(v) = attr_name { v } else { "" }; - let attr_name = self.native_global_string_value(attr_name); - Ok(self.build_call( - &ApiFunc::kclvm_value_Decorator.name(), - &[ - self.current_runtime_ctx_ptr(), - self.native_global_string_value(name.node.as_str()), - list_value, - dict_value, - schema_config_meta, - attr_name, - schema_config_value, - self.bool_value(is_schema_target), - ], - )) - } - - pub fn walk_arguments( - &self, - arguments: &'ctx Option>, - args: BasicValueEnum<'ctx>, - kwargs: BasicValueEnum<'ctx>, - ) { - // Arguments names and defaults - let (arg_names, arg_types, arg_defaults) = if let Some(args) = &arguments { - let names = &args.node.args; - let types = &args.node.ty_list; - let defaults = &args.node.defaults; - ( - names.iter().map(|identifier| &identifier.node).collect(), - types.iter().collect(), - defaults.iter().collect(), - ) - } else { - (vec![], vec![], vec![]) - }; - // Default parameter values - for ((arg_name, arg_type), value) in - arg_names.iter().zip(&arg_types).zip(arg_defaults.iter()) - { - let mut arg_value = if let Some(value) = value { - self.walk_expr(value).expect(kcl_error::COMPILE_ERROR_MSG) - } else { - self.none_value() - }; - if let Some(ty) = arg_type { - let type_annotation = self.native_global_string_value(&ty.node.to_string()); - arg_value = self.build_call( - &ApiFunc::kclvm_convert_collection_value.name(), - &[ - self.current_runtime_ctx_ptr(), - arg_value, - type_annotation, - self.bool_value(false), - ], - ); - } - // Arguments are immutable, so we place them in different scopes. - self.store_argument_in_current_scope(&arg_name.get_name()); - self.walk_identifier_with_ctx(arg_name, &ast::ExprContext::Store, Some(arg_value)) - .expect(kcl_error::COMPILE_ERROR_MSG); - } - // for loop in 0..argument_len in LLVM begin - let argument_len = self.build_call(&ApiFunc::kclvm_list_len.name(), &[args]); - let end_block = self.append_block(""); - for (i, (arg_name, arg_type)) in arg_names.iter().zip(arg_types).enumerate() { - // Positional arguments - let is_in_range = self.builder.build_int_compare( - IntPredicate::ULT, - self.native_int_value(i as i32).into_int_value(), - argument_len.into_int_value(), - "", - ); - let next_block = self.append_block(""); - self.builder - .build_conditional_branch(is_in_range, next_block, end_block); - self.builder.position_at_end(next_block); - let mut arg_value = self.build_call( - &ApiFunc::kclvm_list_get_option.name(), - &[ - self.current_runtime_ctx_ptr(), - args, - self.native_int_value(i as i32), - ], - ); - if let Some(ty) = arg_type { - let type_annotation = self.native_global_string_value(&ty.node.to_string()); - arg_value = self.build_call( - &ApiFunc::kclvm_convert_collection_value.name(), - &[ - self.current_runtime_ctx_ptr(), - arg_value, - type_annotation, - self.bool_value(false), - ], - ); - } - self.store_variable(&arg_name.names[0].node, arg_value); - } - // for loop in 0..argument_len in LLVM end - self.br(end_block); - self.builder.position_at_end(end_block); - // Keyword arguments - for arg_name in arg_names.iter() { - let name = &arg_name.names[0].node; - let string_ptr_value = self.native_global_string(name.as_str(), "").into(); - let has_key = self - .build_call( - &ApiFunc::kclvm_dict_has_value.name(), - &[kwargs, string_ptr_value], - ) - .into_int_value(); - let has_key = self.builder.build_int_compare( - IntPredicate::NE, - has_key, - self.native_i8_zero(), - "", - ); - let then_block = self.append_block(""); - let else_block = self.append_block(""); - self.builder - .build_conditional_branch(has_key, then_block, else_block); - self.builder.position_at_end(then_block); - let arg = self.build_call( - &ApiFunc::kclvm_dict_get_value.name(), - &[self.current_runtime_ctx_ptr(), kwargs, string_ptr_value], - ); - // Find argument name in the scope - self.store_variable(&arg_name.names[0].node, arg); - self.br(else_block); - self.builder.position_at_end(else_block); - } - } - - pub fn walk_generator( - &self, - generators: &'ctx [Box>], - elt: &'ctx ast::Node, - val: Option<&'ctx ast::Node>, - op: Option<&'ctx ast::ConfigEntryOperation>, - gen_index: usize, - collection_value: BasicValueEnum<'ctx>, - comp_type: ast::CompType, - ) { - let start_block = self.append_block(""); - let next_value_block = self.append_block(""); - let continue_block = self.append_block(""); - let end_for_block = self.append_block(""); - let generator = &generators[gen_index]; - let iter_host_value = self - .walk_expr(&generator.node.iter) - .expect(kcl_error::COMPILE_ERROR_MSG); - let iter_value = self.build_call(&ApiFunc::kclvm_value_iter.name(), &[iter_host_value]); - self.br(start_block); - self.builder.position_at_end(start_block); - let is_end = self - .build_call(&ApiFunc::kclvm_iterator_is_end.name(), &[iter_value]) - .into_int_value(); - let is_end = - self.builder - .build_int_compare(IntPredicate::NE, is_end, self.native_i8_zero(), ""); - self.builder - .build_conditional_branch(is_end, end_for_block, next_value_block); - self.builder.position_at_end(next_value_block); - let next_value = self.build_call( - &ApiFunc::kclvm_iterator_next_value.name(), - &[iter_value, iter_host_value], - ); - let targets = &generator.node.targets; - { - let mut local_vars = self.local_vars.borrow_mut(); - for v in targets { - let name = &v.node.names[0].node; - local_vars.insert(name.clone()); - } - } - if targets.len() == 1 { - // Store the target - self.walk_identifier_with_ctx( - &targets.first().expect(kcl_error::INTERNAL_ERROR_MSG).node, - &ast::ExprContext::Store, - Some(next_value), - ) - .expect(kcl_error::COMPILE_ERROR_MSG); - } else if targets.len() == 2 { - let key = self.build_call(&ApiFunc::kclvm_iterator_cur_key.name(), &[iter_value]); - let value = self.build_call(&ApiFunc::kclvm_iterator_cur_value.name(), &[iter_value]); - // Store the target - self.walk_identifier_with_ctx( - &targets.first().expect(kcl_error::INTERNAL_ERROR_MSG).node, - &ast::ExprContext::Store, - Some(key), - ) - .expect(kcl_error::COMPILE_ERROR_MSG); - self.walk_identifier_with_ctx( - &targets.get(1).expect(kcl_error::INTERNAL_ERROR_MSG).node, - &ast::ExprContext::Store, - Some(value), - ) - .expect(kcl_error::COMPILE_ERROR_MSG); - } else { - panic!( - "the number of loop variables is {}, which can only be 1 or 2", - generator.node.targets.len() - ) - } - for if_expr in &generator.node.ifs { - let is_truth = self.walk_expr(if_expr).expect(kcl_error::COMPILE_ERROR_MSG); - let is_truth = self.value_is_truthy(is_truth); - self.cond_br(is_truth, continue_block, start_block); - } - if generator.node.ifs.is_empty() { - self.br(continue_block); - } - self.builder.position_at_end(continue_block); - let next_gen_index = gen_index + 1; - if next_gen_index >= generators.len() { - match comp_type { - ast::CompType::List => { - let item = self.walk_expr(elt).expect(kcl_error::COMPILE_ERROR_MSG); - self.list_append(collection_value, item); - } - ast::CompType::Dict => { - let value = self - .walk_expr(val.expect(kcl_error::INTERNAL_ERROR_MSG)) - .expect(kcl_error::COMPILE_ERROR_MSG); - let key = self.walk_expr(elt).expect(kcl_error::COMPILE_ERROR_MSG); - let op = op.expect(kcl_error::INTERNAL_ERROR_MSG); - self.dict_insert_with_key_value( - collection_value, - key, - self.value_deep_copy(value), - op.value(), - None, - ); - } - } - } else { - self.walk_generator( - generators, - elt, - val, - op, - next_gen_index, - collection_value, - comp_type, - ); - } - self.br(start_block); - self.builder.position_at_end(end_for_block); - self.build_void_call(&ApiFunc::kclvm_iterator_delete.name(), &[iter_value]); - { - let mut local_vars = self.local_vars.borrow_mut(); - for v in targets { - let name = &v.node.names[0].node; - local_vars.remove(name); - } - } - } - - pub(crate) fn walk_config_entries( - &self, - items: &'ctx [NodeRef], - ) -> CompileResult<'ctx> { - let config_value = self.dict_value(); - for item in items { - let value = self.walk_expr(&item.node.value)?; - if let Some(key) = &item.node.key { - let mut insert_index = None; - let optional_name = match &key.node { - ast::Expr::Identifier(identifier) => Some(identifier.names[0].node.clone()), - ast::Expr::StringLit(string_lit) => Some(string_lit.value.clone()), - ast::Expr::Subscript(subscript) => { - let mut name = None; - if let ast::Expr::Identifier(identifier) = &subscript.value.node { - if let Some(index_node) = &subscript.index { - // Insert index - if let ast::Expr::NumberLit(number) = &index_node.node { - if let ast::NumberLitValue::Int(v) = number.value { - insert_index = Some(v as i32); - name = Some(identifier.names[0].node.clone()) - } - } else if let ast::Expr::Unary(unary_expr) = &index_node.node { - // Negative insert index - if let ast::Expr::NumberLit(number) = &unary_expr.operand.node { - if let ast::NumberLitValue::Int(v) = number.value { - insert_index = Some(-v as i32); - name = Some(identifier.names[0].node.clone()) - } - } - } - } - } - name - } - _ => None, - }; - // Store a local variable for every entry key. - let key = match &optional_name { - Some(name) if !self.is_local_var(name) => self.string_value(name), - _ => self.walk_expr(key)?, - }; - self.dict_insert_with_key_value( - config_value, - key, - value, - item.node.operation.value(), - insert_index, - ); - if let Some(name) = &optional_name { - let value = - self.dict_get(config_value, self.native_global_string(name, "").into()); - self.add_or_update_local_variable_within_scope(name, Some(value)); - } - } else { - // If the key does not exist, execute the logic of unpacking expression `**expr` here. - self.build_void_call( - &ApiFunc::kclvm_dict_insert_unpack.name(), - &[self.current_runtime_ctx_ptr(), config_value, value], - ); - } - } - Ok(config_value) - } -} diff --git a/kclvm/compiler/src/codegen/llvm/schema.rs b/kclvm/compiler/src/codegen/llvm/schema.rs deleted file mode 100644 index 5d53dc6eb..000000000 --- a/kclvm/compiler/src/codegen/llvm/schema.rs +++ /dev/null @@ -1,358 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. - -use inkwell::values::{BasicValueEnum, FunctionValue}; -use inkwell::{AddressSpace, IntPredicate}; -use kclvm_ast::ast; -use kclvm_runtime::ApiFunc; -use kclvm_sema::pkgpath_without_prefix; -use std::collections::HashMap; -use std::str; - -use super::context::LLVMCodeGenContext; -use crate::codegen::llvm::context::BacktrackKind; -use crate::codegen::traits::{ - BuilderMethods, DerivedTypeMethods, DerivedValueCalculationMethods, ProgramCodeGen, - ValueMethods, -}; -use crate::codegen::{error as kcl_error, INNER_LEVEL}; -use crate::value; - -impl<'ctx> LLVMCodeGenContext<'ctx> { - /// Emit all left identifiers because all the attribute can be forward referenced. - pub(crate) fn emit_left_identifiers( - &self, - body: &'ctx [Box>], - index_signature: &'ctx Option>, - cal_map: BasicValueEnum<'ctx>, - runtime_type: &str, - is_in_if: bool, - place_holder_map: &mut HashMap>>, - body_map: &mut HashMap, BacktrackKind)>>, - in_if_names: &mut Vec, - ) { - let schema_value = self - .get_variable(value::SCHEMA_SELF_NAME) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let value = self.undefined_value(); - let add_stmt = |name: &str, - stmt: &'ctx ast::Node, - kind: BacktrackKind, - place_holder_map: &mut HashMap>>, - body_map: &mut HashMap< - String, - Vec<(&'ctx ast::Node, BacktrackKind)>, - >| { - let function = self.add_function(&format!( - "{}.{}.{}", - value::SCHEMA_ATTR_NAME, - pkgpath_without_prefix!(runtime_type), - name - )); - let lambda_fn_ptr = self.builder.build_bitcast( - function.as_global_value().as_pointer_value(), - self.context.i64_type().ptr_type(AddressSpace::default()), - "", - ); - if !place_holder_map.contains_key(name) { - place_holder_map.insert(name.to_string(), vec![]); - } - let name_vec = place_holder_map - .get_mut(name) - .expect(kcl_error::INTERNAL_ERROR_MSG); - name_vec.push(function); - self.default_collection_insert_int_pointer(cal_map, name, lambda_fn_ptr); - self.default_collection_insert_value( - cal_map, - &format!("{}_{}", name, kclvm_runtime::CAL_MAP_RUNTIME_TYPE), - self.string_value(runtime_type), - ); - self.default_collection_insert_value( - cal_map, - &format!("{}_{}", name, kclvm_runtime::CAL_MAP_META_LINE), - self.int_value(stmt.line as i64), - ); - if !body_map.contains_key(name) { - body_map.insert(name.to_string(), vec![]); - } - let body_vec = body_map.get_mut(name).expect(kcl_error::INTERNAL_ERROR_MSG); - body_vec.push((stmt, kind)); - }; - if let Some(index_signature) = index_signature { - self.default_collection_insert_value( - cal_map, - kclvm_runtime::CAL_MAP_INDEX_SIGNATURE, - self.int_value(index_signature.line as i64), - ); - place_holder_map.insert(kclvm_runtime::CAL_MAP_INDEX_SIGNATURE.to_string(), vec![]); - } - for stmt in body { - match &stmt.node { - ast::Stmt::Unification(unification_stmt) => { - let name = &unification_stmt.target.node.names[0].node; - self.dict_merge(schema_value, name, value, 0, None); - if is_in_if { - in_if_names.push(name.to_string()); - } else { - add_stmt( - name, - stmt, - BacktrackKind::Normal, - place_holder_map, - body_map, - ); - } - } - ast::Stmt::Assign(assign_stmt) => { - for target in &assign_stmt.targets { - let name = &target.node.name.node; - self.dict_merge(schema_value, name, value, 0, None); - if is_in_if { - in_if_names.push(name.to_string()); - } else { - add_stmt( - name, - stmt, - BacktrackKind::Normal, - place_holder_map, - body_map, - ); - } - } - } - ast::Stmt::AugAssign(aug_assign_stmt) => { - let target = &aug_assign_stmt.target; - let name = &target.node.name.node; - self.dict_merge(schema_value, name, value, 0, None); - if is_in_if { - in_if_names.push(name.to_string()); - } else { - add_stmt( - name, - stmt, - BacktrackKind::Normal, - place_holder_map, - body_map, - ); - } - } - ast::Stmt::If(if_stmt) => { - let mut names: Vec = vec![]; - self.emit_left_identifiers( - &if_stmt.body, - &None, - cal_map, - runtime_type, - true, - place_holder_map, - body_map, - &mut names, - ); - if is_in_if { - for name in &names { - in_if_names.push(name.to_string()); - } - } else { - for name in &names { - add_stmt(name, stmt, BacktrackKind::If, place_holder_map, body_map); - } - } - names.clear(); - self.emit_left_identifiers( - &if_stmt.orelse, - &None, - cal_map, - runtime_type, - true, - place_holder_map, - body_map, - &mut names, - ); - if is_in_if { - for name in &names { - in_if_names.push(name.to_string()); - } - } else { - for name in &names { - add_stmt( - name, - stmt, - BacktrackKind::OrElse, - place_holder_map, - body_map, - ); - } - } - names.clear(); - } - ast::Stmt::SchemaAttr(schema_attr) => { - let name = schema_attr.name.node.as_str(); - self.dict_merge(schema_value, name, value, 0, None); - if is_in_if { - in_if_names.push(name.to_string()); - } else { - add_stmt( - name, - stmt, - BacktrackKind::Normal, - place_holder_map, - body_map, - ); - } - } - _ => {} - } - } - } - - pub(crate) fn get_schema_config_meta( - &self, - n: Option<&'ctx ast::Node>, - t: &'ctx ast::ConfigExpr, - ) -> BasicValueEnum<'ctx> { - let config_meta = self.dict_value(); - if let Some(n) = n { - let value = self.string_value(&n.filename); - self.dict_insert_override_item(config_meta, kclvm_runtime::CONFIG_META_FILENAME, value); - let value = self.int_value(n.line as i64); - self.dict_insert_override_item(config_meta, kclvm_runtime::CONFIG_META_LINE, value); - let value = self.int_value(n.column as i64); - self.dict_insert_override_item(config_meta, kclvm_runtime::CONFIG_META_COLUMN, value); - } - for item in &t.items { - if let Some(key) = &item.node.key { - let name = match &key.node { - ast::Expr::Identifier(t) => t.names[0].node.clone(), - ast::Expr::NumberLit(t) => match t.value { - ast::NumberLitValue::Int(i) => i.to_string(), - ast::NumberLitValue::Float(f) => f.to_string(), - }, - ast::Expr::StringLit(t) => t.value.clone(), - ast::Expr::NameConstantLit(t) => match t.value { - ast::NameConstant::True => { - kclvm_runtime::KCL_NAME_CONSTANT_TRUE.to_string() - } - ast::NameConstant::False => { - kclvm_runtime::KCL_NAME_CONSTANT_FALSE.to_string() - } - ast::NameConstant::None => { - kclvm_runtime::KCL_NAME_CONSTANT_NONE.to_string() - } - ast::NameConstant::Undefined => { - kclvm_runtime::KCL_NAME_CONSTANT_UNDEFINED.to_string() - } - }, - _ => format!("{:?}", key.node), - }; - let config_item_meta = self.dict_value(); - let value = self.string_value(&key.filename); - self.dict_insert_override_item( - config_item_meta, - kclvm_runtime::CONFIG_ITEM_META_FILENAME, - value, - ); - let value = self.int_value(key.line as i64); - self.dict_insert_override_item( - config_item_meta, - kclvm_runtime::CONFIG_ITEM_META_LINE, - value, - ); - let value = self.int_value(key.column as i64); - self.dict_insert_override_item( - config_item_meta, - kclvm_runtime::CONFIG_ITEM_META_COLUMN, - value, - ); - let value = match &item.node.value.node { - ast::Expr::Config(config_expr) => { - self.get_schema_config_meta(None, config_expr) - } - _ => self.dict_value(), - }; - self.dict_insert_override_item( - config_item_meta, - kclvm_runtime::CONFIG_ITEM_META, - value, - ); - self.dict_insert_override_item(config_meta, &name, config_item_meta) - } - } - config_meta - } - - pub(crate) fn update_schema_scope_value( - &self, - schema_value: BasicValueEnum<'ctx>, // Schema self value - config_value: BasicValueEnum<'ctx>, // Schema config value - name: &str, // Schema attribute name - value: Option>, // Optional right override value - ) -> bool { - // Attribute name - let string_ptr_value = self.native_global_string(name, "").into(); - // i8 has_key - let has_key = self - .build_call( - &ApiFunc::kclvm_dict_has_value.name(), - &[config_value, string_ptr_value], - ) - .into_int_value(); - // i1 has_key - let has_key = - self.builder - .build_int_compare(IntPredicate::NE, has_key, self.native_i8_zero(), ""); - let last_block = self.append_block(""); - let then_block = self.append_block(""); - let else_block = self.append_block(""); - self.br(last_block); - self.builder.position_at_end(last_block); - let none_value = self.none_value(); - self.builder - .build_conditional_branch(has_key, then_block, else_block); - self.builder.position_at_end(then_block); - let config_entry = self.build_call( - &ApiFunc::kclvm_dict_get_entry.name(), - &[ - self.current_runtime_ctx_ptr(), - config_value, - string_ptr_value, - ], - ); - self.br(else_block); - self.builder.position_at_end(else_block); - let tpe = self.value_ptr_type(); - let phi = self.builder.build_phi(tpe, ""); - phi.add_incoming(&[(&none_value, last_block), (&config_entry, then_block)]); - let config_value = phi.as_basic_value(); - if self.scope_level() >= INNER_LEVEL && !self.local_vars.borrow().contains(name) { - if let Some(value) = value { - self.dict_merge(schema_value, name, value, 1, None); - } - self.value_union(schema_value, config_value); - let cal_map = self - .get_variable(value::SCHEMA_CAL_MAP) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let backtrack_cache = self - .get_variable(value::BACKTRACK_CACHE) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let runtime_type = self - .get_variable(value::SCHEMA_RUNTIME_TYPE) - .expect(kcl_error::INTERNAL_ERROR_MSG); - let name_native_str = self.native_global_string_value(name); - self.build_void_call( - &ApiFunc::kclvm_schema_backtrack_cache.name(), - &[ - self.current_runtime_ctx_ptr(), - schema_value, - backtrack_cache, - cal_map, - name_native_str, - runtime_type, - ], - ); - // Update backtrack meta - if self.update_backtrack_meta(name, schema_value) { - return true; - } - } - false - } -} diff --git a/kclvm/compiler/src/codegen/llvm/utils.rs b/kclvm/compiler/src/codegen/llvm/utils.rs deleted file mode 100644 index 7bffb4a2f..000000000 --- a/kclvm/compiler/src/codegen/llvm/utils.rs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. - -use kclvm_ast::ast; -use kclvm_runtime::ApiFunc; -use std::str; - -use crate::codegen::traits::ValueMethods; - -use super::context::LLVMCodeGenContext; - -/* - * Temporal functions - */ - -/// Update runtime context pkgpath -pub(crate) fn update_ctx_pkgpath(gen: &LLVMCodeGenContext, pkgpath: &str) { - gen.build_void_call( - &ApiFunc::kclvm_context_set_kcl_pkgpath.name(), - &[ - gen.current_runtime_ctx_ptr(), - gen.native_global_string_value(pkgpath), - ], - ); -} - -/// Update runtime context filename -pub(crate) fn update_ctx_filename<'ctx, T>( - gen: &'ctx LLVMCodeGenContext, - node: &'ctx ast::Node, -) { - if !node.filename.is_empty() { - gen.build_void_call( - &ApiFunc::kclvm_context_set_kcl_filename.name(), - &[ - gen.current_runtime_ctx_ptr(), - gen.native_global_string_value(&node.filename), - ], - ); - } -} - -/// Update runtime context line and column -pub(crate) fn update_ctx_line_col<'ctx, T>( - gen: &'ctx LLVMCodeGenContext, - node: &'ctx ast::Node, -) { - let mut current_line = gen.current_line.borrow_mut(); - if node.line != *current_line { - *current_line = node.line; - gen.build_void_call( - &ApiFunc::kclvm_context_set_kcl_line_col.name(), - &[ - gen.current_runtime_ctx_ptr(), - gen.native_int_value(node.line as i32), - gen.native_int_value(0), - ], - ); - } -} - -/// Update runtime context line and column -pub(crate) fn update_ctx_current_line(gen: &LLVMCodeGenContext) { - let current_line = gen.current_line.borrow_mut(); - gen.build_void_call( - &ApiFunc::kclvm_context_set_kcl_line_col.name(), - &[ - gen.current_runtime_ctx_ptr(), - gen.native_int_value(*current_line as i32), - gen.native_int_value(0), - ], - ); -} - -/// Reset target vars -pub(crate) fn reset_target_vars(gen: &LLVMCodeGenContext) { - gen.target_vars.borrow_mut().clear(); - gen.target_vars.borrow_mut().push("".to_string()); -} diff --git a/kclvm/compiler/src/codegen/mod.rs b/kclvm/compiler/src/codegen/mod.rs deleted file mode 100644 index 6c2bacb1a..000000000 --- a/kclvm/compiler/src/codegen/mod.rs +++ /dev/null @@ -1,82 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -use kclvm_ast::ast; -use kclvm_primitives::IndexMap; - -mod abi; -pub mod error; -#[cfg(feature = "llvm")] -pub mod llvm; -mod traits; - -/// The kclvm runner main function name. -pub const MODULE_NAME: &str = "kclvm_main"; -/// The kclvm runner main function entry block name. -pub const ENTRY_NAME: &str = "entry"; -/// The kclvm runtime value type name. -pub const VALUE_TYPE_NAME: &str = "kclvm_value_ref_t"; -/// The kclvm runtime context type name. -pub const CONTEXT_TYPE_NAME: &str = "kclvm_context_t"; -/// The kclvm runtime evaluation type name. -pub const SCOPE_TYPE_NAME: &str = "kclvm_eval_scope_t"; -/// Package init function name suffix -pub const PKG_INIT_FUNCTION_SUFFIX: &str = "init"; -/// Global level -pub const GLOBAL_LEVEL: usize = 1; -/// Inner level -pub const INNER_LEVEL: usize = 2; -/// Global variable alignment -pub const GLOBAL_VAL_ALIGNMENT: u32 = 8; -/// Object file type format suffix. -#[cfg(target_os = "windows")] -pub const OBJECT_FILE_SUFFIX: &str = ".obj"; -#[cfg(not(target_os = "windows"))] -pub const OBJECT_FILE_SUFFIX: &str = ".o"; -/// LLVM IR text format suffix .ll -pub const LL_FILE_SUFFIX: &str = ".ll"; - -/// CodeGenContext is a trait used by the compiler to emit code to different targets. -pub trait CodeGenContext: traits::ProgramCodeGen { - fn emit(&self, opt: &EmitOptions) -> Result<(), Box>; -} - -/// EmitOptions represents the general emit options -#[derive(Debug, Default)] -pub struct EmitOptions<'a> { - /// Path to load exist module, if not set, create an empty module. - pub from_path: Option<&'a str>, - /// Path to emit module. - pub emit_path: Option<&'a str>, - /// no_link indicates whether to link the generated code of different KCL packages to the same module. - pub no_link: bool, -} - -/// Emit code with the options using CodeGenContext. -pub fn emit_code_with( - ctx: impl CodeGenContext, - opt: &EmitOptions, -) -> Result<(), Box> { - ctx.emit(opt) -} - -/// Generate LLVM IR of KCL ast module. -#[inline] -pub fn emit_code( - program: &ast::Program, - workdir: String, - import_names: IndexMap>, - opts: &EmitOptions, -) -> Result<(), Box> { - #[cfg(feature = "llvm")] - { - llvm::emit_code(program, workdir, import_names, opts) - } - #[cfg(not(feature = "llvm"))] - { - let _ = program; - let _ = workdir; - let _ = import_names; - let _ = opts; - Err("error: llvm feature is not enabled. Note: Set KCL_FAST_EVAL=1 or rebuild the crate with the llvm feature.".to_string().into()) - } -} diff --git a/kclvm/compiler/src/lib.rs b/kclvm/compiler/src/lib.rs deleted file mode 100644 index 446c83911..000000000 --- a/kclvm/compiler/src/lib.rs +++ /dev/null @@ -1,9 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -pub mod codegen; -pub mod value; - -#[macro_use] -mod macros; - -extern crate kclvm_error; diff --git a/kclvm/compiler/src/value/lambda.rs b/kclvm/compiler/src/value/lambda.rs deleted file mode 100644 index 4e7c84440..000000000 --- a/kclvm/compiler/src/value/lambda.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -pub const LAMBDA_NAME: &str = "kclvm_lambda"; -pub const LAMBDA_CLOSURE: &str = "$lambda_closure"; diff --git a/kclvm/compiler/src/value/schema.rs b/kclvm/compiler/src/value/schema.rs deleted file mode 100644 index 2984672f4..000000000 --- a/kclvm/compiler/src/value/schema.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -pub const SCHEMA_NAME: &str = "$kclvm_schema"; -pub const SCHEMA_ATTR_NAME: &str = "$kclvm_schema_attr"; -pub const SCHEMA_CHECK_BLOCK_NAME: &str = "$kclvm_schema_check_block"; -pub const SCHEMA_SELF_NAME: &str = "$schema_self"; -pub const SCHEMA_CONFIG_NAME: &str = "$schema_config"; -pub const SCHEMA_CONFIG_META_NAME: &str = "$schema_config_meta"; -pub const SCHEMA_CAL_MAP: &str = "$schema_cal_map"; -pub const SCHEMA_ARGS: &str = "$schema_args"; -pub const SCHEMA_KWARGS: &str = "$schema_kwargs"; -pub const SCHEMA_RUNTIME_TYPE: &str = "$schema_runtime_type"; -pub const SCHEMA_VARIABLE_LIST: &[&str] = &[ - BACKTRACK_CACHE, - BACKTRACK_LEVEL_MAP, - SCHEMA_CAL_MAP, - SCHEMA_CONFIG_NAME, - SCHEMA_CONFIG_META_NAME, - SCHEMA_SELF_NAME, - SCHEMA_ARGS, - SCHEMA_KWARGS, - SCHEMA_RUNTIME_TYPE, -]; -pub const BACKTRACK_LEVEL_MAP: &str = "$backtrack_level_map"; -pub const BACKTRACK_CACHE: &str = "$backtrack_cache"; -pub const GLOBAL_SETTER: &str = "$set"; - -/// KCL schema type -pub struct SchemaType { - pub name: String, - pub pkgpath: String, - pub runtime_type: String, - pub is_mixin: bool, - pub is_protocol: bool, - pub is_rule: bool, -} - -impl SchemaType { - pub fn new(name: &str, pkgpath: &str, runtime_type: &str, is_mixin: bool) -> SchemaType { - SchemaType { - name: name.to_string(), - pkgpath: pkgpath.to_string(), - runtime_type: runtime_type.to_string(), - is_mixin, - is_protocol: false, - is_rule: false, - } - } -} diff --git a/kclvm/config/Cargo.lock b/kclvm/config/Cargo.lock deleted file mode 100644 index d8754d979..000000000 --- a/kclvm/config/Cargo.lock +++ /dev/null @@ -1,384 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "ahash" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" -dependencies = [ - "getrandom", - "once_cell", - "version_check", -] - -[[package]] -name = "autocfg" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" - -[[package]] -name = "base64" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "chrono" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" -dependencies = [ - "libc", - "num-integer", - "num-traits", - "time", - "winapi", -] - -[[package]] -name = "dtoa" -version = "0.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56899898ce76aaf4a0f24d914c97ea6ed976d42fec6ad33fcbb0a1103e07b2b0" - -[[package]] -name = "fslock" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04412b8935272e3a9bae6f48c7bfff74c2911f60525404edfdd28e49884c3bfb" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "fuchsia-cprng" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" - -[[package]] -name = "gcc" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2" - -[[package]] -name = "getrandom" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753" -dependencies = [ - "cfg-if", - "libc", - "wasi", -] - -[[package]] -name = "glob" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" - -[[package]] -name = "hashbrown" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" - -[[package]] -name = "indexmap" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc633605454125dec4b66843673f01c7df2b89479b32e0ed634e43a91cff62a5" -dependencies = [ - "autocfg", - "hashbrown", -] - -[[package]] -name = "kclvm-config" -version = "0.1.0" -dependencies = [ - "ahash", - "chrono", - "fslock", - "glob", - "indexmap", - "kclvm-version", - "pathdiff", - "ron", - "rust-crypto", - "serde", - "serde_yaml", - "toml", -] - -[[package]] -name = "kclvm-version" -version = "0.1.0" - -[[package]] -name = "libc" -version = "0.2.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f98a04dce437184842841303488f70d0188c5f51437d2a834dc097eafa909a01" - -[[package]] -name = "linked-hash-map" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3" - -[[package]] -name = "num-integer" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db" -dependencies = [ - "autocfg", - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" -dependencies = [ - "autocfg", -] - -[[package]] -name = "once_cell" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "692fcb63b64b1758029e0a96ee63e049ce8c5948587f2f7208df04625e5f6b56" - -[[package]] -name = "pathdiff" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" - -[[package]] -name = "proc-macro2" -version = "1.0.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba508cc11742c0dc5c1659771673afbab7a0efab23aa17e854cbab0837ed0b43" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "quote" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38bc8cc6a5f2e3655e0899c1b848643b2562f853f114bfec7be120678e3ace05" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rand" -version = "0.3.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64ac302d8f83c0c1974bf758f6b041c6c8ada916fbb44a609158ca8b064cc76c" -dependencies = [ - "libc", - "rand 0.4.6", -] - -[[package]] -name = "rand" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293" -dependencies = [ - "fuchsia-cprng", - "libc", - "rand_core 0.3.1", - "rdrand", - "winapi", -] - -[[package]] -name = "rand_core" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" -dependencies = [ - "rand_core 0.4.2", -] - -[[package]] -name = "rand_core" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" - -[[package]] -name = "rdrand" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" -dependencies = [ - "rand_core 0.3.1", -] - -[[package]] -name = "ron" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b861ecaade43ac97886a512b360d01d66be9f41f3c61088b42cedf92e03d678" -dependencies = [ - "base64", - "bitflags", - "serde", -] - -[[package]] -name = "rust-crypto" -version = "0.2.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f76d05d3993fd5f4af9434e8e436db163a12a9d40e1a58a726f27a01dfd12a2a" -dependencies = [ - "gcc", - "libc", - "rand 0.3.23", - "rustc-serialize", - "time", -] - -[[package]] -name = "rustc-serialize" -version = "0.3.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda" - -[[package]] -name = "serde" -version = "1.0.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f12d06de37cf59146fbdecab66aa99f9fe4f78722e3607577a5375d66bd0c913" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7bc1a1ab1961464eae040d96713baa5a724a8152c1222492465b54322ec508b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_yaml" -version = "0.8.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8c608a35705a5d3cdc9fbe403147647ff34b921f8e833e49306df898f9b20af" -dependencies = [ - "dtoa", - "indexmap", - "serde", - "yaml-rust", -] - -[[package]] -name = "syn" -version = "1.0.81" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2afee18b8beb5a596ecb4a2dce128c719b4ba399d34126b9e4396e3f9860966" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "time" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" -dependencies = [ - "libc", - "wasi", - "winapi", -] - -[[package]] -name = "toml" -version = "0.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a31142970826733df8241ef35dc040ef98c679ab14d7c3e54d827099b3acecaa" -dependencies = [ - "serde", -] - -[[package]] -name = "unicode-xid" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" - -[[package]] -name = "version_check" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" - -[[package]] -name = "wasi" -version = "0.10.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "yaml-rust" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" -dependencies = [ - "linked-hash-map", -] diff --git a/kclvm/config/Cargo.toml b/kclvm/config/Cargo.toml deleted file mode 100644 index ec3d6814e..000000000 --- a/kclvm/config/Cargo.toml +++ /dev/null @@ -1,25 +0,0 @@ -[package] -name = "kclvm-config" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -serde = { version = "1", features = ["derive"] } -serde_yaml_ng = "0.10.0" -serde_json = "1.0" -toml = "0.5.8" -ron = "0.7.0" -chrono = "0.4.19" -glob = "0.3.0" -pathdiff = "0.2.1" -anyhow = "1.0" - -kclvm-version = {path = "../version"} -kclvm-utils = {path = "../utils"} -kclvm-ast = {path = "../ast"} -dirs = "5.0.0" -md-5 = "0.8.0" -regex = "1.10.4" -url = "2.5.4" diff --git a/kclvm/config/src/path.rs b/kclvm/config/src/path.rs deleted file mode 100644 index 3c54c74d3..000000000 --- a/kclvm/config/src/path.rs +++ /dev/null @@ -1,201 +0,0 @@ -//! The file provides the mod relative path type. -//! -//! The mod relative path is a path that is relative to the root package path. -//! The root package is can be specified by the prefix `${:KCL_MOD}`. -//! `` is the name of the root package. -//! If `` is omitted, the root package is the current package. -//! -//! # Examples -//! -//! `/usr/my_pkg` is the real path of the package `my_pkg`. -//! `${my_pkg:KCL_MOD}/sub/main.k` is a mod relative path. -//! The real path of `${my_pkg:KCL_MOD}/xxx/main.k` is `/usr/my_pkg/sub/main.k`. -use anyhow::Result; -use regex::Regex; -use std::path::PathBuf; - -#[derive(Clone, Debug, Default)] -/// [`ModRelativePath`] is a path that is relative to the root package path. -/// The root package is can be specified by the prefix `${:KCL_MOD}`. -/// `` is the name of the root package. -/// If `` is omitted, the root package is the current package. -/// -/// # Examples -/// -/// `/usr/my_pkg` is the real path of the package `my_pkg`. -/// `${my_pkg:KCL_MOD}/sub/main.k` is a mod relative path. -/// The real path of `${my_pkg:KCL_MOD}/xxx/main.k` is `/usr/my_pkg/sub/main.k`. -pub struct ModRelativePath { - path: String, -} - -/// The regular expression to match the mod relative path preffix. -const RELATIVE_PATH_PREFFIX: &str = r#"\$\{((?P[a-zA-Z0-9_-]+):)?KCL_MOD\}/"#; - -/// The name of the root package. -const ROOT_PKG_NAME_FLAG: &str = "name"; - -impl From for ModRelativePath { - fn from(path: String) -> Self { - ModRelativePath::new(path) - } -} - -impl ModRelativePath { - /// [`new`] creates a new [`ModRelativePath`] instance. - pub fn new(path: String) -> ModRelativePath { - ModRelativePath { path } - } - - /// [`get_path`] returns the clone string of path of the [`ModRelativePath`]. - pub fn get_path(&self) -> String { - self.path.clone() - } - - /// [`is_relative_path`] returns true if the path is a mod relative path. - /// - /// # Examples - /// - /// ```rust - /// use kclvm_config::path::ModRelativePath; - /// let path = ModRelativePath::new("${my_pkg:KCL_MOD}/src/path.rs".to_string()); - /// assert_eq!(path.is_relative_path().unwrap(), true); - /// - /// let path = ModRelativePath::new("${KCL_MOD}/src/path.rs".to_string()); - /// assert_eq!(path.is_relative_path().unwrap(), true); - /// - /// let path = ModRelativePath::new("/usr/${my_pkg:KCL_MOD}/src/path.rs".to_string()); - /// assert_eq!(path.is_relative_path().unwrap(), false); - /// - /// let path = ModRelativePath::new("/src/path.rs".to_string()); - /// assert_eq!(path.is_relative_path().unwrap(), false); - /// ``` - pub fn is_relative_path(&self) -> Result { - Ok(Regex::new(RELATIVE_PATH_PREFFIX)? - .find(&self.path) - .map_or(false, |mat| mat.start() == 0)) - } - - /// [`get_root_pkg_name`] returns the name of the root package. - /// - /// # Examples - /// - /// ```rust - /// use kclvm_config::path::ModRelativePath; - /// let path = ModRelativePath::new("${my_pkg:KCL_MOD}/src/path.rs".to_string()); - /// assert_eq!(path.get_root_pkg_name().unwrap(), Some("my_pkg".to_string())); - /// - /// let path = ModRelativePath::new("${KCL_MOD}/src/path.rs".to_string()); - /// assert_eq!(path.get_root_pkg_name().unwrap(), None); - /// - /// let path = ModRelativePath::new("/src/path.rs".to_string()); - /// assert_eq!(path.get_root_pkg_name().unwrap(), None); - /// ``` - pub fn get_root_pkg_name(&self) -> Result> { - if !self.is_relative_path()? { - return Ok(None); - } - - Ok(Regex::new(RELATIVE_PATH_PREFFIX)? - .captures(&self.path) - .and_then(|caps| caps.name(ROOT_PKG_NAME_FLAG)) - .map(|mat| mat.as_str().to_string())) - } - - /// [`canonicalize_by_root_path`] returns the canonicalized path by the root path. - /// - /// # Examples - /// - /// ```rust - /// use kclvm_config::path::ModRelativePath; - /// let path = ModRelativePath::new("${name:KCL_MOD}/src/path".to_string()); - /// #[cfg(target_os = "windows")] - /// assert_eq!(path.canonicalize_by_root_path("/usr/my_pkg").unwrap(), "/usr/my_pkg\\src/path"); - /// #[cfg(not(target_os = "windows"))] - /// assert_eq!(path.canonicalize_by_root_path("/usr/my_pkg").unwrap(), "/usr/my_pkg/src/path"); - /// - /// let path = ModRelativePath::new("/src/path".to_string()); - /// assert_eq!(path.canonicalize_by_root_path("/usr/my_pkg").unwrap(), "/src/path"); - /// ``` - pub fn canonicalize_by_root_path(&self, root_path: &str) -> Result { - if !self.is_relative_path()? { - return Ok(self.get_path()); - } - - Ok(Regex::new(RELATIVE_PATH_PREFFIX)? - .captures(&self.path) - .map_or_else( - || self.get_path(), - |caps| { - // Due to the path format is different between windows and linux, - // Can not use the replace method directly - // by 'replace(std::str::from_utf8(caps.get(0).unwrap().as_bytes()).unwrap(), root_path)'. - let sub_path = self.get_path().replace(caps.get(0).unwrap().as_str(), ""); - let res = PathBuf::from(root_path) - .join(sub_path) - .display() - .to_string(); - - res - }, - )) - } -} - -#[cfg(test)] -mod test_relative_path { - use super::*; - - #[test] - fn test_is_relative_path() { - let path = ModRelativePath::new("${name:KCL_MOD}/src/path.rs".to_string()); - assert!(path.is_relative_path().unwrap()); - let path = ModRelativePath::new("${KCL_MOD}/src/path.rs".to_string()); - assert!(path.is_relative_path().unwrap()); - let path = ModRelativePath::new("/usr/${name:KCL_MOD}/src/path.rs".to_string()); - assert!(!path.is_relative_path().unwrap()); - let path = ModRelativePath::new("/src/path.rs".to_string()); - assert!(!path.is_relative_path().unwrap()); - let path = ModRelativePath::new("./src/path.rs".to_string()); - assert!(!path.is_relative_path().unwrap()); - let path = ModRelativePath::new("${K_MOD}/src/path.rs".to_string()); - assert!(!path.is_relative_path().unwrap()); - let path = ModRelativePath::new("${:KCL_MOD}/src/path.rs".to_string()); - assert!(!path.is_relative_path().unwrap()); - } - - #[test] - fn test_get_root_pkg_name() { - let path = ModRelativePath::new("${my_pkg:KCL_MOD}/src/path.rs".to_string()); - assert_eq!( - path.get_root_pkg_name().unwrap(), - Some("my_pkg".to_string()) - ); - - let path = ModRelativePath::new("${KCL_MOD}/src/path.rs".to_string()); - assert_eq!(path.get_root_pkg_name().unwrap(), None); - - let path = ModRelativePath::new("/src/path.rs".to_string()); - assert_eq!(path.get_root_pkg_name().unwrap(), None); - } - - #[test] - fn test_canonicalize_by_root_path() { - let path = ModRelativePath::new("${name:KCL_MOD}/src/path".to_string()); - #[cfg(target_os = "windows")] - assert_eq!( - path.canonicalize_by_root_path("C:\\usr\\my_pkg").unwrap(), - "C:\\usr\\my_pkg\\src/path" - ); - #[cfg(not(target_os = "windows"))] - assert_eq!( - path.canonicalize_by_root_path("/usr/my_pkg").unwrap(), - "/usr/my_pkg/src/path" - ); - let path = ModRelativePath::new("/src/path".to_string()); - assert_eq!( - path.canonicalize_by_root_path("/usr/my_pkg").unwrap(), - "/src/path" - ); - } -} diff --git a/kclvm/config/src/settings.rs b/kclvm/config/src/settings.rs deleted file mode 100644 index fbc4637a0..000000000 --- a/kclvm/config/src/settings.rs +++ /dev/null @@ -1,526 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. -use anyhow::{Context, Result}; -use serde::{ - de::{DeserializeSeed, Error, MapAccess, SeqAccess, Unexpected, Visitor}, - Deserialize, Serialize, -}; -use std::{collections::HashMap, ops::Deref, path::PathBuf}; - -/// Default settings file `kcl.yaml` -pub const DEFAULT_SETTING_FILE: &str = "kcl.yaml"; - -/// Readonly settings with the filepath. -#[derive(Debug, Default, Clone)] -pub struct SettingsPathBuf(Option, SettingsFile); - -impl SettingsPathBuf { - /// New a settings with path and settings content. - #[inline] - pub fn new(path: Option, settings: SettingsFile) -> Self { - Self(path, settings) - } - - /// Get the output setting. - #[inline] - pub fn output(&self) -> Option { - match &self.1.kcl_cli_configs { - Some(c) => c.output.clone(), - None => None, - } - } - - /// Get the path. - #[inline] - pub fn path(&self) -> &Option { - &self.0 - } - - /// Get the settings. - #[inline] - pub fn settings(&self) -> &SettingsFile { - &self.1 - } -} - -#[derive(Serialize, Deserialize, Debug, Clone)] -pub struct SettingsFile { - pub kcl_cli_configs: Option, - pub kcl_options: Option>, -} - -#[derive(Serialize, Deserialize, Debug, Clone, Default)] -pub struct Config { - pub files: Option>, - pub file: Option>, - pub output: Option, - pub overrides: Option>, - pub path_selector: Option>, - pub strict_range_check: Option, - pub disable_none: Option, - pub verbose: Option, - pub debug: Option, - pub sort_keys: Option, - pub show_hidden: Option, - /// Whether including schema type in JSON/YAML result. - pub include_schema_type_path: Option, - /// kcl needs a mapping between the package name and the package path - /// to determine the source code path corresponding to different version package. - pub package_maps: Option>, - /// Use the evaluator to execute the AST program instead of AOT. - pub fast_eval: Option, -} - -impl SettingsFile { - pub fn new() -> Self { - SettingsFile { - kcl_cli_configs: Some(Config { - file: Some(vec![]), - files: Some(vec![]), - output: None, - overrides: Some(vec![]), - path_selector: Some(vec![]), - strict_range_check: Some(false), - disable_none: Some(false), - verbose: Some(0), - debug: Some(false), - sort_keys: Some(false), - show_hidden: Some(false), - fast_eval: Some(false), - include_schema_type_path: Some(false), - package_maps: Some(HashMap::default()), - }), - kcl_options: Some(vec![]), - } - } - - /// Get the output setting. - #[inline] - pub fn output(&self) -> Option { - match &self.kcl_cli_configs { - Some(c) => c.output.clone(), - None => None, - } - } - - /// Get the input setting. - #[inline] - pub fn input(&self) -> Vec { - match &self.kcl_cli_configs { - Some(c) => match &c.file { - Some(file) => match &c.files { - Some(files) if !files.is_empty() => files.clone(), - _ => file.clone(), - }, - None => match &c.files { - Some(files) => files.clone(), - None => vec![], - }, - }, - None => vec![], - } - } -} - -impl Default for SettingsFile { - fn default() -> Self { - Self::new() - } -} - -/// Top level argument key value pair. -#[derive(Serialize, Deserialize, Debug, Clone, Default)] -pub struct KeyValuePair { - /// key is the top level argument key. - pub key: String, - // Note: here is a normal json string including int, float, string, bool list and dict. - pub value: ValueString, -} - -#[macro_export] -macro_rules! tri { - ($e:expr $(,)?) => { - match $e { - core::result::Result::Ok(val) => val, - core::result::Result::Err(err) => return core::result::Result::Err(err), - } - }; -} - -/// MapStringKey denotes the map deserialize key. -struct MapStringKey; -impl<'de> DeserializeSeed<'de> for MapStringKey { - type Value = String; - - fn deserialize(self, deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - deserializer.deserialize_str(self) - } -} - -impl<'de> Visitor<'de> for MapStringKey { - type Value = String; - - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { - formatter.write_str("a string key") - } - - fn visit_str(self, s: &str) -> Result - where - E: serde::de::Error, - { - Ok(s.to_owned()) - } - - fn visit_string(self, s: String) -> Result - where - E: serde::de::Error, - { - Ok(s) - } -} - -/// Top level argument value string. -/// Note: here is a normal json string including int, float, string, bool list and dict. -#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq)] -pub struct ValueString(pub String); - -impl Deref for ValueString { - type Target = String; - - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl From for ValueString { - fn from(value: String) -> Self { - Self(value) - } -} - -impl From<&str> for ValueString { - fn from(value: &str) -> Self { - Self(value.to_string()) - } -} - -impl<'de> Deserialize<'de> for ValueString { - #[inline] - fn deserialize(deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - { - struct ValueVisitor; - - impl<'de> Visitor<'de> for ValueVisitor { - type Value = ValueString; - - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { - formatter.write_str("any valid JSON value or KCL value expression") - } - - #[inline] - fn visit_bool(self, value: bool) -> Result - where - E: Error, - { - Ok(ValueString(serde_json::to_string(&value).map_err( - |_| Error::invalid_type(Unexpected::Bool(value), &self), - )?)) - } - - #[inline] - fn visit_i64(self, value: i64) -> Result - where - E: Error, - { - Ok(ValueString(serde_json::to_string(&value).map_err( - |_| Error::invalid_type(Unexpected::Signed(value), &self), - )?)) - } - - #[inline] - fn visit_u64(self, value: u64) -> Result - where - E: Error, - { - Ok(ValueString(serde_json::to_string(&value).map_err( - |_| Error::invalid_type(Unexpected::Unsigned(value), &self), - )?)) - } - - #[inline] - fn visit_f64(self, value: f64) -> Result - where - E: Error, - { - Ok(ValueString(serde_json::to_string(&value).map_err( - |_| Error::invalid_type(Unexpected::Float(value), &self), - )?)) - } - - #[inline] - fn visit_str(self, value: &str) -> Result - where - E: serde::de::Error, - { - self.visit_string(String::from(value)) - } - - #[inline] - fn visit_string(self, value: String) -> Result - where - E: Error, - { - Ok(ValueString(serde_json::to_string(&value).map_err( - |_| Error::invalid_type(Unexpected::Str(&value), &self), - )?)) - } - - #[inline] - fn visit_none(self) -> Result - where - E: Error, - { - Ok(ValueString("null".into())) - } - - #[inline] - fn visit_some(self, deserializer: D) -> Result - where - D: serde::Deserializer<'de>, - D::Error: Error, - { - Deserialize::deserialize(deserializer) - } - - #[inline] - fn visit_unit(self) -> Result { - Ok(ValueString("null".into())) - } - - #[inline] - fn visit_seq(self, mut visitor: V) -> Result - where - V: SeqAccess<'de>, - V::Error: Error, - { - let mut vec: Vec = Vec::new(); - - while let Some(elem) = tri!(visitor.next_element()) { - vec.push(elem); - } - - Ok(ValueString(serde_json::to_string(&vec).map_err(|_| { - Error::invalid_type(Unexpected::Seq, &self) - })?)) - } - - fn visit_map(self, mut visitor: V) -> Result - where - V: MapAccess<'de>, - V::Error: Error, - { - match visitor.next_key_seed(MapStringKey)? { - Some(first_key) => { - let mut values: HashMap = HashMap::new(); - - values.insert(first_key, tri!(visitor.next_value())); - while let Some((key, value)) = tri!(visitor.next_entry()) { - values.insert(key, value); - } - - Ok(ValueString(serde_json::to_string(&values).map_err( - |_| Error::invalid_type(Unexpected::Map, &self), - )?)) - } - None => Ok(ValueString("{}".into())), - } - } - } - - deserializer.deserialize_any(ValueVisitor) - } -} - -#[derive(Serialize, Deserialize, Debug, Clone, Default)] -pub struct TestSettingsFile { - kcl_options: Option, -} - -/// Load kcl settings file. -pub fn load_file(filename: &str) -> Result { - let f = std::fs::File::open(filename) - .with_context(|| format!("Failed to load '{}', no such file or directory", filename))?; - let data: SettingsFile = serde_yaml_ng::from_reader(f) - .with_context(|| format!("Failed to load '{}', invalid setting file format", filename))?; - Ok(data) -} - -macro_rules! set_if { - ($result: expr, $attr: ident, $setting: expr) => { - if $setting.$attr.is_some() { - $result.$attr = $setting.$attr.clone(); - } - }; -} - -/// Merge multiple settings into one settings. -pub fn merge_settings(settings: &[SettingsFile]) -> SettingsFile { - let mut result = SettingsFile::new(); - for setting in settings { - if let Some(kcl_cli_configs) = &setting.kcl_cli_configs { - if result.kcl_cli_configs.is_none() { - result.kcl_cli_configs = Some(Config::default()); - } - if let Some(result_kcl_cli_configs) = result.kcl_cli_configs.as_mut() { - set_if!(result_kcl_cli_configs, files, kcl_cli_configs); - set_if!(result_kcl_cli_configs, file, kcl_cli_configs); - set_if!(result_kcl_cli_configs, output, kcl_cli_configs); - set_if!(result_kcl_cli_configs, overrides, kcl_cli_configs); - set_if!(result_kcl_cli_configs, path_selector, kcl_cli_configs); - set_if!(result_kcl_cli_configs, strict_range_check, kcl_cli_configs); - set_if!(result_kcl_cli_configs, disable_none, kcl_cli_configs); - set_if!(result_kcl_cli_configs, verbose, kcl_cli_configs); - set_if!(result_kcl_cli_configs, debug, kcl_cli_configs); - set_if!(result_kcl_cli_configs, sort_keys, kcl_cli_configs); - set_if!(result_kcl_cli_configs, show_hidden, kcl_cli_configs); - set_if!(result_kcl_cli_configs, fast_eval, kcl_cli_configs); - set_if!( - result_kcl_cli_configs, - include_schema_type_path, - kcl_cli_configs - ); - set_if!(result_kcl_cli_configs, package_maps, kcl_cli_configs); - } - } - if let Some(kcl_options) = &setting.kcl_options { - if result.kcl_options.is_none() { - result.kcl_options = Some(vec![]) - } - if let Some(result_kcl_options) = result.kcl_options.as_mut() { - for option in kcl_options { - result_kcl_options.push(option.clone()); - } - } - } - } - result -} - -/// Build SettingsPathBuf from args. -pub fn build_settings_pathbuf( - files: &[&str], - setting_files: Option>, - setting_config: Option, -) -> Result { - let mut path = None; - let settings = if let Some(files) = setting_files { - let mut settings = vec![]; - for file in &files { - let s = load_file(file)?; - if !s.input().is_empty() { - path = Some( - PathBuf::from(file) - .parent() - .map(|p| p.to_path_buf()) - .ok_or(anyhow::anyhow!("The parent path of {file} is not found"))?, - ) - } - settings.push(s); - } - merge_settings(&settings) - // If exists default kcl.yaml, load it. - } else if std::fs::metadata(DEFAULT_SETTING_FILE).is_ok() { - path = Some( - PathBuf::from(DEFAULT_SETTING_FILE) - .parent() - .map(|p| p.to_path_buf()) - .ok_or(anyhow::anyhow!( - "The parent path of {DEFAULT_SETTING_FILE} is not found" - ))?, - ); - load_file(DEFAULT_SETTING_FILE)? - } else { - SettingsFile::default() - }; - let mut settings = if let Some(setting_config) = setting_config { - merge_settings(&[settings, setting_config]) - } else { - settings - }; - if let Some(config) = &mut settings.kcl_cli_configs { - if !files.is_empty() { - config.files = Some(files.iter().map(|f| f.to_string()).collect()); - } - } - Ok(SettingsPathBuf::new(path, settings)) -} - -#[cfg(test)] -mod settings_test { - use crate::settings::*; - - const SETTINGS_FILE: &str = "./src/testdata/settings.yaml"; - - #[test] - fn test_settings_load_file() { - let settings = load_file(SETTINGS_FILE).unwrap(); - assert!(settings.kcl_cli_configs.is_some()); - assert!(settings.kcl_options.is_some()); - if let Some(kcl_cli_configs) = settings.kcl_cli_configs { - let files = vec![ - String::from("../main.k"), - String::from("./before/base.k"), - String::from("./main.k"), - String::from("./sub/sub.k"), - ]; - assert!(kcl_cli_configs.files.is_some()); - assert!(kcl_cli_configs.disable_none.is_some()); - assert!(kcl_cli_configs.strict_range_check.is_some()); - assert!(kcl_cli_configs.debug.is_some()); - assert!(kcl_cli_configs.path_selector.is_none()); - assert!(kcl_cli_configs.overrides.is_none()); - assert!(kcl_cli_configs.include_schema_type_path.is_none()); - assert!(kcl_cli_configs.show_hidden.is_none()); - assert!(kcl_cli_configs.fast_eval.is_none()); - assert_eq!(kcl_cli_configs.sort_keys, Some(true)); - if let Some(config_files) = kcl_cli_configs.files { - assert!(config_files == files); - } - } - if let Some(kcl_options) = settings.kcl_options { - assert!(kcl_options.len() == 6); - } - } - - #[test] - fn test_merge_settings() -> anyhow::Result<()> { - let settings1 = load_file(SETTINGS_FILE)?; - let settings2 = load_file(SETTINGS_FILE)?; - let settings = merge_settings(&vec![settings1, settings2]); - if let Some(kcl_cli_configs) = settings.kcl_cli_configs { - let files = vec![ - String::from("../main.k"), - String::from("./before/base.k"), - String::from("./main.k"), - String::from("./sub/sub.k"), - ]; - assert!(kcl_cli_configs.files.is_some()); - assert!(kcl_cli_configs.disable_none.is_some()); - assert!(kcl_cli_configs.strict_range_check.is_some()); - assert!(kcl_cli_configs.debug.is_some()); - assert!(kcl_cli_configs.path_selector.is_some()); - assert!(kcl_cli_configs.overrides.is_some()); - if let Some(config_files) = kcl_cli_configs.files { - assert!(config_files == files); - } - } - if let Some(kcl_options) = settings.kcl_options { - assert!(kcl_options.len() == 12); - } - Ok(()) - } -} diff --git a/kclvm/config/src/testdata/settings.yaml b/kclvm/config/src/testdata/settings.yaml deleted file mode 100644 index 06c8d62df..000000000 --- a/kclvm/config/src/testdata/settings.yaml +++ /dev/null @@ -1,33 +0,0 @@ -kcl_cli_configs: - files: - - ../main.k - - ./before/base.k - - ./main.k - - ./sub/sub.k - disable_none: false - strict_range_check: false - debug: false - sort_keys: true -kcl_options: - - key: app-name - value: kclvm - - key: image - value: kclvm:v0.0.1 - - key: env-type - value: TEST - - key: deploy-topology - value: - - cluster: my-cluster - id: '000123' - idc: my-idc - is_dev: true - replicas: 2 - value: null - workspace: my-workspace - zone: my-zone - - key: labels - value: - app: app - env: env - - key: ports - value: [80, 8080] diff --git a/kclvm/config/src/tests.rs b/kclvm/config/src/tests.rs deleted file mode 100644 index cb5ef38fe..000000000 --- a/kclvm/config/src/tests.rs +++ /dev/null @@ -1,78 +0,0 @@ -use kclvm_utils::path::PathPrefix; -use kclvm_version as version; -use std::{ - collections::HashMap, - env, - fs::{self, File}, - path::{Path, PathBuf}, -}; - -use crate::{ - cache::{load_pkg_cache, save_pkg_cache, CacheOption}, - modfile::{get_vendor_home, KCL_PKG_PATH}, -}; - -#[test] -fn test_vendor_home() { - env::set_var(KCL_PKG_PATH, "test_vendor_home"); - assert_eq!(get_vendor_home(), "test_vendor_home"); - env::remove_var(KCL_PKG_PATH); - - #[cfg(target_os = "windows")] - let root_dir = env::var("USERPROFILE").unwrap(); - #[cfg(not(target_os = "windows"))] - let root_dir = env::var("HOME").unwrap(); - - let kpm_home = PathBuf::from(root_dir) - .join(".kcl") - .join("kpm") - .canonicalize() - .unwrap(); - assert_eq!( - get_vendor_home(), - kpm_home.display().to_string().adjust_canonicalization() - ) -} - -#[test] -fn test_pkg_cache() { - let root = PathBuf::from("./src/testdata/test_cache/") - .canonicalize() - .unwrap() - .display() - .to_string(); - let mut external_pkgs = HashMap::new(); - external_pkgs.insert( - "test_vendor".to_string(), - "./src/testdata/test_vendor".to_string(), - ); - - let lock_path = Path::new(&root) - .join(".kclvm/cache") - .join(format!("{}-{}", version::VERSION, version::CHECK_SUM)) - .join("test_target"); - - fs::create_dir_all(lock_path.clone()).unwrap(); - File::create(lock_path.join("test_vendor.lock")).unwrap(); - - save_pkg_cache( - &root, - "test_target", - "test_vendor", - "test_data", - CacheOption::default(), - &external_pkgs, - ) - .unwrap(); - - assert_eq!( - load_pkg_cache( - &root, - "test_target", - "test_vendor", - CacheOption::default(), - &external_pkgs, - ), - Some("test_data".to_string()) - ) -} diff --git a/kclvm/driver/Cargo.toml b/kclvm/driver/Cargo.toml deleted file mode 100644 index a9b5fe67e..000000000 --- a/kclvm/driver/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "kclvm-driver" -version = "0.11.2" -edition = "2021" - -# # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -serde_json = "1.0.86" - -kclvm-config = { path = "../config" } -kclvm-runtime = { path = "../runtime" } -kclvm-utils = { path = "../utils" } -kclvm-parser = { path = "../parser" } -kclvm-ast = { path = "../ast" } -kclvm-primitives = { path = "../primitives" } -walkdir = "2" -serde = { version = "1.0", features = ["derive"] } -anyhow = { version = "1.0.70", features = ["backtrace"] } - -flate2 = "1.0.30" -tar = "0.4.40" -once_cell = "1.19.0" -parking_lot = "0.12.3" - -[target.'cfg(not(target_arch = "wasm32"))'.dependencies] -oci-client = { default-features = false, version = "0.11.0", features = [ - "rustls-tls", -] } -tokio = { version = "1.37.0", features = ["full"] } diff --git a/kclvm/driver/src/client/mod.rs b/kclvm/driver/src/client/mod.rs deleted file mode 100644 index 8019388d0..000000000 --- a/kclvm/driver/src/client/mod.rs +++ /dev/null @@ -1,311 +0,0 @@ -mod fs; -mod git; -mod oci; - -use anyhow::Result; -use git::cmd_clone_git_repo_to; -use kclvm_config::modfile::{ - get_vendor_home, load_mod_file, load_mod_lock_file, LockDependency, ModLockFile, -}; -use kclvm_config::modfile::{Dependency, GitSource, ModFile, OciSource}; -use kclvm_primitives::IndexSet; -use kclvm_utils::fslock::open_lock_file; -use oci_client::secrets::RegistryAuth; -use oci_client::{Client, Reference, RegistryOperation}; -use std::path::Path; -use std::path::PathBuf; -use std::sync::Arc; - -use crate::toolchain::{Metadata, Package}; - -pub const DEFAULT_OCI_REGISTRY: &str = "ghcr.io/kcl-lang"; -pub const KCL_SRC_URL_ENV_VAR: &str = "KCL_SRC_URL"; -pub const KCL_SRC_URL_USERNAME_ENV_VAR: &str = "KCL_SRC_USERNAME"; -pub const KCL_SRC_URL_PASSWORD_ENV_VAR: &str = "KCL_SRC_PASSWORD"; - -#[derive(Default)] -pub struct ModClient { - /// The mod file config of current module. - mod_file: ModFile, - /// The mod lock file config of current module. - mod_lock_file: Option, - /// The package search work directory. - work_dir: PathBuf, - /// Optional vendor home. - vendor: Option, - /// A lazy OCI client. - oci_client: Arc, -} - -unsafe impl Send for ModClient {} -unsafe impl Sync for ModClient {} - -impl ModClient { - /// New a default mod client to fetch metadata ot update dependencies. - #[inline] - pub fn new>(work_dir: P) -> Result { - Self::new_with_oci_client(work_dir, Arc::new(Client::default())) - } - - /// New a default mod client to fetch metadata ot update dependencies. - pub fn new_with_oci_client>( - work_dir: P, - oci_client: Arc, - ) -> Result { - Ok(Self { - work_dir: work_dir.as_ref().to_path_buf(), - mod_file: load_mod_file(&work_dir)?, - mod_lock_file: load_mod_lock_file(&work_dir).ok(), - vendor: None, - oci_client, - }) - } - - /// Auth the oci client - pub fn auth(&self) -> Result<()> { - if let (Ok(username), Ok(password)) = ( - std::env::var(KCL_SRC_URL_USERNAME_ENV_VAR), - std::env::var(KCL_SRC_URL_PASSWORD_ENV_VAR), - ) { - let rt = tokio::runtime::Runtime::new()?; - let image: Reference = self.default_oci_registry().parse()?; - let auth = RegistryAuth::Basic(username, password); - let _ = rt.block_on(async { - self.oci_client - .auth(&image, &auth, RegistryOperation::Pull) - .await - .ok()? - }); - } - Ok(()) - } - - #[inline] - pub fn default_oci_registry(&self) -> String { - std::env::var(KCL_SRC_URL_ENV_VAR).unwrap_or(DEFAULT_OCI_REGISTRY.to_string()) - } - - /// Change the work directory. - pub fn change_work_dir>(&mut self, work_dir: P) -> Result<()> { - let work_dir = work_dir.as_ref().to_path_buf(); - self.mod_file = load_mod_file(&work_dir)?; - if let Ok(mod_lock_file) = load_mod_lock_file(&work_dir) { - self.mod_lock_file = Some(mod_lock_file); - } - self.work_dir = work_dir; - Ok(()) - } - - /// Set the vendor path. - pub fn set_vendor>(&mut self, vendor: P) -> &mut Self { - let vendor = vendor.as_ref().to_path_buf(); - self.vendor = Some(vendor); - self - } - - /// Lock the kcl.mod file and resolve package deps to metadata, note this function will download - /// deps from remote sources. If the dependency is downloaded to the local path, calculate the - /// package metadata. - pub fn lock_and_resolve_all_deps>( - &mut self, - lock_file: P, - update: bool, - ) -> Result { - let mut lock_guard = - open_lock_file(lock_file.as_ref().to_string_lossy().to_string().as_str())?; - lock_guard.lock()?; - self.resolve_all_deps(update) - } - - /// Resolve package deps to metadata, note this function will download deps from remote sources. - /// If the dependency is downloaded to the local path, calculate the package metadata. - pub fn resolve_all_deps(&mut self, update: bool) -> Result { - let mut metadata = Metadata::default(); - match &self.mod_file.dependencies { - Some(dependencies) if !dependencies.is_empty() => { - let vendor = self.get_vendor_path()?; - let mut paths: IndexSet = IndexSet::default(); - for (name, dep) in dependencies { - let path = if update { - let path = self.download_dep_to_vendor(name, dep, &vendor)?; - paths.insert(path.clone()); - path - } else { - Default::default() - }; - metadata.packages.insert( - name.replace('-', "_"), - Package { - name: name.to_string(), - manifest_path: path, - }, - ); - } - for path in paths { - if let Ok(mut client) = - ModClient::new_with_oci_client(path, self.oci_client.clone()) - { - let new_metadata = client.resolve_all_deps(update)?; - for (name, package) in new_metadata.packages { - metadata.packages.entry(name).or_insert(package); - } - } - } - Ok(metadata) - } - _ => Ok(metadata), - } - } - - /// Download a dependency to the local path. - pub fn download_dep_to_vendor( - &self, - name: &str, - dep: &Dependency, - vendor: &Path, - ) -> Result { - let path = self.get_local_path_from_dep(name, dep); - let path = Path::new(vendor).join(path); - match dep { - Dependency::Version(version) => self.download_oci_source_to( - name, - &OciSource { - oci: oci::oci_reg_repo_join(&self.default_oci_registry(), name), - tag: Some(version.to_string()), - }, - &path, - ), - Dependency::Git(git_source) => self.download_git_source_to(git_source, &path), - Dependency::Oci(oci_source) => self.download_oci_source_to(name, oci_source, &path), - Dependency::Local(_) => { - // Nothing to do for the local source. - Ok(path) - } - } - } - - /// Get the vendor path. - pub fn get_vendor_path(&self) -> Result { - Ok(match &self.vendor { - Some(vendor) => { - std::fs::create_dir_all(vendor)?; - vendor.to_path_buf() - } - None => PathBuf::from(get_vendor_home()), - }) - } - - pub fn download_git_source_to(&self, git_source: &GitSource, path: &Path) -> Result { - let path = cmd_clone_git_repo_to( - &git_source.git, - &git_source.branch, - &git_source.tag, - &git_source.commit, - path, - )?; - Ok(path) - } - - pub fn download_oci_source_to( - &self, - name: &str, - oci_source: &OciSource, - path: &Path, - ) -> Result { - let rt = tokio::runtime::Runtime::new()?; - let path = rt.block_on(async { - oci::pull_oci_and_extract_layer( - &self.oci_client, - name, - &oci_source.oci, - &oci_source.tag, - path, - ) - .await - })?; - Ok(path) - } - - /// Get the dependency store path - pub fn get_local_path_from_dep(&self, name: &str, dep: &Dependency) -> String { - match dep { - Dependency::Version(version) => { - format!("{}_{}", name, version) - } - Dependency::Git(git_source) => { - if let Some(tag) = &git_source.tag { - format!("{}_{}", name, tag) - } else if let Some(commit) = &git_source.commit { - format!("{}_{}", name, commit) - } else if let Some(branch) = &git_source.branch { - format!("{}_{}", name, branch) - } else { - format!("{name}_latest") - } - } - // Just returns the folder. - Dependency::Oci(_) => "".to_string(), - Dependency::Local(local_source) => { - let local_path = PathBuf::from(&local_source.path); - if local_path.is_absolute() { - local_source.path.clone() - } else { - self.work_dir - .join(&local_source.path) - .to_string_lossy() - .to_string() - } - } - } - } - - /// Get the lock dependency store path - pub fn get_local_path_from_lock_dep(&self, lock_dep: &LockDependency) -> Option { - if lock_dep.reg.is_some() { - lock_dep.full_name.clone() - } else if let Some(git_url) = &lock_dep.url { - Some(self.get_local_path_from_dep( - &lock_dep.gen_filename(), - &Dependency::Git(GitSource { - git: git_url.to_string(), - branch: lock_dep.branch.clone(), - commit: lock_dep.commit.clone(), - tag: lock_dep.git_tag.clone(), - version: lock_dep.version.clone(), - }), - )) - } else { - match &self.mod_file.dependencies { - Some(dependencies) => dependencies - .get(&lock_dep.name) - .as_ref() - .map(|dep| self.get_local_path_from_dep(&lock_dep.name, dep)), - None => None, - } - } - } - - /// Get the package metadata from the kcl.mod.lock file. - pub fn get_metadata_from_mod_lock_file(&self) -> Option { - if let Some(mod_lock_file) = &self.mod_lock_file { - if let Some(dependencies) = &mod_lock_file.dependencies { - let vendor = self.get_vendor_path().ok()?; - let mut metadata = Metadata::default(); - for (name, dep) in dependencies { - metadata.packages.insert( - name.replace('-', "_").to_string(), - Package { - name: name.to_string(), - manifest_path: match self.get_local_path_from_lock_dep(dep) { - Some(path) => vendor.join(path), - None => "".into(), - }, - }, - ); - } - return Some(metadata); - } - } - None - } -} diff --git a/kclvm/driver/src/lib.rs b/kclvm/driver/src/lib.rs deleted file mode 100644 index cedaa6eaa..000000000 --- a/kclvm/driver/src/lib.rs +++ /dev/null @@ -1,476 +0,0 @@ -pub mod arguments; -#[cfg(not(target_arch = "wasm32"))] -pub mod client; -pub mod toolchain; - -#[cfg(test)] -mod tests; - -use anyhow::Result; -use kclvm_config::{ - modfile::{get_pkg_root, load_mod_file, KCL_FILE_EXTENSION, KCL_MOD_FILE, KCL_WORK_FILE}, - settings::{build_settings_pathbuf, DEFAULT_SETTING_FILE}, - workfile::load_work_file, -}; -use kclvm_parser::{get_kcl_files, LoadProgramOptions}; -use kclvm_utils::path::PathPrefix; -use std::iter; -use std::{collections::HashMap, env}; -use std::{ - collections::HashSet, - fs::read_dir, - io::{self, ErrorKind}, - path::{Path, PathBuf}, -}; -use toolchain::{fill_pkg_maps_for_k_file, Metadata, Toolchain}; -use walkdir::WalkDir; - -/// Get compile workspace(files and options) from a single file input. -/// 1. Lookup entry files in kcl.yaml -/// 2. Lookup entry files in kcl.mod -/// 3. If not found, consider the path or folder where the file is -/// located as the compilation entry point -pub fn lookup_compile_workspace( - tool: &dyn Toolchain, - file: &str, - load_pkg: bool, -) -> CompileUnitOptions { - fn default_res(tool: &dyn Toolchain, file: &str, load_pkg: bool) -> CompileUnitOptions { - let mut default_res: CompileUnitOptions = (vec![], None, None); - let mut load_opt = kclvm_parser::LoadProgramOptions::default(); - let metadata = fill_pkg_maps_for_k_file(tool, file.into(), &mut load_opt).unwrap_or(None); - let path = Path::new(file); - if let Some(ext) = path.extension() { - if load_pkg { - if let Some(parent) = path.parent() { - if let Ok(files) = get_kcl_files(parent, false) { - default_res = (files, Some(load_opt), metadata); - } - } - } else { - if ext == KCL_FILE_EXTENSION && path.is_file() { - default_res = (vec![file.to_string()], Some(load_opt), metadata); - } - } - } - default_res - } - - match lookup_compile_unit_path(file) { - Ok(CompileUnitPath::SettingFile(dir)) => { - let settings_files = lookup_setting_files(&dir); - let files = if settings_files.is_empty() { - default_res(tool, file, load_pkg) - .0 - .iter() - .map(|s| s.clone()) - .collect() - } else { - vec![] - }; - let files: Vec<&str> = files.iter().map(|s| s.as_str()).collect(); - let settings_files: Vec<&str> = - settings_files.iter().map(|f| f.to_str().unwrap()).collect(); - match build_settings_pathbuf(&files, Some(settings_files), None) { - Ok(setting_buf) => { - let setting = setting_buf.settings(); - let files = setting.input(); - - let work_dir = setting_buf - .path() - .clone() - .map(|p| p.to_string_lossy().to_string()) - .unwrap_or_default(); - - let mut load_opt = kclvm_parser::LoadProgramOptions { - work_dir: work_dir.clone(), - ..Default::default() - }; - let metadata = - fill_pkg_maps_for_k_file(tool, file.into(), &mut load_opt).unwrap_or(None); - if files.is_empty() { - default_res(tool, file, load_pkg) - } else { - (files, Some(load_opt), metadata) - } - } - Err(_) => default_res(tool, file, load_pkg), - } - } - Ok(CompileUnitPath::ModFile(dir)) => match load_mod_file(&dir) { - Ok(mod_file) => { - let mut load_opt = kclvm_parser::LoadProgramOptions::default(); - let metadata = - fill_pkg_maps_for_k_file(tool, file.into(), &mut load_opt).unwrap_or(None); - if let Some(files) = mod_file.get_entries() { - let work_dir = dir.to_string_lossy().to_string(); - load_opt.work_dir = work_dir.clone(); - (files, Some(load_opt), metadata) - } else { - default_res(tool, file, load_pkg) - } - } - Err(_) => default_res(tool, file, load_pkg), - }, - Ok(CompileUnitPath::NotFound) | Err(_) => default_res(tool, file, load_pkg), - } -} - -pub fn lookup_compile_workspaces( - tool: &dyn Toolchain, - path: &str, - load_pkg: bool, -) -> ( - HashMap, - Option>, -) { - let mut workspaces = HashMap::new(); - match lookup_workspace(path) { - Ok(workspace) => match &workspace { - WorkSpaceKind::WorkFile(work_file_path) => { - if let Ok(mut workfile) = load_work_file(work_file_path) { - let root = work_file_path.parent().unwrap(); - workfile.canonicalize(root.to_path_buf()); - for work in workfile.workspaces { - match lookup_workspace(&work.abs_path) { - Ok(workspace) => { - workspaces.insert( - workspace.clone(), - lookup_compile_workspace(tool, &work.abs_path, load_pkg), - ); - } - Err(_) => {} - } - } - return (workspaces, Some(workfile.failed.clone())); - } - } - WorkSpaceKind::Folder(folder) => { - let load_opt = kclvm_parser::LoadProgramOptions::default(); - let metadata = None; - - if load_pkg { - if folder.is_dir() { - if let Ok(files) = get_kcl_files(folder.clone(), false) { - match lookup_the_nearest_file_dir(folder.to_path_buf(), KCL_MOD_FILE) { - Some(dir) => { - let nearest_mod = dir.join(KCL_MOD_FILE); - let (_, opt, metadata) = lookup_compile_workspace( - tool, - &nearest_mod.adjust_canonicalization(), - load_pkg, - ); - workspaces.insert(workspace, (files, opt, metadata)); - } - None => { - workspaces.insert(workspace, (files, Some(load_opt), metadata)); - } - } - return (workspaces, None); - } - } - } - workspaces.insert( - workspace, - (vec![path.to_string()], Some(load_opt), metadata), - ); - } - WorkSpaceKind::SettingFile(setting_file) => { - workspaces.insert( - workspace.clone(), - lookup_compile_workspace( - tool, - &setting_file.as_path().adjust_canonicalization(), - load_pkg, - ), - ); - } - WorkSpaceKind::ModFile(mod_file) => { - workspaces.insert( - workspace.clone(), - lookup_compile_workspace( - tool, - &mod_file.as_path().adjust_canonicalization(), - load_pkg, - ), - ); - } - WorkSpaceKind::File(_) | WorkSpaceKind::NotFound => { - let pathbuf = PathBuf::from(path); - let file_path = pathbuf.as_path(); - if file_path.is_file() { - workspaces.insert(workspace, lookup_compile_workspace(tool, path, load_pkg)); - } - } - }, - Err(_) => {} - } - - (workspaces, None) -} - -/// Lookup default setting files e.g. kcl.yaml -pub fn lookup_setting_files(dir: &Path) -> Vec { - let mut settings = vec![]; - if let Ok(p) = lookup_kcl_yaml(dir) { - settings.push(p); - } - settings -} - -fn lookup_kcl_yaml(dir: &Path) -> io::Result { - let mut path = dir.to_path_buf(); - path.push(DEFAULT_SETTING_FILE); - if path.is_file() { - Ok(path) - } else { - Err(io::Error::new( - ErrorKind::NotFound, - "Ran out of places to find kcl.yaml", - )) - } -} - -pub type CompileUnitOptions = (Vec, Option, Option); - -/// CompileUnitPath is the kcl program default entries that are defined -/// in the config files. -#[derive(Debug, PartialEq, Eq, Clone)] -pub enum CompileUnitPath { - SettingFile(PathBuf), - ModFile(PathBuf), - NotFound, -} - -/// LSP workspace, will replace CompileUnitPath -#[derive(Debug, PartialEq, Eq, Clone, Hash)] -pub enum WorkSpaceKind { - WorkFile(PathBuf), - ModFile(PathBuf), - SettingFile(PathBuf), - Folder(PathBuf), - File(PathBuf), - NotFound, -} - -/// For the KCL project, some definitions may be introduced through multi-file -/// compilation (kcl.yaml). This function is used to start from a single file and try -/// to find a `compile unit` that contains all definitions -/// Given a file path, search for the nearest "kcl.yaml" file or the nearest "kcl.mod" file. -/// If a "kcl.yaml" file is found, return the path of the directory containing the file. -/// If a "kcl.mod" file is found, return the path of the directory containing the file. -/// If none of these files are found, return an error indicating that the files were not found. -/// -/// Example: -/// +-- project -/// | +-- base -/// | | +-- base.k -/// | +-- prod -/// | | +-- main.k -/// | | +-- kcl.yaml -/// | +-- test -/// | | +-- main.k -/// | | +-- kcl.yaml -/// | +-- kcl.mod -/// -/// If the input file is project/prod/main.k or project/test/main.k, it will return -/// Path("project/prod") or Path("project/test") -pub fn lookup_compile_unit_path(file: &str) -> io::Result { - let path = PathBuf::from(file); - let current_dir_path = path.as_path().parent().unwrap(); - let entries = read_dir(current_dir_path)?; - for entry in entries { - let entry = entry?; - // The entry priority of `kcl.yaml`` is higher than that of `kcl.mod`. - if entry.file_name() == *DEFAULT_SETTING_FILE { - // If find "kcl.yaml", the input file is in a compile stack, return the - // path of this compile stack - return Ok(CompileUnitPath::SettingFile(PathBuf::from( - current_dir_path, - ))); - } else if entry.file_name() == *KCL_MOD_FILE { - return Ok(CompileUnitPath::ModFile(PathBuf::from(current_dir_path))); - } - } - Ok(CompileUnitPath::NotFound) -} - -/// It will replace lookup_compile_unit_path() -pub fn lookup_workspace(path: &str) -> io::Result { - let pathbuf = PathBuf::from(path); - let path = pathbuf.as_path(); - if path.is_dir() { - for entry in read_dir(path)? { - let entry = entry?; - if entry.file_name() == *KCL_WORK_FILE { - return Ok(WorkSpaceKind::WorkFile(entry.path())); - } - } - - for entry in read_dir(path)? { - let entry = entry?; - if entry.file_name() == *KCL_MOD_FILE { - return Ok(WorkSpaceKind::ModFile(entry.path())); - } - } - - for entry in read_dir(path)? { - let entry = entry?; - if entry.file_name() == *DEFAULT_SETTING_FILE { - return Ok(WorkSpaceKind::SettingFile(entry.path())); - } - } - - return Ok(WorkSpaceKind::Folder(PathBuf::from(path))); - } - if path.is_file() { - if let Some(ext) = path.extension() { - if ext.to_str().unwrap() == KCL_FILE_EXTENSION { - return Ok(WorkSpaceKind::File(PathBuf::from(path))); - } - } - } - Ok(WorkSpaceKind::NotFound) -} - -/// Get the package string list form the package path. -pub fn get_pkg_list(pkgpath: &str) -> Result> { - let mut dir_list: Vec = Vec::new(); - let mut dir_map: HashSet = HashSet::new(); - let cwd = std::env::current_dir()?; - - let pkgpath = if pkgpath.is_empty() { - cwd.to_string_lossy().to_string() - } else { - pkgpath.to_string() - }; - - let include_sub_pkg = pkgpath.ends_with("/..."); - let pkgpath = if include_sub_pkg { - pkgpath.trim_end_matches("/...").to_string() - } else { - pkgpath - }; - - if pkgpath != "." && pkgpath.ends_with('.') { - return Ok(Vec::new()); - } - - if pkgpath.is_empty() { - return Ok(Vec::new()); - } - - match pkgpath.chars().next() { - Some('.') => { - let pkgpath = Path::new(&cwd).join(&pkgpath); - pkgpath.to_string_lossy().to_string() - } - _ => { - if Path::new(&pkgpath).is_absolute() { - pkgpath.clone() - } else if !pkgpath.contains('/') && !pkgpath.contains('\\') { - pkgpath.replace('.', "/") - } else { - let pkgroot = - get_pkg_root(cwd.to_str().ok_or(anyhow::anyhow!("cwd path not found"))?) - .unwrap_or_default(); - if !pkgroot.is_empty() { - PathBuf::from(pkgroot) - .join(&pkgpath) - .to_string_lossy() - .to_string() - } else { - Path::new(&cwd).join(&pkgpath).to_string_lossy().to_string() - } - } - } - }; - - if !include_sub_pkg { - return Ok(vec![pkgpath]); - } - - for entry in WalkDir::new(&pkgpath).into_iter().filter_map(|e| e.ok()) { - let path = entry.path(); - if !path.is_dir() - && path.extension().and_then(|ext| ext.to_str()) == Some(KCL_FILE_EXTENSION) - && !path - .file_name() - .map(|name| name.to_string_lossy().starts_with('_')) - .unwrap_or(false) - { - if let Some(dir) = path.parent().map(|p| p.to_string_lossy().to_string()) { - if !dir_map.contains(&dir) { - dir_list.push(dir.clone()); - dir_map.insert(dir); - } - } - } - } - - Ok(dir_list) -} - -/// [`lookup_the_nearest_file_dir`] will start from [`from`] and search for file [`the_nearest_file`] in the parent directories. -/// If found, it will return the [`Some`] of [`the_nearest_file`] file path. If not found, it will return [`None`] -pub(crate) fn lookup_the_nearest_file_dir( - from: PathBuf, - the_nearest_file: &str, -) -> Option { - let mut current_dir = from; - - loop { - let found_path = current_dir.join(the_nearest_file); - if found_path.is_file() { - return current_dir.canonicalize().ok(); - } - - match current_dir.parent() { - Some(parent) => current_dir = parent.to_path_buf(), - None => return None, - } - } -} - -/// [`kcl`] will return the path for executable kcl binary. -pub fn kcl() -> PathBuf { - get_path_for_executable("kcl") -} - -/// [`get_path_for_executable`] will return the path for [`executable_name`]. -pub fn get_path_for_executable(executable_name: &'static str) -> PathBuf { - // The current implementation checks $PATH for an executable to use: - // `` - // example: for , this tries just , which will succeed if is on the $PATH - - if lookup_in_path(executable_name) { - return executable_name.into(); - } - - executable_name.into() -} - -/// [`lookup_in_path`] will search for an executable file [`exec`] in the environment variable ‘PATH’. -/// If found, return true, otherwise return false. -fn lookup_in_path(exec: &str) -> bool { - let paths = env::var_os("PATH").unwrap_or_default(); - env::split_paths(&paths) - .map(|path| path.join(exec)) - .find_map(probe) - .is_some() -} - -/// [`probe`] check if the given path points to a file. -/// If it does, return [`Some`] of the path. -/// If not, check if adding the current operating system's executable file extension (if any) to the path points to a file. -/// If it does, return [`Some`] of the path with the extension added. -/// If neither, return [`None`]. -fn probe(path: PathBuf) -> Option { - let with_extension = match env::consts::EXE_EXTENSION { - "" => None, - it => Some(path.with_extension(it)), - }; - iter::once(path) - .chain(with_extension) - .find(|it| it.is_file()) -} diff --git a/kclvm/driver/src/test_data/kpm_metadata/kcl.mod.lock b/kclvm/driver/src/test_data/kpm_metadata/kcl.mod.lock deleted file mode 100644 index 4dc847701..000000000 --- a/kclvm/driver/src/test_data/kpm_metadata/kcl.mod.lock +++ /dev/null @@ -1,7 +0,0 @@ -[dependencies] - [dependencies.flask_manifests] - name = "flask_manifests" - full_name = "flask_manifests_0.0.1" - version = "0.0.1" - url = "https://github.com/kcl-lang/flask-demo-kcl-manifests.git" - commit = "ade147b" diff --git a/kclvm/driver/src/test_data/kpm_metadata_with_line/dep-with-line/kcl.mod.lock b/kclvm/driver/src/test_data/kpm_metadata_with_line/dep-with-line/kcl.mod.lock deleted file mode 100644 index e69de29bb..000000000 diff --git a/kclvm/driver/src/test_data/kpm_metadata_with_line/main_pkg/kcl.mod.lock b/kclvm/driver/src/test_data/kpm_metadata_with_line/main_pkg/kcl.mod.lock deleted file mode 100644 index 8165e52f9..000000000 --- a/kclvm/driver/src/test_data/kpm_metadata_with_line/main_pkg/kcl.mod.lock +++ /dev/null @@ -1,5 +0,0 @@ -[dependencies] - [dependencies.dep-with-line] - name = "dep-with-line" - full_name = "dep-with-line_0.0.1" - version = "0.0.1" diff --git a/kclvm/driver/src/test_data/test_vendor/.kpm/config/kpm.json b/kclvm/driver/src/test_data/test_vendor/.kpm/config/kpm.json deleted file mode 100644 index c2aa99813..000000000 --- a/kclvm/driver/src/test_data/test_vendor/.kpm/config/kpm.json +++ /dev/null @@ -1 +0,0 @@ -{"DefaultOciRegistry":"ghcr.io","DefaultOciRepo":"kcl-lang"} \ No newline at end of file diff --git a/kclvm/driver/src/test_data/test_vendor/.kpm/config/package-cache b/kclvm/driver/src/test_data/test_vendor/.kpm/config/package-cache deleted file mode 100644 index e69de29bb..000000000 diff --git a/kclvm/driver/src/test_data/test_vendor/kcl4_v0.0.1/kcl.mod.lock b/kclvm/driver/src/test_data/test_vendor/kcl4_v0.0.1/kcl.mod.lock deleted file mode 100644 index e69de29bb..000000000 diff --git a/kclvm/driver/src/tests.rs b/kclvm/driver/src/tests.rs deleted file mode 100644 index e98fddcf1..000000000 --- a/kclvm/driver/src/tests.rs +++ /dev/null @@ -1,372 +0,0 @@ -use std::path::PathBuf; -use std::{env, fs, panic}; - -use kclvm_config::modfile::get_vendor_home; -use kclvm_config::settings::KeyValuePair; -use kclvm_parser::LoadProgramOptions; -use walkdir::WalkDir; - -use crate::arguments::parse_key_value_pair; -use crate::toolchain::Toolchain; -use crate::toolchain::{fill_pkg_maps_for_k_file, CommandToolchain, NativeToolchain}; -use crate::{get_pkg_list, lookup_the_nearest_file_dir, toolchain}; - -#[test] -fn test_parse_key_value_pair() { - let cases = [ - ( - "k=v", - KeyValuePair { - key: "k".to_string(), - value: "\"v\"".into(), - }, - ), - ( - "k=1", - KeyValuePair { - key: "k".to_string(), - value: "1".into(), - }, - ), - ( - "k=None", - KeyValuePair { - key: "k".to_string(), - value: "null".into(), - }, - ), - ( - "k=True", - KeyValuePair { - key: "k".to_string(), - value: "true".into(), - }, - ), - ( - "k=true", - KeyValuePair { - key: "k".to_string(), - value: "true".into(), - }, - ), - ( - "k={\"key\": \"value\"}", - KeyValuePair { - key: "k".to_string(), - value: "{\"key\": \"value\"}".into(), - }, - ), - ( - "k=[1, 2, 3]", - KeyValuePair { - key: "k".to_string(), - value: "[1, 2, 3]".into(), - }, - ), - ]; - for (value, pair) in cases { - let result = parse_key_value_pair(value).unwrap(); - assert_eq!(result.key, pair.key); - assert_eq!(result.value, pair.value); - } -} - -fn clear_path(path: PathBuf) { - WalkDir::new(path) - .into_iter() - .filter_map(|e| e.ok()) - .for_each(|e| { - fs::remove_file(e.path()) - .or_else(|_| fs::remove_dir(e.path())) - .ok(); - }); -} - -#[test] -fn test_parse_key_value_pair_fail() { - let cases = ["=v", "k=", "="]; - for case in cases { - assert!(parse_key_value_pair(case).is_err()); - } -} - -fn test_fill_pkg_maps_for_k_file_with_line() { - let root_path = PathBuf::from(".") - .join("src") - .join("test_data") - .join("kpm_metadata_with_line"); - - let main_pkg_path = root_path.join("main_pkg").join("main.k"); - let dep_with_line_path = root_path.join("dep-with-line"); - - let mut opts = LoadProgramOptions::default(); - assert_eq!(format!("{:?}", opts.package_maps), "{}"); - - let res = fill_pkg_maps_for_k_file(&toolchain::default(), main_pkg_path.clone(), &mut opts); - assert!(res.is_ok()); - - let pkg_maps = opts.package_maps.clone(); - assert_eq!(pkg_maps.len(), 1); - assert!(pkg_maps.get("dep_with_line").is_some()); - - assert_eq!( - PathBuf::from(pkg_maps.get("dep_with_line").unwrap().clone()) - .canonicalize() - .unwrap() - .display() - .to_string(), - dep_with_line_path - .canonicalize() - .unwrap() - .display() - .to_string() - ); -} - -#[test] -fn test_native_fill_pkg_maps_for_k_file_with_line() { - let root_path = PathBuf::from(".") - .join("src") - .join("test_data") - .join("kpm_metadata_with_line"); - - let main_pkg_path = root_path.join("main_pkg").join("main.k"); - let dep_with_line_path = root_path.join("dep-with-line"); - - let mut opts = LoadProgramOptions::default(); - assert_eq!(format!("{:?}", opts.package_maps), "{}"); - - let res = fill_pkg_maps_for_k_file( - &NativeToolchain::default(), - main_pkg_path.clone(), - &mut opts, - ); - assert!(res.is_ok()); - - let pkg_maps = opts.package_maps.clone(); - assert_eq!(pkg_maps.len(), 1); - assert!(pkg_maps.get("dep_with_line").is_some()); - - assert_eq!( - PathBuf::from(pkg_maps.get("dep_with_line").unwrap().clone()) - .canonicalize() - .unwrap() - .display() - .to_string(), - dep_with_line_path - .canonicalize() - .unwrap() - .display() - .to_string() - ); -} - -fn test_fill_pkg_maps_for_k_file() { - let path = PathBuf::from(".") - .join("src") - .join("test_data") - .join("kpm_metadata") - .join("subdir") - .join("main.k"); - - let vendor_path = PathBuf::from(".") - .join("src") - .join("test_data") - .join("test_vendor"); - - env::set_var( - "KCL_PKG_PATH", - vendor_path.canonicalize().unwrap().display().to_string(), - ); - - let mut opts = LoadProgramOptions::default(); - assert_eq!(format!("{:?}", opts.package_maps), "{}"); - - let res = fill_pkg_maps_for_k_file(&toolchain::default(), path.clone(), &mut opts); - assert!(res.is_ok()); - let vendor_home = get_vendor_home(); - - let pkg_maps = opts.package_maps.clone(); - assert_eq!(pkg_maps.len(), 1); - assert!(pkg_maps.get("flask_manifests").is_some()); - assert_eq!( - PathBuf::from(pkg_maps.get("flask_manifests").unwrap().clone()) - .canonicalize() - .unwrap() - .display() - .to_string(), - PathBuf::from(vendor_home) - .join("flask-demo-kcl-manifests_ade147b") - .canonicalize() - .unwrap() - .display() - .to_string() - ); - - clear_path(vendor_path.join(".kpm")) -} - -#[test] -fn test_lookup_the_nearest_file_dir() { - let path = PathBuf::from(".") - .join("src") - .join("test_data") - .join("kpm_metadata"); - let result = lookup_the_nearest_file_dir(path.clone(), "kcl.mod"); - assert!(result.is_some()); - assert_eq!( - result.unwrap().display().to_string(), - path.canonicalize().unwrap().display().to_string() - ); - - let main_path = path.join("subdir").join("main.k"); - let result = lookup_the_nearest_file_dir(main_path, "kcl.mod"); - assert!(result.is_some()); - assert_eq!( - result.unwrap().display().to_string(), - path.canonicalize().unwrap().display().to_string() - ); -} - -#[test] -fn test_fetch_metadata_in_order() { - test_cmd_tool_fetch_metadata(); - println!("test_cmd_tool_fetch_metadata() passed"); - test_native_tool_fetch_metadata(); - println!("test_native_tool_fetch_metadata() passed"); - test_fill_pkg_maps_for_k_file(); - println!("test_fill_pkg_maps_for_k_file() passed"); - test_native_fill_pkg_maps_for_k_file_with_line(); - println!("test_native_fill_pkg_maps_for_k_file_with_line() passed"); - test_fill_pkg_maps_for_k_file_with_line(); - println!("test_fill_pkg_maps_for_k_file_with_line() passed"); - test_native_update_dependencies(); - println!("test_native_update_dependencies() passed"); - test_update_dependencies(); - println!("test_update_dependencies() passed"); -} - -fn test_cmd_tool_fetch_metadata() { - test_tool_fetch_metadata(CommandToolchain::default()) -} - -fn test_native_tool_fetch_metadata() { - test_tool_fetch_metadata(NativeToolchain::default()) -} - -fn test_tool_fetch_metadata(tool: impl Toolchain) { - let path = PathBuf::from(".") - .join("src") - .join("test_data") - .join("kpm_metadata"); - - let vendor_path = PathBuf::from(".") - .join("src") - .join("test_data") - .join("test_vendor"); - - env::set_var( - "KCL_PKG_PATH", - vendor_path.canonicalize().unwrap().display().to_string(), - ); - let vendor_home = get_vendor_home(); - let metadata = tool.fetch_metadata(path.clone()); - let pkgs = metadata.unwrap().packages.clone(); - assert_eq!(pkgs.len(), 1); - assert!(pkgs.get("flask_manifests").is_some()); - assert_eq!(pkgs.get("flask_manifests").unwrap().name, "flask_manifests"); - - let manifest_path = pkgs.get("flask_manifests").unwrap().manifest_path.clone(); - println!("Manifest path: {:?}", manifest_path); - - let canonicalized_manifest_path = manifest_path.canonicalize(); - println!( - "Canonicalized manifest path: {:?}", - canonicalized_manifest_path - ); - - assert_eq!( - canonicalized_manifest_path.unwrap().display().to_string(), - PathBuf::from(vendor_home) - .join("flask-demo-kcl-manifests_ade147b") - .canonicalize() - .unwrap() - .display() - .to_string() - ); - clear_path(vendor_path.join(".kpm")) -} - -#[test] -fn test_fetch_metadata_invalid() { - let result = panic::catch_unwind(|| { - let tool = toolchain::default(); - let result = tool.fetch_metadata("invalid_path".to_string().into()); - match result { - Ok(_) => { - panic!("The method should not return Ok") - } - Err(_) => { - println!("return with an error.") - } - } - }); - - match result { - Ok(_) => println!("no panic"), - Err(e) => panic!("The method should not panic forever.: {:?}", e), - } -} - -#[test] -fn test_native_fetch_metadata_invalid() { - let result = panic::catch_unwind(|| { - let tool = NativeToolchain::default(); - let result = tool.fetch_metadata("invalid_path".to_string().into()); - match result { - Ok(_) => { - panic!("The method should not return Ok") - } - Err(_) => { - println!("return with an error.") - } - } - }); - - match result { - Ok(_) => println!("no panic"), - Err(e) => panic!("The method should not panic forever.: {:?}", e), - } -} - -#[test] -fn test_get_pkg_list() { - assert_eq!(get_pkg_list("./src/test_data/pkg_list/").unwrap().len(), 1); - assert_eq!( - get_pkg_list("./src/test_data/pkg_list/...").unwrap().len(), - 3 - ); -} - -fn test_update_dependencies() { - let path = PathBuf::from(".") - .join("src") - .join("test_data") - .join("kpm_update"); - - let tool = toolchain::default(); - let update_mod = tool.update_dependencies(path.clone()); - // Show more information when the test fails. - println!("{:?}", update_mod); - assert!(update_mod.is_ok()); -} - -fn test_native_update_dependencies() { - let path = PathBuf::from(".") - .join("src") - .join("test_data") - .join("kpm_update"); - - let tool = NativeToolchain::default(); - tool.update_dependencies(path.clone()).unwrap(); -} diff --git a/kclvm/error/Cargo.lock b/kclvm/error/Cargo.lock deleted file mode 100644 index b74f9b8ee..000000000 --- a/kclvm/error/Cargo.lock +++ /dev/null @@ -1,1186 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "ahash" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" -dependencies = [ - "getrandom", - "once_cell", - "version_check", -] - -[[package]] -name = "aho-corasick" -version = "0.7.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" -dependencies = [ - "memchr", -] - -[[package]] -name = "annotate-snippets" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78ea013094e5ea606b1c05fe35f1dd7ea1eb1ea259908d040b25bd5ec677ee5" - -[[package]] -name = "arrayvec" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" - -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi", - "libc", - "winapi", -] - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "base64" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" - -[[package]] -name = "bit-set" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e11e16035ea35e4e5997b393eacbf6f63983188f7a2ad25bfb13465f5ad59de" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "generic-array", -] - -[[package]] -name = "block-buffer" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bstr" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" -dependencies = [ - "lazy_static", - "memchr", - "regex-automata", -] - -[[package]] -name = "cc" -version = "1.0.73" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "chrono" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" -dependencies = [ - "libc", - "num-integer", - "num-traits", - "time", - "winapi", -] - -[[package]] -name = "cpufeatures" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b" -dependencies = [ - "libc", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" -dependencies = [ - "cfg-if 1.0.0", - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1145cf131a2c6ba0615079ab6a638f7e1973ac9c2634fcbeaaad6114246efe8c" -dependencies = [ - "autocfg", - "cfg-if 1.0.0", - "crossbeam-utils", - "lazy_static", - "memoffset", - "scopeguard", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf124c720b7686e3c2663cf54062ab0f68a88af2fb6a030e87e30bf721fcb38" -dependencies = [ - "cfg-if 1.0.0", - "lazy_static", -] - -[[package]] -name = "crypto-common" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "digest" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" -dependencies = [ - "generic-array", -] - -[[package]] -name = "digest" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506" -dependencies = [ - "block-buffer 0.10.2", - "crypto-common", -] - -[[package]] -name = "either" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" - -[[package]] -name = "ena" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7402b94a93c24e742487327a7cd839dc9d36fec9de9fb25b09f2dae459f36c3" -dependencies = [ - "log", -] - -[[package]] -name = "fancy-regex" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d6b8560a05112eb52f04b00e5d3790c0dd75d9d980eb8a122fb23b92a623ccf" -dependencies = [ - "bit-set", - "regex", -] - -[[package]] -name = "fastrand" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf" -dependencies = [ - "instant", -] - -[[package]] -name = "generic-array" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "wasi", -] - -[[package]] -name = "hashbrown" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" - -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - -[[package]] -name = "indexmap" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" -dependencies = [ - "autocfg", - "hashbrown", - "rustc-rayon", -] - -[[package]] -name = "instant" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "itertools" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112c678d4050afce233f4f2852bb2eb519230b3cf12f33585275537d7e41578d" - -[[package]] -name = "jobserver" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af25a77299a7f711a01975c35a6a424eb6862092cc2d6c72c4ed6cbc56dfc1fa" -dependencies = [ - "libc", -] - -[[package]] -name = "json_minimal" -version = "0.1.3" - -[[package]] -name = "kclvm-error" -version = "0.1.0" -dependencies = [ - "annotate-snippets", - "atty", - "indexmap", - "kclvm-runtime", - "kclvm-span", - "rustc_span", - "termcolor", - "termize", - "tracing", -] - -[[package]] -name = "kclvm-macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "kclvm-runtime" -version = "0.1.0" -dependencies = [ - "ahash", - "base64", - "bstr", - "chrono", - "fancy-regex", - "indexmap", - "itertools", - "json_minimal", - "kclvm_runtime_internal_macros", - "libc", - "md5", - "num-integer", - "phf", - "regex", - "serde", - "serde_json", - "serde_yaml", - "sha1", - "sha2 0.9.9", - "unic-ucd-bidi", - "unic-ucd-category", - "unicode-casing", -] - -[[package]] -name = "kclvm-span" -version = "0.1.0" -dependencies = [ - "kclvm-macros", - "rustc_span", - "scoped-tls", -] - -[[package]] -name = "kclvm_runtime_internal_macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.122" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec647867e2bf0772e28c8bcde4f0d19a9216916e890543b5a03ed8ef27b8f259" - -[[package]] -name = "linked-hash-map" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3" - -[[package]] -name = "lock_api" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" -dependencies = [ - "autocfg", - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6389c490849ff5bc16be905ae24bc913a9c8892e19b2341dbc175e14c341c2b8" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "matches" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" - -[[package]] -name = "md-5" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "658646b21e0b72f7866c7038ab086d3d5e1cd6271f060fd37defb241949d0582" -dependencies = [ - "digest 0.10.3", -] - -[[package]] -name = "md5" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" - -[[package]] -name = "memchr" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" - -[[package]] -name = "memmap2" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "723e3ebdcdc5c023db1df315364573789f8857c11b631a2fdfad7c00f5c046b4" -dependencies = [ - "libc", -] - -[[package]] -name = "memoffset" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num-integer" -version = "0.1.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" -dependencies = [ - "autocfg", - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_cpus" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "once_cell" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225" - -[[package]] -name = "opaque-debug" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" - -[[package]] -name = "parking_lot" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f5ec2493a61ac0506c0f4199f99070cbe83857b0337006a30f3e6719b8ef58" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "995f667a6c822200b0433ac218e05582f0e2efa1b922a3fd2fbaadc5f87bab37" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "redox_syscall", - "smallvec", - "windows-sys", -] - -[[package]] -name = "phf" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2ac8b67553a7ca9457ce0e526948cad581819238f4a9d1ea74545851fa24f37" -dependencies = [ - "phf_macros", - "phf_shared", - "proc-macro-hack", -] - -[[package]] -name = "phf_generator" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43f3220d96e0080cc9ea234978ccd80d904eafb17be31bb0f76daaea6493082" -dependencies = [ - "phf_shared", - "rand", -] - -[[package]] -name = "phf_macros" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b706f5936eb50ed880ae3009395b43ed19db5bff2ebd459c95e7bf013a89ab86" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro-hack", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "phf_shared" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a68318426de33640f02be62b4ae8eb1261be2efbc337b60c54d845bf4484e0d9" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e280fbe77cc62c91527259e9442153f4688736748d24660126286329742b4c6c" - -[[package]] -name = "ppv-lite86" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" - -[[package]] -name = "proc-macro-hack" -version = "0.5.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" - -[[package]] -name = "proc-macro2" -version = "1.0.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "psm" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "871372391786ccec00d3c5d3d6608905b3d4db263639cfe075d3b60a736d115a" -dependencies = [ - "cc", -] - -[[package]] -name = "quote" -version = "1.0.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "632d02bff7f874a36f33ea8bb416cd484b90cc66c1194b1a1110d067a7013f58" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha", - "rand_core", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" -dependencies = [ - "getrandom", -] - -[[package]] -name = "redox_syscall" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" -dependencies = [ - "bitflags", -] - -[[package]] -name = "regex" -version = "1.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83f127d94bdbcda4c8cc2e50f6f84f4b611f69c902699ca385a39c3a75f9ff1" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" - -[[package]] -name = "regex-syntax" -version = "0.6.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49b3de9ec5dc0a3417da371aab17d729997c15010e7fd24ff707773a33bddb64" - -[[package]] -name = "remove_dir_all" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" -dependencies = [ - "winapi", -] - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - -[[package]] -name = "rustc-rayon" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9974ab223660e61c1b4e7b43b827379df286736ca988308ce7e16f59f2d89246" -dependencies = [ - "crossbeam-deque", - "either", - "rustc-rayon-core", -] - -[[package]] -name = "rustc-rayon-core" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "564bfd27be8db888d0fa76aa4335e7851aaed0c2c11ad1e93aeb9349f6b88500" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", - "lazy_static", - "num_cpus", -] - -[[package]] -name = "rustc_data_structures" -version = "0.0.0" -dependencies = [ - "arrayvec", - "bitflags", - "cfg-if 0.1.10", - "ena", - "indexmap", - "jobserver", - "libc", - "memmap2", - "parking_lot", - "rustc-hash", - "rustc-rayon", - "rustc-rayon-core", - "stable_deref_trait", - "stacker", - "tempfile", - "tracing", - "winapi", -] - -[[package]] -name = "rustc_span" -version = "0.0.0" -dependencies = [ - "cfg-if 0.1.10", - "md-5", - "rustc_data_structures", - "scoped-tls", - "sha-1", - "sha2 0.10.2", - "tracing", - "unicode-width", -] - -[[package]] -name = "ryu" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3f6f92acf49d1b98f7a81226834412ada05458b7364277387724a237f062695" - -[[package]] -name = "scoped-tls" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" - -[[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - -[[package]] -name = "serde" -version = "1.0.137" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.137" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.81" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b7ce2b32a1aed03c558dc61a5cd328f15aff2dbc17daad8fb8af04d2100e15c" -dependencies = [ - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_yaml" -version = "0.8.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707d15895415db6628332b737c838b88c598522e4dc70647e59b72312924aebc" -dependencies = [ - "indexmap", - "ryu", - "serde", - "yaml-rust", -] - -[[package]] -name = "sha-1" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.3", -] - -[[package]] -name = "sha1" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" -dependencies = [ - "sha1_smol", -] - -[[package]] -name = "sha1_smol" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" - -[[package]] -name = "sha2" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.9.0", - "opaque-debug", -] - -[[package]] -name = "sha2" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.3", -] - -[[package]] -name = "siphasher" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bd3e3206899af3f8b12af284fafc038cc1dc2b41d1b89dd17297221c5d225de" - -[[package]] -name = "smallvec" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83" - -[[package]] -name = "stable_deref_trait" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" - -[[package]] -name = "stacker" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90939d5171a4420b3ff5fbc8954d641e7377335454c259dcb80786f3f21dc9b4" -dependencies = [ - "cc", - "cfg-if 1.0.0", - "libc", - "psm", - "winapi", -] - -[[package]] -name = "syn" -version = "1.0.91" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "synstructure" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "unicode-xid", -] - -[[package]] -name = "tempfile" -version = "3.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" -dependencies = [ - "cfg-if 1.0.0", - "fastrand", - "libc", - "redox_syscall", - "remove_dir_all", - "winapi", -] - -[[package]] -name = "termcolor" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "termize" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1706be6b564323ce7092f5f7e6b118a14c8ef7ed0e69c8c5329c914a9f101295" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "time" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" -dependencies = [ - "libc", - "wasi", - "winapi", -] - -[[package]] -name = "tracing" -version = "0.1.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a1bdf54a7c28a2bbf701e1d2233f6c77f473486b94bee4f9678da5a148dca7f" -dependencies = [ - "cfg-if 1.0.0", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e65ce065b4b5c53e73bb28912318cb8c9e9ad3921f1d669eb0e68b4c8143a2b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tracing-core" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90442985ee2f57c9e1b548ee72ae842f4a9a20e3f417cc38dbc5dc684d9bb4ee" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "typenum" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" - -[[package]] -name = "unic-char-property" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" -dependencies = [ - "unic-char-range", -] - -[[package]] -name = "unic-char-range" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" - -[[package]] -name = "unic-common" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" - -[[package]] -name = "unic-ucd-bidi" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1d568b51222484e1f8209ce48caa6b430bf352962b877d592c29ab31fb53d8c" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-category" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b8d4591f5fcfe1bd4453baaf803c40e1b1e69ff8455c47620440b46efef91c0" -dependencies = [ - "matches", - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-version" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" -dependencies = [ - "unic-common", -] - -[[package]] -name = "unicode-casing" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "623f59e6af2a98bdafeb93fa277ac8e1e40440973001ca15cf4ae1541cd16d56" - -[[package]] -name = "unicode-width" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" - -[[package]] -name = "unicode-xid" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "wasi" -version = "0.10.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" -dependencies = [ - "winapi", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-sys" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5acdd78cb4ba54c0045ac14f62d8f94a03d10047904ae2a40afa1e99d8f70825" -dependencies = [ - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17cffbe740121affb56fad0fc0e421804adf0ae00891205213b5cecd30db881d" - -[[package]] -name = "windows_i686_gnu" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2564fde759adb79129d9b4f54be42b32c89970c18ebf93124ca8870a498688ed" - -[[package]] -name = "windows_i686_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cd9d32ba70453522332c14d38814bceeb747d80b3958676007acadd7e166956" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfce6deae227ee8d356d19effc141a509cc503dfd1f850622ec4b0f84428e1f4" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d19538ccc21819d01deaf88d6a17eae6596a12e9aafdbb97916fb49896d89de9" - -[[package]] -name = "yaml-rust" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" -dependencies = [ - "linked-hash-map", -] diff --git a/kclvm/error/Cargo.toml b/kclvm/error/Cargo.toml deleted file mode 100644 index 18413f2c6..000000000 --- a/kclvm/error/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "kclvm-error" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -compiler_base_span = "0.1.2" -compiler_base_session = "0.1.3" -compiler_base_error = "0.1.6" -compiler_base_macros = "0.1.1" - -kclvm-primitives = { path = "../primitives" } -kclvm-span = { path = "../span" } -kclvm-runtime = { path = "../runtime" } -kclvm-utils = { path = "../utils" } - -anyhow = "1.0" -tracing = "0.1" -annotate-snippets = { version = "0.9.2", default-features = false, features = [ - "color", -] } -serde = { version = "1.0", features = ["derive"] } -termize = "0.1.1" -serde_json = "1.0" -thiserror = "2.0.17" diff --git a/kclvm/error/src/lib.rs b/kclvm/error/src/lib.rs deleted file mode 100644 index e70fa3f92..000000000 --- a/kclvm/error/src/lib.rs +++ /dev/null @@ -1,618 +0,0 @@ -//! Diagnostics creation and emission for `KCLVM`. -//! This module contains the code for creating and emitting diagnostics. -//! -//! We can use `Handler` to create and emit diagnostics. - -pub mod diagnostic; -mod error; - -use annotate_snippets::{ - display_list::DisplayList, - display_list::FormatOptions, - snippet::{AnnotationType, Slice, Snippet, SourceAnnotation}, -}; -use anyhow::Result; -use compiler_base_error::errors::ComponentFormatError; -use compiler_base_error::StyledBuffer; -use compiler_base_error::{ - components::{CodeSnippet, Label}, - Component, Diagnostic as DiagnosticTrait, DiagnosticStyle, -}; -use compiler_base_session::{Session, SessionDiagnostic}; -use compiler_base_span::{span::new_byte_pos, Span}; -use diagnostic::Range; -use kclvm_primitives::{DefaultHashBuilder, IndexSet}; -use kclvm_runtime::PanicInfo; -use std::{any::Any, sync::Arc}; -use thiserror::Error; - -pub use diagnostic::{Diagnostic, DiagnosticId, Level, Message, Position, Style}; -pub use error::*; - -/// A handler deals with errors and other compiler output. -/// Certain errors (error, bug) may cause immediate exit, -/// others log errors for later reporting. -#[derive(Clone, Debug, PartialEq, Eq, Default)] -pub struct Handler { - pub diagnostics: IndexSet, -} - -impl Handler { - /// New a handler using a emitter - pub fn new() -> Self { - Self { - diagnostics: Default::default(), - } - } - - /// Panic program and report a bug - #[inline] - pub fn bug(&self, msg: &str) -> ! { - compiler_base_macros::bug!("{}", msg) - } - - #[inline] - pub fn has_errors(&self) -> bool { - self.diagnostics - .iter() - .any(|diag| diag.level == Level::Error) - } - - /// Emit all diagnostics and return whether has errors. - pub fn emit(&mut self) -> Result { - let sess = Session::default(); - for diag in &self.diagnostics { - sess.add_err(diag.clone())?; - } - sess.emit_stashed_diagnostics()?; - Ok(self.has_errors()) - } - - /// Emit diagnostic to string. - pub fn emit_to_string(&mut self) -> Result { - let sess = Session::default(); - for diag in &self.diagnostics { - sess.add_err(diag.clone())?; - } - let errors = sess.emit_all_diags_into_string()?; - let mut error_strings = vec![]; - for error in errors { - error_strings.push(error?); - } - Ok(error_strings.join("\n")) - } - - /// Emit all diagnostics and abort if has any errors. - pub fn abort_if_any_errors(&mut self) { - match self.emit() { - Ok(has_error) => { - if has_error { - std::process::exit(1); - } - } - Err(err) => self.bug(&format!("{err}")), - } - } - - /// Construct a parse error and put it into the handler diagnostic buffer - pub fn add_syntex_error(&mut self, msg: &str, range: Range) -> &mut Self { - let message = format!("Invalid syntax: {msg}"); - let diag = Diagnostic::new_with_code( - Level::Error, - &message, - None, - range, - Some(DiagnosticId::Error(E1001.kind)), - None, - ); - self.add_diagnostic(diag); - - self - } - - /// Construct a type error and put it into the handler diagnostic buffer - pub fn add_type_error(&mut self, msg: &str, range: Range) -> &mut Self { - let diag = Diagnostic::new_with_code( - Level::Error, - msg, - None, - range, - Some(DiagnosticId::Error(E2G22.kind)), - None, - ); - self.add_diagnostic(diag); - - self - } - - /// Construct a type error and put it into the handler diagnostic buffer - pub fn add_compile_error(&mut self, msg: &str, range: Range) -> &mut Self { - self.add_compile_error_with_suggestions(msg, range, None) - } - - pub fn add_compile_error_with_suggestions( - &mut self, - msg: &str, - range: Range, - suggestions: Option>, - ) -> &mut Self { - let diag = Diagnostic::new_with_code( - Level::Error, - msg, - None, - range, - Some(DiagnosticId::Error(E2L23.kind)), - suggestions, - ); - self.add_diagnostic(diag); - - self - } - - /// Put a runtime panic info the handler diagnostic buffer. - pub fn add_panic_info(&mut self, panic_info: &PanicInfo) -> &mut Self { - self.add_diagnostic(panic_info.clone().into()); - - self - } - - /// Add an error into the handler - /// ``` - /// use kclvm_error::*; - /// let mut handler = Handler::default(); - /// handler.add_error(ErrorKind::InvalidSyntax, &[ - /// Message { - /// range: (Position::dummy_pos(), Position::dummy_pos()), - /// style: Style::LineAndColumn, - /// message: "Invalid syntax: expected '+', got '-'".to_string(), - /// note: None, - /// suggested_replacement: None, - /// } - /// ]); - /// ``` - pub fn add_error(&mut self, err: ErrorKind, msgs: &[Message]) -> &mut Self { - let diag = Diagnostic { - level: Level::Error, - messages: msgs.to_owned(), - code: Some(DiagnosticId::Error(err)), - }; - self.add_diagnostic(diag); - - self - } - - pub fn add_suggestions(&mut self, msgs: Vec) -> &mut Self { - msgs.iter().for_each(|s| { - self.add_diagnostic(Diagnostic { - level: Level::Suggestions, - messages: vec![Message { - range: Range::default(), - style: Style::Line, - message: s.to_string(), - note: None, - suggested_replacement: None, - }], - code: Some(DiagnosticId::Suggestions), - }); - }); - - self - } - - /// Add an warning into the handler - /// ``` - /// use kclvm_error::*; - /// let mut handler = Handler::default(); - /// handler.add_warning(WarningKind::UnusedImportWarning, &[ - /// Message { - /// range: (Position::dummy_pos(), Position::dummy_pos()), - /// style: Style::LineAndColumn, - /// message: "Module 'a' imported but unused.".to_string(), - /// note: None, - /// suggested_replacement: None, - /// }], - /// ); - /// ``` - pub fn add_warning(&mut self, warning: WarningKind, msgs: &[Message]) -> &mut Self { - let diag = Diagnostic { - level: Level::Warning, - messages: msgs.to_owned(), - code: Some(DiagnosticId::Warning(warning)), - }; - self.add_diagnostic(diag); - - self - } - - /// Classify diagnostics into errors and warnings. - pub fn classification(&self) -> (IndexSet, IndexSet) { - let (mut errs, mut warnings) = ( - IndexSet::with_hasher(DefaultHashBuilder::default()), - IndexSet::with_hasher(DefaultHashBuilder::default()), - ); - for diag in &self.diagnostics { - if diag.level == Level::Error || diag.level == Level::Suggestions { - errs.insert(diag.clone()); - } else if diag.level == Level::Warning { - warnings.insert(diag.clone()); - } else { - continue; - } - } - (errs, warnings) - } - - /// Store a diagnostics into the handler. - /// - /// # Example - /// - /// ``` - /// use kclvm_error::*; - /// let mut handler = Handler::default(); - /// handler.add_diagnostic(Diagnostic::new_with_code(Level::Error, "error message", None, (Position::dummy_pos(), Position::dummy_pos()), Some(DiagnosticId::Error(E1001.kind)), None)); - /// ``` - #[inline] - pub fn add_diagnostic(&mut self, diagnostic: Diagnostic) -> &mut Self { - self.diagnostics.insert(diagnostic); - - self - } -} - -impl From for Diagnostic { - fn from(panic_info: PanicInfo) -> Self { - let panic_msg = if panic_info.kcl_arg_msg.is_empty() { - &panic_info.message - } else { - &panic_info.kcl_arg_msg - }; - - let mut diag = if panic_info.backtrace.is_empty() { - let pos = Position { - filename: panic_info.kcl_file.clone(), - line: panic_info.kcl_line as u64, - column: None, - }; - Diagnostic::new_with_code( - Level::Error, - panic_msg, - None, - (pos.clone(), pos), - None, - None, - ) - } else { - let mut backtrace_msg = "backtrace:\n".to_string(); - let mut backtrace = panic_info.backtrace.clone(); - backtrace.reverse(); - for (index, frame) in backtrace.iter().enumerate() { - backtrace_msg.push_str(&format!( - "\t{index}: {}\n\t\tat {}:{}", - frame.func, frame.file, frame.line - )); - if frame.col != 0 { - backtrace_msg.push_str(&format!(":{}", frame.col)) - } - backtrace_msg.push('\n') - } - let pos = Position { - filename: panic_info.kcl_file.clone(), - line: panic_info.kcl_line as u64, - column: None, - }; - Diagnostic::new_with_code( - Level::Error, - panic_msg, - Some(&backtrace_msg), - (pos.clone(), pos), - None, - None, - ) - }; - - if panic_info.kcl_config_meta_file.is_empty() { - return diag; - } - let pos = Position { - filename: panic_info.kcl_config_meta_file.clone(), - line: panic_info.kcl_config_meta_line as u64, - column: Some(panic_info.kcl_config_meta_col as u64), - }; - let mut config_meta_diag = Diagnostic::new_with_code( - Level::Error, - &panic_info.kcl_config_meta_arg_msg, - None, - (pos.clone(), pos), - None, - None, - ); - config_meta_diag.messages.append(&mut diag.messages); - config_meta_diag - } -} - -#[derive(Error, Debug, Clone)] -pub enum ParseErrorMessage { - #[error("invalid token '!', consider using 'not '")] - InvalidTokenNot, - #[error("'else if' here is invalid in KCL, consider using the 'elif' keyword")] - InvalidTokenElseIf, - #[error("unterminated string")] - UnterminatedString, - #[error("unexpected character after line continuation character")] - CharAfterLineContinuationToken, - #[error("the semicolon ';' here is unnecessary, please remove it")] - RedundantSemicolon, - #[error("expected expression, got {0}")] - ExpectExpr(String), - #[error("invalid string interpolation expression: '{0}'")] - InvalidStringInterpolationExpr(String), - #[error("invalid joined string spec without #")] - InvalidJoinedStringSpec, - #[error("invalid joined string")] - InvalidJoinedStringExpr, -} - -#[derive(Debug, Clone)] -pub enum ParseError { - UnexpectedToken { - expected: Vec, - got: String, - span: Span, - }, - Message { - message: ParseErrorMessage, - span: Span, - suggestions: Option>, - }, - String { - message: String, - span: Span, - }, -} - -/// A single string error. -pub struct StringError(pub String); - -impl ParseError { - /// New a unexpected token parse error with span and token information. - pub fn unexpected_token(expected: &[&str], got: &str, span: Span) -> Self { - ParseError::UnexpectedToken { - expected: expected - .iter() - .map(|v| v.to_string()) - .collect::>(), - got: got.to_string(), - span, - } - } - - /// New a message parse error with span. - pub fn message( - message: ParseErrorMessage, - span: Span, - suggestions: Option>, - ) -> Self { - ParseError::Message { - message, - span, - suggestions, - } - } -} - -impl ParseError { - /// Convert a parse error into an error diagnostic. - pub fn into_diag(self, sess: &Session) -> Result { - let span = match self { - ParseError::UnexpectedToken { span, .. } => span, - ParseError::Message { span, .. } => span, - ParseError::String { span, .. } => span, - }; - let start_pos = sess.sm.lookup_char_pos(span.lo()).into(); - let end_pos = sess.sm.lookup_char_pos(span.hi()).into(); - let suggestions = match &self { - ParseError::Message { suggestions, .. } => suggestions.clone(), - _ => None, - }; - Ok(Diagnostic::new_with_code( - Level::Error, - &self.to_string(), - None, - (start_pos, end_pos), - Some(DiagnosticId::Error(ErrorKind::InvalidSyntax)), - suggestions, - )) - } -} - -impl ToString for ParseError { - fn to_string(&self) -> String { - match self { - ParseError::UnexpectedToken { expected, got, .. } => { - format!("expected one of {expected:?} got {got}") - } - ParseError::Message { message, .. } => message.to_string(), - ParseError::String { message, .. } => message.to_string(), - } - } -} - -impl SessionDiagnostic for ParseError { - fn into_diagnostic(self, sess: &Session) -> Result> { - let mut diag = DiagnosticTrait::::new(); - diag.append_component(Box::new(Label::Error(E1001.code.to_string()))); - diag.append_component(Box::new(": invalid syntax\n".to_string())); - match self { - ParseError::UnexpectedToken { span, .. } => { - let code_snippet = CodeSnippet::new(span, Arc::clone(&sess.sm)); - diag.append_component(Box::new(code_snippet)); - diag.append_component(Box::new(format!(" {}\n", self.to_string()))); - Ok(diag) - } - ParseError::Message { message, span, .. } => { - let code_snippet = CodeSnippet::new(span, Arc::clone(&sess.sm)); - diag.append_component(Box::new(code_snippet)); - diag.append_component(Box::new(format!(" {message}\n"))); - Ok(diag) - } - ParseError::String { message, span } => { - let code_snippet = CodeSnippet::new(span, Arc::clone(&sess.sm)); - diag.append_component(Box::new(code_snippet)); - diag.append_component(Box::new(format!(" {message}\n"))); - Ok(diag) - } - } - } -} - -#[derive(Default)] -pub struct SuggestionsLabel; - -impl Component for SuggestionsLabel { - fn format(&self, sb: &mut StyledBuffer, _: &mut Vec) { - sb.appendl("suggestion: ", Some(DiagnosticStyle::NeedAttention)); - } -} - -impl SessionDiagnostic for Diagnostic { - fn into_diagnostic(self, _: &Session) -> Result> { - let mut diag = DiagnosticTrait::::new(); - match self.code { - Some(id) => match id { - DiagnosticId::Error(error) => { - diag.append_component(Box::new(Label::Error(error.code()))); - diag.append_component(Box::new(format!(": {}\n", error.name()))); - } - DiagnosticId::Warning(warning) => { - diag.append_component(Box::new(Label::Warning(warning.code()))); - diag.append_component(Box::new(format!(": {}\n", warning.name()))); - } - DiagnosticId::Suggestions => { - diag.append_component(Box::new(SuggestionsLabel)); - } - }, - None => match self.level { - Level::Error => { - diag.append_component(Box::new(format!("{}\n", ErrorKind::EvaluationError))); - } - Level::Warning => { - diag.append_component(Box::new(format!("{}\n", WarningKind::CompilerWarning))); - } - Level::Note => { - diag.append_component(Box::new(Label::Note)); - } - Level::Suggestions => { - diag.append_component(Box::new(SuggestionsLabel)); - } - }, - } - for msg in &self.messages { - match Session::new_with_file_and_code(&msg.range.0.filename, None) { - Ok(sess) => { - let source = sess.sm.lookup_source_file(new_byte_pos(0)); - let line = source.get_line( - (if msg.range.0.line >= 1 { - msg.range.0.line - 1 - } else { - 0 - }) as usize, - ); - match line.as_ref() { - Some(content) => { - let length = content.chars().count(); - let snippet = Snippet { - title: None, - footer: vec![], - slices: vec![Slice { - source: content, - line_start: msg.range.0.line as usize, - origin: Some(&msg.range.0.filename), - annotations: vec![SourceAnnotation { - range: match msg.range.0.column { - Some(column) if length >= 1 => { - let column = column as usize; - // If the position exceeds the length of the content, - // put the annotation at the end of the line. - if column >= length { - (length - 1, length) - } else { - (column, column + 1) - } - } - _ => (0, 0), - }, - label: &msg.message, - annotation_type: AnnotationType::Error, - }], - fold: true, - }], - opt: FormatOptions { - color: true, - anonymized_line_numbers: false, - margin: None, - }, - }; - let dl = DisplayList::from(snippet); - diag.append_component(Box::new(format!("{dl}\n"))); - } - None => { - let info = msg.range.0.info(); - if !info.is_empty() { - diag.append_component(Box::new(format!( - "{}: {}\n", - info, msg.message - ))); - } else { - diag.append_component(Box::new(format!("{}\n", msg.message))); - } - } - }; - } - Err(_) => { - let info = msg.range.0.info(); - if !info.is_empty() { - diag.append_component(Box::new(format!("{}: {}\n", info, msg.message))); - } else { - diag.append_component(Box::new(format!("{}\n", msg.message))); - } - } - }; - if let Some(note) = &msg.note { - diag.append_component(Box::new(Label::Note)); - diag.append_component(Box::new(format!(": {note}\n"))); - } - // Append a new line. - diag.append_component(Box::new(String::from("\n"))); - } - Ok(diag) - } -} - -impl SessionDiagnostic for StringError { - fn into_diagnostic(self, _: &Session) -> Result> { - let mut diag = DiagnosticTrait::::new(); - diag.append_component(Box::new(Label::Error(E3M38.code.to_string()))); - diag.append_component(Box::new(format!(": {}\n", self.0))); - Ok(diag) - } -} - -/// Convert an error to string. -/// -/// ``` -/// use kclvm_error::err_to_str; -/// -/// assert_eq!(err_to_str(Box::new("error_string".to_string())), "error_string"); -/// ``` -pub fn err_to_str(err: Box) -> String { - if let Some(s) = err.downcast_ref::<&str>() { - s.to_string() - } else if let Some(s) = err.downcast_ref::<&String>() { - (*s).clone() - } else if let Some(s) = err.downcast_ref::() { - (*s).clone() - } else { - "".to_string() - } -} diff --git a/kclvm/evaluator/Cargo.toml b/kclvm/evaluator/Cargo.toml deleted file mode 100644 index 61f7bee72..000000000 --- a/kclvm/evaluator/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "kclvm-evaluator" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -anyhow = "1.0" -generational-arena = "0.2.9" -kclvm-ast = { path = "../ast" } -kclvm-sema = { path = "../sema" } -kclvm-runtime = { path = "../runtime" } -kclvm-error = { path = "../error" } -kclvm-primitives = { path = "../primitives" } -scopeguard = "1.2.0" - -[dev-dependencies] -kclvm-parser = { path = "../parser" } -kclvm-loader = { path = "../loader" } -insta = "1.8.0" diff --git a/kclvm/evaluator/src/calculation.rs b/kclvm/evaluator/src/calculation.rs deleted file mode 100644 index c526e632a..000000000 --- a/kclvm/evaluator/src/calculation.rs +++ /dev/null @@ -1,327 +0,0 @@ -/* Calculation methods */ - -use kclvm_ast::ast; -use kclvm_runtime::{ConfigEntryOperationKind, DictValue, UnionOptions, Value, ValueRef}; - -use crate::ty::{resolve_schema, type_pack_and_check}; -use crate::union::union_entry; -use crate::Evaluator; - -impl<'ctx> Evaluator<'ctx> { - /// lhs + rhs - #[inline] - pub(crate) fn add(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.bin_add(&mut self.runtime_ctx.borrow_mut(), &rhs) - } - /// lhs - rhs - #[inline] - pub(crate) fn sub(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.bin_sub(&mut self.runtime_ctx.borrow_mut(), &rhs) - } - /// lhs * rhs - #[inline] - pub(crate) fn mul(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.bin_mul(&mut self.runtime_ctx.borrow_mut(), &rhs) - } - /// lhs / rhs - #[inline] - pub(crate) fn div(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.bin_div(&rhs) - } - /// lhs // rhs - #[inline] - pub(crate) fn floor_div(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.bin_floor_div(&rhs) - } - /// lhs % rhs - #[inline] - pub(crate) fn r#mod(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.bin_mod(&rhs) - } - /// lhs ** rhs - #[inline] - pub(crate) fn pow(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.bin_pow(&mut self.runtime_ctx.borrow_mut(), &rhs) - } - /// lhs << rhs - #[inline] - pub(crate) fn bit_lshift(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.bin_bit_lshift(&mut self.runtime_ctx.borrow_mut(), &rhs) - } - /// lhs >> rhs - #[inline] - pub(crate) fn bit_rshift(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.bin_bit_rshift(&mut self.runtime_ctx.borrow_mut(), &rhs) - } - /// lhs & rhs - #[inline] - pub(crate) fn bit_and(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.bin_bit_and(&rhs) - } - /// lhs | rhs - #[inline] - pub(crate) fn bit_or(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - if let (Value::int_value(a), Value::int_value(b)) = (&*lhs.rc.borrow(), &*rhs.rc.borrow()) { - return ValueRef::int(*a | *b); - }; - union_entry( - self, - &mut lhs.deep_copy(), - &rhs, - true, - &UnionOptions::default(), - ) - } - /// lhs ^ rhs - #[inline] - pub(crate) fn bit_xor(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.bin_bit_xor(&rhs) - } - /// lhs and rhs - #[inline] - pub(crate) fn logic_and(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.logic_and(&rhs).into() - } - /// lhs or rhs - #[inline] - pub(crate) fn logic_or(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.logic_or(&rhs).into() - } - /// lhs == rhs - #[inline] - pub(crate) fn cmp_equal_to(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.cmp_equal(&rhs).into() - } - /// lhs != rhs - #[inline] - pub(crate) fn cmp_not_equal_to(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.cmp_not_equal(&rhs).into() - } - /// lhs > rhs - #[inline] - pub(crate) fn cmp_greater_than(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.cmp_greater_than(&rhs).into() - } - /// lhs >= rhs - #[inline] - pub(crate) fn cmp_greater_than_or_equal(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.cmp_greater_than_or_equal(&rhs).into() - } - /// lhs < rhs - #[inline] - pub(crate) fn cmp_less_than(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.cmp_less_than(&rhs).into() - } - /// lhs <= rhs - #[inline] - pub(crate) fn cmp_less_than_or_equal(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.cmp_less_than_or_equal(&rhs).into() - } - /// lhs as rhs - #[inline] - pub(crate) fn r#as(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - type_pack_and_check(self, &lhs, vec![&rhs.as_str()], true) - } - /// lhs is rhs - #[inline] - pub(crate) fn is(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - (lhs == rhs).into() - } - /// lhs is not rhs - #[inline] - pub(crate) fn is_not(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - (lhs != rhs).into() - } - /// lhs in rhs - #[inline] - pub(crate) fn r#in(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.r#in(&rhs).into() - } - /// lhs not in rhs - #[inline] - pub(crate) fn not_in(&self, lhs: ValueRef, rhs: ValueRef) -> ValueRef { - lhs.not_in(&rhs).into() - } -} - -impl<'ctx> Evaluator<'ctx> { - /// Value is truth function, return i1 value. - #[inline] - pub(crate) fn value_is_truthy(&self, value: &ValueRef) -> bool { - value.is_truthy() - } - /// Value deep copy - #[inline] - pub(crate) fn value_deep_copy(&self, value: &ValueRef) -> ValueRef { - value.deep_copy() - } - /// value_union unions two collection elements. - pub(crate) fn value_union(&self, lhs: &mut ValueRef, rhs: &ValueRef) -> ValueRef { - let attr_map = match &*lhs.rc.borrow() { - Value::dict_value(dict) => dict.attr_map.clone(), - Value::schema_value(schema) => schema.config.attr_map.clone(), - _ => panic!("invalid object '{}' in attr_map", lhs.type_str()), - }; - let opts = UnionOptions { - list_override: false, - idempotent_check: false, - config_resolve: true, - }; - if rhs.is_config() { - let dict = rhs.as_dict_ref(); - for k in dict.values.keys() { - let entry = rhs.dict_get_entry(k).unwrap(); - union_entry(self, lhs, &entry, true, &opts); - // Has type annotation - if let Some(ty) = attr_map.get(k) { - let value = lhs.dict_get_value(k).unwrap(); - lhs.dict_update_key_value( - k, - type_pack_and_check(self, &value, vec![ty], false), - ); - } - } - lhs.clone() - } else { - union_entry(self, lhs, rhs, true, &opts) - } - } - /// Append a item into the list. - #[inline] - pub(crate) fn list_append(&self, list: &mut ValueRef, item: &ValueRef) { - list.list_append(item) - } - /// Append a list item and unpack it into the list. - #[inline] - pub(crate) fn list_append_unpack(&self, list: &mut ValueRef, item: &ValueRef) { - list.list_append_unpack(item) - } - #[inline] - pub(crate) fn dict_get_value(&self, dict: &ValueRef, key: &str) -> ValueRef { - dict.dict_get_value(key).unwrap_or(self.undefined_value()) - } - /// Insert a dict entry including key, value, op and insert_index into the dict, - /// and the type of key is `&str` - #[inline] - pub(crate) fn dict_insert( - &self, - dict: &mut ValueRef, - key: &str, - value: &ValueRef, - op: &ast::ConfigEntryOperation, - insert_index: Option, - ) { - let op = match op { - ast::ConfigEntryOperation::Union => ConfigEntryOperationKind::Union, - ast::ConfigEntryOperation::Override => ConfigEntryOperationKind::Override, - ast::ConfigEntryOperation::Insert => ConfigEntryOperationKind::Insert, - }; - self.dict_merge_key_value_pair(dict, key, value, op, insert_index, true); - } - - /// Insert a dict entry including key, value, op and insert_index into the dict, - /// and the type of key is `&str` - #[inline] - pub(crate) fn schema_dict_merge( - &self, - dict: &mut ValueRef, - key: &str, - value: &ValueRef, - op: &ast::ConfigEntryOperation, - insert_index: Option, - ) { - let op = match op { - ast::ConfigEntryOperation::Union => ConfigEntryOperationKind::Union, - ast::ConfigEntryOperation::Override => ConfigEntryOperationKind::Override, - ast::ConfigEntryOperation::Insert => ConfigEntryOperationKind::Insert, - }; - let attr_map = { - match &*dict.rc.borrow() { - Value::dict_value(dict) => dict.attr_map.clone(), - Value::schema_value(schema) => schema.config.attr_map.clone(), - _ => panic!("invalid object '{}' in attr_map", dict.type_str()), - } - }; - if attr_map.contains_key(key) { - let v = type_pack_and_check(self, value, vec![attr_map.get(key).unwrap()], false); - self.dict_merge_key_value_pair(dict, key, &v, op, insert_index, false); - } else { - self.dict_merge_key_value_pair(dict, key, value, op, insert_index, false); - } - } - - /// Insert an entry including key and value into the dict. - #[inline] - pub(crate) fn dict_insert_value(&self, dict: &mut ValueRef, key: &str, value: &ValueRef) { - dict.dict_update_key_value(key, value.clone()) - } - - /// Insert an entry including key and value into the dict, and merge the original entry. - #[inline] - pub(crate) fn dict_insert_merge_value(&self, dict: &mut ValueRef, key: &str, value: &ValueRef) { - self.dict_merge_key_value_pair( - dict, - key, - value, - ConfigEntryOperationKind::Union, - None, - true, - ); - } - - /// Set dict key with the value. When the dict is a schema and resolve schema validations. - pub(crate) fn dict_set_value(&self, p: &mut ValueRef, key: &str, val: &ValueRef) { - if p.is_config() { - p.dict_update_key_value(key, val.clone()); - if p.is_schema() { - let schema: ValueRef; - { - let schema_value = p.as_schema(); - let mut config_keys = schema_value.config_keys.clone(); - config_keys.push(key.to_string()); - schema = resolve_schema(self, p, &config_keys); - } - p.schema_update_with_schema(&schema); - } - } else { - panic!( - "failed to update the dict. An iterable of key-value pairs was expected, but got {}. Check if the syntax for updating the dictionary with the attribute '{}' is correct", - p.type_str(), - key - ); - } - } - - /// Private dict merge key value pair with the idempotent check option - pub(crate) fn dict_merge_key_value_pair( - &self, - p: &mut ValueRef, - key: &str, - v: &ValueRef, - op: ConfigEntryOperationKind, - insert_index: Option, - idempotent_check: bool, - ) { - if p.is_config() { - let mut dict: DictValue = Default::default(); - dict.values.insert(key.to_string(), v.clone()); - dict.ops.insert(key.to_string(), op); - if let Some(index) = insert_index { - dict.insert_indexs.insert(key.to_string(), index); - } - union_entry( - self, - p, - &ValueRef::from(Value::dict_value(Box::new(dict))), - true, - &UnionOptions { - config_resolve: false, - idempotent_check, - ..Default::default() - }, - ); - } else { - panic!("invalid dict insert value: {}", p.type_str()) - } - } -} diff --git a/kclvm/evaluator/src/context.rs b/kclvm/evaluator/src/context.rs deleted file mode 100644 index d968a9cad..000000000 --- a/kclvm/evaluator/src/context.rs +++ /dev/null @@ -1,321 +0,0 @@ -use std::{collections::HashSet, rc::Rc}; - -use generational_arena::Index; -use kclvm_ast::ast; -use kclvm_runtime::{BacktraceFrame, MAIN_PKG_PATH}; - -use crate::{ - error as kcl_error, - func::{FunctionCaller, FunctionEvalContextRef}, - lazy::{BacktrackMeta, Setter, SetterKind}, - proxy::{Frame, Proxy}, - rule::RuleCaller, - schema::SchemaCaller, - EvalContext, Evaluator, LambdaOrSchemaEvalContext, -}; - -impl<'ctx> Evaluator<'ctx> { - /// Current package path - #[inline] - pub(crate) fn current_pkgpath(&self) -> String { - self.pkgpath_stack - .borrow() - .last() - .expect(kcl_error::INTERNAL_ERROR_MSG) - .to_string() - } - - /// Last package path - #[inline] - pub(crate) fn last_pkgpath(&self) -> String { - let len = self.pkgpath_stack.borrow().len(); - self.pkgpath_stack - .borrow() - .get(if len > 2 { len - 2 } else { 2 - len }) - .unwrap_or(&MAIN_PKG_PATH.to_string()) - .to_string() - } - - /// Update current runtime context kcl filename and line - #[inline] - pub(crate) fn update_ctx_panic_info(&self, node: &'ctx ast::Node) { - let mut ctx = self.runtime_ctx.borrow_mut(); - ctx.panic_info.kcl_file = node.filename.clone(); - ctx.panic_info.kcl_line = node.line as i32; - } - - /// Update current AST index. - #[inline] - pub(crate) fn update_ast_id(&self, node: &'ctx ast::Node) { - *self.ast_id.borrow_mut() = node.id.clone(); - } - - /// Push a lambda definition scope into the lambda stack - #[inline] - pub fn push_lambda( - &self, - lambda_ctx: FunctionEvalContextRef, - current_pkgpath: &str, - frame_pkgpath: &str, - level: usize, - ) { - // Capture function schema this reference. - if let Some(this) = &lambda_ctx.this { - self.push_schema(this.eval_ctx()); - } - // Inner scope function calling. - // Note the minimum lambda.ctx.level is 2 for the top level lambda definitions. - if frame_pkgpath == current_pkgpath && level >= lambda_ctx.level { - // The scope cover is [lambda.ctx.level, self.scope_level()] - self.push_scope_cover(lambda_ctx.level, level); - } - self.lambda_stack.borrow_mut().push(lambda_ctx.clone()); - self.ctx_stack - .borrow_mut() - .push(LambdaOrSchemaEvalContext::Lambda(lambda_ctx)); - } - - /// Pop a lambda definition scope. - #[inline] - pub fn pop_lambda( - &self, - lambda_ctx: FunctionEvalContextRef, - current_pkgpath: &str, - frame_pkgpath: &str, - level: usize, - ) { - self.lambda_stack.borrow_mut().pop(); - self.ctx_stack.borrow_mut().pop(); - // Inner scope function calling. - if frame_pkgpath == current_pkgpath && level >= lambda_ctx.level { - self.pop_scope_cover(); - } - // Release function schema this reference. - if lambda_ctx.this.is_some() { - self.pop_schema() - } - } - - #[inline] - pub fn is_in_lambda(&self) -> bool { - !self.lambda_stack.borrow().is_empty() - } - - #[inline] - pub fn last_lambda_ctx(&self) -> Option { - self.lambda_stack.borrow().last().cloned() - } - - #[inline] - pub fn push_schema(&self, v: EvalContext) { - self.schema_stack.borrow_mut().push(v.clone()); - self.ctx_stack - .borrow_mut() - .push(LambdaOrSchemaEvalContext::Schema(v)); - } - - #[inline] - pub fn pop_schema(&self) { - self.schema_stack.borrow_mut().pop(); - self.ctx_stack.borrow_mut().pop(); - } - - #[inline] - pub fn is_in_schema(&self) -> bool { - !self.schema_stack.borrow().is_empty() - } - - #[inline] - pub fn push_schema_expr(&self) { - self.schema_expr_stack.borrow_mut().push(()); - } - - #[inline] - pub fn pop_schema_expr(&self) { - self.schema_expr_stack.borrow_mut().pop(); - } - - #[inline] - pub fn is_in_schema_expr(&self) -> bool { - !self.schema_expr_stack.borrow().is_empty() - } - - #[inline] - pub fn add_local_var(&self, name: &str) { - self.local_vars.borrow_mut().insert(name.to_string()); - } - - #[inline] - pub fn remove_local_var(&self, name: &str) { - self.local_vars.borrow_mut().remove(name); - } - - #[inline] - pub fn is_local_var(&self, name: &str) -> bool { - self.local_vars.borrow().contains(name) - } - - #[inline] - pub(crate) fn clear_local_vars(&self) { - self.local_vars.borrow_mut().clear(); - } - - #[inline] - pub(crate) fn clean_and_cloned_local_vars(&self) -> HashSet { - let mut local_vars = self.local_vars.borrow_mut(); - let r = local_vars.clone(); - local_vars.clear(); - r - } - - #[inline] - pub(crate) fn set_local_vars(&self, vars: HashSet) { - self.local_vars.borrow_mut().extend(vars); - } - - #[inline] - pub(crate) fn add_target_var(&self, name: &str) { - self.target_vars.borrow_mut().push(name.to_string()); - } - - #[inline] - pub(crate) fn pop_target_var(&self) { - self.target_vars.borrow_mut().pop(); - } - - #[inline] - pub(crate) fn get_target_var(&self) -> String { - self.target_vars - .borrow() - .last() - .cloned() - .unwrap_or_default() - } - - #[inline] - pub(crate) fn check_imported(&self, pkgpath: &str) -> bool { - let imported = &mut self.imported.borrow_mut(); - imported.contains(pkgpath) - } - - #[inline] - pub(crate) fn mark_imported(&self, pkgpath: &str) { - let imported = &mut self.imported.borrow_mut(); - (*imported).insert(pkgpath.to_string()); - } - - #[inline] - pub(crate) fn push_pkgpath(&self, pkgpath: &str) { - self.pkgpath_stack.borrow_mut().push(pkgpath.to_string()); - self.runtime_ctx.borrow_mut().set_kcl_pkgpath(pkgpath); - } - - #[inline] - pub(crate) fn pop_pkgpath(&self) { - if let Some(pkgpath) = self.pkgpath_stack.borrow_mut().pop() { - self.runtime_ctx.borrow_mut().set_kcl_pkgpath(&pkgpath); - } - } - - /// Append a global body into the scope. - #[inline] - pub(crate) fn add_global_body(&self, index: usize) -> Index { - let pkgpath = self.current_pkgpath(); - self.frames.borrow_mut().insert(Rc::new(Frame { - pkgpath, - proxy: Proxy::Global(index), - })) - } - - /// Append a function into the scope. - #[inline] - pub(crate) fn add_function(&self, function: FunctionCaller) -> Index { - let pkgpath = self.current_pkgpath(); - self.frames.borrow_mut().insert(Rc::new(Frame { - pkgpath, - proxy: Proxy::Lambda(function), - })) - } - - /// Append a schema into the scope. - #[inline] - pub(crate) fn add_schema(&self, schema: SchemaCaller) -> Index { - let pkgpath = self.current_pkgpath(); - self.frames.borrow_mut().insert(Rc::new(Frame { - pkgpath, - proxy: Proxy::Schema(schema), - })) - } - - /// Append a rule into the scope. - #[inline] - pub(crate) fn add_rule(&self, rule: RuleCaller) -> Index { - let pkgpath = self.current_pkgpath(); - self.frames.borrow_mut().insert(Rc::new(Frame { - pkgpath, - proxy: Proxy::Rule(rule), - })) - } - - pub(crate) fn push_backtrace(&self, frame: &Frame) { - let ctx = &mut self.runtime_ctx.borrow_mut(); - if ctx.cfg.debug_mode { - let backtrace_frame = BacktraceFrame::from_panic_info(&ctx.panic_info); - ctx.backtrace.push(backtrace_frame); - ctx.panic_info.kcl_func = frame.proxy.get_name(); - } - } - - pub(crate) fn pop_backtrace(&self) { - let ctx = &mut self.runtime_ctx.borrow_mut(); - if ctx.cfg.debug_mode { - if let Some(backtrace_frame) = ctx.backtrace.pop() { - ctx.panic_info.kcl_func = backtrace_frame.func; - ctx.panic_info.kcl_line = backtrace_frame.line; - ctx.panic_info.kcl_file = backtrace_frame.file; - } - } - } - - #[inline] - pub(crate) fn push_backtrack_meta(&self, setter: &Setter) { - let meta = &mut self.backtrack_meta.borrow_mut(); - meta.push(BacktrackMeta { - stopped: setter.stopped.clone(), - is_break: false, - kind: setter.kind.clone(), - }); - } - - #[inline] - pub(crate) fn pop_backtrack_meta(&self) { - let meta = &mut self.backtrack_meta.borrow_mut(); - meta.pop(); - } - - #[inline] - pub(crate) fn is_backtrack_only_if(&self) -> bool { - let meta = &mut self.backtrack_meta.borrow_mut(); - match meta.last().map(|m| matches!(m.kind, SetterKind::If)) { - Some(r) => r, - None => false, - } - } - - #[inline] - pub(crate) fn is_backtrack_only_or_else(&self) -> bool { - let meta = &mut self.backtrack_meta.borrow_mut(); - match meta.last().map(|m| matches!(m.kind, SetterKind::OrElse)) { - Some(r) => r, - None => false, - } - } - - pub(crate) fn push_scope_cover(&self, start: usize, stop: usize) { - self.scope_covers.borrow_mut().push((start, stop)); - } - - pub(crate) fn pop_scope_cover(&self) { - self.scope_covers.borrow_mut().pop(); - } -} diff --git a/kclvm/evaluator/src/lib.rs b/kclvm/evaluator/src/lib.rs deleted file mode 100644 index 399ed40c2..000000000 --- a/kclvm/evaluator/src/lib.rs +++ /dev/null @@ -1,243 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -#[cfg(test)] -mod tests; - -mod calculation; -mod context; -mod error; -mod func; -#[macro_use] -mod lazy; -mod module; -mod node; -mod proxy; -mod rule; -mod runtime; -mod schema; -mod scope; -mod ty; -mod union; -mod value; - -extern crate kclvm_error; - -use func::FunctionEvalContextRef; -use generational_arena::{Arena, Index}; -use kclvm_primitives::IndexMap; -use kclvm_runtime::val_plan::KCL_PRIVATE_VAR_PREFIX; -use lazy::{BacktrackMeta, LazyEvalScope}; -use proxy::{Frame, Proxy}; -use rule::RuleEvalContextRef; -use schema::SchemaEvalContextRef; -use scope::Scope; -use std::collections::{HashMap, HashSet}; -use std::panic::RefUnwindSafe; -use std::rc::Rc; -use std::str; -use std::{cell::RefCell, panic::UnwindSafe}; - -use crate::error as kcl_error; -use anyhow::Result; -use kclvm_ast::ast::{self, AstIndex}; -use kclvm_runtime::{Context, ValueRef}; - -/// SCALAR_KEY denotes the temp scalar key for the global variable json plan process. -const SCALAR_KEY: &str = ""; -/// Global level -const GLOBAL_LEVEL: usize = 1; -/// Inner level -const INNER_LEVEL: usize = 2; - -/// The evaluator function result -pub type EvalResult = Result; - -/// The evaluator for the program -pub struct Evaluator<'ctx> { - pub program: &'ctx ast::Program, - /// All frames including functions, schemas and rules - pub frames: RefCell>>, - /// All schema index in the package path, we can find the frame through the index. - pub schemas: RefCell>, - /// Runtime evaluation context. - pub runtime_ctx: Rc>, - /// Package path stack. - pub pkgpath_stack: RefCell>, - /// Filename stack. - pub filename_stack: RefCell>, - /// The names of possible assignment objects for the current instruction. - pub target_vars: RefCell>, - /// Imported package path set to judge is there a duplicate import. - pub imported: RefCell>, - /// The lambda stack index denotes the scope level of the lambda function. - pub lambda_stack: RefCell>, - /// To judge is in the schema statement. - pub schema_stack: RefCell>, - /// Order lambda and schema ctx vec - pub ctx_stack: RefCell>, - /// To judge is in the schema expression. - pub schema_expr_stack: RefCell>, - /// Import names mapping - pub import_names: RefCell>>, - /// Package scope to store variable values. - pub pkg_scopes: RefCell>>, - /// Package lazy scope to store variable cached values. - pub lazy_scopes: RefCell>, - /// Scope cover to block the acquisition of certain scopes. - pub scope_covers: RefCell>, - /// Local variables in the loop. - pub local_vars: RefCell>, - /// Schema attr backtrack meta. - pub backtrack_meta: RefCell>, - /// Current AST id for the evaluator walker. - pub ast_id: RefCell, -} - -#[derive(Clone)] -pub enum LambdaOrSchemaEvalContext { - Schema(EvalContext), - Lambda(FunctionEvalContextRef), -} - -#[derive(Clone)] -pub enum EvalContext { - Schema(SchemaEvalContextRef), - Rule(RuleEvalContextRef), -} - -impl EvalContext { - #[inline] - pub fn value(&self) -> ValueRef { - match self { - EvalContext::Schema(schema) => schema.borrow().value.clone(), - EvalContext::Rule(rule) => rule.borrow().value.clone(), - } - } - - #[inline] - pub fn config(&self) -> ValueRef { - match self { - EvalContext::Schema(schema) => schema.borrow().config.clone(), - EvalContext::Rule(rule) => rule.borrow().config.clone(), - } - } -} - -impl<'ctx> Evaluator<'ctx> { - /// New aa Evaluator using the AST program - #[inline] - pub fn new(program: &'ctx ast::Program) -> Evaluator<'ctx> { - Self::new_with_runtime_ctx(program, Rc::new(RefCell::new(Context::new()))) - } - - /// New aa Evaluator using the AST program and runtime context - #[inline] - pub fn new_with_runtime_ctx( - program: &'ctx ast::Program, - runtime_ctx: Rc>, - ) -> Evaluator<'ctx> { - Evaluator { - runtime_ctx, - program, - frames: RefCell::new(Arena::new()), - schemas: RefCell::new(Default::default()), - target_vars: RefCell::new(vec![]), - lambda_stack: RefCell::new(vec![]), - imported: RefCell::new(Default::default()), - schema_stack: RefCell::new(Default::default()), - schema_expr_stack: RefCell::new(Default::default()), - pkgpath_stack: RefCell::new(vec![kclvm_ast::MAIN_PKG.to_string()]), - filename_stack: RefCell::new(Default::default()), - import_names: RefCell::new(Default::default()), - pkg_scopes: RefCell::new(Default::default()), - lazy_scopes: RefCell::new(Default::default()), - scope_covers: RefCell::new(Default::default()), - local_vars: RefCell::new(Default::default()), - backtrack_meta: RefCell::new(Default::default()), - ast_id: RefCell::new(AstIndex::default()), - ctx_stack: RefCell::new(Default::default()), - } - } - - /// Evaluate the program and return the JSON and YAML result. - pub fn run(self: &Evaluator<'ctx>) -> Result<(String, String)> { - let modules = self.program.get_modules_for_pkg(kclvm_ast::MAIN_PKG); - self.init_scope(kclvm_ast::MAIN_PKG); - self.compile_ast_modules(&modules); - Ok(self.plan_globals_to_string()) - } - - /// Evaluate the program with the function mode and return the JSON and YAML result, - /// which means treating the files in the entire main package as a function run to - /// return the result of the function run, rather than a dictionary composed of each - /// configuration attribute. - pub fn run_as_function(self: &Evaluator<'ctx>) -> ValueRef { - let modules = self.program.get_modules_for_pkg(kclvm_ast::MAIN_PKG); - if modules.is_empty() { - ValueRef::undefined() - } else { - self.init_scope(kclvm_ast::MAIN_PKG); - self.compile_ast_modules(&modules) - } - } - - /// Plan globals to a planed json and yaml string. - pub(crate) fn plan_globals_to_string(&self) -> (String, String) { - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = &self.pkg_scopes.borrow(); - let scopes = pkg_scopes - .get(¤t_pkgpath) - .unwrap_or_else(|| panic!("pkgpath {} is not found", current_pkgpath)); - // The global scope. - let scope = scopes.last().expect(kcl_error::INTERNAL_ERROR_MSG); - let scalars = &scope.scalars; - let globals = &scope.variables; - // Construct a plan object. - let mut global_dict = self.dict_value(); - // Plan empty dict result. - if scalars.is_empty() && globals.is_empty() { - return self.plan_value(&global_dict); - } - // Deal scalars - for scalar in scalars.iter() { - self.dict_insert_merge_value(&mut global_dict, SCALAR_KEY, scalar); - } - // Deal global variables - for (name, value) in globals.iter() { - if name.starts_with(KCL_PRIVATE_VAR_PREFIX) - && !self.runtime_ctx.borrow().plan_opts.show_hidden - { - continue; - } - let mut value_dict = self.dict_value(); - self.dict_insert_merge_value(&mut value_dict, name.as_str(), value); - self.dict_insert_merge_value(&mut global_dict, SCALAR_KEY, &value_dict); - } - // Plan result to JSON and YAML string. - match global_dict.dict_get_value(SCALAR_KEY) { - Some(value) => self.plan_value(&value), - None => self.plan_value(&self.dict_value()), - } - } - - /// Get evaluator default ok result - #[inline] - pub fn ok_result(&self) -> EvalResult { - Ok(self.undefined_value()) - } - - pub fn plan_value(&self, value: &ValueRef) -> (String, String) { - let mut ctx = self.runtime_ctx.borrow_mut(); - let value = match ctx.buffer.custom_manifests_output.clone() { - Some(output) => ValueRef::from_yaml_stream(&mut ctx, &output).unwrap(), - None => value.clone(), - }; - let (json_string, yaml_string) = value.plan(&ctx); - ctx.json_result = json_string.clone(); - ctx.yaml_result = yaml_string.clone(); - (json_string, yaml_string) - } -} - -impl UnwindSafe for Evaluator<'_> {} -impl RefUnwindSafe for Evaluator<'_> {} diff --git a/kclvm/evaluator/src/module.rs b/kclvm/evaluator/src/module.rs deleted file mode 100644 index 61c24ca15..000000000 --- a/kclvm/evaluator/src/module.rs +++ /dev/null @@ -1,108 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. - -use std::sync::{Arc, RwLock}; - -use kclvm_ast::ast; -use kclvm_ast::walker::TypedResultWalker; -use kclvm_runtime::ValueRef; - -use super::Evaluator; -use crate::error as kcl_error; - -impl<'ctx> Evaluator<'_> { - pub fn compile_module_import_and_types(&self, module: &'ctx ast::Module) { - for stmt in &module.body { - match &stmt.node { - ast::Stmt::Import(import_stmt) => { - self.walk_import_stmt(import_stmt) - .expect(kcl_error::RUNTIME_ERROR_MSG); - } - ast::Stmt::Schema(schema_stmt) => { - // Pre define global types with undefined values - self.predefine_global_types(&schema_stmt.name.node); - self.walk_schema_stmt(schema_stmt) - .expect(kcl_error::RUNTIME_ERROR_MSG); - } - ast::Stmt::Rule(rule_stmt) => { - // Pre define global types with undefined values - self.predefine_global_types(&rule_stmt.name.node); - self.walk_rule_stmt(rule_stmt) - .expect(kcl_error::RUNTIME_ERROR_MSG); - } - _ => {} - }; - } - } - - pub fn predefine_global_types(&self, name: &str) { - // Store or add the variable in the scope - let function = self.undefined_value(); - if !self.store_variable(name, function.clone()) { - self.add_variable(name, function); - } - } - - /// Predefine all global variables. - #[inline] - pub(crate) fn predefine_global_vars(&self, module: &'ctx ast::Module) { - self.emit_global_vars(&module.body); - } - - fn emit_global_vars(&self, body: &'ctx [Box>]) { - for stmt in body { - match &stmt.node { - ast::Stmt::Unification(unification_stmt) => { - let names = &unification_stmt.target.node.names; - if names.len() == 1 { - self.add_or_update_global_variable( - &names[0].node, - self.undefined_value(), - false, - ); - } - } - ast::Stmt::Assign(assign_stmt) => { - for target in &assign_stmt.targets { - self.add_or_update_global_variable( - &target.node.get_name(), - self.undefined_value(), - false, - ); - } - } - ast::Stmt::If(if_stmt) => { - self.emit_global_vars(&if_stmt.body); - self.emit_global_vars(&if_stmt.orelse); - } - _ => {} - } - } - } - - /// Compile AST Modules, which requires traversing three times. - /// 1. scan all possible global variables and allocate undefined values to global pointers. - /// 2. build all user-defined schema/rule types. - /// 3. evaluate all codes for the third time. - pub(crate) fn compile_ast_modules(&self, modules: &[Arc>]) -> ValueRef { - // Scan global variables - for ast_module in modules { - let ast_module = ast_module.read().expect("Failed to acquire module lock"); - // Pre define global variables with undefined values - self.predefine_global_vars(&ast_module); - } - // Scan global types - for ast_module in modules { - let ast_module = ast_module.read().expect("Failed to acquire module lock"); - self.compile_module_import_and_types(&ast_module); - } - let mut result = ValueRef::undefined(); - // Compile the ast module in the pkgpath. - for ast_module in modules { - let ast_module = ast_module.read().expect("Failed to acquire module lock"); - result = self - .walk_module(&ast_module) - .expect(kcl_error::RUNTIME_ERROR_MSG); - } - result - } -} diff --git a/kclvm/evaluator/src/node.rs b/kclvm/evaluator/src/node.rs deleted file mode 100644 index 3490e5c62..000000000 --- a/kclvm/evaluator/src/node.rs +++ /dev/null @@ -1,1667 +0,0 @@ -// Copyright The KCL Authors. All rights reserved. - -use std::cell::RefCell; -use std::rc::Rc; -use std::sync::{Arc, RwLock}; - -use anyhow::Ok; -use generational_arena::Index; -use kclvm_ast::ast::{self, CallExpr, ConfigEntry, Module, NodeRef}; -use kclvm_ast::walker::TypedResultWalker; -use kclvm_runtime::{ - schema_assert, schema_runtime_type, ConfigEntryOperationKind, DecoratorValue, RuntimeErrorType, - UnionOptions, ValueRef, PKG_PATH_PREFIX, -}; -use kclvm_sema::{builtin, pkgpath_without_prefix, plugin}; -use scopeguard::defer; - -use crate::error::INTERNAL_ERROR_MSG; -use crate::func::{func_body, FunctionCaller, FunctionEvalContext, FunctionEvalThis}; -use crate::lazy::Setter; -use crate::proxy::Proxy; -use crate::rule::{rule_body, rule_check, RuleCaller, RuleEvalContext}; -use crate::runtime::invoke_function; -use crate::schema::{schema_body, schema_check, SchemaCaller, SchemaEvalContext}; -use crate::ty::type_pack_and_check; -use crate::union::union_entry; -use crate::{backtrack_break_here, backtrack_update_break}; -use crate::{error as kcl_error, GLOBAL_LEVEL, INNER_LEVEL}; -use crate::{EvalResult, Evaluator}; - -/// Impl TypedResultWalker for Evaluator to visit AST nodes to evaluate the result. -impl<'ctx> TypedResultWalker<'ctx> for Evaluator<'ctx> { - type Result = EvalResult; - - /* - * Stmt - */ - - fn walk_stmt(&self, stmt: &'ctx ast::Node) -> Self::Result { - backtrack_break_here!(self, stmt); - self.update_ctx_panic_info(stmt); - self.update_ast_id(stmt); - let value = match &stmt.node { - ast::Stmt::TypeAlias(type_alias) => self.walk_type_alias_stmt(type_alias), - ast::Stmt::Expr(expr_stmt) => self.walk_expr_stmt(expr_stmt), - ast::Stmt::Unification(unification_stmt) => { - self.walk_unification_stmt(unification_stmt) - } - ast::Stmt::Assign(assign_stmt) => self.walk_assign_stmt(assign_stmt), - ast::Stmt::AugAssign(aug_assign_stmt) => self.walk_aug_assign_stmt(aug_assign_stmt), - ast::Stmt::Assert(assert_stmt) => self.walk_assert_stmt(assert_stmt), - ast::Stmt::If(if_stmt) => self.walk_if_stmt(if_stmt), - ast::Stmt::Import(import_stmt) => self.walk_import_stmt(import_stmt), - ast::Stmt::SchemaAttr(schema_attr) => self.walk_schema_attr(schema_attr), - ast::Stmt::Schema(schema_stmt) => self.walk_schema_stmt(schema_stmt), - ast::Stmt::Rule(rule_stmt) => self.walk_rule_stmt(rule_stmt), - }; - backtrack_update_break!(self, stmt); - value - } - - fn walk_expr_stmt(&self, expr_stmt: &'ctx ast::ExprStmt) -> Self::Result { - let mut result = self.ok_result(); - for expr in &expr_stmt.exprs { - let scalar = self.walk_expr(expr)?; - // Only non-call expressions are allowed to emit values because of the function void return type. - if !matches!(expr.node, ast::Expr::Call(_)) { - self.add_scalar(scalar.clone(), matches!(expr.node, ast::Expr::Schema(_))); - } - result = Ok(scalar); - } - result - } - - fn walk_unification_stmt(&self, unification_stmt: &'ctx ast::UnificationStmt) -> Self::Result { - self.clear_local_vars(); - let name = &unification_stmt.target.node.names[0].node; - self.add_target_var(name); - // The right value of the unification_stmt is a schema_expr. - let value = self.walk_schema_expr(&unification_stmt.value.node)?; - // Load the identifier value - let org_value = self - .walk_identifier_with_ctx(&unification_stmt.target.node, &ast::ExprContext::Load, None) - .unwrap_or(self.undefined_value()); - let value = self.bit_or(org_value, value); - // Store the identifier value - self.walk_identifier_with_ctx( - &unification_stmt.target.node, - &ast::ExprContext::Store, - Some(value.clone()), - )?; - self.pop_target_var(); - Ok(value) - } - - fn walk_type_alias_stmt(&self, _type_alias_stmt: &'ctx ast::TypeAliasStmt) -> Self::Result { - // Nothing to do, because all type aliases have been replaced at compile time - self.ok_result() - } - - fn walk_assign_stmt(&self, assign_stmt: &'ctx ast::AssignStmt) -> Self::Result { - self.clear_local_vars(); - // Set target vars. - for name in &assign_stmt.targets { - self.add_target_var(&name.node.name.node) - } - // Load the right value - let mut value = self.walk_expr(&assign_stmt.value)?; - // Runtime type cast if exists the type annotation. - if let Some(ty) = &assign_stmt.ty { - value = type_pack_and_check(self, &value, vec![&ty.node.to_string()], false); - } - if assign_stmt.targets.len() == 1 { - // Store the single target - let name = &assign_stmt.targets[0]; - self.walk_target_with_value(&name.node, value.clone())?; - } else { - // Store multiple targets - for name in &assign_stmt.targets { - let value = self.value_deep_copy(&value); - self.walk_target_with_value(&name.node, value.clone())?; - } - } - // Pop target vars. - for _ in &assign_stmt.targets { - self.pop_target_var(); - } - Ok(value) - } - - fn walk_aug_assign_stmt(&self, aug_assign_stmt: &'ctx ast::AugAssignStmt) -> Self::Result { - self.add_target_var(&aug_assign_stmt.target.node.name.node); - // Load the right value - let right_value = self.walk_expr(&aug_assign_stmt.value)?; - // Load the identifier value - let org_value = self.load_target(&aug_assign_stmt.target.node)?; - let value = match aug_assign_stmt.op { - ast::AugOp::Add => self.add(org_value, right_value), - ast::AugOp::Sub => self.sub(org_value, right_value), - ast::AugOp::Mul => self.mul(org_value, right_value), - ast::AugOp::Div => self.div(org_value, right_value), - ast::AugOp::Mod => self.r#mod(org_value, right_value), - ast::AugOp::Pow => self.pow(org_value, right_value), - ast::AugOp::LShift => self.bit_lshift(org_value, right_value), - ast::AugOp::RShift => self.bit_rshift(org_value, right_value), - ast::AugOp::BitOr => self.bit_or(org_value, right_value), - ast::AugOp::BitXor => self.bit_xor(org_value, right_value), - ast::AugOp::BitAnd => self.bit_and(org_value, right_value), - ast::AugOp::FloorDiv => self.floor_div(org_value, right_value), - ast::AugOp::Assign => { - return Err(anyhow::anyhow!(kcl_error::INVALID_OPERATOR_MSG)); - } - }; - // Store the target value - self.walk_target_with_value(&aug_assign_stmt.target.node, value.clone())?; - self.pop_target_var(); - Ok(value) - } - - fn walk_assert_stmt(&self, assert_stmt: &'ctx ast::AssertStmt) -> Self::Result { - let do_assert = || { - let assert_result = self - .walk_expr(&assert_stmt.test) - .expect(kcl_error::RUNTIME_ERROR_MSG); - // Assert statement error message. - let msg = { - if let Some(msg) = &assert_stmt.msg { - self.walk_expr(msg).expect(kcl_error::RUNTIME_ERROR_MSG) - } else { - self.string_value("") - } - }; - if !assert_result.is_truthy() { - let mut ctx = self.runtime_ctx.borrow_mut(); - ctx.set_err_type(&RuntimeErrorType::AssertionError); - let msg = msg.as_str(); - panic!("{}", msg); - } - }; - if let Some(if_cond) = &assert_stmt.if_cond { - let if_value = self.walk_expr(if_cond)?; - let is_truth = self.value_is_truthy(&if_value); - if is_truth { - do_assert() - } - } else { - do_assert() - } - self.ok_result() - } - - fn walk_if_stmt(&self, if_stmt: &'ctx ast::IfStmt) -> Self::Result { - let cond = self.walk_expr(&if_stmt.cond)?; - let is_truth = self.value_is_truthy(&cond); - // Is backtrack only orelse stmt? - if self.is_backtrack_only_or_else() { - if !is_truth { - self.walk_stmts(&if_stmt.orelse)?; - } - return self.ok_result(); - } - // Is backtrack only if stmt? - if self.is_backtrack_only_if() { - if is_truth { - self.walk_stmts(&if_stmt.body)?; - } - return self.ok_result(); - } - // Normal full if stmt. - if is_truth { - self.walk_stmts(&if_stmt.body)?; - } else { - self.walk_stmts(&if_stmt.orelse)?; - } - self.ok_result() - } - - fn walk_import_stmt(&self, import_stmt: &'ctx ast::ImportStmt) -> Self::Result { - let pkgpath = import_stmt.path.node.as_str(); - // Check if it has already been generated, there is no need to generate code - // for duplicate import statements. - if self.check_imported(pkgpath) { - return self.ok_result(); - } - // Standard or plugin modules. - if builtin::STANDARD_SYSTEM_MODULES.contains(&pkgpath) - || pkgpath.starts_with(plugin::PLUGIN_MODULE_PREFIX) - { - // Nothing to do on the builtin system module import because the check has been done. - return self.ok_result(); - } else { - let pkgpath = format!("{}{}", PKG_PATH_PREFIX, import_stmt.path.node); - if let Some(modules) = self.program.pkgs.get(&import_stmt.path.node) { - self.push_pkgpath(&pkgpath); - self.init_scope(&pkgpath); - let modules: Vec>> = modules - .iter() - .map(|m| { - let m = self - .program - .get_module_ref(&m) - .expect(&format!("module {:?} not found in program", m)); - m - }) - .collect(); - self.compile_ast_modules(&modules); - self.pop_pkgpath(); - } - } - self.mark_imported(pkgpath); - self.ok_result() - } - - fn walk_schema_stmt(&self, schema_stmt: &'ctx ast::SchemaStmt) -> Self::Result { - let body = Arc::new(schema_body); - let check = Arc::new(schema_check); - let caller = SchemaCaller { - ctx: Rc::new(RefCell::new(SchemaEvalContext::new_with_node( - schema_stmt.clone(), - Index::from_raw_parts(self.frames.borrow().len(), 0), - SchemaEvalContext::get_parent_schema(self, &schema_stmt.parent_name), - SchemaEvalContext::get_mixin_schemas(self, &schema_stmt.mixins), - ))), - body, - check, - }; - // Add function to the global state - let index = self.add_schema(caller); - let runtime_type = schema_runtime_type(&schema_stmt.name.node, &self.current_pkgpath()); - let function = self.proxy_function_value_with_type(index, &runtime_type); - // Store or add the variable in the scope - let name = &schema_stmt.name.node; - if !self.store_variable(name, function.clone()) { - self.add_variable(name, function.clone()); - } - self.schemas.borrow_mut().insert(runtime_type, index); - Ok(function) - } - - fn walk_rule_stmt(&self, rule_stmt: &'ctx ast::RuleStmt) -> Self::Result { - let body = Arc::new(rule_body); - let check = Arc::new(rule_check); - let caller = RuleCaller { - ctx: Rc::new(RefCell::new(RuleEvalContext::new_with_node( - rule_stmt.clone(), - ))), - body, - check, - }; - // Add function to the global state - let index = self.add_rule(caller); - let runtime_type = schema_runtime_type(&rule_stmt.name.node, &self.current_pkgpath()); - let function = self.proxy_function_value_with_type(index, &runtime_type); - // Store or add the variable in the scope - let name = &rule_stmt.name.node; - if !self.store_variable(name, function.clone()) { - self.add_variable(name, function.clone()); - } - Ok(function) - } - - /* - * Expr - */ - - fn walk_expr(&self, expr: &'ctx ast::Node) -> Self::Result { - self.update_ctx_panic_info(expr); - match &expr.node { - ast::Expr::Target(target) => self.walk_target(target), - ast::Expr::Identifier(identifier) => self.walk_identifier(identifier), - ast::Expr::Unary(unary_expr) => self.walk_unary_expr(unary_expr), - ast::Expr::Binary(binary_expr) => self.walk_binary_expr(binary_expr), - ast::Expr::If(if_expr) => self.walk_if_expr(if_expr), - ast::Expr::Selector(selector_expr) => self.walk_selector_expr(selector_expr), - ast::Expr::Call(call_expr) => self.walk_call_expr(call_expr), - ast::Expr::Paren(paren_expr) => self.walk_paren_expr(paren_expr), - ast::Expr::Quant(quant_expr) => self.walk_quant_expr(quant_expr), - ast::Expr::List(list_expr) => self.walk_list_expr(list_expr), - ast::Expr::ListIfItem(list_if_item_expr) => { - self.walk_list_if_item_expr(list_if_item_expr) - } - ast::Expr::ListComp(list_comp) => self.walk_list_comp(list_comp), - ast::Expr::Starred(starred_expr) => self.walk_starred_expr(starred_expr), - ast::Expr::DictComp(dict_comp) => self.walk_dict_comp(dict_comp), - ast::Expr::ConfigIfEntry(config_if_entry_expr) => { - self.walk_config_if_entry_expr(config_if_entry_expr) - } - ast::Expr::CompClause(comp_clause) => self.walk_comp_clause(comp_clause), - ast::Expr::Schema(schema_expr) => self.walk_schema_expr(schema_expr), - ast::Expr::Config(config_expr) => self.walk_config_expr(config_expr), - ast::Expr::Check(check) => self.walk_check_expr(check), - ast::Expr::Lambda(lambda) => self.walk_lambda_expr(lambda), - ast::Expr::Subscript(subscript) => self.walk_subscript(subscript), - ast::Expr::Keyword(keyword) => self.walk_keyword(keyword), - ast::Expr::Arguments(..) => self.ok_result(), - ast::Expr::Compare(compare) => self.walk_compare(compare), - ast::Expr::NumberLit(number_lit) => self.walk_number_lit(number_lit), - ast::Expr::StringLit(string_lit) => self.walk_string_lit(string_lit), - ast::Expr::NameConstantLit(name_constant_lit) => { - self.walk_name_constant_lit(name_constant_lit) - } - ast::Expr::JoinedString(joined_string) => self.walk_joined_string(joined_string), - ast::Expr::FormattedValue(formatted_value) => { - self.walk_formatted_value(formatted_value) - } - ast::Expr::Missing(missing_expr) => self.walk_missing_expr(missing_expr), - } - } - - fn walk_quant_expr(&self, quant_expr: &'ctx ast::QuantExpr) -> Self::Result { - let mut result = match quant_expr.op { - ast::QuantOperation::All => self.bool_value(true), - ast::QuantOperation::Any => self.bool_value(false), - ast::QuantOperation::Map => self.list_value(), - ast::QuantOperation::Filter => { - self.value_deep_copy(&self.walk_expr(&quant_expr.target)?) - } - }; - // Iterator - let iter_host_value = if let ast::QuantOperation::Filter = quant_expr.op { - self.value_deep_copy(&result) - } else { - self.walk_expr(&quant_expr.target)? - }; - let mut iter_value = iter_host_value.iter(); - // Start iteration and enter the loop scope for the loop variable. - self.enter_scope(); - defer! { - self.leave_scope(); - self.clear_local_vars(); - } - // Start block - while let Some((next_value, key, value)) = iter_value.next_with_key_value(&iter_host_value) - { - // Next value block - let variables = &quant_expr.variables; - for v in variables { - self.add_local_var(&v.node.names[0].node); - } - if variables.len() == 1 { - // Store the target - self.walk_identifier_with_ctx( - &variables.first().expect(kcl_error::INTERNAL_ERROR_MSG).node, - &ast::ExprContext::Store, - Some(next_value.clone()), - )?; - } else if variables.len() == 2 { - // Store the target - self.walk_identifier_with_ctx( - &variables.first().expect(kcl_error::INTERNAL_ERROR_MSG).node, - &ast::ExprContext::Store, - Some(key.clone()), - )?; - self.walk_identifier_with_ctx( - &variables.get(1).expect(kcl_error::INTERNAL_ERROR_MSG).node, - &ast::ExprContext::Store, - Some(value.clone()), - )?; - } else { - panic!( - "the number of loop variables is {}, which can only be 1 or 2", - variables.len() - ) - } - // Check the if filter condition - if let Some(if_expr) = &quant_expr.if_cond { - let value = self.walk_expr(if_expr)?; - // Skip the iteration - if !value.is_truthy() { - continue; - } - } - // Loop var generation body block - let test = &quant_expr.test; - let value = self.walk_expr(test)?; - let is_truth = self.value_is_truthy(&value); - match quant_expr.op { - ast::QuantOperation::All => { - if !is_truth { - return Ok(self.bool_value(false)); - } - } - ast::QuantOperation::Any => { - if is_truth { - return Ok(self.bool_value(true)); - } - } - ast::QuantOperation::Filter => { - if !is_truth { - if result.is_dict() { - result.dict_remove(&next_value.as_str()); - } else if result.is_list() { - result.list_remove(&next_value); - } else { - panic!("only list, dict and schema can be removed item"); - } - } - } - ast::QuantOperation::Map => { - self.list_append(&mut result, &value); - } - } - } - // End for block. - Ok(result) - } - - fn walk_schema_attr(&self, schema_attr: &'ctx ast::SchemaAttr) -> Self::Result { - self.clear_local_vars(); - let name = schema_attr.name.node.as_str(); - self.add_target_var(name); - for decorator in &schema_attr.decorators { - self.walk_decorator_with_name(&decorator.node, Some(name), false) - .expect(kcl_error::INTERNAL_ERROR_MSG); - } - let (mut schema_value, config_value, _) = self - .get_schema_or_rule_config_info() - .expect(kcl_error::INTERNAL_ERROR_MSG); - schema_value.update_attr_map(name, &schema_attr.ty.node.to_string()); - if let Some(entry) = config_value.dict_get_entry(name) { - let is_override_attr = { - let is_override_op = matches!( - config_value.dict_get_attr_operator(name), - Some(ConfigEntryOperationKind::Override) - ); - let without_index = matches!(config_value.dict_get_insert_index(name), None); - is_override_op && without_index - }; - if !is_override_attr { - let value = match &schema_attr.value { - Some(value) => self.walk_expr(value)?, - None => self.undefined_value(), - }; - if let Some(op) = &schema_attr.op { - match op { - // Union - ast::AugOp::BitOr => { - let org_value = schema_value - .dict_get_value(name) - .unwrap_or(self.undefined_value()); - let value = self.bit_or(org_value, value); - self.schema_dict_merge( - &mut schema_value, - name, - &value, - &ast::ConfigEntryOperation::Override, - None, - ); - } - // Assign - _ => self.schema_dict_merge( - &mut schema_value, - name, - &value, - &ast::ConfigEntryOperation::Override, - None, - ), - } - } - } - self.value_union(&mut schema_value, &entry); - } else { - // Lazy eval for the schema attribute. - let value = match &schema_attr.value { - Some(value) => self.walk_expr(value)?, - None => { - let value = self.undefined_value(); - // When the schema has no default value and config value, - // set it with a undefined value. - // Note that do not override the existed attribute value. - if schema_value.dict_get_entry(name).is_none() { - self.dict_insert_value(&mut schema_value, name, &value); - } - value - } - }; - if let Some(op) = &schema_attr.op { - match op { - // Union - ast::AugOp::BitOr => { - let org_value = schema_value - .dict_get_value(name) - .unwrap_or(self.undefined_value()); - let value = self.bit_or(org_value, value); - self.schema_dict_merge( - &mut schema_value, - name, - &value, - &ast::ConfigEntryOperation::Override, - None, - ); - } - // Assign - _ => self.schema_dict_merge( - &mut schema_value, - name, - &value, - &ast::ConfigEntryOperation::Override, - None, - ), - } - } - } - // Set config cache for the schema eval context. - if let Some(schema_ctx) = self.get_schema_eval_context() { - schema_ctx.borrow().set_value(self, name); - } - self.pop_target_var(); - Ok(schema_value) - } - - fn walk_if_expr(&self, if_expr: &'ctx ast::IfExpr) -> Self::Result { - let cond = self.walk_expr(&if_expr.cond)?; - let is_truth = self.value_is_truthy(&cond); - if is_truth { - self.walk_expr(&if_expr.body) - } else { - self.walk_expr(&if_expr.orelse) - } - } - - fn walk_unary_expr(&self, unary_expr: &'ctx ast::UnaryExpr) -> Self::Result { - let value = self.walk_expr(&unary_expr.operand)?; - Ok(match unary_expr.op { - ast::UnaryOp::UAdd => value.unary_plus(), - ast::UnaryOp::USub => value.unary_minus(), - ast::UnaryOp::Invert => value.unary_not(), - ast::UnaryOp::Not => value.unary_l_not(), - }) - } - - fn walk_binary_expr(&self, binary_expr: &'ctx ast::BinaryExpr) -> Self::Result { - let is_logic_op = matches!(binary_expr.op, ast::BinOp::And | ast::BinOp::Or); - let is_membership_as_op = matches!(binary_expr.op, ast::BinOp::As); - if !is_logic_op { - let left_value = self.walk_expr(&binary_expr.left)?; - let right_value = if is_membership_as_op { - match &binary_expr.right.node { - ast::Expr::Identifier(id) => { - let name = id.get_names().join("."); - self.string_value(&name) - } - _ => self.none_value(), - } - } else { - self.walk_expr(&binary_expr.right)? - }; - let value = match binary_expr.op { - ast::BinOp::Add => self.add(left_value, right_value), - ast::BinOp::Sub => self.sub(left_value, right_value), - ast::BinOp::Mul => self.mul(left_value, right_value), - ast::BinOp::Div => self.div(left_value, right_value), - ast::BinOp::FloorDiv => self.floor_div(left_value, right_value), - ast::BinOp::Mod => self.r#mod(left_value, right_value), - ast::BinOp::Pow => self.pow(left_value, right_value), - ast::BinOp::LShift => self.bit_lshift(left_value, right_value), - ast::BinOp::RShift => self.bit_rshift(left_value, right_value), - ast::BinOp::BitAnd => self.bit_and(left_value, right_value), - ast::BinOp::BitOr => self.bit_or(left_value, right_value), - ast::BinOp::BitXor => self.bit_xor(left_value, right_value), - ast::BinOp::And => self.logic_and(left_value, right_value), - ast::BinOp::Or => self.logic_or(left_value, right_value), - ast::BinOp::As => self.r#as(left_value, right_value), - }; - Ok(value) - } else { - // Short circuit operation of logical operators - let jump_if_false = matches!(binary_expr.op, ast::BinOp::And); - let left_value = self.walk_expr(&binary_expr.left)?; - let is_truth = self.value_is_truthy(&left_value); - if jump_if_false { - // Jump if false on logic and - if is_truth { - let right_value = self.walk_expr(&binary_expr.right)?; - return Ok(right_value); - } - } else { - // Jump if true on logic or - if !is_truth { - let right_value = self.walk_expr(&binary_expr.right)?; - return Ok(right_value); - } - }; - Ok(left_value) - } - } - - fn walk_selector_expr(&self, selector_expr: &'ctx ast::SelectorExpr) -> Self::Result { - let value = self.walk_expr(&selector_expr.value)?; - let key = selector_expr.attr.node.names[0].node.as_str(); - let mut value = if selector_expr.has_question { - if value.is_truthy() { - value.load_attr(key) - } else { - self.none_value() - } - } else { - value.load_attr(key) - }; - for name in &selector_expr.attr.node.names[1..] { - value = value.load_attr(&name.node) - } - Ok(value) - } - - fn walk_call_expr(&self, call_expr: &'ctx ast::CallExpr) -> Self::Result { - let func = self.walk_expr(&call_expr.func)?; - // args - let mut list_value = self.list_value(); - for arg in &call_expr.args { - let value = self.walk_expr(arg)?; - self.list_append(&mut list_value, &value); - } - let mut dict_value = self.dict_value(); - // keyword arguments - for keyword in &call_expr.keywords { - let name = &keyword.node.arg.node.names[0]; - let value = if let Some(value) = &keyword.node.value { - self.walk_expr(value)? - } else { - self.none_value() - }; - self.dict_insert_value(&mut dict_value, name.node.as_str(), &value); - } - let vars = self.clean_and_cloned_local_vars(); - let result = if let Some(proxy) = func.try_get_proxy() { - // Invoke user defined functions, schemas or rules. - Ok(self.invoke_proxy_function(proxy, &list_value, &dict_value)) - } else { - // Invoke runtime builtin functions or external plugin functions. - Ok(invoke_function(self, &func, &mut list_value, &dict_value)) - }; - self.set_local_vars(vars); - result - } - - fn walk_subscript(&self, subscript: &'ctx ast::Subscript) -> Self::Result { - let mut value = self.walk_expr(&subscript.value)?; - if let Some(index) = &subscript.index { - // index - let index = self.walk_expr(index)?; - value = if subscript.has_question { - value.bin_subscr_option(&index) - } else { - value.bin_subscr(&index) - }; - } else { - let lower = { - if let Some(lower) = &subscript.lower { - self.walk_expr(lower)? - } else { - self.none_value() - } - }; - let upper = { - if let Some(upper) = &subscript.upper { - self.walk_expr(upper)? - } else { - self.none_value() - } - }; - let step = { - if let Some(step) = &subscript.step { - self.walk_expr(step)? - } else { - self.none_value() - } - }; - value = if subscript.has_question { - if value.is_truthy() { - value.list_slice(&lower, &upper, &step) - } else { - self.none_value() - } - } else { - value.list_slice(&lower, &upper, &step) - }; - } - Ok(value) - } - - fn walk_paren_expr(&self, paren_expr: &'ctx ast::ParenExpr) -> Self::Result { - self.walk_expr(&paren_expr.expr) - } - - fn walk_list_expr(&self, list_expr: &'ctx ast::ListExpr) -> Self::Result { - let mut list_value = self.list_value(); - for item in &list_expr.elts { - let value = self.walk_expr(item)?; - match &item.node { - ast::Expr::Starred(_) | ast::Expr::ListIfItem(_) => { - self.list_append_unpack(&mut list_value, &value); - } - _ => self.list_append(&mut list_value, &value), - }; - } - Ok(list_value) - } - - fn walk_list_if_item_expr(&self, list_if_item_expr: &'ctx ast::ListIfItemExpr) -> Self::Result { - let cond = self.walk_expr(&list_if_item_expr.if_cond)?; - let is_truth = self.value_is_truthy(&cond); - Ok(if is_truth { - let mut then_value = self.list_value(); - for expr in &list_if_item_expr.exprs { - let value = self.walk_expr(expr)?; - match &expr.node { - ast::Expr::Starred(_) | ast::Expr::ListIfItem(_) => { - self.list_append_unpack(&mut then_value, &value) - } - _ => self.list_append(&mut then_value, &value), - }; - } - then_value - } else if let Some(orelse) = &list_if_item_expr.orelse { - self.walk_expr(orelse)? - } else { - self.none_value() - }) - } - - fn walk_starred_expr(&self, starred_expr: &'ctx ast::StarredExpr) -> Self::Result { - self.walk_expr(&starred_expr.value) - } - - fn walk_list_comp(&self, list_comp: &'ctx ast::ListComp) -> Self::Result { - let mut collection_value = self.list_value(); - self.enter_scope(); - defer! { - self.leave_scope(); - } - self.walk_generator( - &list_comp.generators, - &list_comp.elt, - None, - None, - 0, - &mut collection_value, - &ast::CompType::List, - ); - Ok(collection_value) - } - - fn walk_dict_comp(&self, dict_comp: &'ctx ast::DictComp) -> Self::Result { - let mut collection_value = self.dict_value(); - self.enter_scope(); - defer! { - self.leave_scope(); - } - let key = dict_comp - .entry - .key - .as_ref() - .expect(kcl_error::INTERNAL_ERROR_MSG); - self.walk_generator( - &dict_comp.generators, - key, - Some(&dict_comp.entry.value), - Some(&dict_comp.entry.operation), - 0, - &mut collection_value, - &ast::CompType::Dict, - ); - - Ok(collection_value) - } - - fn walk_config_if_entry_expr( - &self, - config_if_entry_expr: &'ctx ast::ConfigIfEntryExpr, - ) -> Self::Result { - let cond = self.walk_expr(&config_if_entry_expr.if_cond)?; - let is_truth = self.value_is_truthy(&cond); - Ok(if is_truth { - self.walk_config_entries(&config_if_entry_expr.items)? - } else if let Some(orelse) = &config_if_entry_expr.orelse { - // Config expr or config if entry expr. - if let ast::Expr::Config(config_expr) = &orelse.node { - self.walk_config_entries(&config_expr.items)? - } else { - self.walk_expr(orelse)? - } - } else { - self.none_value() - }) - } - - fn walk_comp_clause(&self, _comp_clause: &'ctx ast::CompClause) -> Self::Result { - // Nothing to do on this AST node - self.ok_result() - } - - fn walk_schema_expr(&self, schema_expr: &'ctx ast::SchemaExpr) -> Self::Result { - // Check the required attributes only when the values of all attributes - // in the final schema are solved. - self.push_schema_expr(); - defer! { - self.pop_schema_expr(); - } - let config_value = self.walk_expr(&schema_expr.config)?; - let schema_type = self.walk_identifier_with_ctx( - &schema_expr.name.node, - &schema_expr.name.node.ctx, - None, - )?; - let config_expr = match &schema_expr.config.node { - ast::Expr::Config(config_expr) => config_expr, - _ => panic!("invalid schema config expr"), - }; - let config_meta = self.construct_schema_config_meta(Some(&schema_expr.name), config_expr); - let mut list_value = self.list_value(); - for arg in &schema_expr.args { - let value = self.walk_expr(arg)?; - self.list_append(&mut list_value, &value); - } - let mut dict_value = self.dict_value(); - for keyword in &schema_expr.kwargs { - let name = &keyword.node.arg.node.names[0]; - let value = if let Some(value) = &keyword.node.value { - self.walk_expr(value)? - } else { - self.none_value() - }; - self.dict_insert_merge_value(&mut dict_value, name.node.as_str(), &value); - } - let schema = if let Some(index) = schema_type.try_get_proxy() { - let frame = { - let frames = self.frames.borrow(); - frames - .get(index) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone() - }; - if let Proxy::Schema(schema) = &frame.proxy { - self.push_pkgpath(&frame.pkgpath); - self.push_backtrace(&frame); - defer! { - self.pop_backtrace(); - self.pop_pkgpath(); - } - let value = (schema.body)( - self, - &schema.ctx.borrow().snapshot(config_value, config_meta), - &list_value, - &dict_value, - ); - value - } else if let Proxy::Rule(rule) = &frame.proxy { - self.push_pkgpath(&frame.pkgpath); - self.push_backtrace(&frame); - defer! { - self.pop_backtrace(); - self.pop_pkgpath(); - } - let value = (rule.body)( - self, - &rule.ctx.borrow().snapshot(config_value, config_meta), - &list_value, - &dict_value, - ); - value - } else { - self.undefined_value() - } - } else { - union_entry( - self, - &mut schema_type.deep_copy(), - &config_value, - true, - &UnionOptions::default(), - ) - }; - Ok(schema) - } - - #[inline] - fn walk_config_expr(&self, config_expr: &'ctx ast::ConfigExpr) -> Self::Result { - self.enter_scope(); - defer! { - self.leave_scope(); - } - let result = self.walk_config_entries(&config_expr.items); - result - } - - fn walk_check_expr(&self, check_expr: &'ctx ast::CheckExpr) -> Self::Result { - if let Some(if_cond) = &check_expr.if_cond { - let if_value = self.walk_expr(if_cond)?; - let is_truth = self.value_is_truthy(&if_value); - if !is_truth { - return self.ok_result(); - } - } - let check_result = self.walk_expr(&check_expr.test)?; - let msg = { - if let Some(msg) = &check_expr.msg { - self.walk_expr(msg).expect(kcl_error::INTERNAL_ERROR_MSG) - } else { - self.string_value("") - } - } - .as_str(); - let (_, _, config_meta) = self - .get_schema_or_rule_config_info() - .expect(kcl_error::INTERNAL_ERROR_MSG); - schema_assert( - &mut self.runtime_ctx.borrow_mut(), - &check_result, - &msg, - &config_meta, - ); - self.ok_result() - } - - fn walk_lambda_expr(&self, lambda_expr: &'ctx ast::LambdaExpr) -> Self::Result { - let func = Arc::new(func_body); - // Capture schema self - let proxy = FunctionCaller::new( - FunctionEvalContext { - node: lambda_expr.clone(), - this: self - .schema_stack - .borrow() - .last() - .map(|ctx| FunctionEvalThis { - ctx: ctx.clone(), - value: ctx.value(), - config: ctx.config(), - }), - closure: self.get_current_closure_map(), - level: self.scope_level() + 1, - }, - func, - ); - // Add function to the global state - let index = self.add_function(proxy); - Ok(self.proxy_function_value(index)) - } - - fn walk_keyword(&self, _keyword: &'ctx ast::Keyword) -> Self::Result { - // Nothing to do - self.ok_result() - } - - fn walk_arguments(&self, _arguments: &'ctx ast::Arguments) -> Self::Result { - // Nothing to do - self.ok_result() - } - - fn walk_compare(&self, compare: &'ctx ast::Compare) -> Self::Result { - let mut left_value = self.walk_expr(&compare.left)?; - if compare.comparators.len() > 1 { - let mut result_value = self.undefined_value(); - for (i, op) in compare.ops.iter().enumerate() { - let has_next = i < (compare.ops.len() - 1); - let right_value = self.walk_expr(&compare.comparators[i])?; - result_value = match op { - ast::CmpOp::Eq => self.cmp_equal_to(left_value, right_value.clone()), - ast::CmpOp::NotEq => self.cmp_not_equal_to(left_value, right_value.clone()), - ast::CmpOp::Gt => self.cmp_greater_than(left_value, right_value.clone()), - ast::CmpOp::GtE => { - self.cmp_greater_than_or_equal(left_value, right_value.clone()) - } - ast::CmpOp::Lt => self.cmp_less_than(left_value, right_value.clone()), - ast::CmpOp::LtE => self.cmp_less_than_or_equal(left_value, right_value.clone()), - ast::CmpOp::Is => self.is(left_value, right_value.clone()), - ast::CmpOp::IsNot => self.is_not(left_value, right_value.clone()), - ast::CmpOp::Not => self.is_not(left_value, right_value.clone()), - ast::CmpOp::NotIn => self.not_in(left_value, right_value.clone()), - ast::CmpOp::In => self.r#in(left_value, right_value.clone()), - }; - left_value = right_value; - let is_truth = self.value_is_truthy(&result_value); - if has_next { - if !is_truth { - break; - } - } else { - break; - } - } - Ok(result_value) - } else { - let right_value = self.walk_expr(&compare.comparators[0])?; - Ok(match &compare.ops[0] { - ast::CmpOp::Eq => self.cmp_equal_to(left_value, right_value), - ast::CmpOp::NotEq => self.cmp_not_equal_to(left_value, right_value), - ast::CmpOp::Gt => self.cmp_greater_than(left_value, right_value), - ast::CmpOp::GtE => self.cmp_greater_than_or_equal(left_value, right_value), - ast::CmpOp::Lt => self.cmp_less_than(left_value, right_value), - ast::CmpOp::LtE => self.cmp_less_than_or_equal(left_value, right_value), - ast::CmpOp::Is => self.is(left_value, right_value), - ast::CmpOp::IsNot => self.is_not(left_value, right_value), - ast::CmpOp::Not => self.is_not(left_value, right_value), - ast::CmpOp::NotIn => self.not_in(left_value, right_value), - ast::CmpOp::In => self.r#in(left_value, right_value), - }) - } - } - - #[inline] - fn walk_identifier(&self, identifier: &'ctx ast::Identifier) -> Self::Result { - self.walk_identifier_with_ctx(identifier, &identifier.ctx, None) - } - - #[inline] - fn walk_target(&self, target: &'ctx ast::Target) -> Self::Result { - self.load_target(target) - } - - fn walk_number_lit(&self, number_lit: &'ctx ast::NumberLit) -> Self::Result { - match number_lit.value { - ast::NumberLitValue::Int(int_value) => match &number_lit.binary_suffix { - Some(binary_suffix) => { - let unit = binary_suffix.value(); - let value = kclvm_runtime::cal_num(int_value, unit.as_str()); - Ok(self.unit_value(value, int_value, &unit)) - } - None => Ok(self.int_value(int_value)), - }, - ast::NumberLitValue::Float(float_value) => Ok(self.float_value(float_value)), - } - } - - #[inline] - fn walk_string_lit(&self, string_lit: &'ctx ast::StringLit) -> Self::Result { - Ok(ValueRef::str(string_lit.value.as_str())) - } - - #[inline] - fn walk_name_constant_lit( - &self, - name_constant_lit: &'ctx ast::NameConstantLit, - ) -> Self::Result { - match name_constant_lit.value { - ast::NameConstant::True => Ok(self.bool_value(true)), - ast::NameConstant::False => Ok(self.bool_value(false)), - ast::NameConstant::None => Ok(self.none_value()), - ast::NameConstant::Undefined => Ok(self.undefined_value()), - } - } - - fn walk_joined_string(&self, joined_string: &'ctx ast::JoinedString) -> Self::Result { - let mut result_value = self.string_value(""); - for value in &joined_string.values { - let value = &value.node; - let value = match value { - ast::Expr::FormattedValue(formatted_value) => self - .walk_formatted_value(formatted_value) - .expect(kcl_error::INTERNAL_ERROR_MSG), - ast::Expr::StringLit(string_lit) => self - .walk_string_lit(string_lit) - .expect(kcl_error::INTERNAL_ERROR_MSG), - _ => panic!("{}", kcl_error::INVALID_JOINED_STR_MSG), - }; - result_value = self.add(result_value, value) - } - Ok(result_value) - } - - fn walk_formatted_value(&self, formatted_value: &'ctx ast::FormattedValue) -> Self::Result { - let formatted_expr_value = self.walk_expr(&formatted_value.value)?; - let value = if let Some(spec) = &formatted_value.format_spec { - match spec.to_lowercase().as_str() { - "#json" => formatted_expr_value.to_json_string(), - "#yaml" => formatted_expr_value.to_yaml_string(), - _ => panic!("{}", kcl_error::INVALID_STR_INTERPOLATION_SPEC_MSG), - } - } else { - formatted_expr_value.to_string() - }; - Ok(ValueRef::str(&value)) - } - - fn walk_comment(&self, _comment: &'ctx ast::Comment) -> Self::Result { - // Nothing to do - self.ok_result() - } - - fn walk_missing_expr(&self, _missing_expr: &'ctx ast::MissingExpr) -> Self::Result { - Err(anyhow::anyhow!("compile error: missing expression",)) - } - - fn walk_module(&self, module: &'ctx ast::Module) -> Self::Result { - // Compile all statements of the module except all import statements - self.walk_stmts_except_import(&module.body) - } -} - -impl<'ctx> Evaluator<'ctx> { - pub fn walk_stmts_except_import(&self, stmts: &'ctx [Box>]) -> EvalResult { - let mut result = self.ok_result(); - for stmt in stmts { - if !matches!(&stmt.node, ast::Stmt::Import(..)) { - result = self.walk_stmt(stmt); - } - } - result - } - - pub fn walk_stmts(&self, stmts: &'ctx [Box>]) -> EvalResult { - // Empty statements return None value - let mut result = self.ok_result(); - for stmt in stmts { - result = self.walk_stmt(stmt); - } - result - } - - pub(crate) fn walk_stmts_with_setter(&self, setter: &Setter) { - if let Some(index) = setter.index { - let frame = { - let frames = self.frames.borrow(); - frames - .get(index) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone() - }; - if let Proxy::Global(index) = &frame.proxy { - if let Some(module_list) = self - .program - .pkgs - .get(&pkgpath_without_prefix!(frame.pkgpath)) - { - if let Some(module) = module_list.get(*index) { - let module = self - .program - .get_module(module) - .expect("Failed to acquire module lock") - .expect(&format!("module {:?} not found in program", module)); - if let Some(stmt) = module.body.get(setter.stmt) { - self.push_backtrack_meta(setter); - self.walk_stmt(stmt).expect(INTERNAL_ERROR_MSG); - self.pop_backtrack_meta(); - } - } - } - } - } - } - - pub(crate) fn walk_schema_stmts_with_setter( - &self, - stmts: &'ctx [Box>], - setter: &Setter, - ) -> EvalResult { - if let Some(index) = setter.index { - let frame = { - let frames = self.frames.borrow(); - frames - .get(index) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone() - }; - if let Proxy::Schema(schema) = &frame.proxy { - if let Some(stmt) = schema.ctx.borrow().node.body.get(setter.stmt) { - self.push_pkgpath(&frame.pkgpath); - self.enter_scope(); - self.push_backtrack_meta(setter); - defer! { - self.pop_backtrack_meta(); - self.leave_scope(); - self.pop_pkgpath(); - } - let value = self.walk_stmt(stmt); - value - } else { - self.ok_result() - } - } else { - self.ok_result() - } - } else if let Some(stmt) = stmts.get(setter.stmt) { - self.walk_stmt(stmt) - } else { - self.ok_result() - } - } - - pub fn walk_target_with_value( - &self, - target: &'ctx ast::Target, - right_value: ValueRef, - ) -> EvalResult { - let is_in_schema = self.is_in_schema(); - if target.paths.is_empty() { - let name = target.get_name(); - // Global variables - if self.scope_level() == GLOBAL_LEVEL { - self.add_or_update_global_variable(name, right_value.clone(), true); - // Lambda local variables. - } else if self.is_in_lambda() { - let value = right_value.clone(); - // schema frame in the lambda - if self.is_schema_scope() { - let is_local_var = self.is_local_var(name); - let value = right_value.clone(); - match (is_local_var, is_in_schema) { - (false, true) => self.update_schema_or_rule_scope_value(name, Some(&value)), - _ => self.add_variable(name, value), - } - } else { - // If variable exists in the scope and update it, if not, add it to the scope. - if !self.store_variable_in_current_scope(name, value.clone()) { - self.add_variable(name, self.undefined_value()); - self.store_variable(name, value); - } - } - } else { - let is_local_var = self.is_local_var(name); - let value = right_value.clone(); - match (is_local_var, is_in_schema) { - (false, true) => self.update_schema_or_rule_scope_value(name, Some(&value)), - _ => self.add_variable(name, value), - } - } - } else { - let name = target.get_name(); - // In KCL, we cannot modify global variables in other packages, - // so pkgpath is empty here. - let mut value = self.load_value("", &[name]); - // Convert `store a.b.c = 1` -> `%t = load &a; %t = load_attr %t %b; store_attr %t %c with 1` - for (i, path) in target.paths.iter().enumerate() { - let ctx = if i < target.paths.len() - 1 { - ast::ExprContext::Load - } else { - ast::ExprContext::Store - }; - match ctx { - ast::ExprContext::Load => { - value = self.load_target_path(&value, path)?; - } - ast::ExprContext::Store => { - self.store_target_path(&mut value, path, &right_value)?; - let is_local_var = self.is_local_var(name); - let is_in_lambda = self.is_in_lambda(); - // Set config value for the schema attribute if the attribute is in the schema and - // it is not a local variable in the lambda function. - if self.scope_level() >= INNER_LEVEL - && is_in_schema - && !is_in_lambda - && !is_local_var - { - self.update_schema_or_rule_scope_value(name, None); - } - } - } - } - } - Ok(right_value) - } - - pub fn walk_identifier_with_ctx( - &self, - identifier: &'ctx ast::Identifier, - identifier_ctx: &ast::ExprContext, - right_value: Option, - ) -> EvalResult { - let is_in_schema = self.is_in_schema(); - match identifier_ctx { - // Store a.b.c = 1 - ast::ExprContext::Store => { - if identifier.names.len() == 1 { - let name = identifier.names[0].node.as_str(); - // Global variables - if self.scope_level() == GLOBAL_LEVEL { - self.add_or_update_global_variable( - name, - right_value.clone().expect(kcl_error::INTERNAL_ERROR_MSG), - true, - ); - // Lambda local variables. - } else if self.is_in_lambda() { - let value = right_value.clone().expect(kcl_error::INTERNAL_ERROR_MSG); - // schema frame in the lambda - if self.is_schema_scope() { - let is_local_var = self.is_local_var(name); - let value = right_value.clone().expect(kcl_error::INTERNAL_ERROR_MSG); - match (is_local_var, is_in_schema) { - (false, true) => { - self.update_schema_or_rule_scope_value(name, Some(&value)) - } - _ => self.add_variable(name, value), - } - } else { - // If variable exists in the scope and update it, if not, add it to the scope. - if !self.store_variable_in_current_scope(name, value.clone()) { - self.add_variable(name, self.undefined_value()); - self.store_variable(name, value); - } - } - } else { - let is_local_var = self.is_local_var(name); - let value = right_value.clone().expect(kcl_error::INTERNAL_ERROR_MSG); - match (is_local_var, is_in_schema) { - (false, true) => { - self.update_schema_or_rule_scope_value(name, Some(&value)) - } - _ => self.add_variable(name, value), - } - } - } else { - let names = &identifier.names; - let name = names[0].node.as_str(); - // In KCL, we cannot modify global variables in other packages, - // so pkgpath is empty here. - let mut value = self.load_value("", &[name]); - // Convert `store a.b.c = 1` -> `%t = load &a; %t = load_attr %t %b; store_attr %t %c with 1` - for i in 0..names.len() - 1 { - let attr = names[i + 1].node.as_str(); - let ctx = if matches!(identifier_ctx, ast::ExprContext::Store) - && i != names.len() - 2 - && names.len() > 2 - { - &ast::ExprContext::Load - } else { - identifier_ctx - }; - match ctx { - ast::ExprContext::Load => { - value = value.load_attr(attr); - } - ast::ExprContext::Store => { - self.dict_set_value( - &mut value, - attr, - &right_value.clone().expect(kcl_error::INTERNAL_ERROR_MSG), - ); - let is_local_var = self.is_local_var(name); - let is_in_lambda = self.is_in_lambda(); - // Set config value for the schema attribute if the attribute is in the schema and - // it is not a local variable in the lambda function. - if self.scope_level() >= INNER_LEVEL - && is_in_schema - && !is_in_lambda - && !is_local_var - { - self.update_schema_or_rule_scope_value(name, None); - } - } - } - } - } - Ok(right_value.expect(kcl_error::INTERNAL_ERROR_MSG)) - } - // Load .a.b.c - ast::ExprContext::Load => Ok(self.load_value( - &identifier.pkgpath, - &identifier - .names - .iter() - .map(|n| n.node.as_str()) - .collect::>(), - )), - } - } - - pub fn walk_decorator_with_name( - &self, - decorator: &'ctx CallExpr, - attr_name: Option<&str>, - is_schema_target: bool, - ) -> EvalResult { - let mut list_value = self.list_value(); - let mut dict_value = self.dict_value(); - let (_, config_value, config_meta) = self - .get_schema_or_rule_config_info() - .expect(kcl_error::INTERNAL_ERROR_MSG); - for arg in &decorator.args { - let value = self.walk_expr(arg)?; - self.list_append(&mut list_value, &value); - } - for keyword in &decorator.keywords { - let name = &keyword.node.arg.node.names[0]; - let value = if let Some(value) = &keyword.node.value { - self.walk_expr(value)? - } else { - self.none_value() - }; - self.dict_insert_value(&mut dict_value, name.node.as_str(), &value); - } - let name = match &decorator.func.node { - ast::Expr::Identifier(ident) if ident.names.len() == 1 => ident.names[0].clone(), - _ => panic!("invalid decorator name, expect single identifier"), - }; - let attr_name = if let Some(v) = attr_name { v } else { "" }; - DecoratorValue::new(&name.node, &list_value, &dict_value).run( - &mut self.runtime_ctx.borrow_mut(), - attr_name, - is_schema_target, - &config_value, - &config_meta, - ); - self.ok_result() - } - - pub fn walk_arguments( - &self, - arguments: &'ctx Option>, - args: &ValueRef, - kwargs: &ValueRef, - ) { - // Arguments names and defaults - let (arg_names, arg_types, arg_defaults) = if let Some(args) = &arguments { - let names = &args.node.args; - let types = &args.node.ty_list; - let defaults = &args.node.defaults; - ( - names.iter().map(|identifier| &identifier.node).collect(), - types.iter().collect(), - defaults.iter().collect(), - ) - } else { - (vec![], vec![], vec![]) - }; - // Default parameter values - for ((arg_name, arg_type), value) in - arg_names.iter().zip(&arg_types).zip(arg_defaults.iter()) - { - let mut arg_value = if let Some(value) = value { - self.walk_expr(value).expect(kcl_error::RUNTIME_ERROR_MSG) - } else { - self.none_value() - }; - if let Some(ty) = arg_type { - arg_value = - type_pack_and_check(self, &arg_value, vec![&ty.node.to_string()], false); - } - // Arguments are immutable, so we place them in different scopes. - let name = arg_name.get_name(); - self.store_argument_in_current_scope(&name); - // Argument is a local variable instead of a global variable or schema attribute. - self.add_local_var(&name); - self.walk_identifier_with_ctx(arg_name, &ast::ExprContext::Store, Some(arg_value)) - .expect(kcl_error::RUNTIME_ERROR_MSG); - self.remove_local_var(&name); - } - // Positional arguments - let argument_len = args.len(); - for (i, (arg_name, arg_type)) in arg_names.iter().zip(arg_types).enumerate() { - // Positional arguments - let is_in_range = i < argument_len; - if is_in_range { - let mut arg_value = match args.list_get_option(i as isize) { - Some(v) => v, - None => self.undefined_value(), - }; - if let Some(ty) = arg_type { - arg_value = - type_pack_and_check(self, &arg_value, vec![&ty.node.to_string()], false); - } - self.store_variable(&arg_name.names[0].node, arg_value); - } else { - break; - } - } - // Keyword arguments - for arg_name in arg_names.iter() { - let name = &arg_name.names[0].node; - if let Some(arg) = kwargs.dict_get_value(name) { - // Find argument name in the scope - self.store_variable(&arg_name.names[0].node, arg); - } - } - } - - pub fn walk_generator( - &self, - generators: &'ctx [Box>], - elt: &'ctx ast::Node, - val: Option<&'ctx ast::Node>, - op: Option<&'ctx ast::ConfigEntryOperation>, - gen_index: usize, - collection_value: &mut ValueRef, - comp_type: &ast::CompType, - ) { - // Start block - let generator = &generators[gen_index]; - let iter_host_value = self - .walk_expr(&generator.node.iter) - .expect(kcl_error::RUNTIME_ERROR_MSG); - let mut iter_value = iter_host_value.iter(); - let targets = &generator.node.targets; - - while let Some((next_value, key, value)) = iter_value.next_with_key_value(&iter_host_value) - { - for v in targets { - self.add_local_var(&v.node.names[0].node) - } - if targets.len() == 1 { - // Store the target - self.walk_identifier_with_ctx( - &targets.first().expect(kcl_error::INTERNAL_ERROR_MSG).node, - &ast::ExprContext::Store, - Some(next_value), - ) - .expect(kcl_error::RUNTIME_ERROR_MSG); - } else if targets.len() == 2 { - // Store the target - self.walk_identifier_with_ctx( - &targets.first().expect(kcl_error::INTERNAL_ERROR_MSG).node, - &ast::ExprContext::Store, - Some(key), - ) - .expect(kcl_error::RUNTIME_ERROR_MSG); - self.walk_identifier_with_ctx( - &targets.get(1).expect(kcl_error::INTERNAL_ERROR_MSG).node, - &ast::ExprContext::Store, - Some(value), - ) - .expect(kcl_error::RUNTIME_ERROR_MSG); - } else { - panic!( - "the number of loop variables is {}, which can only be 1 or 2", - generator.node.targets.len() - ) - } - // Check the if filter - let mut skip = false; - for if_expr in &generator.node.ifs { - let value = self.walk_expr(if_expr).expect(kcl_error::RUNTIME_ERROR_MSG); - // Skip the iteration - if !value.is_truthy() { - skip = true; - } - } - if skip { - continue; - } - let next_gen_index = gen_index + 1; - if next_gen_index >= generators.len() { - match comp_type { - ast::CompType::List => { - let item = self.walk_expr(elt).expect(kcl_error::RUNTIME_ERROR_MSG); - self.list_append(collection_value, &item); - } - ast::CompType::Dict => { - let value = self - .walk_expr(val.expect(kcl_error::INTERNAL_ERROR_MSG)) - .expect(kcl_error::RUNTIME_ERROR_MSG); - let key = self.walk_expr(elt).expect(kcl_error::RUNTIME_ERROR_MSG); - let op = op.expect(kcl_error::INTERNAL_ERROR_MSG); - self.dict_insert( - collection_value, - &key.as_str(), - &value.deep_copy(), - op, - None, - ); - } - } - } else { - self.walk_generator( - generators, - elt, - val, - op, - next_gen_index, - collection_value, - comp_type, - ); - } - } - for v in targets { - self.remove_local_var(&v.node.names[0].node) - } - } - - pub(crate) fn walk_config_entries(&self, items: &'ctx [NodeRef]) -> EvalResult { - let mut config_value = self.dict_value(); - for item in items { - let value = self.walk_expr(&item.node.value)?; - if let Some(key_node) = &item.node.key { - let mut insert_index = None; - let optional_name = match &key_node.node { - ast::Expr::Identifier(identifier) => Some(identifier.names[0].node.clone()), - ast::Expr::StringLit(string_lit) => Some(string_lit.value.clone()), - ast::Expr::Subscript(subscript) => { - let mut name = None; - if let ast::Expr::Identifier(identifier) = &subscript.value.node { - if let Some(index_node) = &subscript.index { - // Insert index - if let ast::Expr::NumberLit(number) = &index_node.node { - if let ast::NumberLitValue::Int(v) = number.value { - insert_index = Some(v as i32); - name = Some(identifier.names[0].node.clone()) - } - } else if let ast::Expr::Unary(unary_expr) = &index_node.node { - // Negative insert index - if let ast::Expr::NumberLit(number) = &unary_expr.operand.node { - if let ast::NumberLitValue::Int(v) = number.value { - insert_index = Some(-v as i32); - name = Some(identifier.names[0].node.clone()) - } - } - } - } - } - name - } - _ => None, - }; - // Store a local variable for every entry key. - let key = match &optional_name { - Some(name) if !self.is_local_var(name) => self.string_value(name), - _ => self.walk_expr(key_node)?, - }; - self.dict_insert( - &mut config_value, - &key.as_str(), - &value, - &item.node.operation, - insert_index, - ); - if let Some(name) = &optional_name { - let value = self.dict_get_value(&config_value, name); - self.add_or_update_local_variable_within_scope(name, value); - } - } else { - // If the key does not exist, execute the logic of unpacking expression `**expr` here. - config_value.dict_insert_unpack(&mut self.runtime_ctx.borrow_mut(), &value) - } - } - Ok(config_value) - } -} diff --git a/kclvm/evaluator/src/schema.rs b/kclvm/evaluator/src/schema.rs deleted file mode 100644 index 12985fe49..000000000 --- a/kclvm/evaluator/src/schema.rs +++ /dev/null @@ -1,919 +0,0 @@ -use std::cell::RefCell; -use std::rc::Rc; -use std::sync::Arc; - -use generational_arena::Index; -use kclvm_ast::ast; -use kclvm_ast::walker::TypedResultWalker; -use kclvm_primitives::{DefaultHashBuilder, IndexMap}; -use kclvm_runtime::{schema_runtime_type, ConfigEntryOperationKind, ValueRef}; -use scopeguard::defer; - -use crate::lazy::{merge_variables_and_setters, LazyEvalScope, LazyEvalScopeRef}; -use crate::proxy::{call_schema_body, call_schema_check}; -use crate::rule::RuleEvalContext; -use crate::ty::type_pack_and_check; -use crate::{error as kcl_error, Proxy}; -use crate::{Evaluator, INNER_LEVEL}; - -pub type SchemaBodyHandler = - Arc ValueRef>; - -pub type SchemaCheckHandler = - Arc ()>; - -pub type SchemaEvalContextRef = Rc>; - -/// Proxy functions represent the saved functions of the runtime its, -/// rather than executing KCL defined functions or plugin functions. -#[derive(Clone, Debug)] -pub struct SchemaEvalContext { - pub node: Rc, - pub scope: Option, - pub index: Index, - pub parent: Option, - pub mixins: Vec, - pub value: ValueRef, - pub config: ValueRef, - pub config_meta: ValueRef, - pub optional_mapping: ValueRef, - pub is_sub_schema: bool, -} - -impl SchemaEvalContext { - #[inline] - pub fn new_with_node( - node: ast::SchemaStmt, - index: Index, - parent: Option, - mixins: Vec, - ) -> Self { - Self { - node: Rc::new(node), - scope: None, - index, - parent, - mixins, - value: ValueRef::dict(None), - config: ValueRef::dict(None), - config_meta: ValueRef::dict(None), - optional_mapping: ValueRef::dict(None), - is_sub_schema: true, - } - } - - /// Reset schema evaluation context state. - #[inline] - pub fn snapshot(&self, config: ValueRef, config_meta: ValueRef) -> SchemaEvalContextRef { - Rc::new(RefCell::new(Self { - node: self.node.clone(), - index: self.index, - parent: self.parent, - mixins: self.mixins.clone(), - scope: None, - value: ValueRef::dict(None), - config, - config_meta, - optional_mapping: ValueRef::dict(None), - is_sub_schema: true, - })) - } - - /// New a schema evaluation context with schema value and config. - #[inline] - pub fn new_with_value(&self, value: &ValueRef, config: &ValueRef) -> SchemaEvalContextRef { - Rc::new(RefCell::new(Self { - node: self.node.clone(), - index: self.index, - parent: self.parent, - mixins: self.mixins.clone(), - scope: None, - value: value.clone(), - config: config.clone(), - config_meta: ValueRef::dict(None), - optional_mapping: ValueRef::dict(None), - is_sub_schema: true, - })) - } - - /// Pass value references from other schema eval context. - /// Note that do not change the schema node. - pub fn set_info_with_schema(&mut self, other: &SchemaEvalContext) { - self.config = other.config.clone(); - self.config_meta = other.config_meta.clone(); - self.value = other.value.clone(); - self.optional_mapping = other.optional_mapping.clone(); - self.is_sub_schema = false; - // Set lazy eval scope. - if let Some(other) = &other.scope { - if let Some(scope) = &self.scope { - let mut scope = scope.borrow_mut(); - let other = other.borrow(); - scope.cache = other.cache.clone(); - scope.levels = other.levels.clone(); - scope.cal_times = other.cal_times.clone(); - scope.setters = other.setters.clone(); - } else { - let other = other.borrow(); - self.scope = Some(Rc::new(RefCell::new(LazyEvalScope { - cache: other.cache.clone(), - levels: other.levels.clone(), - cal_times: other.cal_times.clone(), - setters: other.setters.clone(), - }))) - } - } - } - - /// Pass value references from other rule eval context. - /// Note that do not change the schema node. - pub fn set_info_with_rule(&mut self, other: &RuleEvalContext) { - self.config = other.config.clone(); - self.config_meta = other.config_meta.clone(); - self.value = other.value.clone(); - self.optional_mapping = other.optional_mapping.clone(); - // Note that for the host schema, it will evaluate the final value. - self.is_sub_schema = true; - } - - /// Update parent schema and mixin schema information in the current scope. - pub fn get_parent_schema( - s: &Evaluator, - parent: &Option>>, - ) -> Option { - if let Some(parent) = parent { - let func = s - .walk_identifier_with_ctx(&parent.node, &ast::ExprContext::Load, None) - .expect(kcl_error::RUNTIME_ERROR_MSG); - if let Some(index) = func.try_get_proxy() { - Some(index) - } else { - None - } - } else { - None - } - } - - /// Update parent schema and mixin schema information - pub fn get_mixin_schemas( - s: &Evaluator, - mixins: &[Box>], - ) -> Vec { - let mut results = vec![]; - for mixin in mixins { - let func = s - .walk_identifier_with_ctx(&mixin.node, &ast::ExprContext::Load, None) - .expect(kcl_error::RUNTIME_ERROR_MSG); - if let Some(index) = func.try_get_proxy() { - let frame = { - let frames = s.frames.borrow(); - frames - .get(index) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone() - }; - if let Proxy::Schema(_) = &frame.proxy { - results.push(index); - } - } - } - results - } - - /// Whether the attribute is the schema context. - pub fn has_attr(s: &Evaluator, ctx: &SchemaEvalContextRef, name: &str) -> bool { - for stmt in &ctx.borrow().node.body { - if let ast::Stmt::SchemaAttr(attr) = &stmt.node { - if attr.name.node == name { - return true; - } - } - } - if let Some(index) = ctx.borrow().parent { - let frame = { - let frames = s.frames.borrow(); - frames - .get(index) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone() - }; - if let Proxy::Schema(schema) = &frame.proxy { - return SchemaEvalContext::has_attr(s, &schema.ctx, name); - } - } - false - } - - /// Get all attribute from schema - pub fn get_attrs(s: &Evaluator, ctx: &SchemaEvalContextRef) -> Vec<(String, bool)> { - let mut attrs = vec![]; - for stmt in &ctx.borrow().node.body { - if let ast::Stmt::SchemaAttr(attr) = &stmt.node { - attrs.push((attr.name.node.clone(), attr.is_optional)); - } - } - if let Some(index) = ctx.borrow().parent { - let frame = { - let frames = s.frames.borrow(); - frames - .get(index) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone() - }; - if let Proxy::Schema(schema) = &frame.proxy { - attrs.extend(SchemaEvalContext::get_attrs(s, &schema.ctx)); - } - } - attrs - } - - /// Whether the index signature is the schema context. - pub fn has_index_signature(s: &Evaluator, ctx: &SchemaEvalContextRef) -> bool { - if ctx.borrow().node.index_signature.is_some() { - return true; - } - - if let Some(index) = ctx.borrow().parent { - let frame = { - let frames = s.frames.borrow(); - frames - .get(index) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone() - }; - if let Proxy::Schema(schema) = &frame.proxy { - return SchemaEvalContext::has_index_signature(s, &schema.ctx); - } - } - false - } - - #[inline] - pub fn is_fit_config(s: &Evaluator, ctx: &SchemaEvalContextRef, value: &ValueRef) -> bool { - if value.is_config() { - let config = value.as_dict_ref(); - for (key, _) in &config.values { - let no_such_attr = - !SchemaEvalContext::has_attr(s, ctx, key) && !key.starts_with('_'); - let has_index_signature = SchemaEvalContext::has_index_signature(s, ctx); - if !has_index_signature && no_such_attr { - return false; - } - } - true - } else { - false - } - } - - /// Init the lazy scope used to cache the lazy evaluation result. - pub fn init_lazy_scope(&mut self, s: &Evaluator, index: Option) { - // TODO: cache the lazy scope cross different schema instances. - let mut setters = IndexMap::with_hasher(DefaultHashBuilder::default()); - // Parent schema setters - if let Some(idx) = self.parent { - let frame = { - let frames = s.frames.borrow(); - frames - .get(idx) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone() - }; - if let Proxy::Schema(schema) = &frame.proxy { - let mut parent = schema.ctx.borrow_mut(); - parent.init_lazy_scope(s, Some(idx)); - if let Some(scope) = &parent.scope { - merge_variables_and_setters( - &mut self.value, - &mut setters, - &scope.borrow().setters, - ); - } - } - } - // Self setters - merge_variables_and_setters( - &mut self.value, - &mut setters, - &s.emit_setters(&self.node.body, index), - ); - // Mixin schema setters - for idx in &self.mixins { - let frame = { - let frames = s.frames.borrow(); - frames - .get(*idx) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone() - }; - if let Proxy::Schema(schema) = &frame.proxy { - let mut mixin = schema.ctx.borrow_mut(); - mixin.init_lazy_scope(s, Some(*idx)); - if let Some(scope) = &mixin.scope { - merge_variables_and_setters( - &mut self.value, - &mut setters, - &scope.borrow().setters, - ); - } - } - } - self.scope = Some(Rc::new(RefCell::new(LazyEvalScope { - setters, - ..Default::default() - }))) - } - - /// Get the value from the context. - pub fn get_value(&self, s: &Evaluator, key: &str, pkgpath: &str, target: &str) -> ValueRef { - if let Some(scope) = &self.scope { - let value = { - match self.value.get_by_key(key) { - Some(value) => value.clone(), - None => s.get_variable_in_pkgpath(key, pkgpath), - } - }; - // Deal in-place modify and return it self immediately. - if key == target && { - let scope = scope.borrow(); - !scope.is_backtracking(key) || scope.setter_len(key) <= 1 - } { - value - } else { - let cached_value = { - let scope = scope.borrow(); - scope.cache.get(key).cloned() - }; - match cached_value { - Some(value) => value.clone(), - None => { - let setters = { - let scope = scope.borrow(); - scope.setters.get(key).cloned() - }; - match &setters { - Some(setters) if !setters.is_empty() => { - // Call all setters function to calculate the value recursively. - let level = { - let scope = scope.borrow(); - *scope.levels.get(key).unwrap_or(&0) - }; - let next_level = level + 1; - { - let mut scope = scope.borrow_mut(); - scope.levels.insert(key.to_string(), next_level); - } - let n = setters.len(); - let index = n - next_level; - if index >= n { - value - } else { - // Call setter function - s.walk_schema_stmts_with_setter( - &self.node.body, - &setters[index], - ) - .expect(kcl_error::INTERNAL_ERROR_MSG); - { - let mut scope = scope.borrow_mut(); - scope.levels.insert(key.to_string(), level); - let value = match self.value.get_by_key(key) { - Some(value) => value.clone(), - None => s.undefined_value(), - }; - scope.cache.insert(key.to_string(), value.clone()); - value - } - } - } - _ => value, - } - } - } - } - } else if let Some(value) = self.value.dict_get_value(key) { - value - } else { - s.get_variable_in_pkgpath(key, pkgpath) - } - } - - /// Set value to the context. - #[inline] - pub fn set_value(&self, s: &Evaluator, key: &str) { - if let Some(scope) = &self.scope { - let mut scope = scope.borrow_mut(); - if (scope.cal_increment(key) || scope.is_last_setter_ast_index(key, &s.ast_id.borrow())) - && scope.cache.get(key).is_none() - { - scope - .cache - .insert(key.to_string(), s.dict_get_value(&self.value, key)); - } - } - } -} - -#[derive(Clone)] -pub struct SchemaCaller { - pub ctx: SchemaEvalContextRef, - pub body: SchemaBodyHandler, - pub check: SchemaCheckHandler, -} - -/// Init or reset the schema lazy eval scope. -pub(crate) fn init_lazy_scope(s: &Evaluator, ctx: &mut SchemaEvalContext) { - let is_sub_schema = { ctx.is_sub_schema }; - let index = { ctx.index }; - if is_sub_schema { - ctx.init_lazy_scope(s, Some(index)); - } -} - -/// Schema body function -pub(crate) fn schema_body( - s: &Evaluator, - ctx: &SchemaEvalContextRef, - args: &ValueRef, - kwargs: &ValueRef, -) -> ValueRef { - init_lazy_scope(s, &mut ctx.borrow_mut()); - // Schema self value or parent schema value; - let mut schema_ctx_value = if let Some(parent_name) = &ctx.borrow().node.parent_name { - let base_constructor_func = s.load_global_value( - &parent_name.node.pkgpath, - &parent_name - .node - .names - .iter() - .map(|n| n.node.as_str()) - .collect::>(), - ); - // Call base schema function - call_schema_body(s, &base_constructor_func, args, kwargs, ctx) - } else { - ctx.borrow().value.clone() - }; - let schema_name = { ctx.borrow().node.name.node.to_string() }; - s.push_schema(crate::EvalContext::Schema(ctx.clone())); - s.enter_schema_scope(true); - defer! { - s.leave_scope(); - s.pop_schema(); - } - // Evaluate arguments and keyword arguments and store values to local variables. - s.walk_arguments(&ctx.borrow().node.args, args, kwargs); - // Eval schema body and record schema instances. - { - let schema_pkgpath = &s.current_pkgpath(); - // To prevent schema recursive calling, thus clone the AST here. - let node = { - let ctx = ctx.borrow(); - ctx.node.clone() - }; - // Run schema compiled function - for stmt in &node.body { - s.walk_stmt(stmt).expect(kcl_error::RUNTIME_ERROR_MSG); - } - // Schema decorators check - for decorator in &node.decorators { - s.walk_decorator_with_name(&decorator.node, Some(&schema_name), true) - .expect(kcl_error::RUNTIME_ERROR_MSG); - } - let runtime_type = kclvm_runtime::schema_runtime_type(&schema_name, schema_pkgpath); - schema_ctx_value.set_potential_schema_type(&runtime_type); - // Set schema arguments and keyword arguments - schema_ctx_value.set_schema_args(args, kwargs); - } - // Schema Mixins - { - let ctx_ref = ctx.borrow(); - for mixin in &ctx_ref.node.mixins { - let mixin_func = s.load_global_value( - &mixin.node.pkgpath, - &mixin - .node - .names - .iter() - .map(|n| n.node.as_str()) - .collect::>(), - ); - schema_ctx_value = call_schema_body(s, &mixin_func, args, kwargs, ctx); - } - } - // Schema Attribute optional check - let mut optional_mapping = { ctx.borrow().optional_mapping.clone() }; - { - let ctx = ctx.borrow(); - for stmt in &ctx.node.body { - if let ast::Stmt::SchemaAttr(schema_attr) = &stmt.node { - s.dict_insert_value( - &mut optional_mapping, - &schema_attr.name.node, - &s.bool_value(schema_attr.is_optional), - ) - } - } - } - // Do schema check for the sub schema. - let is_sub_schema = { ctx.borrow().is_sub_schema }; - let schema = if is_sub_schema { - let index_sign_key_name = if let Some(index_signature) = &ctx.borrow().node.index_signature - { - if let Some(key_name) = &index_signature.node.key_name { - key_name.node.clone() - } else { - "".to_string() - } - } else { - "".to_string() - }; - if index_sign_key_name.is_empty() { - // Update schema relaxed attribute - update_schema_relaxed_attr(s, ctx, &mut schema_ctx_value); - // Construct schema instance - let schema = schema_with_config(s, ctx, &schema_ctx_value, args, kwargs); - // Do schema optional attribute check recursively before evaluate check expressions. - check_schema_optional_attr(s, &schema); - // Call schema check block function - schema_check(s, ctx, &schema, args, kwargs); - schema - } else { - // Do check function for every index signature key - let config = { - let ctx = ctx.borrow(); - ctx.config.clone() - }; - for (k, _) in &config.as_dict_ref().values { - // relaxed keys - if schema_ctx_value.attr_map_get(k).is_none() { - // Update index signature key value - let value = ValueRef::str(k); - schema_ctx_value.dict_update_key_value(&index_sign_key_name, value.clone()); - // Update schema relaxed attribute - update_schema_relaxed_attr(s, ctx, &mut schema_ctx_value); - // Call schema check block function - schema_check(s, ctx, &schema_ctx_value, args, kwargs); - } - } - schema_ctx_value.dict_remove(&index_sign_key_name); - // Construct schema instance - let schema = schema_with_config(s, ctx, &schema_ctx_value, args, kwargs); - // Do schema optional attribute check recursively before evaluate check expressions. - check_schema_optional_attr(s, &schema); - schema - } - } else { - // Record base schema instances. - schema_with_config(s, ctx, &schema_ctx_value, args, kwargs) - }; - schema -} - -// Schema check and index sign value update function -pub(crate) fn schema_check( - s: &Evaluator, - ctx: &SchemaEvalContextRef, - schema_value: &ValueRef, - args: &ValueRef, - kwargs: &ValueRef, -) { - // Call base check function - { - let ctx_ref = ctx.borrow(); - if let Some(parent_name) = &ctx_ref.node.parent_name { - let base_constructor_func = s - .walk_identifier_with_ctx(&parent_name.node, &ast::ExprContext::Load, None) - .expect(kcl_error::RUNTIME_ERROR_MSG); - call_schema_check( - s, - &base_constructor_func, - schema_value, - args, - kwargs, - Some(ctx), - ) - } - } - // Call self check function - { - let ctx = ctx.borrow(); - for check_expr in &ctx.node.checks { - s.walk_check_expr(&check_expr.node) - .expect(kcl_error::RUNTIME_ERROR_MSG); - } - } - - // Call mixin check functions - { - let ctx = ctx.borrow(); - for mixin in &ctx.node.mixins { - let mixin_func = s - .walk_identifier_with_ctx(&mixin.node, &ast::ExprContext::Load, None) - .expect(kcl_error::RUNTIME_ERROR_MSG); - if let Some(index) = mixin_func.try_get_proxy() { - let frame = { - let frames = s.frames.borrow(); - frames - .get(index) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone() - }; - if let Proxy::Schema(schema) = &frame.proxy { - s.push_pkgpath(&frame.pkgpath); - s.push_backtrace(&frame); - defer! { - s.pop_backtrace(); - s.pop_pkgpath(); - } - (schema.check)(s, &schema.ctx, schema_value, args, kwargs); - } - } - } - } -} - -pub(crate) fn schema_with_config( - s: &Evaluator, - ctx: &SchemaEvalContextRef, - schema_ctx_value: &ValueRef, - args: &ValueRef, - kwargs: &ValueRef, -) -> ValueRef { - let name = { ctx.borrow().node.name.node.to_string() }; - let pkgpath = s.current_pkgpath(); - let config_keys: Vec = { - ctx.borrow() - .config - .as_dict_ref() - .values - .keys() - .cloned() - .collect() - }; - let runtime_type = schema_runtime_type(&name, &pkgpath); - // Instance package path is the last frame calling package path. - let instance_pkgpath = s.last_pkgpath(); - // Currently, `MySchema.instances()` it is only valid for files in the main package to - // avoid unexpected non idempotent calls. For example, I instantiated a MySchema in pkg1, - // but the length of the list returned by calling the instances method in other packages - // is uncertain. - { - let mut ctx = s.runtime_ctx.borrow_mut(); - // Record schema instance in the context - if !ctx.instances.contains_key(&runtime_type) { - ctx.instances - .insert(runtime_type.clone(), IndexMap::default()); - } - let pkg_instance_map = ctx.instances.get_mut(&runtime_type).unwrap(); - if !pkg_instance_map.contains_key(&instance_pkgpath) { - pkg_instance_map.insert(instance_pkgpath.clone(), vec![]); - } - pkg_instance_map - .get_mut(&instance_pkgpath) - .unwrap() - .push(schema_ctx_value.clone()); - } - // Dict to schema - let is_sub_schema = { ctx.borrow().is_sub_schema }; - if is_sub_schema { - let ctx = ctx.borrow(); - // Record instance copy and convert it to schema value. - schema_ctx_value.dict_to_schema( - &name, - &pkgpath, - &config_keys, - &ctx.config_meta, - &ctx.optional_mapping, - Some(args.clone()), - Some(kwargs.clone()), - ) - } else { - schema_ctx_value.clone() - } -} - -fn update_schema_relaxed_attr( - s: &Evaluator, - ctx: &SchemaEvalContextRef, - schema_value: &mut ValueRef, -) { - let schema_name = { ctx.borrow().node.name.node.to_string() }; - // Do check function - // Schema runtime index signature and relaxed check - { - let ctx = ctx.borrow(); - if let Some(index_signature) = &ctx.node.index_signature { - let index_sign_value = if let Some(value) = &index_signature.node.value { - s.walk_expr(value).expect(kcl_error::RUNTIME_ERROR_MSG) - } else { - s.undefined_value() - }; - let key_name = if let Some(key_name) = &index_signature.node.key_name { - key_name.node.as_str() - } else { - "" - }; - schema_relaxed_attr_update_and_check( - s, - schema_value, - &ctx.config, - &schema_name, - &index_sign_value, - key_name, - index_signature.node.key_ty.node.to_string().as_str(), - index_signature.node.value_ty.node.to_string().as_str(), - ); - } else { - schema_relaxed_attr_update_and_check( - s, - schema_value, - &ctx.config, - &schema_name, - &s.undefined_value(), - "", - "", - "", - ); - } - } -} - -fn check_schema_optional_attr(s: &Evaluator, schema_value: &ValueRef) { - if is_top_level_schema_instance(s) { - schema_value.schema_check_attr_optional(&mut s.runtime_ctx.borrow_mut(), true); - } -} - -/// Schema additional value check -fn schema_relaxed_attr_update_and_check( - s: &Evaluator, - schema_value: &mut ValueRef, - schema_config: &ValueRef, - schema_name: &str, - index_sign_value: &ValueRef, - index_key_name: &str, - key_type: &str, - value_type: &str, -) { - let has_index_signature = !key_type.is_empty(); - let config = schema_config.as_dict_ref(); - for (key, value) in &config.values { - let no_such_attr = schema_value.dict_get_value(key).is_none(); - if has_index_signature && no_such_attr { - // Allow index signature value has different values - // related to the index signature key name. - let should_update = - if let Some(index_key_value) = schema_value.dict_get_value(index_key_name) { - index_key_value.is_str() && key == &index_key_value.as_str() - } else { - true - }; - if should_update { - let op = config - .ops - .get(key) - .unwrap_or(&ConfigEntryOperationKind::Union); - schema_value.dict_update_entry( - key.as_str(), - &index_sign_value.deep_copy(), - &ConfigEntryOperationKind::Override, - None, - ); - s.dict_merge_key_value_pair( - schema_value, - key.as_str(), - value, - op.clone(), - None, - false, - ); - let value = schema_value.dict_get_value(key).unwrap(); - schema_value.dict_update_key_value( - key.as_str(), - type_pack_and_check(s, &value, vec![value_type], false), - ); - } - } else if !has_index_signature && no_such_attr { - panic!("No attribute named '{key}' in the schema '{schema_name}'"); - } - } -} - -/// For a schema instance returned by the schema body. Its schema and schema expr stack -/// length are both 1, if > 1, it's not a top level schema instance. -#[inline] -fn is_top_level_schema_instance(s: &Evaluator) -> bool { - !(s.schema_stack.borrow().len() > 1 || s.schema_expr_stack.borrow().len() > 1) -} - -impl<'ctx> Evaluator<'ctx> { - pub(crate) fn construct_schema_config_meta( - &self, - n: Option<&'ctx ast::Node>, - t: &'ctx ast::ConfigExpr, - ) -> ValueRef { - let mut config_meta = self.dict_value(); - if let Some(n) = n { - let value = self.string_value(&n.filename); - self.dict_insert_value( - &mut config_meta, - kclvm_runtime::CONFIG_META_FILENAME, - &value, - ); - let value = self.int_value(n.line as i64); - self.dict_insert_value(&mut config_meta, kclvm_runtime::CONFIG_META_LINE, &value); - let value = self.int_value(n.column as i64); - self.dict_insert_value(&mut config_meta, kclvm_runtime::CONFIG_META_COLUMN, &value); - } - for item in &t.items { - if let Some(key) = &item.node.key { - let name = match &key.node { - ast::Expr::Identifier(t) => t.names[0].node.clone(), - ast::Expr::NumberLit(t) => match t.value { - ast::NumberLitValue::Int(i) => i.to_string(), - ast::NumberLitValue::Float(f) => f.to_string(), - }, - ast::Expr::StringLit(t) => t.value.clone(), - ast::Expr::NameConstantLit(t) => match t.value { - ast::NameConstant::True => { - kclvm_runtime::KCL_NAME_CONSTANT_TRUE.to_string() - } - ast::NameConstant::False => { - kclvm_runtime::KCL_NAME_CONSTANT_FALSE.to_string() - } - ast::NameConstant::None => { - kclvm_runtime::KCL_NAME_CONSTANT_NONE.to_string() - } - ast::NameConstant::Undefined => { - kclvm_runtime::KCL_NAME_CONSTANT_UNDEFINED.to_string() - } - }, - _ => format!("{:?}", key.node), - }; - let mut config_item_meta = self.dict_value(); - let value = self.string_value(&key.filename); - self.dict_insert_value( - &mut config_item_meta, - kclvm_runtime::CONFIG_ITEM_META_FILENAME, - &value, - ); - let value = self.int_value(key.line as i64); - self.dict_insert_value( - &mut config_item_meta, - kclvm_runtime::CONFIG_ITEM_META_LINE, - &value, - ); - let value = self.int_value(key.column as i64); - self.dict_insert_value( - &mut config_item_meta, - kclvm_runtime::CONFIG_ITEM_META_COLUMN, - &value, - ); - let value = match &item.node.value.node { - ast::Expr::Config(config_expr) => { - self.construct_schema_config_meta(None, config_expr) - } - _ => self.dict_value(), - }; - self.dict_insert_value( - &mut config_item_meta, - kclvm_runtime::CONFIG_ITEM_META, - &value, - ); - self.dict_insert_value(&mut config_meta, &name, &config_item_meta) - } - } - config_meta - } - - pub(crate) fn update_schema_or_rule_scope_value( - &self, - name: &str, // Schema attribute name - value: Option<&ValueRef>, // Optional right override value - ) { - let (mut schema_value, config_value, _) = self - .get_schema_or_rule_config_info() - .expect(kcl_error::INTERNAL_ERROR_MSG); - let config_value = config_value - .dict_get_entry(name) - .unwrap_or(self.undefined_value()); - if self.scope_level() >= INNER_LEVEL && !self.is_local_var(name) { - if let Some(value) = value { - self.schema_dict_merge( - &mut schema_value, - name, - value, - &ast::ConfigEntryOperation::Override, - None, - ); - } - self.value_union(&mut schema_value, &config_value); - // Set config cache for the schema eval context. - if let Some(schema_ctx) = self.get_schema_eval_context() { - schema_ctx.borrow().set_value(self, name); - } - } - } -} diff --git a/kclvm/evaluator/src/scope.rs b/kclvm/evaluator/src/scope.rs deleted file mode 100644 index 25f569b05..000000000 --- a/kclvm/evaluator/src/scope.rs +++ /dev/null @@ -1,746 +0,0 @@ -use std::sync::{Arc, RwLock}; - -use crate::func::ClosureMap; -use crate::lazy::merge_setters; -use crate::{ - error as kcl_error, lazy::LazyEvalScope, rule::RuleEvalContextRef, schema::SchemaEvalContextRef, -}; -use kclvm_ast::ast; -use kclvm_ast::walker::TypedResultWalker; -use kclvm_primitives::{DefaultHashBuilder, IndexMap, IndexSet}; -use kclvm_runtime::{ValueRef, _kclvm_get_fn_ptr_by_name, MAIN_PKG_PATH}; -use kclvm_sema::{builtin, plugin}; - -use crate::{EvalResult, Evaluator, GLOBAL_LEVEL, INNER_LEVEL}; - -/// The evaluator scope. -#[derive(Debug, Default)] -pub struct Scope { - /// Scalars denotes the expression statement values without attribute. - pub scalars: Vec, - /// schema_scalar_idx denotes whether a schema exists in the scalar list. - pub schema_scalar_idx: usize, - /// is_schema denotes whether the scope is a schema. - pub is_schema: bool, - /// Scope normal variables - pub variables: IndexMap, - /// Potential arguments in the current scope, such as schema/lambda arguments. - pub arguments: IndexSet, -} - -impl<'ctx> Evaluator<'ctx> { - /// Init a scope named `pkgpath` with all builtin functions - pub(crate) fn init_scope(&self, pkgpath: &str) { - { - let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); - if pkg_scopes.contains_key(pkgpath) { - return; - } - let scopes = vec![Scope::default()]; - pkg_scopes.insert(String::from(pkgpath), scopes); - } - // Get the AST module list in the package path. - let module_list: Vec>> = if self.program.pkgs.contains_key(pkgpath) - { - self.program.get_modules_for_pkg(pkgpath) - } else if pkgpath.starts_with(kclvm_runtime::PKG_PATH_PREFIX) - && self.program.pkgs.contains_key(&pkgpath[1..]) - { - self.program.get_modules_for_pkg(&pkgpath[1..]) - } else { - panic!("pkgpath {} not found", pkgpath); - }; - // Init all global types including schema and rule. - for module in &module_list { - let module = module.read().expect("Failed to acquire module lock"); - for stmt in &module.body { - let name = match &stmt.node { - ast::Stmt::Schema(schema_stmt) => schema_stmt.name.node.clone(), - ast::Stmt::Rule(rule_stmt) => rule_stmt.name.node.clone(), - _ => "".to_string(), - }; - if !name.is_empty() { - self.add_variable(&name, self.undefined_value()); - } - } - } - // Init all builtin functions - for symbol in builtin::BUILTIN_FUNCTION_NAMES { - let function_name = - format!("{}_{}", builtin::KCL_BUILTIN_FUNCTION_MANGLE_PREFIX, symbol); - let function_ptr = _kclvm_get_fn_ptr_by_name(&function_name); - self.add_variable(symbol, self.function_value_with_ptr(function_ptr)); - } - // Init lazy scopes. - { - let mut lazy_scopes = self.lazy_scopes.borrow_mut(); - let mut setters = IndexMap::with_hasher(DefaultHashBuilder::default()); - for (index, module) in module_list.iter().enumerate() { - let index = self.add_global_body(index); - let module = module.read().expect("Failed to acquire module lock"); - merge_setters(&mut setters, &self.emit_setters(&module.body, Some(index))) - } - if !lazy_scopes.contains_key(pkgpath) { - lazy_scopes.insert( - pkgpath.to_string(), - LazyEvalScope { - setters, - ..Default::default() - }, - ); - } - } - // Enter the global scope. - self.enter_scope(); - } - - /// Get the scope level - pub(crate) fn scope_level(&self) -> usize { - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = &self.pkg_scopes.borrow(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get(¤t_pkgpath).expect(&msg); - // Sub the builtin global scope - scopes.len() - 1 - } - - /// Get the scope level - pub(crate) fn is_schema_scope(&self) -> bool { - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = &self.pkg_scopes.borrow(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get(¤t_pkgpath).expect(&msg); - if let Some(last_scope) = scopes.last() { - last_scope.is_schema - } else { - false - } - } - - /// Enter a schema scope - pub(crate) fn enter_schema_scope(&self, is_schema: bool) { - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); - let mut scope = Scope::default(); - scope.is_schema = is_schema; - scopes.push(scope); - } - - /// Enter scope - #[inline] - pub(crate) fn enter_scope(&self) { - self.enter_schema_scope(false); - } - - /// Leave scope - pub(crate) fn leave_scope(&self) { - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); - scopes.pop(); - } - - pub(crate) fn get_schema_eval_context(&self) -> Option { - match self.schema_stack.borrow().last() { - Some(ctx) => match ctx { - crate::EvalContext::Schema(schema) => Some(schema.clone()), - crate::EvalContext::Rule(_) => None, - }, - None => None, - } - } - - pub(crate) fn get_rule_eval_context(&self) -> Option { - match self.schema_stack.borrow().last() { - Some(ctx) => match ctx { - crate::EvalContext::Schema(_) => None, - crate::EvalContext::Rule(rule) => Some(rule.clone()), - }, - None => None, - } - } - - /// Returns (value, config, config_meta) - #[inline] - pub(crate) fn get_schema_or_rule_config_info(&self) -> Option<(ValueRef, ValueRef, ValueRef)> { - match self.get_schema_eval_context() { - Some(v) => Some(( - v.borrow().value.clone(), - v.borrow().config.clone(), - v.borrow().config_meta.clone(), - )), - None => self.get_rule_eval_context().map(|v| { - ( - v.borrow().value.clone(), - v.borrow().config.clone(), - v.borrow().config_meta.clone(), - ) - }), - } - } - - /// Append a scalar value into the scope. - pub fn add_scalar(&self, scalar: ValueRef, is_schema: bool) { - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); - let scopes = pkg_scopes - .get_mut(¤t_pkgpath) - .unwrap_or_else(|| panic!("pkgpath {} is not found", current_pkgpath)); - if let Some(last) = scopes.last_mut() { - let scalars = &mut last.scalars; - let schema_scalar_idx = &mut last.schema_scalar_idx; - if is_schema { - // Remove the last schema scalar. - if *schema_scalar_idx < scalars.len() { - scalars.remove(*schema_scalar_idx); - } - // Override the last schema scalar. - scalars.push(scalar); - *schema_scalar_idx = scalars.len() - 1; - } else { - scalars.push(scalar); - } - } - } - - /// Append a variable into the scope - pub fn add_variable(&self, name: &str, pointer: ValueRef) { - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); - if let Some(last) = scopes.last_mut() { - let variables = &mut last.variables; - variables.insert(name.to_string(), pointer); - } - } - - /// Store the argument named `name` in the current scope. - pub(crate) fn store_argument_in_current_scope(&self, name: &str) { - // Find argument name in the scope - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); - let index = scopes.len() - 1; - let arguments_mut = &mut scopes[index].arguments; - arguments_mut.insert(name.to_string()); - } - - /// Store the variable named `name` with `value` from the current scope, return false when not found - pub fn store_variable_in_current_scope(&self, name: &str, value: ValueRef) -> bool { - // Find argument name in the scope - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); - let index = scopes.len() - 1; - let variables = &mut scopes[index].variables; - // If exists and update it - if variables.get(&name.to_string()).is_some() { - variables.insert(name.to_string(), value); - return true; - } - false - } - - /// Store the variable named `name` with `value` from the scope, return false when not found - pub fn store_variable(&self, name: &str, value: ValueRef) -> bool { - // Find argument name in the scope - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); - for i in 0..scopes.len() { - let index = scopes.len() - i - 1; - let variables = &mut scopes[index].variables; - // If exists and update it - if variables.get(&name.to_string()).is_some() { - variables.insert(name.to_string(), value); - return true; - } - } - false - } - - /// Resolve variable in scope, return false when not found. - #[inline] - pub fn resolve_variable(&self, name: &str) -> bool { - self.resolve_variable_level(name).is_some() - } - - /// Resolve variable level in scope, return None when not found. - pub fn resolve_variable_level(&self, name: &str) -> Option { - // Find argument name in the scope - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = &self.pkg_scopes.borrow(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get(¤t_pkgpath).expect(&msg); - let mut level = None; - for i in 0..scopes.len() { - let index = scopes.len() - i - 1; - let variables = &scopes[index].variables; - let arguments = &scopes[index].arguments; - if variables.get(name).is_some() { - level = Some(index); - break; - } - if arguments.contains(name) { - level = Some(index); - break; - } - } - level - } - - /// Append a variable or update the existed local variable within the current scope. - pub(crate) fn add_or_update_local_variable_within_scope(&self, name: &str, value: ValueRef) { - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); - let index = scopes.len() - 1; - if let Some(scope) = scopes.last_mut() { - let variables_mut = &mut scope.variables; - if index > GLOBAL_LEVEL { - variables_mut.insert(name.to_string(), value.clone()); - } - } - } - - /// Append a variable or update the existed variable - pub fn add_or_update_global_variable( - &self, - name: &str, - value: ValueRef, - save_lazy_scope: bool, - ) { - // Find argument name in the scope - let current_pkgpath = self.current_pkgpath(); - let pkg_scopes = &mut self.pkg_scopes.borrow_mut(); - let msg = format!("pkgpath {} is not found", current_pkgpath); - let scopes = pkg_scopes.get_mut(¤t_pkgpath).expect(&msg); - let mut existed = false; - if let Some(last) = scopes.last_mut() { - let variables = &mut last.variables; - if variables.get(&name.to_string()).is_some() { - variables.insert(name.to_string(), value.clone()); - if save_lazy_scope { - self.set_value_to_lazy_scope(¤t_pkgpath, name, &value) - } - existed = true; - } - } - if !existed { - if let Some(last) = scopes.last_mut() { - let variables = &mut last.variables; - if !variables.contains_key(name) { - variables.insert(name.to_string(), value.clone()); - if save_lazy_scope { - self.set_value_to_lazy_scope(¤t_pkgpath, name, &value) - } - } - } - } - } - - /// Get the variable value named `name` from the scope, return Err when not found - pub fn get_variable(&self, name: &str) -> ValueRef { - let current_pkgpath = self.current_pkgpath(); - self.get_variable_in_pkgpath(name, ¤t_pkgpath) - } - - /// Get the variable value named `name` from the scope, return Err when not found - pub fn get_variable_in_schema_or_rule(&self, name: &str) -> ValueRef { - let pkgpath = self.current_pkgpath(); - if let Some(schema_ctx) = self.get_schema_eval_context() { - return schema_ctx - .borrow() - .get_value(self, name, &pkgpath, &self.get_target_var()); - } else if let Some(rule_ctx) = self.get_rule_eval_context() { - let rule_value: ValueRef = rule_ctx.borrow().value.clone(); - return if let Some(value) = rule_value.dict_get_value(name) { - value - } else { - self.get_variable_in_pkgpath(name, &pkgpath) - }; - } else { - self.get_variable_in_pkgpath(name, &pkgpath) - } - } - - /// Get the variable value named `name` from the scope named `pkgpath`, return Err when not found - pub fn get_variable_in_pkgpath(&self, name: &str, pkgpath: &str) -> ValueRef { - let pkg_scopes = self.pkg_scopes.borrow(); - let pkgpath = - if !pkgpath.starts_with(kclvm_runtime::PKG_PATH_PREFIX) && pkgpath != MAIN_PKG_PATH { - format!("{}{}", kclvm_runtime::PKG_PATH_PREFIX, pkgpath) - } else { - pkgpath.to_string() - }; - let mut result = self.undefined_value(); - // System module - if builtin::STANDARD_SYSTEM_MODULE_NAMES_WITH_AT.contains(&pkgpath.as_str()) { - let pkgpath = &pkgpath[1..]; - - if pkgpath == builtin::system_module::UNITS - && builtin::system_module::UNITS_FIELD_NAMES.contains(&name) - { - let value_float: f64 = kclvm_runtime::f64_unit_value(name); - let value_int: u64 = kclvm_runtime::u64_unit_value(name); - if value_int != 1 { - self.int_value(value_int as i64) - } else { - self.float_value(value_float) - } - } else { - let func_name = format!( - "{}{}_{}", - builtin::KCL_SYSTEM_MODULE_MANGLE_PREFIX, - pkgpath, - name - ); - let function_ptr = _kclvm_get_fn_ptr_by_name(&func_name); - self.function_value_with_ptr(function_ptr) - } - } - // Plugin pkgpath - else if pkgpath.starts_with(plugin::PLUGIN_PREFIX_WITH_AT) { - // Strip the @kcl_plugin to kcl_plugin. - let name = format!("{}.{}", &pkgpath[1..], name); - ValueRef::func(0, 0, self.undefined_value(), &name, "", true) - // User pkgpath - } else { - // Global or local variables. - let scopes = pkg_scopes - .get(&pkgpath) - .unwrap_or_else(|| panic!("package {} is not found", pkgpath)); - // Scopes 0 is builtin scope, Scopes 1 is the global scope, Scopes 2~ are the local scopes - let scopes_len = scopes.len(); - let mut found = false; - for i in 0..scopes_len { - let index = scopes_len - i - 1; - let variables = &scopes[index].variables; - - if let Some(var) = variables.get(name) { - // Closure vars, 2 denotes the builtin scope and the global scope, here is a closure scope. - result = if let Some(lambda_ctx) = self.last_lambda_ctx() { - let last_lambda_scope = lambda_ctx.level; - // Local scope variable or lambda closure variable. - let ignore = if let Some((start, end)) = self.scope_covers.borrow().last() { - *start <= index && index <= *end - } else { - false - }; - if index >= last_lambda_scope && !ignore { - var.clone() - } else { - lambda_ctx.closure.get(name).unwrap_or(var).clone() - } - } else { - // Not in the lambda, maybe a local variable. - var.clone() - }; - found = true; - break; - } - } - if found { - result - } else { - // Not found variable in the scope, maybe lambda closures captured in other package scopes. - self.last_lambda_ctx() - .map(|ctx| ctx.closure.get(name).cloned().unwrap_or(result.clone())) - .unwrap_or(result) - } - } - } - - fn get_variable_in_pkgpath_from_last_scope(&self, name: &str, pkgpath: &str) -> ValueRef { - let pkg_scopes = self.pkg_scopes.borrow(); - let pkgpath = - if !pkgpath.starts_with(kclvm_runtime::PKG_PATH_PREFIX) && pkgpath != MAIN_PKG_PATH { - format!("{}{}", kclvm_runtime::PKG_PATH_PREFIX, pkgpath) - } else { - pkgpath.to_string() - }; - let mut result = self.undefined_value(); - // System module - if builtin::STANDARD_SYSTEM_MODULE_NAMES_WITH_AT.contains(&pkgpath.as_str()) { - let pkgpath = &pkgpath[1..]; - - if pkgpath == builtin::system_module::UNITS - && builtin::system_module::UNITS_FIELD_NAMES.contains(&name) - { - let value_float: f64 = kclvm_runtime::f64_unit_value(name); - let value_int: u64 = kclvm_runtime::u64_unit_value(name); - if value_int != 1 { - self.int_value(value_int as i64) - } else { - self.float_value(value_float) - } - } else { - let func_name = format!( - "{}{}_{}", - builtin::KCL_SYSTEM_MODULE_MANGLE_PREFIX, - pkgpath, - name - ); - let function_ptr = _kclvm_get_fn_ptr_by_name(&func_name); - self.function_value_with_ptr(function_ptr) - } - } - // Plugin pkgpath - else if pkgpath.starts_with(plugin::PLUGIN_PREFIX_WITH_AT) { - // Strip the @kcl_plugin to kcl_plugin. - let name = format!("{}.{}", &pkgpath[1..], name); - ValueRef::func(0, 0, self.undefined_value(), &name, "", true) - // User pkgpath - } else { - // Global or local variables. - let scopes = pkg_scopes - .get(&pkgpath) - .unwrap_or_else(|| panic!("package {} is not found", pkgpath)); - // Scopes 0 is builtin scope, Scopes 1 is the global scope, Scopes 2~ are the local scopes - let scopes_len = scopes.len(); - - let index = scopes_len - 1; - let variables = &scopes[index].variables; - - if let Some(var) = variables.get(name) { - // Closure vars, 2 denotes the builtin scope and the global scope, here is a closure scope. - result = if let Some(lambda_ctx) = self.last_lambda_ctx() { - let last_lambda_scope = lambda_ctx.level; - // Local scope variable or lambda closure variable. - let ignore = if let Some((start, end)) = self.scope_covers.borrow().last() { - *start <= index && index <= *end - } else { - false - }; - if index >= last_lambda_scope && !ignore { - var.clone() - } else { - lambda_ctx.closure.get(name).unwrap_or(var).clone() - } - } else { - // Not in the lambda, maybe a local variable. - var.clone() - }; - } - result - } - } - - /// Get closure map in the current inner scope. - pub(crate) fn get_current_closure_map(&self) -> ClosureMap { - // Get variable map in the current scope. - let pkgpath = self.current_pkgpath(); - let pkg_scopes = self.pkg_scopes.borrow(); - let scopes = pkg_scopes - .get(&pkgpath) - .unwrap_or_else(|| panic!("package {} is not found", pkgpath)); - let last_lambda_ctx = self.last_lambda_ctx(); - // Get current closure map. - let mut closure_map = last_lambda_ctx - .as_ref() - .map(|ctx| ctx.closure.clone()) - .unwrap_or_default(); - // Get variable map including schema in the current scope. - for i in INNER_LEVEL..scopes.len() { - let variables = &scopes - .get(i) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .variables; - for (k, v) in variables { - closure_map.insert(k.to_string(), v.clone()); - } - } - closure_map - } - - /// Load value from name. - pub fn load_value(&self, pkgpath: &str, names: &[&str]) -> ValueRef { - if names.is_empty() { - return self.undefined_value(); - } - let name = names[0]; - if names.len() == 1 { - self.load_name(name) - } else { - let mut value = if pkgpath.is_empty() { - self.load_name(name) - } else { - self.undefined_value() - }; - for i in 0..names.len() - 1 { - let attr = names[i + 1]; - if i == 0 && !pkgpath.is_empty() { - value = self.get_variable_in_pkgpath(attr, pkgpath); - } else { - value = value.load_attr(attr) - } - } - value - } - } - - /// Load global value from name. - pub fn load_global_value(&self, pkgpath: &str, names: &[&str]) -> ValueRef { - if names.is_empty() { - return self.undefined_value(); - } - let name = names[0]; - if names.len() == 1 { - self.get_variable(name) - } else { - let mut value = if pkgpath.is_empty() { - self.get_variable(name) - } else { - self.undefined_value() - }; - for i in 0..names.len() - 1 { - let attr = names[i + 1]; - if i == 0 && !pkgpath.is_empty() { - value = self.get_variable_in_pkgpath(attr, pkgpath); - } else { - value = value.load_attr(attr) - } - } - value - } - } - - /// Load global or local value from name. - pub fn load_name(&self, name: &str) -> ValueRef { - match ( - self.is_in_schema(), - self.is_in_lambda(), - self.is_local_var(name), - ) { - // Get variable from the global lazy scope. - (false, _, false) => { - let variable = self.get_variable(name); - match self.resolve_variable_level(name) { - // Closure variable or local variables - Some(level) if level <= GLOBAL_LEVEL => self.get_value_from_lazy_scope( - &self.current_pkgpath(), - name, - &self.get_target_var(), - variable, - ), - // Schema closure or global variables - _ => variable, - } - } - // Get variable from the local or global scope. - (false, _, _) | (_, _, true) => self.get_variable(name), - // Get variable from the current schema scope. - (true, false, false) => self.get_variable_in_schema_or_rule(name), - // Get from local scope including lambda arguments, lambda variables, - // loop variables or global variables. - (true, true, _) => - // Get from local scope including lambda arguments, lambda variables, - // loop variables or global variables. - { - match self.resolve_variable_level(name) { - // Closure variable or local variables - Some(level) if level > GLOBAL_LEVEL => { - let ctx_stack = self.ctx_stack.borrow(); - let mut result = self.undefined_value(); - let mut found = false; - for i in 0..ctx_stack.len() { - let index = ctx_stack.len() - i - 1; - match &ctx_stack[index] { - crate::LambdaOrSchemaEvalContext::Schema(_) => { - let res = self.get_variable_in_schema_or_rule(name); - - if !res.is_undefined() { - result = res; - found = true; - break; - } - } - crate::LambdaOrSchemaEvalContext::Lambda(_) => { - let current_pkgpath = self.current_pkgpath(); - let res = self.get_variable_in_pkgpath_from_last_scope( - name, - ¤t_pkgpath, - ); - if !res.is_undefined() { - result = res; - found = true; - break; - } - } - } - } - if found { - result - } else { - // Not found variable in the scope, maybe lambda closures captured in other package scopes. - self.last_lambda_ctx() - .map(|ctx| ctx.closure.get(name).cloned().unwrap_or(result.clone())) - .unwrap_or(result) - } - } - // Schema closure or global variables - _ => self.get_variable_in_schema_or_rule(name), - } - } - } - } - - /// Load assignment target value. - pub fn load_target(&self, target: &'ctx ast::Target) -> EvalResult { - let mut value = self.load_name(target.get_name()); - for path in &target.paths { - match path { - ast::MemberOrIndex::Member(member) => { - let attr = &member.node; - value = value.load_attr(attr); - } - ast::MemberOrIndex::Index(index) => { - let index = self.walk_expr(index)?; - value = value.bin_subscr(&index); - } - } - } - Ok(value) - } - - /// Load value from assignment target path. - pub fn load_target_path(&self, value: &ValueRef, path: &'ctx ast::MemberOrIndex) -> EvalResult { - Ok(match path { - ast::MemberOrIndex::Member(member) => { - let attr = &member.node; - value.load_attr(attr) - } - ast::MemberOrIndex::Index(index) => { - let index = self.walk_expr(index)?; - value.bin_subscr(&index) - } - }) - } - - pub fn store_target_path( - &self, - value: &mut ValueRef, - path: &'ctx ast::MemberOrIndex, - right_value: &ValueRef, - ) -> EvalResult { - match path { - ast::MemberOrIndex::Member(member) => { - let attr = &member.node; - self.dict_set_value(value, attr, &right_value); - } - ast::MemberOrIndex::Index(index) => { - let index = self.walk_expr(index)?; - value.bin_subscr_set(&mut self.runtime_ctx.borrow_mut(), &index, &right_value); - } - } - self.ok_result() - } -} diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assert_stmt_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assert_stmt_0.snap deleted file mode 100644 index 36e89bb3f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assert_stmt_0.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assert_stmt_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assert_stmt_1.snap deleted file mode 100644 index 36e89bb3f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assert_stmt_1.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_0.snap deleted file mode 100644 index 36e89bb3f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_0.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_1.snap deleted file mode 100644 index 5e4bff410..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_1.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_2.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_2.snap deleted file mode 100644 index 6742ebd45..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_2.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 3 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_3.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_3.snap deleted file mode 100644 index 7a404a65f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_3.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1 -b: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_4.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_4.snap deleted file mode 100644 index 7a404a65f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_4.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1 -b: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_5.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_5.snap deleted file mode 100644 index e56d37d9b..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_5.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -- 1 -- 0 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_6.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_6.snap deleted file mode 100644 index 5a0777795..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_6.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -- key: 1 -- key: 0 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_7.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_7.snap deleted file mode 100644 index 9b744ff8d..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__assign_stmt_7.snap +++ /dev/null @@ -1,13 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -- key: - key: - - 1 - - 0 -- key: - key: - - 0 - - 0 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_0.snap deleted file mode 100644 index 5e4bff410..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_0.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_1.snap deleted file mode 100644 index d1fb2f6b6..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_1.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 0 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_10.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_10.snap deleted file mode 100644 index 36e89bb3f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_10.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_11.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_11.snap deleted file mode 100644 index 36e89bb3f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_11.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_12.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_12.snap deleted file mode 100644 index 1f84c9b2b..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_12.snap +++ /dev/null @@ -1,10 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -- 1 -- 0 -- 0 -- 0 -- 0 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_13.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_13.snap deleted file mode 100644 index 1afd0a31d..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_13.snap +++ /dev/null @@ -1,10 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -- key: 2 -- key: 1 -- key: 1 -- key: 1 -- key: 1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_14.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_14.snap deleted file mode 100644 index eecfa14bb..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_14.snap +++ /dev/null @@ -1,25 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -- key: - key: - - 1 - - 0 -- key: - key: - - 0 - - 0 -- key: - key: - - 0 - - 0 -- key: - key: - - 0 - - 0 -- key: - key: - - 0 - - 0 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_2.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_2.snap deleted file mode 100644 index 5e4bff410..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_2.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_3.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_3.snap deleted file mode 100644 index b6f161a65..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_3.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1.0 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_4.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_4.snap deleted file mode 100644 index 36e89bb3f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_4.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_5.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_5.snap deleted file mode 100644 index 97594b724..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_5.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 9 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_6.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_6.snap deleted file mode 100644 index 07db3ae4a..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_6.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 6 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_7.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_7.snap deleted file mode 100644 index 36e89bb3f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_7.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_8.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_8.snap deleted file mode 100644 index 6742ebd45..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_8.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 3 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_9.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_9.snap deleted file mode 100644 index 5e4bff410..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__aug_assign_stmt_9.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__binary_expr_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__binary_expr_0.snap deleted file mode 100644 index 78fdeb343..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__binary_expr_0.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__binary_expr_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__binary_expr_1.snap deleted file mode 100644 index fc2c22613..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__binary_expr_1.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: {} -b: [] diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__compare_expr_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__compare_expr_0.snap deleted file mode 100644 index 54215b924..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__compare_expr_0.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: true -b: true -c: false -d: false diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__dict_expr_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__dict_expr_0.snap deleted file mode 100644 index 0f2e7e449..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__dict_expr_0.snap +++ /dev/null @@ -1,15 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: - k1: v1 - k2: v2 -b: - k1: v1 - k2: v2 -c: - k1: v1 -d: - k1: v1 - k2: v2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__exec_with_plugin.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__exec_with_plugin.snap deleted file mode 100644 index 7541ff36e..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__exec_with_plugin.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -sum: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_0.snap deleted file mode 100644 index 49182c57f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_0.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -1 - diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_1.snap deleted file mode 100644 index 59eed1b6b..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_1.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -2.0 - diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_2.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_2.snap deleted file mode 100644 index 5148a004e..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_2.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -true - diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_3.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_3.snap deleted file mode 100644 index 81e7a4fec..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_3.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -null - diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_4.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_4.snap deleted file mode 100644 index aa2a630ba..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_4.snap +++ /dev/null @@ -1,9 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -1 ---- -2 ---- -3 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_5.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_5.snap deleted file mode 100644 index c4f84418b..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__expr_stmt_5.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -k: v diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__function_stmt_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__function_stmt_0.snap deleted file mode 100644 index 3d3de056a..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__function_stmt_0.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run_as_function().to_string())" ---- -"bar" diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_expr_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_expr_0.snap deleted file mode 100644 index 36e89bb3f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_expr_0.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_expr_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_expr_1.snap deleted file mode 100644 index d1fb2f6b6..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_expr_1.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 0 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_expr_2.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_expr_2.snap deleted file mode 100644 index 5e4bff410..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_expr_2.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_0.snap deleted file mode 100644 index 36e89bb3f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_0.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_1.snap deleted file mode 100644 index b49088fc6..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_1.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -b: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_3.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_3.snap deleted file mode 100644 index b49088fc6..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_3.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -b: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_4.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_4.snap deleted file mode 100644 index fb00bbfd6..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_4.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -c: 3 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_5.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_5.snap deleted file mode 100644 index b49088fc6..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_5.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -b: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_6.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_6.snap deleted file mode 100644 index fe81f5423..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_6.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -b: 1 -c: 1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_7.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_7.snap deleted file mode 100644 index afb873c8d..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_7.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 3 -c: - a: 3 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_8.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_8.snap deleted file mode 100644 index 10f5ca505..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__if_stmt_8.snap +++ /dev/null @@ -1,9 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -items: -- key2: value2 -c: - items: - - key2: value2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__import_stmt_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__import_stmt_0.snap deleted file mode 100644 index 36e89bb3f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__import_stmt_0.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__import_stmt_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__import_stmt_1.snap deleted file mode 100644 index b49088fc6..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__import_stmt_1.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -b: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__import_stmt_2.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__import_stmt_2.snap deleted file mode 100644 index 23788f0ea..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__import_stmt_2.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -v: null -x: true diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__import_stmt_3.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__import_stmt_3.snap deleted file mode 100644 index 05da1a0b2..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__import_stmt_3.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -x: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_0.snap deleted file mode 100644 index 8ab678285..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_0.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 2 -b: 4 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_1.snap deleted file mode 100644 index 8ab678285..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_1.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 2 -b: 4 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_2.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_2.snap deleted file mode 100644 index e4e42ff0f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_2.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 2 -b: 3 -c: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_3.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_3.snap deleted file mode 100644 index 05da1a0b2..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_3.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -x: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_4.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_4.snap deleted file mode 100644 index 536a7cb4e..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_4.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -x: 6 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_5.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_5.snap deleted file mode 100644 index 2301a537b..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_5.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -x: - value: 4 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_6.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_6.snap deleted file mode 100644 index 2e26e4ec1..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lambda_6.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format! (\"{}\", evaluator.run().unwrap().1)" ---- -my_dict: - my_field: 1 - x: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lazy_scope_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lazy_scope_0.snap deleted file mode 100644 index 79c9ffcea..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lazy_scope_0.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -b: 3 -a: 1 -c: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lazy_scope_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lazy_scope_1.snap deleted file mode 100644 index 88f118d5c..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lazy_scope_1.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -data: - b: 3 - a: 1 - c: 2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lazy_scope_2.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lazy_scope_2.snap deleted file mode 100644 index 0841b0bf1..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__lazy_scope_2.snap +++ /dev/null @@ -1,10 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -data1: - name: '1' -data2: - name: '1' - version: v0.1.0 -version: v0.1.0 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__list_comp1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__list_comp1.snap deleted file mode 100644 index 07d14f179..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__list_comp1.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format! (\"{}\", evaluator.run().unwrap().1)" ---- -a: -- 你 -- 好 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__list_expr_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__list_expr_0.snap deleted file mode 100644 index 6c52f64c4..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__list_expr_0.snap +++ /dev/null @@ -1,19 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -- 1 -- 2 -- 3 -b: -- 1 -- 2 -- 3 -c: -- 1 -- 3 -d: -- 1 -- 2 -- 3 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__literal_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__literal_0.snap deleted file mode 100644 index e6371b1b8..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__literal_0.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -longStringStartWithNewline: | - This is the second line - This is the third line diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__literal_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__literal_1.snap deleted file mode 100644 index 007822861..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__literal_1.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: - k: v -b: '{"k": "v"}' diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__literal_2.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__literal_2.snap deleted file mode 100644 index 09411b88c..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__literal_2.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1048576.0 -b: 2000.0 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__loop_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__loop_0.snap deleted file mode 100644 index 60fa5c9b3..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__loop_0.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -- 1 -- 4 -- 9 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__loop_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__loop_1.snap deleted file mode 100644 index 4940f8f17..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__loop_1.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -- 3 -- 4 -- 5 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__paren_expr_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__paren_expr_0.snap deleted file mode 100644 index bb3e7496e..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__paren_expr_0.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 4 -b: 4 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_0.snap deleted file mode 100644 index d7b389385..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_0.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -b: true diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_1.snap deleted file mode 100644 index d7b389385..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_1.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -b: true diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_2.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_2.snap deleted file mode 100644 index 21f291ddd..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_2.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -b: false diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_3.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_3.snap deleted file mode 100644 index 21f291ddd..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_3.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -b: false diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_4.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_4.snap deleted file mode 100644 index 5134cc404..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_4.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -b: -- 2 -- 3 -- 4 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_5.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_5.snap deleted file mode 100644 index d2a641e73..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_5.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -b: -- 2 -- 3 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_6.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_6.snap deleted file mode 100644 index a131910c6..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_6.snap +++ /dev/null @@ -1,8 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -b: -- 1 -- 4 -- 9 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_7.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_7.snap deleted file mode 100644 index 0a75719c6..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__quant_expr_7.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -b: [] diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__schema_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__schema_0.snap deleted file mode 100644 index 07d05c98a..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__schema_0.snap +++ /dev/null @@ -1,10 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -alice: - name: Alice - age: 10 -bob: - name: Bob - age: 18 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__schema_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__schema_1.snap deleted file mode 100644 index 07d05c98a..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__schema_1.snap +++ /dev/null @@ -1,10 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -alice: - name: Alice - age: 10 -bob: - name: Bob - age: 18 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__schema_2.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__schema_2.snap deleted file mode 100644 index 43c6b8277..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__schema_2.snap +++ /dev/null @@ -1,15 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -VALUES_MAP: - '1': - attr1: foobar - '2': - attr2: bar -config: - provider: '1' - values: - attr1: foobar - provider_values: - attr1: foobar diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__selector_expr_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__selector_expr_0.snap deleted file mode 100644 index 81597c887..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__selector_expr_0.snap +++ /dev/null @@ -1,7 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: v -b: v -c: null diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__selector_expr_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__selector_expr_1.snap deleted file mode 100644 index d133972ec..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__selector_expr_1.snap +++ /dev/null @@ -1,11 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -- 3 -- 2 -- 1 -b: 1 -c: 3 -d: null diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__subscript_expr_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__subscript_expr_0.snap deleted file mode 100644 index ae5e13d61..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__subscript_expr_0.snap +++ /dev/null @@ -1,10 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -- 3 -- 2 -- 1 -b: 1 -c: 3 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__subscript_expr_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__subscript_expr_1.snap deleted file mode 100644 index d133972ec..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__subscript_expr_1.snap +++ /dev/null @@ -1,11 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -- 3 -- 2 -- 1 -b: 1 -c: 3 -d: null diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__unary_expr_0.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__unary_expr_0.snap deleted file mode 100644 index 36e89bb3f..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__unary_expr_0.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: 1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__unary_expr_1.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__unary_expr_1.snap deleted file mode 100644 index 78fdeb343..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__unary_expr_1.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -1 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__unary_expr_2.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__unary_expr_2.snap deleted file mode 100644 index d38bc7238..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__unary_expr_2.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: -2 diff --git a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__unary_expr_3.snap b/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__unary_expr_3.snap deleted file mode 100644 index dc5414160..000000000 --- a/kclvm/evaluator/src/snapshots/kclvm_evaluator__tests__unary_expr_3.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: evaluator/src/tests.rs -expression: "format!(\"{}\", evaluator.run().unwrap().1)" ---- -a: true diff --git a/kclvm/evaluator/src/tests.rs b/kclvm/evaluator/src/tests.rs deleted file mode 100644 index e2c06d087..000000000 --- a/kclvm/evaluator/src/tests.rs +++ /dev/null @@ -1,621 +0,0 @@ -use crate::Evaluator; -use kclvm_ast::MAIN_PKG; -use kclvm_loader::{load_packages, LoadPackageOptions}; -use kclvm_parser::LoadProgramOptions; -use kclvm_runtime::{Context, ValueRef}; - -#[macro_export] -macro_rules! evaluator_snapshot { - ($name:ident, $src:expr) => { - #[test] - fn $name() { - let p = load_packages(&LoadPackageOptions { - paths: vec!["test.k".to_string()], - load_opts: Some(LoadProgramOptions { - k_code_list: vec![$src.to_string()], - ..Default::default() - }), - load_builtin: false, - ..Default::default() - }) - .unwrap(); - let evaluator = Evaluator::new(&p.program); - insta::assert_snapshot!(format!("{}", evaluator.run().unwrap().1)); - } - }; -} - -#[macro_export] -macro_rules! evaluator_function_snapshot { - ($name:ident, $src:expr) => { - #[test] - fn $name() { - let p = load_packages(&LoadPackageOptions { - paths: vec!["test.k".to_string()], - load_opts: Some(LoadProgramOptions { - k_code_list: vec![$src.to_string()], - ..Default::default() - }), - load_builtin: false, - ..Default::default() - }) - .unwrap(); - let evaluator = Evaluator::new(&p.program); - insta::assert_snapshot!(format!("{}", evaluator.run_as_function().to_string())); - } - }; -} - -evaluator_function_snapshot! {function_stmt_0, r#" -import json - -config = { - foo: "bar" -} - -json.encode("${config.foo}") -"#} - -evaluator_snapshot! {expr_stmt_0, "1"} -evaluator_snapshot! {expr_stmt_1, "2.0"} -evaluator_snapshot! {expr_stmt_2, "True"} -evaluator_snapshot! {expr_stmt_3, r#"None"#} -evaluator_snapshot! {expr_stmt_4, r#"[1, 2, 3]"#} -evaluator_snapshot! {expr_stmt_5, r#"{k = "v"}"#} - -evaluator_snapshot! {assign_stmt_0, "a = 1"} -evaluator_snapshot! {assign_stmt_1, "a = 1 + 1"} -evaluator_snapshot! {assign_stmt_2, "a = (1 + 2)"} -evaluator_snapshot! {assign_stmt_3, r#"a = 1 -b = a + 1 -"#} -evaluator_snapshot! {assign_stmt_4, r#"a: int = 1 -b: int = a + 1 -"#} -evaluator_snapshot! {assign_stmt_5, r#"_a = [0] * 2 -_a[0] = 1 -a = _a -"#} -evaluator_snapshot! {assign_stmt_6, r#"_a = [{"key": 0}] * 2 -_a[0].key = 1 -a = _a -"#} -evaluator_snapshot! {assign_stmt_7, r#"_a = [{key.key = [0] * 2}] * 2 -_a[0].key.key[0] = 1 -a = _a -"#} - -evaluator_snapshot! {aug_assign_stmt_0, r#"_a = 1 -_a += 1 -a = _a -"#} -evaluator_snapshot! {aug_assign_stmt_1, r#"_a = 1 -_a -= 1 -a = _a -"#} -evaluator_snapshot! {aug_assign_stmt_2, r#"_a = 1 -_a *= 2 -a = _a -"#} -evaluator_snapshot! {aug_assign_stmt_3, r#"_a = 2 -_a /= 2 -a = _a -"#} -evaluator_snapshot! {aug_assign_stmt_4, r#"_a = 3 -_a %= 2 -a = _a -"#} -evaluator_snapshot! {aug_assign_stmt_5, r#"_a = 3 -_a **= 2 -a = _a -"#} -evaluator_snapshot! {aug_assign_stmt_6, r#"_a = 3 -_a <<= 1 -a = _a -"#} -evaluator_snapshot! {aug_assign_stmt_7, r#"_a = 3 -_a >>= 1 -a = _a -"#} -evaluator_snapshot! {aug_assign_stmt_8, r#"_a = 3 -_a |= 1 -a = _a -"#} -evaluator_snapshot! {aug_assign_stmt_9, r#"_a = 3 -_a ^= 1 -a = _a -"#} -evaluator_snapshot! {aug_assign_stmt_10, r#"_a = 3 -_a &= 1 -a = _a -"#} -evaluator_snapshot! {aug_assign_stmt_11, r#"_a = 3 -_a //= 2 -a = _a -"#} -evaluator_snapshot! {aug_assign_stmt_12, r#"_a = [0] * 5 -_a[0] += 1 -a = _a -"#} -evaluator_snapshot! {aug_assign_stmt_13, r#"_a = [{"key": 1}] * 5 -_a[0].key += 1 -a = _a -"#} -evaluator_snapshot! {aug_assign_stmt_14, r#"_a = [{key.key = [0, 0]}] * 5 -_a[0].key.key[0] += 1 -a = _a -"#} - -evaluator_snapshot! {assert_stmt_0, r#"assert True, "msg" -a = 1 -"#} - -evaluator_snapshot! {assert_stmt_1, r#"assert False if False, "msg" -a = 1 -"#} - -evaluator_snapshot! {if_stmt_0, r#"if True: - a = 1 -else: - b = 2 -"#} -evaluator_snapshot! {if_stmt_1, r#"if False: - a = 1 -else: - b = 2 -"#} -evaluator_snapshot! {if_stmt_3, r#"if False: - a = 1 -elif True: - b = 2 -else: - c = 3 -"#} -evaluator_snapshot! {if_stmt_4, r#"if False: - a = 1 -elif False: - b = 2 -else: - c = 3 -"#} -evaluator_snapshot! {if_stmt_5, r#"if False: - a = 1 -else: - if True: - b = 2 - else: - c = 3 -"#} -evaluator_snapshot! {if_stmt_6, r#" -if False: - a = 1 -else: - if True: - b = 1 - if True: - c = 1 -"#} -evaluator_snapshot! {if_stmt_7, r#" -_a = 1 -if True: - _a = 2 - _a += 1 -a = _a - -schema Config: - _a = 1 - if True: - _a = 2 - _a += 1 - a = _a - -c = Config {} -"#} -evaluator_snapshot! {if_stmt_8, r#" -_items = [] -if False: - _items += [ {key1 = "value1"} ] -if True: - _items += [ {key2 = "value2"} ] -items = _items - -schema Config: - _items = [] - if False: - _items += [ {key1 = "value1"} ] - if True: - _items += [ {key2 = "value2"} ] - items = _items - -c = Config {} -"#} - -evaluator_snapshot! {import_stmt_0, r#"import math -a = 1 -"#} -evaluator_snapshot! {import_stmt_1, r#"import math -import math -b = 2 -"#} -evaluator_snapshot! {import_stmt_2, r#" -import regex - -v = option("foo") -x = regex.match("foo", "^\\w+$") -"#} -evaluator_snapshot! {import_stmt_3, r#"import math - -x = math.log(10) -"#} - -evaluator_snapshot! {quant_expr_0, r#"b = all a in [1, 2, 3] { - a > 0 -} -"#} -evaluator_snapshot! {quant_expr_1, r#"b = any a in [1, 2, 3] { - a > 2 -} -"#} -evaluator_snapshot! {quant_expr_2, r#"b = all a in [1, 2, 3] { - a > 5 -} -"#} -evaluator_snapshot! {quant_expr_3, r#"b = any a in [1, 2, 3] { - a > 5 -} -"#} -evaluator_snapshot! {quant_expr_4, r#"b = map a in [1, 2, 3] { - a + 1 -} -"#} -evaluator_snapshot! {quant_expr_5, r#"b = filter a in [1, 2, 3] { - a > 1 -} -"#} -evaluator_snapshot! {quant_expr_6, r#"b = map a in [1, 2, 3] { - a ** 2 -} -"#} -evaluator_snapshot! {quant_expr_7, r#"b = filter a in [1, 2, 3] { - a == 0 -} -"#} - -evaluator_snapshot! {if_expr_0, r#"a = 1 if True else 0"#} -evaluator_snapshot! {if_expr_1, r#"a = 1 if False else 0"#} -evaluator_snapshot! {if_expr_2, r#"a = 1 if False else 0 if False else 2"#} - -evaluator_snapshot! {unary_expr_0, r#"a = +1"#} -evaluator_snapshot! {unary_expr_1, r#"a = -1"#} -evaluator_snapshot! {unary_expr_2, r#"a = ~1"#} -evaluator_snapshot! {unary_expr_3, r#"a = not None"#} - -evaluator_snapshot! {binary_expr_0, r#"a = 1 + 1 * 2 - 4"#} -evaluator_snapshot! {binary_expr_1, r#"a = None or {} -b = [] and {} -"#} - -evaluator_snapshot! {selector_expr_0, r#"a = {k = "v"}.k -b = {k = "v"}?.k -c = None?.k -"#} -evaluator_snapshot! {selector_expr_1, r#"a = [1, 2, 3]?[::-1] -b = a?[-1] -c = a?[0] -d = None?[1] -"#} - -evaluator_snapshot! {subscript_expr_0, r#"a = [1, 2, 3][::-1] -b = a[-1] -c = a[0] -"#} -evaluator_snapshot! {subscript_expr_1, r#"a = [1, 2, 3]?[::-1] -b = a?[-1] -c = a?[0] -d = None?[1] -"#} - -evaluator_snapshot! {compare_expr_0, r#"a = 1 < 10 -b = 1 < 10 < 100 -c = 1 > 10 > 100 -d = 1 < 10 > 100 -"#} - -evaluator_snapshot! {paren_expr_0, r#"a = 2 * (1 + 1) -b = (((1 + 1))) * 2 -"#} - -evaluator_snapshot! {list_expr_0, r#"a = [1, 2, 3] -b = [1, if True: 2, 3] -c = [1, if False: 2, 3] -d = [1, *[2, 3]] -"#} - -evaluator_snapshot! {dict_expr_0, r#"a = {k1 = "v1", k2 = "v2"} -b = {k1 = "v1", if True: k2 = "v2"} -c = {k1 = "v1", if False: k2 = "v2"} -d = {k1 = "v1", **{k2 = "v2"}} -"#} - -evaluator_snapshot! {loop_0, r#"a = [i ** 2 for i in [1, 2, 3]]"#} -evaluator_snapshot! {loop_1, r#"a = [i + j for i in [1, 2, 3] for j in [1, 2, 3] if i < j]"#} - -evaluator_snapshot! {literal_0, r#"longStringStartWithNewline = """\ -This is the second line -This is the third line -""" -"#} -evaluator_snapshot! {literal_1, r#"a = {k = "v"} -b = "${a: #json}" -"#} -evaluator_snapshot! {literal_2, r#"a = 1Mi -b = 2K -"#} - -evaluator_snapshot! {lambda_0, r#"f = lambda x {x * 2} -a = f(1) -b = f(2) -"#} -evaluator_snapshot! {lambda_1, r#"a = lambda x {x * 2}(1) -b = lambda x {x * 2}(2) -"#} -evaluator_snapshot! {lambda_2, r#"import math -a = math.log(10) -b = len("abc") -c = len([1, 2]) -"#} -evaluator_snapshot! {lambda_3, r#" -x = lambda { - a = 1 - lambda { - a + 1 - }() -}() -"#} -evaluator_snapshot! {lambda_4, r#" -x = lambda { - a = 1 - b = 2 - lambda x { - a + b + x - }(3) -}() -"#} -evaluator_snapshot! {lambda_5, r#" -func = lambda config: {str:} { - x = 1 - lambda { - y = 1 - lambda { - z = 1 - lambda { - {value = x + y + z + config.key} - }() - }() - }() -} - -x = func({key = 1}) -"#} - -evaluator_snapshot! {lambda_6, r#" -schema A: - my_field: int - - get_field: () -> int = lambda { - my_field - } - -_a = A{my_field = 2} -my_dict = { - my_field = 1 - x = _a.get_field() -} -"#} - -evaluator_snapshot! {schema_0, r#" -schema Person: - name: str = "Alice" - age: int = 10 - -alice = Person {} -bob = Person { - name = "Bob" - age = 18 -} -"#} -evaluator_snapshot! {schema_1, r#" -schema Person: - name: str = "Alice" - age: int = 10 - -alice: Person {} -bob: Person { - name: "Bob" - age: 18 -} -"#} -evaluator_snapshot! {schema_2, r#" -VALUES_MAP = { - "1": Values1{ - attr1 = "foo" - } - "2": Values2 { - attr2 = "bar" - } -} - -schema Config: - provider: "1" | "2" - values = VALUES_MAP[provider] - provider_values: Values1 | Values2 = values - -schema CommonValues: - -schema Values1(CommonValues): - attr1: str - -schema Values2(CommonValues): - attr2: str - -config: Config { - provider = "1" - provider_values.attr1 = "foobar" -} -"#} -evaluator_snapshot! {lazy_scope_0, r#" -b = a + c -a = 1 -c = a + 1 -"#} -evaluator_snapshot! {lazy_scope_1, r#" -schema Data: - b = a + c - a = 1 - c = a + 1 - -data = Data {} -"#} -evaluator_snapshot! {lazy_scope_2, r#" -schema Data: - name: str - version?: str - -data1 = Data { - name = data2.name -} - -data2 = Data { - name = "1" - version = version -} - -version = "v0.1.0" -"#} - -evaluator_snapshot! {list_comp1, r#" -a = [ x for x in "你好"] -"#} - -#[test] -fn test_if_stmt_setters() { - let p = load_packages(&LoadPackageOptions { - paths: vec!["test.k".to_string()], - load_opts: Some(LoadProgramOptions { - k_code_list: vec![r#" - _a = 1 - if True: - _a += 1 - elif False: - _a += 1 - a=_a - "# - .to_string()], - ..Default::default() - }), - load_builtin: false, - ..Default::default() - }) - .unwrap(); - let evaluator = Evaluator::new(&p.program); - evaluator.run().unwrap(); - let scopes = evaluator.lazy_scopes.borrow(); - let var_setters = scopes.get(MAIN_PKG).unwrap().setters.get("_a").unwrap(); - assert_eq!(var_setters.len(), 3); -} - -use std::cell::RefCell; -use std::rc::Rc; -use std::sync::Arc; -use std::thread; - -const MULTI_THREAD_SOURCE: &str = r#" -import regex -foo = option("foo") -bar = option("bar") -x = regex.match("", "") -"#; - -#[test] -fn test_multithread_exec() { - let threads = 10; - multithread_check(threads, |thread| { - println!("run: {}", thread); - for _ in 0..1000 { - run_code(MULTI_THREAD_SOURCE); - } - println!("done: {}", thread); - }); -} - -fn multithread_check(threads: i32, check: impl Fn(i32) + Send + Sync + 'static) { - let check_shared = Arc::new(check); - let mut handles = vec![]; - for thread in 0..threads { - let check_shared = Arc::clone(&check_shared); - let handle = thread::spawn(move || { - check_shared(thread); - }); - handles.push(handle); - } - for handle in handles { - handle.join().unwrap(); - } -} - -fn run_code(source: &str) -> (String, String) { - let p = load_packages(&LoadPackageOptions { - paths: vec!["test.k".to_string()], - load_opts: Some(LoadProgramOptions { - k_code_list: vec![source.to_string()], - ..Default::default() - }), - load_builtin: false, - ..Default::default() - }) - .unwrap(); - let evaluator = Evaluator::new(&p.program); - evaluator.run().unwrap() -} - -fn testing_sum(_: &Context, args: &ValueRef, _: &ValueRef) -> anyhow::Result { - let a = args - .arg_i_int(0, Some(0)) - .ok_or(anyhow::anyhow!("expect int value for the first param"))?; - let b = args - .arg_i_int(1, Some(0)) - .ok_or(anyhow::anyhow!("expect int value for the second param"))?; - Ok((a + b).into()) -} - -fn context_with_plugin() -> Rc> { - let mut plugin_functions: kclvm_primitives::IndexMap = - Default::default(); - let func = Arc::new(testing_sum); - plugin_functions.insert("testing.add".to_string(), func); - let mut ctx = Context::new(); - ctx.plugin_functions = plugin_functions; - Rc::new(RefCell::new(ctx)) -} - -#[test] -fn test_exec_with_plugin() { - let src = r#" -import kcl_plugin.testing - -sum = testing.add(1, 1) -"#; - let p = load_packages(&LoadPackageOptions { - paths: vec!["test.k".to_string()], - load_opts: Some(LoadProgramOptions { - load_plugins: true, - k_code_list: vec![src.to_string()], - ..Default::default() - }), - load_builtin: false, - ..Default::default() - }) - .unwrap(); - let evaluator = Evaluator::new_with_runtime_ctx(&p.program, context_with_plugin()); - insta::assert_snapshot!(format!("{}", evaluator.run().unwrap().1)); -} diff --git a/kclvm/evaluator/src/ty.rs b/kclvm/evaluator/src/ty.rs deleted file mode 100644 index e66063f9b..000000000 --- a/kclvm/evaluator/src/ty.rs +++ /dev/null @@ -1,277 +0,0 @@ -use kclvm_runtime::{ - check_type, dereference_type, is_dict_type, is_list_type, is_schema_type, is_type_union, - schema_config_meta, schema_runtime_type, separate_kv, split_type_union, val_plan, - ConfigEntryOperationKind, ValueRef, BUILTIN_TYPES, KCL_TYPE_ANY, PKG_PATH_PREFIX, -}; -use scopeguard::defer; - -use crate::error as kcl_error; -use crate::schema::SchemaEvalContext; -use crate::{proxy::Proxy, Evaluator}; - -/// Use the schema instance to build a new schema instance using the schema construct function -pub fn resolve_schema(s: &Evaluator, schema: &ValueRef, keys: &[String]) -> ValueRef { - if !schema.is_schema() { - return schema.clone(); - } - let schema_value = schema.as_schema(); - let schema_type_name = schema_runtime_type(&schema_value.name, &schema_value.pkgpath); - if let Some(index) = s.schemas.borrow().get(&schema_type_name) { - let keys = keys.iter().map(|v| v.as_str()).collect(); - let config_value = - schema.dict_get_entries_with_op(keys, &ConfigEntryOperationKind::Override); - let config_meta = { - let ctx = s.runtime_ctx.borrow(); - schema_config_meta( - &ctx.panic_info.kcl_file, - ctx.panic_info.kcl_line as u64, - ctx.panic_info.kcl_col as u64, - ) - }; - - let frame = { - let frames = s.frames.borrow(); - frames - .get(*index) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone() - }; - let schema = if let Proxy::Schema(caller) = &frame.proxy { - s.push_pkgpath(&frame.pkgpath); - s.push_backtrace(&frame); - defer! { - s.pop_backtrace(); - s.pop_pkgpath(); - } - let value = (caller.body)( - s, - &caller.ctx.borrow().snapshot(config_value, config_meta), - &schema_value.args, - &schema_value.kwargs, - ); - value - } else { - schema.clone() - }; - return schema; - } - schema.clone() -} - -/// Type pack and check ValueRef with the expected type vector -pub fn type_pack_and_check( - s: &Evaluator, - value: &ValueRef, - expected_types: Vec<&str>, - strict: bool, -) -> ValueRef { - if value.is_none_or_undefined() || expected_types.is_empty() { - return value.clone(); - } - let is_schema = value.is_schema(); - let mut checked = false; - let mut converted_value = value.clone(); - let expected_type = &expected_types.join(" | ").replace('@', ""); - for tpe in &expected_types { - if !is_schema { - converted_value = convert_collection_value(s, value, tpe); - } - // Runtime type check - checked = check_type( - &converted_value, - &s.runtime_ctx.borrow().panic_info.kcl_pkgpath, - tpe, - strict, - ); - if checked { - break; - } - } - if !checked { - let mut error_msgs = vec![]; - for tpe in &expected_types { - if is_schema_type(tpe) { - let schema_type_name = if tpe.contains('.') { - if tpe.starts_with(PKG_PATH_PREFIX) { - tpe.to_string() - } else { - format!("{PKG_PATH_PREFIX}{tpe}") - } - } else { - format!("{}.{}", s.current_pkgpath(), tpe) - }; - - if let Some(index) = s.schemas.borrow().get(&schema_type_name) { - let frame = { - let frames = s.frames.borrow(); - frames - .get(*index) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone() - }; - if let Proxy::Schema(caller) = &frame.proxy { - if value.is_config() { - let config = value.as_dict_ref(); - for (key, _) in &config.values { - let no_such_attr = - !SchemaEvalContext::has_attr(s, &caller.ctx, key) - && !key.starts_with('_'); - let has_index_signature = - SchemaEvalContext::has_index_signature(s, &caller.ctx); - if !has_index_signature && no_such_attr { - error_msgs.push(format!( - "Schema {} does not contain attribute {}", - tpe, key - )); - } - } - - for (attr, is_optional) in SchemaEvalContext::get_attrs(s, &caller.ctx) - { - if !config.values.contains_key(&attr) && !is_optional { - error_msgs.push(format!( - "Schema {}'s attribute {} is missing", - tpe, attr - )); - } - } - } - } - } - } - } - panic!( - "expect {expected_type}, got {}{}", - val_plan::type_of(value, true), - if error_msgs.is_empty() { - "".to_string() - } else { - format!(". For details:\n{}", error_msgs.join("\n")) - } - ); - } - converted_value -} - -/// Convert collection value including dict/list to the potential schema -pub fn convert_collection_value(s: &Evaluator, value: &ValueRef, tpe: &str) -> ValueRef { - if tpe.is_empty() || tpe == KCL_TYPE_ANY { - return value.clone(); - } - let is_collection = value.is_list() || value.is_dict(); - let invalid_match_dict = is_dict_type(tpe) && !value.is_dict(); - let invalid_match_list = is_list_type(tpe) && !value.is_list(); - let invalid_match = invalid_match_dict || invalid_match_list; - if !is_collection || invalid_match { - return value.clone(); - } - // Convert a value to union types e.g., {a: 1} => A | B - if is_type_union(tpe) { - let types = split_type_union(tpe); - convert_collection_value_with_union_types(s, value, &types) - } else if is_dict_type(tpe) { - //let (key_tpe, value_tpe) = separate_kv(tpe); - let (_, value_tpe) = separate_kv(&dereference_type(tpe)); - let mut expected_dict = ValueRef::dict(None); - let dict_ref = value.as_dict_ref(); - expected_dict - .set_potential_schema_type(&dict_ref.potential_schema.clone().unwrap_or_default()); - for (k, v) in &dict_ref.values { - let expected_value = convert_collection_value(s, v, &value_tpe); - let op = dict_ref - .ops - .get(k) - .unwrap_or(&ConfigEntryOperationKind::Union); - let index = dict_ref.insert_indexs.get(k); - expected_dict.dict_update_entry(k, &expected_value, op, index) - } - expected_dict - } else if is_list_type(tpe) { - let expected_type = dereference_type(tpe); - let mut expected_list = ValueRef::list(None); - let list_ref = value.as_list_ref(); - for v in &list_ref.values { - let expected_value = convert_collection_value(s, v, &expected_type); - expected_list.list_append(&expected_value) - } - expected_list - } else if BUILTIN_TYPES.contains(&tpe) { - value.clone() - } else { - // Get the type form @pkg.Schema - let schema_type_name = if tpe.contains('.') { - if tpe.starts_with(PKG_PATH_PREFIX) { - tpe.to_string() - } else { - format!("{PKG_PATH_PREFIX}{tpe}") - } - } else { - format!("{}.{}", s.current_pkgpath(), tpe) - }; - if let Some(index) = s.schemas.borrow().get(&schema_type_name) { - let config_meta = { - let ctx = s.runtime_ctx.borrow(); - schema_config_meta( - &ctx.panic_info.kcl_file, - ctx.panic_info.kcl_line as u64, - ctx.panic_info.kcl_col as u64, - ) - }; - let frame = { - let frames = s.frames.borrow(); - frames - .get(*index) - .expect(kcl_error::INTERNAL_ERROR_MSG) - .clone() - }; - let schema = if let Proxy::Schema(caller) = &frame.proxy { - // Try convert the config to schema, if failed, return the config directly. - if !SchemaEvalContext::is_fit_config(s, &caller.ctx, value) { - return value.clone(); - } - s.push_pkgpath(&frame.pkgpath); - s.push_backtrace(&frame); - let value = (caller.body)( - s, - &caller.ctx.borrow().snapshot(value.clone(), config_meta), - &s.list_value(), - &s.dict_value(), - ); - s.pop_backtrace(); - s.pop_pkgpath(); - value - } else { - value.clone() - }; - // ctx.panic_info = now_panic_info; - return schema.clone(); - } - // ctx.panic_info = now_meta_info; - value.clone() - } -} - -/// Convert collection value including dict/list to the potential schema and return errors. -pub fn convert_collection_value_with_union_types( - s: &Evaluator, - value: &ValueRef, - types: &[&str], -) -> ValueRef { - if value.is_schema() { - value.clone() - } else { - for tpe in types { - // Try match every type and convert the value, if matched, return the value. - let value = convert_collection_value(s, value, tpe); - if check_type( - &value, - &s.runtime_ctx.borrow().panic_info.kcl_pkgpath, - tpe, - false, - ) { - return value; - } - } - value.clone() - } -} diff --git a/kclvm/lexer/Cargo.lock b/kclvm/lexer/Cargo.lock deleted file mode 100644 index 4b94f8d05..000000000 --- a/kclvm/lexer/Cargo.lock +++ /dev/null @@ -1,1232 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "ahash" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" -dependencies = [ - "getrandom", - "once_cell", - "version_check", -] - -[[package]] -name = "aho-corasick" -version = "0.7.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" -dependencies = [ - "memchr", -] - -[[package]] -name = "annotate-snippets" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78ea013094e5ea606b1c05fe35f1dd7ea1eb1ea259908d040b25bd5ec677ee5" - -[[package]] -name = "arrayvec" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" - -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi", - "libc", - "winapi", -] - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "base64" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" - -[[package]] -name = "bit-set" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e11e16035ea35e4e5997b393eacbf6f63983188f7a2ad25bfb13465f5ad59de" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "generic-array", -] - -[[package]] -name = "block-buffer" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bstr" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" -dependencies = [ - "lazy_static", - "memchr", - "regex-automata", -] - -[[package]] -name = "cc" -version = "1.0.73" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "chrono" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" -dependencies = [ - "libc", - "num-integer", - "num-traits", - "time", - "winapi", -] - -[[package]] -name = "cpufeatures" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b" -dependencies = [ - "libc", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" -dependencies = [ - "cfg-if 1.0.0", - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1145cf131a2c6ba0615079ab6a638f7e1973ac9c2634fcbeaaad6114246efe8c" -dependencies = [ - "autocfg", - "cfg-if 1.0.0", - "crossbeam-utils", - "lazy_static", - "memoffset", - "scopeguard", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf124c720b7686e3c2663cf54062ab0f68a88af2fb6a030e87e30bf721fcb38" -dependencies = [ - "cfg-if 1.0.0", - "lazy_static", -] - -[[package]] -name = "crypto-common" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "digest" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" -dependencies = [ - "generic-array", -] - -[[package]] -name = "digest" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506" -dependencies = [ - "block-buffer 0.10.2", - "crypto-common", -] - -[[package]] -name = "dissimilar" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31ad93652f40969dead8d4bf897a41e9462095152eb21c56e5830537e41179dd" - -[[package]] -name = "either" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" - -[[package]] -name = "ena" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7402b94a93c24e742487327a7cd839dc9d36fec9de9fb25b09f2dae459f36c3" -dependencies = [ - "log", -] - -[[package]] -name = "expect-test" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3e6b28dccda91d8742195c71fbda412112c0c77febf56bf3d895d68b19db16" -dependencies = [ - "dissimilar", - "once_cell", -] - -[[package]] -name = "fancy-regex" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d6b8560a05112eb52f04b00e5d3790c0dd75d9d980eb8a122fb23b92a623ccf" -dependencies = [ - "bit-set", - "regex", -] - -[[package]] -name = "fastrand" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf" -dependencies = [ - "instant", -] - -[[package]] -name = "generic-array" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "wasi", -] - -[[package]] -name = "hashbrown" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" - -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - -[[package]] -name = "indexmap" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" -dependencies = [ - "autocfg", - "hashbrown", - "rustc-rayon", -] - -[[package]] -name = "instant" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "itertools" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112c678d4050afce233f4f2852bb2eb519230b3cf12f33585275537d7e41578d" - -[[package]] -name = "jobserver" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af25a77299a7f711a01975c35a6a424eb6862092cc2d6c72c4ed6cbc56dfc1fa" -dependencies = [ - "libc", -] - -[[package]] -name = "json_minimal" -version = "0.1.3" - -[[package]] -name = "kclvm-error" -version = "0.1.0" -dependencies = [ - "annotate-snippets", - "atty", - "indexmap", - "kclvm-runtime", - "kclvm-span", - "rustc_span", - "termcolor", - "termize", - "tracing", -] - -[[package]] -name = "kclvm-lexer" -version = "0.1.0" -dependencies = [ - "expect-test", - "kclvm-error", - "rustc_lexer", - "unic-emoji-char", -] - -[[package]] -name = "kclvm-macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "kclvm-runtime" -version = "0.1.0" -dependencies = [ - "ahash", - "base64", - "bstr", - "chrono", - "fancy-regex", - "indexmap", - "itertools", - "json_minimal", - "kclvm_runtime_internal_macros", - "libc", - "md5", - "num-integer", - "phf", - "regex", - "serde", - "serde_json", - "serde_yaml", - "sha1", - "sha2 0.9.9", - "unic-ucd-bidi", - "unic-ucd-category", - "unicode-casing", -] - -[[package]] -name = "kclvm-span" -version = "0.1.0" -dependencies = [ - "kclvm-macros", - "rustc_span", - "scoped-tls", -] - -[[package]] -name = "kclvm_runtime_internal_macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.123" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb691a747a7ab48abc15c5b42066eaafde10dc427e3b6ee2a1cf43db04c763bd" - -[[package]] -name = "linked-hash-map" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3" - -[[package]] -name = "lock_api" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" -dependencies = [ - "autocfg", - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6389c490849ff5bc16be905ae24bc913a9c8892e19b2341dbc175e14c341c2b8" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "matches" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" - -[[package]] -name = "md-5" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "658646b21e0b72f7866c7038ab086d3d5e1cd6271f060fd37defb241949d0582" -dependencies = [ - "digest 0.10.3", -] - -[[package]] -name = "md5" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" - -[[package]] -name = "memchr" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" - -[[package]] -name = "memmap2" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "723e3ebdcdc5c023db1df315364573789f8857c11b631a2fdfad7c00f5c046b4" -dependencies = [ - "libc", -] - -[[package]] -name = "memoffset" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num-integer" -version = "0.1.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" -dependencies = [ - "autocfg", - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_cpus" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "once_cell" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9" - -[[package]] -name = "opaque-debug" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" - -[[package]] -name = "parking_lot" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f5ec2493a61ac0506c0f4199f99070cbe83857b0337006a30f3e6719b8ef58" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "995f667a6c822200b0433ac218e05582f0e2efa1b922a3fd2fbaadc5f87bab37" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "redox_syscall", - "smallvec", - "windows-sys", -] - -[[package]] -name = "phf" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2ac8b67553a7ca9457ce0e526948cad581819238f4a9d1ea74545851fa24f37" -dependencies = [ - "phf_macros", - "phf_shared", - "proc-macro-hack", -] - -[[package]] -name = "phf_generator" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43f3220d96e0080cc9ea234978ccd80d904eafb17be31bb0f76daaea6493082" -dependencies = [ - "phf_shared", - "rand", -] - -[[package]] -name = "phf_macros" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b706f5936eb50ed880ae3009395b43ed19db5bff2ebd459c95e7bf013a89ab86" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro-hack", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "phf_shared" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a68318426de33640f02be62b4ae8eb1261be2efbc337b60c54d845bf4484e0d9" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e280fbe77cc62c91527259e9442153f4688736748d24660126286329742b4c6c" - -[[package]] -name = "ppv-lite86" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" - -[[package]] -name = "proc-macro-hack" -version = "0.5.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" - -[[package]] -name = "proc-macro2" -version = "1.0.37" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec757218438d5fda206afc041538b2f6d889286160d649a86a24d37e1235afd1" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "psm" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "871372391786ccec00d3c5d3d6608905b3d4db263639cfe075d3b60a736d115a" -dependencies = [ - "cc", -] - -[[package]] -name = "quote" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha", - "rand_core", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core", -] - -[[package]] -name = "rand_core" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" -dependencies = [ - "getrandom", -] - -[[package]] -name = "redox_syscall" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" -dependencies = [ - "bitflags", -] - -[[package]] -name = "regex" -version = "1.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d83f127d94bdbcda4c8cc2e50f6f84f4b611f69c902699ca385a39c3a75f9ff1" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" - -[[package]] -name = "regex-syntax" -version = "0.6.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49b3de9ec5dc0a3417da371aab17d729997c15010e7fd24ff707773a33bddb64" - -[[package]] -name = "remove_dir_all" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" -dependencies = [ - "winapi", -] - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - -[[package]] -name = "rustc-rayon" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9974ab223660e61c1b4e7b43b827379df286736ca988308ce7e16f59f2d89246" -dependencies = [ - "crossbeam-deque", - "either", - "rustc-rayon-core", -] - -[[package]] -name = "rustc-rayon-core" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "564bfd27be8db888d0fa76aa4335e7851aaed0c2c11ad1e93aeb9349f6b88500" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", - "lazy_static", - "num_cpus", -] - -[[package]] -name = "rustc_data_structures" -version = "0.0.0" -dependencies = [ - "arrayvec", - "bitflags", - "cfg-if 0.1.10", - "ena", - "indexmap", - "jobserver", - "libc", - "memmap2", - "parking_lot", - "rustc-hash", - "rustc-rayon", - "rustc-rayon-core", - "stable_deref_trait", - "stacker", - "tempfile", - "tracing", - "winapi", -] - -[[package]] -name = "rustc_lexer" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c86aae0c77166108c01305ee1a36a1e77289d7dc6ca0a3cd91ff4992de2d16a5" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "rustc_span" -version = "0.0.0" -dependencies = [ - "cfg-if 0.1.10", - "md-5", - "rustc_data_structures", - "scoped-tls", - "sha-1", - "sha2 0.10.2", - "tracing", - "unicode-width", -] - -[[package]] -name = "ryu" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3f6f92acf49d1b98f7a81226834412ada05458b7364277387724a237f062695" - -[[package]] -name = "scoped-tls" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" - -[[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - -[[package]] -name = "serde" -version = "1.0.137" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.137" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.81" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b7ce2b32a1aed03c558dc61a5cd328f15aff2dbc17daad8fb8af04d2100e15c" -dependencies = [ - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_yaml" -version = "0.8.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "707d15895415db6628332b737c838b88c598522e4dc70647e59b72312924aebc" -dependencies = [ - "indexmap", - "ryu", - "serde", - "yaml-rust", -] - -[[package]] -name = "sha-1" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.3", -] - -[[package]] -name = "sha1" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" -dependencies = [ - "sha1_smol", -] - -[[package]] -name = "sha1_smol" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" - -[[package]] -name = "sha2" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.9.0", - "opaque-debug", -] - -[[package]] -name = "sha2" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.3", -] - -[[package]] -name = "siphasher" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bd3e3206899af3f8b12af284fafc038cc1dc2b41d1b89dd17297221c5d225de" - -[[package]] -name = "smallvec" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83" - -[[package]] -name = "stable_deref_trait" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" - -[[package]] -name = "stacker" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90939d5171a4420b3ff5fbc8954d641e7377335454c259dcb80786f3f21dc9b4" -dependencies = [ - "cc", - "cfg-if 1.0.0", - "libc", - "psm", - "winapi", -] - -[[package]] -name = "syn" -version = "1.0.91" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b683b2b825c8eef438b77c36a06dc262294da3d5a5813fac20da149241dcd44d" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "synstructure" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "unicode-xid", -] - -[[package]] -name = "tempfile" -version = "3.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" -dependencies = [ - "cfg-if 1.0.0", - "fastrand", - "libc", - "redox_syscall", - "remove_dir_all", - "winapi", -] - -[[package]] -name = "termcolor" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "termize" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1706be6b564323ce7092f5f7e6b118a14c8ef7ed0e69c8c5329c914a9f101295" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "time" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" -dependencies = [ - "libc", - "wasi", - "winapi", -] - -[[package]] -name = "tracing" -version = "0.1.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d0ecdcb44a79f0fe9844f0c4f33a342cbcbb5117de8001e6ba0dc2351327d09" -dependencies = [ - "cfg-if 1.0.0", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e65ce065b4b5c53e73bb28912318cb8c9e9ad3921f1d669eb0e68b4c8143a2b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tracing-core" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f54c8ca710e81886d498c2fd3331b56c93aa248d49de2222ad2742247c60072f" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "typenum" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" - -[[package]] -name = "unic-char-property" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" -dependencies = [ - "unic-char-range", -] - -[[package]] -name = "unic-char-range" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" - -[[package]] -name = "unic-common" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" - -[[package]] -name = "unic-emoji-char" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b07221e68897210270a38bde4babb655869637af0f69407f96053a34f76494d" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-bidi" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1d568b51222484e1f8209ce48caa6b430bf352962b877d592c29ab31fb53d8c" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-category" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b8d4591f5fcfe1bd4453baaf803c40e1b1e69ff8455c47620440b46efef91c0" -dependencies = [ - "matches", - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-version" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" -dependencies = [ - "unic-common", -] - -[[package]] -name = "unicode-casing" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "623f59e6af2a98bdafeb93fa277ac8e1e40440973001ca15cf4ae1541cd16d56" - -[[package]] -name = "unicode-width" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" - -[[package]] -name = "unicode-xid" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "wasi" -version = "0.10.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" -dependencies = [ - "winapi", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-sys" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5acdd78cb4ba54c0045ac14f62d8f94a03d10047904ae2a40afa1e99d8f70825" -dependencies = [ - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17cffbe740121affb56fad0fc0e421804adf0ae00891205213b5cecd30db881d" - -[[package]] -name = "windows_i686_gnu" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2564fde759adb79129d9b4f54be42b32c89970c18ebf93124ca8870a498688ed" - -[[package]] -name = "windows_i686_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cd9d32ba70453522332c14d38814bceeb747d80b3958676007acadd7e166956" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfce6deae227ee8d356d19effc141a509cc503dfd1f850622ec4b0f84428e1f4" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d19538ccc21819d01deaf88d6a17eae6596a12e9aafdbb97916fb49896d89de9" - -[[package]] -name = "yaml-rust" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" -dependencies = [ - "linked-hash-map", -] diff --git a/kclvm/lexer/Cargo.toml b/kclvm/lexer/Cargo.toml deleted file mode 100644 index bd2d73bd9..000000000 --- a/kclvm/lexer/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "kclvm-lexer" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -rustc_lexer = "0.1.0" -unic-emoji-char = "0.9.0" -kclvm-error = {path = "../error"} - -[dev-dependencies] -expect-test = "1.0" \ No newline at end of file diff --git a/kclvm/lexer/src/lib.rs b/kclvm/lexer/src/lib.rs deleted file mode 100644 index a7f1fa17d..000000000 --- a/kclvm/lexer/src/lib.rs +++ /dev/null @@ -1,618 +0,0 @@ -//! Low-level token stream lexer. -//! -//! The purpose of `kclvm_lexer` is similar to [`rustc_lexer`] crate, -//! which separates out pure lexing and language-specific designs. -//! -//! The difference with [`rustc_lexer`] is that here we want to define -//! a more general and wider range of tokens used by more languages. -//! -//! A language-specific lexer is needed to convert the basic token stream -//! into wide tokens consumed by the parser. -//! -//! The purpose of the lexer is to convert raw sources into a labeled sequence -//! of well-known token types. No error reporting on obvious error(e.g., string-not-closed error), -//! instead storing them as flags on the token. Checking of literal content is -//! not performed in this lexer. -//! -//! The main entity of this crate is the [`TokenKind`] enum which represents common -//! lexeme types. -//! -//! [`parser::lexer`]: ../parser/lexer/index.html -//! We want to be able to build this crate with a stable compiler, so no -//! `#![feature]` attributes should be added. - -mod cursor; -mod kcl_cursor; -mod number; - -#[cfg(test)] -mod tests; - -extern crate kclvm_error; - -use cursor::EOF_CHAR; - -use self::TokenKind::*; -pub use crate::cursor::Cursor; - -/// Parsed token. -#[derive(Debug)] -pub struct Token { - pub kind: TokenKind, - pub len: usize, -} - -impl Token { - fn new(kind: TokenKind, len: usize) -> Self { - Token { kind, len } - } -} - -/// Enum representing common lexeme types. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub enum TokenKind { - /// "# comment" or "// comment" - LineComment { doc_style: Option }, - - /// `/* block comment */` - /// - /// Block comments can be recursive, so the sequence like `/* /* */` - /// will not be considered terminated and will result in a parsing error. - BlockComment { - doc_style: Option, - terminated: bool, - }, - - /// "\t" - Tab, - - /// " " - Space, - - /// "\r" - CarriageReturn, - - /// "\n" - Newline, - - /// Any other whitespace characters sequence. - Whitespace, - - /// "ident" - Ident, - - /// Like the above, but containing invalid unicode codepoints. - InvalidIdent, - - /// Invalid line continue symbol `\\` without the `\n` followed. - InvalidLineContinue, - - /// Valid Line continue '\\' - LineContinue, - - /// "12_u8", "1.0e-40", "b"123"". See `LiteralKind` for more details. - Literal { - kind: LiteralKind, - suffix_start: usize, - }, - - /// ";" - Semi, - - /// "," - Comma, - - /// "." - Dot, - - /// ".." - DotDot, - - /// "..." - DotDotDot, - - /// "(" - OpenParen, - - /// ")" - CloseParen, - - /// "{" - OpenBrace, - - /// "}" - CloseBrace, - - /// "[" - OpenBracket, - - /// "]" - CloseBracket, - - /// "@" - At, - - /// "#" - Pound, - - /// "~" - Tilde, - - /// "?" - Question, - - /// ":" - Colon, - - /// "$" - Dollar, - - /// "=" - Eq, - - /// "!" - Bang, - - /// "<" - Lt, - - /// ">" - Gt, - - /// "==" - EqEq, - - /// "!=" - BangEq, - - /// ">=" - GtEq, - - /// "<=" - LtEq, - - /// "-" - Minus, - - /// "&" - And, - - /// "|" - Or, - - /// "+" - Plus, - - /// "*" - Star, - - /// "/" - Slash, - - /// "^" - Caret, - - /// "%" - Percent, - - /// "**" - StarStar, - - /// "//" - SlashSlash, - - /// "<<" - LtLt, - - /// ">>" - GtGt, - - /// "+=" - PlusEq, - - /// "-=" - MinusEq, - - /// "*=" - StarEq, - - /// "/=" - SlashEq, - - /// "%=" - PercentEq, - - /// "&=" - AndEq, - - /// "|=" - OrEq, - - /// "^=" - CaretEq, - - /// "**=" - StarStarEq, - - /// "//=" - SlashSlashEq, - - /// "<<=" - LtLtEq, - - /// ">>=" - GtGtEq, - - /// Unknown token, not expected by the lexer, e.g. "№" - Unknown, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub enum DocStyle { - Outer, - Inner, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub enum LiteralKind { - /// "12", "0o100", "0b120199" - Int { base: Base, empty_int: bool }, - /// "12.34", "0b100.100" - Float { base: Base, empty_exponent: bool }, - /// ""abc"", "'abc'", "'''abc'''" - Str { - terminated: bool, - triple_quoted: bool, - }, - /// True, False - Bool { terminated: bool }, -} - -/// Base of numeric literal encoding according to its prefix. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub enum Base { - /// Literal starts with "0b". - Binary, - /// Literal starts with "0o". - Octal, - /// Literal starts with "0x". - Hexadecimal, - /// Literal doesn't contain a prefix. - Decimal, -} - -impl Base { - /// Returns the description string of the numeric literal base. - pub fn describe(&self) -> &'static str { - match self { - Base::Binary => "binary", - Base::Octal => "octal", - Base::Hexadecimal => "hexadecimal", - Base::Decimal => "decimal", - } - } -} - -/// Parses the first token from the provided input string. -pub fn first_token(input: &str) -> Token { - debug_assert!(!input.is_empty()); - Cursor::new(input).token() -} - -/// Creates an iterator that produces tokens from the input string. -pub fn tokenize(input: &str) -> impl Iterator + '_ { - let mut cursor = Cursor::new(input); - std::iter::from_fn(move || { - if cursor.is_eof() { - None - } else { - cursor.reset_len_consumed(); - Some(cursor.token()) - } - }) -} - -pub trait ICursor: ITokenCursor + ICommentCursor {} - -// Cursor trait to read one token from char stream. -pub trait ITokenCursor { - fn token(&mut self) -> Token; -} - -// Cursor trait to read comment. -// Line comment and block comment should be considered here. -pub trait ICommentCursor { - // If we encounter a comment. - // Returns true if exists, otherwise returns false. - fn try_comment_magic(&self, _c: char) -> bool { - false - } - - // Eat it if so. - // This mehod **MUST** be called after 'try_comment_magic'. - // No gurantee to ensure the correctness if no comment here, - // and return 'Unknown' if it happens. - fn eat_comment(&mut self) -> TokenKind { - Unknown - } -} - -// Cursor trait to read string. -// Simple string, raw string, unicode string, multi-lines string, -// and more string cases should be considered here. -pub trait IStringCursor { - // If we encounter a string. - // Returns true if exists, otherwise returns false. - fn try_string_magic(&self, _c: char) -> bool { - false - } - - // Eat it if so. - // This mehod **MUST** be called after 'try_string_magic'. - // No gurantee to ensure the correctness if no string here, - // and return 'Unknown' if it happens. - // For example, no identifier check if no string found. - fn eat_string(&mut self, _c: char) -> TokenKind { - Unknown - } -} - -// Cursor trait to read identifier. -// Simple identifier, raw identifier, and more identifier cases should be considered here. -pub trait IIdentCursor { - // If we encounter a identifier. - // Returns true if exists, otherwise returns false. - fn try_ident_magic(&self, _c: char) -> bool { - false - } - - // Eat it if so. - // This method **MUST** be called after 'try_ident_magic'. - // No guarantee to ensure the correctness if no identifier here, - // and return 'Unknown' if it happens. - fn eat_ident(&mut self) -> TokenKind { - Unknown - } -} - -/// True if `c` is considered a whitespace. -pub fn is_whitespace(c: char) -> bool { - match c { - // Usual ASCII suspects - | '\u{000B}' // vertical tab - | '\u{000C}' // form feed - | '\u{000D}' // \r - // NEXT LINE from latin1 - | '\u{0085}' - - // Bidi markers - | '\u{200E}' // LEFT-TO-RIGHT MARK - | '\u{200F}' // RIGHT-TO-LEFT MARK - - // Dedicated whitespace characters from Unicode - | '\u{2028}' // LINE SEPARATOR - | '\u{2029}' // PARAGRAPH SEPARATOR - => true, - _ => false, - } -} - -impl<'a> ITokenCursor for Cursor<'a> { - fn token(&mut self) -> Token { - let char = self.bump().unwrap_or(EOF_CHAR); - - let token_kind = match char { - // Comment or block comment, or a simple token - c if self.try_comment_magic(c) => self.eat_comment(), - - // Whitespace sequence. - c if is_whitespace(c) => Whitespace, - - // Various of string. E.g., quoted string, raw string. - c if self.try_string_magic(c) => self.eat_string(c), - - // Identifier (this should be checked after other variant that can - // start as identifier). - c if self.try_ident_magic(c) => self.eat_ident(), - - // Numeric literal. - c @ '0'..='9' => { - let kind = self.number(c); - let suffix_start = self.len_consumed(); - self.eat_lit_suffix(); // In case we have some suffix - - TokenKind::Literal { kind, suffix_start } - } - - // '\r' will be considered as a 'WhiteSpace'. - '\u{0009}' => Tab, - '\u{0020}' => Space, - '\u{000A}' => Newline, - - ';' => Semi, - ',' => Comma, - '.' => match (self.peek(), self.peek1th()) { - ('.', '.') => { - self.bump(); - self.bump(); - DotDotDot - } - _ => Dot, - }, - '(' => OpenParen, - ')' => CloseParen, - '{' => OpenBrace, - '}' => CloseBrace, - '[' => OpenBracket, - ']' => CloseBracket, - '@' => At, - '#' => Pound, - '~' => Tilde, - '?' => Question, - ':' => Colon, - '$' => Dollar, - '=' => match self.peek() { - '=' => { - self.bump(); - EqEq - } - _ => Eq, - }, - '!' => match self.peek() { - '=' => { - self.bump(); - BangEq - } - _ => Bang, - }, - '<' => match self.peek() { - '=' => { - self.bump(); - LtEq - } - '<' => { - self.bump(); - match self.peek() { - '=' => { - self.bump(); - LtLtEq - } - _ => LtLt, - } - } - _ => Lt, - }, - '>' => match self.peek() { - '=' => { - self.bump(); - GtEq - } - '>' => { - self.bump(); - match self.peek() { - '=' => { - self.bump(); - GtGtEq - } - _ => GtGt, - } - } - _ => Gt, - }, - '-' => match self.peek() { - '=' => { - self.bump(); - MinusEq - } - _ => Minus, - }, - '&' => match self.peek() { - '=' => { - self.bump(); - AndEq - } - _ => And, - }, - '|' => match self.peek() { - '=' => { - self.bump(); - OrEq - } - _ => Or, - }, - '+' => match self.peek() { - '=' => { - self.bump(); - PlusEq - } - _ => Plus, - }, - '*' => match self.peek() { - '*' => { - self.bump(); - match self.peek() { - '=' => { - self.bump(); - StarStarEq - } - _ => StarStar, - } - } - '=' => { - self.bump(); - StarEq - } - _ => Star, - }, - '/' => match self.peek() { - '/' => { - self.bump(); - match self.peek() { - '=' => { - self.bump(); - SlashSlashEq - } - _ => SlashSlash, - } - } - '=' => { - self.bump(); - SlashEq - } - _ => Slash, - }, - '^' => match self.peek() { - '=' => { - self.bump(); - CaretEq - } - _ => Caret, - }, - '%' => match self.peek() { - '=' => { - self.bump(); - PercentEq - } - _ => Percent, - }, - '\\' => match self.peek() { - '\n' => { - self.bump(); - LineContinue - } - EOF_CHAR => LineContinue, - _ => InvalidLineContinue, - }, - // Identifier starting with an emoji. Only lexed for graceful error recovery. - c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { - self.fake_ident_or_unknown_prefix() - } - _ => Unknown, - }; - Token::new(token_kind, self.len_consumed()) - } -} - -impl<'a> Cursor<'a> { - // Eats the suffix of the literal, e.g. 'Ki', 'M', etc. - fn eat_lit_suffix(&mut self) { - if !rustc_lexer::is_id_start(self.peek()) { - return; - } - self.bump(); - - self.eat_while(rustc_lexer::is_id_continue); - } - - fn fake_ident_or_unknown_prefix(&mut self) -> TokenKind { - // Start is already eaten, eat the rest of identifier. - self.eat_while(|c| { - rustc_lexer::is_id_continue(c) - || (!c.is_ascii() && unic_emoji_char::is_emoji(c)) - || c == '\u{200d}' - }); - // Known prefixes must have been handled earlier. So if - // we see a prefix here, it is definitely an unknown prefix. - InvalidIdent - } -} diff --git a/kclvm/lexer/src/tests.rs b/kclvm/lexer/src/tests.rs deleted file mode 100644 index 6b430f45e..000000000 --- a/kclvm/lexer/src/tests.rs +++ /dev/null @@ -1,369 +0,0 @@ -use super::*; -use expect_test::{expect, Expect}; -use std::fmt::Write; - -fn check_lexing(src: &str, expect: Expect) { - let actual: String = tokenize(src).fold(String::new(), |mut acc, token| { - writeln!(acc, "{:?}", token).expect("Failed to write to string"); - acc - }); - expect.assert_eq(&actual) -} - -#[test] -fn smoke_test() { - check_lexing( - " lambda { println(\"kclvm\"); }\n", - expect![[r#" - Token { kind: Space, len: 1 } - Token { kind: Space, len: 1 } - Token { kind: Ident, len: 6 } - Token { kind: Space, len: 1 } - Token { kind: OpenBrace, len: 1 } - Token { kind: Space, len: 1 } - Token { kind: Ident, len: 7 } - Token { kind: OpenParen, len: 1 } - Token { kind: Literal { kind: Str { terminated: true, triple_quoted: false }, suffix_start: 7 }, len: 7 } - Token { kind: CloseParen, len: 1 } - Token { kind: Semi, len: 1 } - Token { kind: Space, len: 1 } - Token { kind: CloseBrace, len: 1 } - Token { kind: Newline, len: 1 } - "#]], - ) -} - -#[test] -fn comment_flavors() { - check_lexing( - r" -# -# line -", - expect![[r#" - Token { kind: Newline, len: 1 } - Token { kind: LineComment { doc_style: Some(Inner) }, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: LineComment { doc_style: Some(Inner) }, len: 6 } - Token { kind: Newline, len: 1 } -"#]], - ) -} - -#[test] -fn simple_tokens() { - check_lexing( - r####" -; -, -. -( -) -{ -} -[ -] -@ -# -~ -? -: -$ -= -! -< -> -== -!= ->= -<= -- -& -| -+ -* -/ -^ -% -** -// -<< ->> -... -+= --= -*= -/= -%= -&= -|= -^= -**= -//= -<<= ->>= -"####, - expect![[r#" - Token { kind: Newline, len: 1 } - Token { kind: Semi, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Comma, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Dot, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: OpenParen, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: CloseParen, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: OpenBrace, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: CloseBrace, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: OpenBracket, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: CloseBracket, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: At, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: LineComment { doc_style: Some(Inner) }, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Tilde, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Question, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Colon, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Dollar, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Eq, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Bang, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Lt, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Gt, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: EqEq, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: BangEq, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: GtEq, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: LtEq, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: Minus, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: And, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Or, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Plus, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Star, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Slash, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Caret, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Percent, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: StarStar, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: SlashSlash, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: LtLt, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: GtGt, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: DotDotDot, len: 3 } - Token { kind: Newline, len: 1 } - Token { kind: PlusEq, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: MinusEq, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: StarEq, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: SlashEq, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: PercentEq, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: AndEq, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: OrEq, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: CaretEq, len: 2 } - Token { kind: Newline, len: 1 } - Token { kind: StarStarEq, len: 3 } - Token { kind: Newline, len: 1 } - Token { kind: SlashSlashEq, len: 3 } - Token { kind: Newline, len: 1 } - Token { kind: LtLtEq, len: 3 } - Token { kind: Newline, len: 1 } - Token { kind: GtGtEq, len: 3 } - Token { kind: Newline, len: 1 } - "#]], - ) -} - -#[test] -fn nonstring_literal() { - check_lexing( - r####" -1234 -0b101 -0xABC -1.0 -1.0e10 -0777 -0077 -1Ki -"####, - expect![[r#" - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Int { base: Decimal, empty_int: false }, suffix_start: 4 }, len: 4 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Int { base: Binary, empty_int: false }, suffix_start: 5 }, len: 5 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Int { base: Hexadecimal, empty_int: false }, suffix_start: 5 }, len: 5 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Float { base: Decimal, empty_exponent: false }, suffix_start: 3 }, len: 3 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Float { base: Decimal, empty_exponent: false }, suffix_start: 6 }, len: 6 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Int { base: Octal, empty_int: false }, suffix_start: 4 }, len: 4 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Int { base: Octal, empty_int: false }, suffix_start: 4 }, len: 4 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Int { base: Decimal, empty_int: false }, suffix_start: 1 }, len: 3 } - Token { kind: Newline, len: 1 } - "#]], - ) -} - -#[test] -fn string_literal() { - check_lexing( - r####" -'a' -"a" -'''a''' -"""a""" -r'a' -r"a" -r'''a''' -r"""a""" -R'a' -R"a" -R'''a''' -R"""a""" -"####, - expect![[r#" - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Str { terminated: true, triple_quoted: false }, suffix_start: 3 }, len: 3 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Str { terminated: true, triple_quoted: false }, suffix_start: 3 }, len: 3 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Str { terminated: true, triple_quoted: true }, suffix_start: 7 }, len: 7 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Str { terminated: true, triple_quoted: true }, suffix_start: 7 }, len: 7 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Str { terminated: true, triple_quoted: false }, suffix_start: 4 }, len: 4 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Str { terminated: true, triple_quoted: false }, suffix_start: 4 }, len: 4 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Str { terminated: true, triple_quoted: true }, suffix_start: 8 }, len: 8 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Str { terminated: true, triple_quoted: true }, suffix_start: 8 }, len: 8 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Str { terminated: true, triple_quoted: false }, suffix_start: 4 }, len: 4 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Str { terminated: true, triple_quoted: false }, suffix_start: 4 }, len: 4 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Str { terminated: true, triple_quoted: true }, suffix_start: 8 }, len: 8 } - Token { kind: Newline, len: 1 } - Token { kind: Literal { kind: Str { terminated: true, triple_quoted: true }, suffix_start: 8 }, len: 8 } - Token { kind: Newline, len: 1 } - "#]], - ) -} - -#[test] -fn identifier() { - check_lexing( - r####" -a -abc -$schema -"####, - expect![[r#" - Token { kind: Newline, len: 1 } - Token { kind: Ident, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Ident, len: 3 } - Token { kind: Newline, len: 1 } - Token { kind: Ident, len: 7 } - Token { kind: Newline, len: 1 } - "#]], - ) -} - -#[test] -fn line_continue() { - check_lexing( - r####" -\ -\ -"####, - expect![[r#" - Token { kind: Newline, len: 1 } - Token { kind: LineContinue, len: 2 } - Token { kind: LineContinue, len: 2 } - "#]], - ) -} - -#[test] -fn newline_r_n() { - check_lexing( - "\r\n", - expect![[r#" - Token { kind: Whitespace, len: 1 } - Token { kind: Newline, len: 1 } - "#]], - ) -} - -#[test] -fn newline_r_n_r_n() { - check_lexing( - "\r\n\r\n", - expect![[r#" - Token { kind: Whitespace, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Whitespace, len: 1 } - Token { kind: Newline, len: 1 } - "#]], - ) -} - -#[test] -fn newline_r() { - check_lexing( - "\r", - expect![[r#" - Token { kind: Whitespace, len: 1 } - "#]], - ) -} - -#[test] -fn newline_r_n_n() { - check_lexing( - "\r\n\n", - expect![[r#" - Token { kind: Whitespace, len: 1 } - Token { kind: Newline, len: 1 } - Token { kind: Newline, len: 1 } - "#]], - ) -} diff --git a/kclvm/loader/Cargo.toml b/kclvm/loader/Cargo.toml deleted file mode 100644 index ce790ee41..000000000 --- a/kclvm/loader/Cargo.toml +++ /dev/null @@ -1,22 +0,0 @@ -[package] -name = "kclvm-loader" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -anyhow = "1.0" - -kclvm-ast = { path = "../ast" } -kclvm-ast-pretty = { path = "../ast_pretty" } -kclvm-parser = { path = "../parser" } -kclvm-sema = { path = "../sema" } -kclvm-error = { path = "../error" } -kclvm-query = { path = "../query" } -kclvm-utils = { path = "../utils" } -kclvm-primitives = { path = "../primitives" } -maplit = "1.0.2" - -[dev-dependencies] -insta = "1.8.0" diff --git a/kclvm/loader/src/lib.rs b/kclvm/loader/src/lib.rs deleted file mode 100644 index bd7c26176..000000000 --- a/kclvm/loader/src/lib.rs +++ /dev/null @@ -1,296 +0,0 @@ -#[cfg(test)] -mod tests; - -pub mod option; -pub mod util; - -use anyhow::Result; -use kclvm_ast::ast::Program; -use kclvm_error::{diagnostic::Range, Diagnostic}; -use kclvm_parser::{load_program, KCLModuleCache, LoadProgramOptions, ParseSessionRef}; -use kclvm_primitives::{IndexMap, IndexSet}; -use kclvm_sema::{ - advanced_resolver::AdvancedResolver, - core::{ - global_state::GlobalState, - scope::{LocalSymbolScopeKind, ScopeData, ScopeRef}, - symbol::{SymbolData, SymbolRef}, - }, - namer::Namer, - resolver::{ - resolve_program_with_opts, - scope::{KCLScopeCache, NodeKey}, - }, - ty::{Type, TypeRef}, -}; -use kclvm_utils::path::PathPrefix; -use std::path::PathBuf; - -type Errors = IndexSet; - -#[derive(Debug, Clone)] -pub struct LoadPackageOptions { - pub paths: Vec, - pub load_opts: Option, - pub resolve_ast: bool, - pub load_builtin: bool, -} - -impl Default for LoadPackageOptions { - fn default() -> Self { - Self { - paths: Default::default(), - load_opts: Default::default(), - resolve_ast: true, - load_builtin: false, - } - } -} - -#[derive(Debug, Clone, Default)] -pub struct Packages { - /// AST Program - pub program: Program, - /// All compiled files in the package - pub paths: Vec, - /// All Parse errors - pub parse_errors: Errors, - /// Type errors - pub type_errors: Errors, - /// Symbol information - pub symbols: IndexMap, - /// Scope information - pub scopes: IndexMap, - /// AST Node-Symbol mapping - pub node_symbol_map: IndexMap, - /// - mapping - pub pkg_scope_map: IndexMap, - /// Symbol-AST Node mapping - pub symbol_node_map: IndexMap, - /// Fully qualified name mapping - pub fully_qualified_name_map: IndexMap, -} - -#[derive(Debug, Clone)] -pub struct SymbolInfo { - pub ty: TypeRef, - pub name: String, - pub range: Range, - pub owner: Option, - pub def: Option, - pub attrs: Vec, - pub is_global: bool, -} - -#[derive(Debug, Clone)] -pub struct ScopeInfo { - /// Scope kind - pub kind: ScopeKind, - /// Scope parent - pub parent: Option, - /// Scope owner - pub owner: Option, - /// Children scopes - pub children: Vec, - /// Definitions - pub defs: Vec, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ScopeKind { - Package, - Module, - List, - Dict, - Quant, - Lambda, - SchemaDef, - Config, - Check, - Callable, -} - -/// load_package provides users with the ability to parse kcl program and sematic model -/// information including symbols, types, definitions, etc. -pub fn load_packages(opts: &LoadPackageOptions) -> Result { - load_packages_with_cache( - opts, - KCLModuleCache::default(), - KCLScopeCache::default(), - &mut GlobalState::default(), - ) -} - -/// load_package_with_cache provides users with the ability to parse kcl program and sematic model -/// information including symbols, types, definitions, etc. -pub fn load_packages_with_cache( - opts: &LoadPackageOptions, - module_cache: KCLModuleCache, - scope_cache: KCLScopeCache, - gs: &mut GlobalState, -) -> Result { - let sess = ParseSessionRef::default(); - let paths: Vec<&str> = opts.paths.iter().map(|s| s.as_str()).collect(); - let parse_result = load_program( - sess.clone(), - &paths, - opts.load_opts.clone(), - Some(module_cache), - )?; - let parse_errors = parse_result.errors; - let (program, type_errors, gs) = if opts.resolve_ast { - let mut program = parse_result.program; - let prog_scope = resolve_program_with_opts( - &mut program, - kclvm_sema::resolver::Options { - merge_program: false, - type_erasure: false, - ..Default::default() - }, - Some(scope_cache), - ); - let node_ty_map = prog_scope.node_ty_map; - Namer::find_symbols(&program, gs); - AdvancedResolver::resolve_program(&program, gs, node_ty_map.clone())?; - (program, prog_scope.handler.diagnostics.clone(), gs) - } else { - (parse_result.program, IndexSet::default(), gs) - }; - let mut packages = Packages { - program, - paths: parse_result.paths, - parse_errors, - type_errors, - ..Default::default() - }; - if !opts.resolve_ast { - return Ok(packages); - } - let symbols = gs.get_symbols(); - if opts.load_builtin { - for (_, symbol_ref) in symbols.get_builtin_symbols() { - if let Some(symbol) = symbols.get_symbol(*symbol_ref) { - let def_ty = match symbol.get_definition() { - Some(def) => symbols - .get_symbol(def) - .unwrap() - .get_sema_info() - .ty - .clone() - .unwrap_or(Type::any_ref()), - None => symbol.get_sema_info().ty.clone().unwrap_or(Type::any_ref()), - }; - let info = SymbolInfo { - ty: def_ty, - range: symbol.get_range(), - name: symbol.get_name(), - owner: symbol.get_owner(), - def: symbol.get_definition(), - attrs: symbol.get_all_attributes(symbols, None), - is_global: symbol.is_global(), - }; - packages.symbols.insert(*symbol_ref, info); - } - } - } - for path in &packages.paths { - let path_str = path - .to_str() - .ok_or(anyhow::anyhow!("path {} to str failed", path.display()))? - .adjust_canonicalization(); - if let Some(files) = gs.get_sema_db().get_file_sema(&path_str) { - for symbol_ref in files.get_symbols() { - if let Some(symbol) = symbols.get_symbol(*symbol_ref) { - let def_ty = match symbol.get_definition() { - Some(def) => symbols - .get_symbol(def) - .unwrap() - .get_sema_info() - .ty - .clone() - .unwrap_or(Type::any_ref()), - None => symbol.get_sema_info().ty.clone().unwrap_or(Type::any_ref()), - }; - let info = SymbolInfo { - ty: def_ty, - range: symbol.get_range(), - name: symbol.get_name(), - owner: symbol.get_owner(), - def: symbol.get_definition(), - attrs: symbol.get_all_attributes(symbols, None), - is_global: symbol.is_global(), - }; - packages.symbols.insert(*symbol_ref, info); - } - } - } - } - let scopes = gs.get_scopes(); - for (path, scope_ref) in scopes.get_root_scope_map() { - packages.pkg_scope_map.insert(path.clone(), *scope_ref); - // Root scopes - if let Some(scope_ref) = scopes.get_root_scope(path.clone()) { - collect_scope_info( - &mut packages.scopes, - &scope_ref, - scopes, - symbols, - ScopeKind::Package, - ); - } - } - // Update package semantic mappings - packages.node_symbol_map = symbols.get_node_symbol_map().clone(); - packages.symbol_node_map = symbols.get_symbol_node_map().clone(); - packages.fully_qualified_name_map = symbols.get_fully_qualified_name_map().clone(); - Ok(packages) -} - -impl From for ScopeKind { - fn from(value: LocalSymbolScopeKind) -> Self { - match value { - LocalSymbolScopeKind::List => ScopeKind::List, - LocalSymbolScopeKind::Dict => ScopeKind::Dict, - LocalSymbolScopeKind::Quant => ScopeKind::Quant, - LocalSymbolScopeKind::Lambda => ScopeKind::Lambda, - LocalSymbolScopeKind::SchemaDef => ScopeKind::SchemaDef, - LocalSymbolScopeKind::Config => ScopeKind::Config, - LocalSymbolScopeKind::Check => ScopeKind::Check, - LocalSymbolScopeKind::Callable => ScopeKind::Callable, - } - } -} - -fn collect_scope_info( - scopes: &mut IndexMap, - scope_ref: &ScopeRef, - scope_data: &ScopeData, - symbol_data: &SymbolData, - kind: ScopeKind, -) { - if let Some(scope) = scope_data.get_scope(scope_ref) { - let kind = if let Some(scope) = scope_data.try_get_local_scope(scope_ref) { - scope.get_kind().clone().into() - } else { - kind - }; - scopes.insert( - *scope_ref, - ScopeInfo { - kind, - parent: scope.get_parent(), - owner: scope.get_owner(), - children: scope.get_children(), - defs: scope - .get_all_defs(scope_data, symbol_data, None, false, true) - .values() - .copied() - .collect::>(), - }, - ); - - for s in scope.get_children() { - collect_scope_info(scopes, &s, scope_data, symbol_data, ScopeKind::Module); - } - } -} diff --git a/kclvm/loader/src/snapshots/kclvm_loader__tests__assign_stmt_0.snap b/kclvm/loader/src/snapshots/kclvm_loader__tests__assign_stmt_0.snap deleted file mode 100644 index fcf5c73b8..000000000 --- a/kclvm/loader/src/snapshots/kclvm_loader__tests__assign_stmt_0.snap +++ /dev/null @@ -1,89 +0,0 @@ ---- -source: loader/src/tests.rs -expression: "format! (\"{:#?}\", p.symbols.values())" -snapshot_kind: text ---- -[ - SymbolInfo { - ty: Type { - kind: Int, - is_type_alias: false, - flags: INT, - }, - name: "a", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 0, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 1, - ), - }, - ), - owner: Some( - SymbolRef { - id: Index { - index: 16, - generation: 0, - }, - kind: Package, - }, - ), - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Value, - }, - ), - attrs: [], - is_global: true, - }, - SymbolInfo { - ty: Type { - kind: IntLit( - 1, - ), - is_type_alias: false, - flags: INT | LITERAL, - }, - name: "@NumberLitExpression", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 5, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 5, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [], - is_global: false, - }, -] diff --git a/kclvm/loader/src/snapshots/kclvm_loader__tests__assign_stmt_1.snap b/kclvm/loader/src/snapshots/kclvm_loader__tests__assign_stmt_1.snap deleted file mode 100644 index eb54c523a..000000000 --- a/kclvm/loader/src/snapshots/kclvm_loader__tests__assign_stmt_1.snap +++ /dev/null @@ -1,127 +0,0 @@ ---- -source: loader/src/tests.rs -expression: "format! (\"{:#?}\", p.symbols.values())" -snapshot_kind: text ---- -[ - SymbolInfo { - ty: Type { - kind: Int, - is_type_alias: false, - flags: INT, - }, - name: "a", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 0, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 1, - ), - }, - ), - owner: Some( - SymbolRef { - id: Index { - index: 16, - generation: 0, - }, - kind: Package, - }, - ), - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Value, - }, - ), - attrs: [], - is_global: true, - }, - SymbolInfo { - ty: Type { - kind: IntLit( - 1, - ), - is_type_alias: false, - flags: INT | LITERAL, - }, - name: "@NumberLitExpression", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 5, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 5, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: IntLit( - 1, - ), - is_type_alias: false, - flags: INT | LITERAL, - }, - name: "@NumberLitExpression", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 9, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 9, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 1, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [], - is_global: false, - }, -] diff --git a/kclvm/loader/src/snapshots/kclvm_loader__tests__assign_stmt_2.snap b/kclvm/loader/src/snapshots/kclvm_loader__tests__assign_stmt_2.snap deleted file mode 100644 index 4353a90aa..000000000 --- a/kclvm/loader/src/snapshots/kclvm_loader__tests__assign_stmt_2.snap +++ /dev/null @@ -1,163 +0,0 @@ ---- -source: loader/src/tests.rs -expression: "format! (\"{:#?}\", p.symbols.values())" -snapshot_kind: text ---- -[ - SymbolInfo { - ty: Type { - kind: Int, - is_type_alias: false, - flags: INT, - }, - name: "a", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 0, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 1, - ), - }, - ), - owner: Some( - SymbolRef { - id: Index { - index: 16, - generation: 0, - }, - kind: Package, - }, - ), - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Value, - }, - ), - attrs: [], - is_global: true, - }, - SymbolInfo { - ty: Type { - kind: IntLit( - 1, - ), - is_type_alias: false, - flags: INT | LITERAL, - }, - name: "@NumberLitExpression", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 6, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 6, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: IntLit( - 1, - ), - is_type_alias: false, - flags: INT | LITERAL, - }, - name: "@NumberLitExpression", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 10, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 10, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 1, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: Int, - is_type_alias: false, - flags: INT, - }, - name: "@ParenExpression", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 11, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 11, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 2, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [], - is_global: false, - }, -] diff --git a/kclvm/loader/src/snapshots/kclvm_loader__tests__builtin_call_0.snap b/kclvm/loader/src/snapshots/kclvm_loader__tests__builtin_call_0.snap deleted file mode 100644 index ffe791fbe..000000000 --- a/kclvm/loader/src/snapshots/kclvm_loader__tests__builtin_call_0.snap +++ /dev/null @@ -1,341 +0,0 @@ ---- -source: loader/src/tests.rs -assertion_line: 37 -expression: "format! (\"{:#?}\", p.symbols.values())" ---- -[ - SymbolInfo { - ty: Type { - kind: Function( - FunctionType { - doc: "Prints the values to a stream, or to the system stdout by default.\nOptional keyword arguments:\nsep: string inserted between values, default a space.\nend: string appended after the last value, default a newline.", - params: [], - self_ty: None, - return_ty: Type { - kind: None, - is_type_alias: false, - flags: NONE, - }, - is_variadic: true, - kw_only_index: None, - }, - ), - is_type_alias: false, - flags: FUNCTION, - }, - name: "print", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 0, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 5, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 1, - generation: 0, - }, - kind: Function, - }, - ), - attrs: [], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: StrLit( - "hello world", - ), - is_type_alias: false, - flags: STR | LITERAL, - }, - name: "@StringLitExpression", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 19, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 19, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [ - SymbolRef { - id: Index { - index: 149, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 150, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 151, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 152, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 153, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 154, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 155, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 156, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 157, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 158, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 159, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 160, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 161, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 162, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 163, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 164, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 165, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 166, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 167, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 168, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 169, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 170, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 171, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 172, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 173, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 174, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 175, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 176, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 177, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 178, - generation: 0, - }, - kind: Function, - }, - ], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: None, - is_type_alias: false, - flags: NONE, - }, - name: "@CallExpression", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 20, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 20, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 1, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [], - is_global: false, - }, -] diff --git a/kclvm/loader/src/snapshots/kclvm_loader__tests__builtin_call_1.snap b/kclvm/loader/src/snapshots/kclvm_loader__tests__builtin_call_1.snap deleted file mode 100644 index c3a7c79d7..000000000 --- a/kclvm/loader/src/snapshots/kclvm_loader__tests__builtin_call_1.snap +++ /dev/null @@ -1,1072 +0,0 @@ ---- -source: loader/src/tests.rs -assertion_line: 38 -expression: "format! (\"{:#?}\", p.symbols.values())" ---- -[ - SymbolInfo { - ty: Type { - kind: Any, - is_type_alias: false, - flags: ANY, - }, - name: "a", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 0, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 1, - ), - }, - ), - owner: Some( - SymbolRef { - id: Index { - index: 16, - generation: 0, - }, - kind: Package, - }, - ), - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Value, - }, - ), - attrs: [], - is_global: true, - }, - SymbolInfo { - ty: Type { - kind: Function( - FunctionType { - doc: "Return the top level argument by the key", - params: [ - Parameter { - name: "key", - ty: Type { - kind: Str, - is_type_alias: false, - flags: STR, - }, - has_default: false, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "type", - ty: Type { - kind: Str, - is_type_alias: false, - flags: STR, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "required", - ty: Type { - kind: Bool, - is_type_alias: false, - flags: BOOL, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "default", - ty: Type { - kind: Any, - is_type_alias: false, - flags: ANY, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "help", - ty: Type { - kind: Str, - is_type_alias: false, - flags: STR, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - ], - self_ty: None, - return_ty: Type { - kind: Any, - is_type_alias: false, - flags: ANY, - }, - is_variadic: false, - kw_only_index: Some( - 1, - ), - }, - ), - is_type_alias: false, - flags: FUNCTION, - }, - name: "option", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 4, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 10, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Function, - }, - ), - attrs: [], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: StrLit( - "key", - ), - is_type_alias: false, - flags: STR | LITERAL, - }, - name: "@StringLitExpression", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 16, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 16, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [ - SymbolRef { - id: Index { - index: 149, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 150, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 151, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 152, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 153, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 154, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 155, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 156, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 157, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 158, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 159, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 160, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 161, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 162, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 163, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 164, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 165, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 166, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 167, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 168, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 169, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 170, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 171, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 172, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 173, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 174, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 175, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 176, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 177, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 178, - generation: 0, - }, - kind: Function, - }, - ], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: StrLit( - "str", - ), - is_type_alias: false, - flags: STR | LITERAL, - }, - name: "type", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 18, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 22, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 1, - generation: 0, - }, - kind: Value, - }, - ), - attrs: [ - SymbolRef { - id: Index { - index: 149, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 150, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 151, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 152, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 153, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 154, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 155, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 156, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 157, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 158, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 159, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 160, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 161, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 162, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 163, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 164, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 165, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 166, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 167, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 168, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 169, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 170, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 171, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 172, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 173, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 174, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 175, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 176, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 177, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 178, - generation: 0, - }, - kind: Function, - }, - ], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: StrLit( - "str", - ), - is_type_alias: false, - flags: STR | LITERAL, - }, - name: "@StringLitExpression", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 28, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 28, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 1, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [ - SymbolRef { - id: Index { - index: 149, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 150, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 151, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 152, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 153, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 154, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 155, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 156, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 157, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 158, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 159, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 160, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 161, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 162, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 163, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 164, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 165, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 166, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 167, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 168, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 169, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 170, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 171, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 172, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 173, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 174, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 175, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 176, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 177, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 178, - generation: 0, - }, - kind: Function, - }, - ], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: BoolLit( - true, - ), - is_type_alias: false, - flags: BOOL | LITERAL, - }, - name: "required", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 30, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 38, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 2, - generation: 0, - }, - kind: Value, - }, - ), - attrs: [], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: BoolLit( - true, - ), - is_type_alias: false, - flags: BOOL | LITERAL, - }, - name: "@NameConstantLitExpression", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 43, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 43, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 2, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: Any, - is_type_alias: false, - flags: ANY, - }, - name: "@CallExpression", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 44, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 44, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 3, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [], - is_global: false, - }, -] diff --git a/kclvm/loader/src/snapshots/kclvm_loader__tests__builtin_call_2.snap b/kclvm/loader/src/snapshots/kclvm_loader__tests__builtin_call_2.snap deleted file mode 100644 index 79ee22f90..000000000 --- a/kclvm/loader/src/snapshots/kclvm_loader__tests__builtin_call_2.snap +++ /dev/null @@ -1,1404 +0,0 @@ ---- -source: loader/src/tests.rs -assertion_line: 39 -expression: "format! (\"{:#?}\", p.symbols.values())" ---- -[ - SymbolInfo { - ty: Type { - kind: Function( - FunctionType { - doc: "Return the top level argument by the key", - params: [ - Parameter { - name: "key", - ty: Type { - kind: Str, - is_type_alias: false, - flags: STR, - }, - has_default: false, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "type", - ty: Type { - kind: Str, - is_type_alias: false, - flags: STR, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "required", - ty: Type { - kind: Bool, - is_type_alias: false, - flags: BOOL, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "default", - ty: Type { - kind: Any, - is_type_alias: false, - flags: ANY, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "help", - ty: Type { - kind: Str, - is_type_alias: false, - flags: STR, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - ], - self_ty: None, - return_ty: Type { - kind: Any, - is_type_alias: false, - flags: ANY, - }, - is_variadic: false, - kw_only_index: Some( - 1, - ), - }, - ), - is_type_alias: false, - flags: FUNCTION, - }, - name: "opt", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 0, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 3, - ), - }, - ), - owner: Some( - SymbolRef { - id: Index { - index: 16, - generation: 0, - }, - kind: Package, - }, - ), - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Value, - }, - ), - attrs: [], - is_global: true, - }, - SymbolInfo { - ty: Type { - kind: Function( - FunctionType { - doc: "Return the top level argument by the key", - params: [ - Parameter { - name: "key", - ty: Type { - kind: Str, - is_type_alias: false, - flags: STR, - }, - has_default: false, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "type", - ty: Type { - kind: Str, - is_type_alias: false, - flags: STR, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "required", - ty: Type { - kind: Bool, - is_type_alias: false, - flags: BOOL, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "default", - ty: Type { - kind: Any, - is_type_alias: false, - flags: ANY, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "help", - ty: Type { - kind: Str, - is_type_alias: false, - flags: STR, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - ], - self_ty: None, - return_ty: Type { - kind: Any, - is_type_alias: false, - flags: ANY, - }, - is_variadic: false, - kw_only_index: Some( - 1, - ), - }, - ), - is_type_alias: false, - flags: FUNCTION, - }, - name: "option", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 6, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 12, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Function, - }, - ), - attrs: [], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: Any, - is_type_alias: false, - flags: ANY, - }, - name: "a", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 0, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 1, - ), - }, - ), - owner: Some( - SymbolRef { - id: Index { - index: 16, - generation: 0, - }, - kind: Package, - }, - ), - def: Some( - SymbolRef { - id: Index { - index: 1, - generation: 0, - }, - kind: Value, - }, - ), - attrs: [], - is_global: true, - }, - SymbolInfo { - ty: Type { - kind: Function( - FunctionType { - doc: "Return the top level argument by the key", - params: [ - Parameter { - name: "key", - ty: Type { - kind: Str, - is_type_alias: false, - flags: STR, - }, - has_default: false, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "type", - ty: Type { - kind: Str, - is_type_alias: false, - flags: STR, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "required", - ty: Type { - kind: Bool, - is_type_alias: false, - flags: BOOL, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "default", - ty: Type { - kind: Any, - is_type_alias: false, - flags: ANY, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "help", - ty: Type { - kind: Str, - is_type_alias: false, - flags: STR, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - ], - self_ty: None, - return_ty: Type { - kind: Any, - is_type_alias: false, - flags: ANY, - }, - is_variadic: false, - kw_only_index: Some( - 1, - ), - }, - ), - is_type_alias: false, - flags: FUNCTION, - }, - name: "opt", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 4, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 7, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Value, - }, - ), - attrs: [], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: StrLit( - "key", - ), - is_type_alias: false, - flags: STR | LITERAL, - }, - name: "@StringLitExpression", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 13, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 13, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [ - SymbolRef { - id: Index { - index: 149, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 150, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 151, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 152, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 153, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 154, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 155, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 156, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 157, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 158, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 159, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 160, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 161, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 162, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 163, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 164, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 165, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 166, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 167, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 168, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 169, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 170, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 171, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 172, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 173, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 174, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 175, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 176, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 177, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 178, - generation: 0, - }, - kind: Function, - }, - ], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: StrLit( - "str", - ), - is_type_alias: false, - flags: STR | LITERAL, - }, - name: "type", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 15, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 19, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 2, - generation: 0, - }, - kind: Value, - }, - ), - attrs: [ - SymbolRef { - id: Index { - index: 149, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 150, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 151, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 152, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 153, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 154, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 155, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 156, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 157, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 158, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 159, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 160, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 161, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 162, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 163, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 164, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 165, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 166, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 167, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 168, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 169, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 170, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 171, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 172, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 173, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 174, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 175, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 176, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 177, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 178, - generation: 0, - }, - kind: Function, - }, - ], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: StrLit( - "str", - ), - is_type_alias: false, - flags: STR | LITERAL, - }, - name: "@StringLitExpression", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 25, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 25, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 1, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [ - SymbolRef { - id: Index { - index: 149, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 150, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 151, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 152, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 153, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 154, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 155, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 156, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 157, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 158, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 159, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 160, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 161, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 162, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 163, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 164, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 165, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 166, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 167, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 168, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 169, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 170, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 171, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 172, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 173, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 174, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 175, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 176, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 177, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 178, - generation: 0, - }, - kind: Function, - }, - ], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: BoolLit( - true, - ), - is_type_alias: false, - flags: BOOL | LITERAL, - }, - name: "required", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 27, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 35, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 3, - generation: 0, - }, - kind: Value, - }, - ), - attrs: [], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: BoolLit( - true, - ), - is_type_alias: false, - flags: BOOL | LITERAL, - }, - name: "@NameConstantLitExpression", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 40, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 40, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 2, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: Any, - is_type_alias: false, - flags: ANY, - }, - name: "@CallExpression", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 41, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 41, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 3, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [], - is_global: false, - }, -] diff --git a/kclvm/loader/src/snapshots/kclvm_loader__tests__import_stmt_0.snap b/kclvm/loader/src/snapshots/kclvm_loader__tests__import_stmt_0.snap deleted file mode 100644 index ae4ad1aea..000000000 --- a/kclvm/loader/src/snapshots/kclvm_loader__tests__import_stmt_0.snap +++ /dev/null @@ -1,546 +0,0 @@ ---- -source: loader/src/tests.rs -assertion_line: 29 -expression: "format! (\"{:#?}\", p.symbols.values())" ---- -[ - SymbolInfo { - ty: Type { - kind: Module( - ModuleType { - pkgpath: "math", - imported: [ - "test.k", - ], - kind: System, - }, - ), - is_type_alias: false, - flags: MODULE, - }, - name: "math", - range: ( - Position { - filename: "test.k", - line: 1, - column: Some( - 7, - ), - }, - Position { - filename: "test.k", - line: 1, - column: Some( - 11, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 3, - generation: 0, - }, - kind: Package, - }, - ), - attrs: [ - SymbolRef { - id: Index { - index: 52, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 53, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 54, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 55, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 56, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 57, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 58, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 59, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 60, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 61, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 62, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 63, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 64, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 65, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 66, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 67, - generation: 0, - }, - kind: Function, - }, - ], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: Float, - is_type_alias: false, - flags: FLOAT, - }, - name: "a", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 0, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 1, - ), - }, - ), - owner: Some( - SymbolRef { - id: Index { - index: 16, - generation: 0, - }, - kind: Package, - }, - ), - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Value, - }, - ), - attrs: [], - is_global: true, - }, - SymbolInfo { - ty: Type { - kind: Module( - ModuleType { - pkgpath: "math", - imported: [ - "test.k", - ], - kind: System, - }, - ), - is_type_alias: false, - flags: MODULE, - }, - name: "math", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 4, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 8, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 3, - generation: 0, - }, - kind: Package, - }, - ), - attrs: [ - SymbolRef { - id: Index { - index: 52, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 53, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 54, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 55, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 56, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 57, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 58, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 59, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 60, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 61, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 62, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 63, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 64, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 65, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 66, - generation: 0, - }, - kind: Function, - }, - SymbolRef { - id: Index { - index: 67, - generation: 0, - }, - kind: Function, - }, - ], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: Function( - FunctionType { - doc: "Return the logarithm of `x` to the base `e`.", - params: [ - Parameter { - name: "x", - ty: Type { - kind: Union( - [ - Type { - kind: Int, - is_type_alias: false, - flags: INT, - }, - Type { - kind: Float, - is_type_alias: false, - flags: FLOAT, - }, - ], - ), - is_type_alias: false, - flags: UNION, - }, - has_default: false, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - Parameter { - name: "e", - ty: Type { - kind: Float, - is_type_alias: false, - flags: FLOAT, - }, - has_default: true, - default_value: None, - range: ( - Position { - filename: "", - line: 1, - column: None, - }, - Position { - filename: "", - line: 1, - column: None, - }, - ), - }, - ], - self_ty: None, - return_ty: Type { - kind: Float, - is_type_alias: false, - flags: FLOAT, - }, - is_variadic: false, - kw_only_index: None, - }, - ), - is_type_alias: false, - flags: FUNCTION, - }, - name: "log", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 9, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 12, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 62, - generation: 0, - }, - kind: Function, - }, - ), - attrs: [], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: IntLit( - 10, - ), - is_type_alias: false, - flags: INT | LITERAL, - }, - name: "@NumberLitExpression", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 15, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 15, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [], - is_global: false, - }, - SymbolInfo { - ty: Type { - kind: Float, - is_type_alias: false, - flags: FLOAT, - }, - name: "@CallExpression", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 16, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 16, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 1, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [], - is_global: false, - }, -] diff --git a/kclvm/loader/src/snapshots/kclvm_loader__tests__import_stmt_1.snap b/kclvm/loader/src/snapshots/kclvm_loader__tests__import_stmt_1.snap deleted file mode 100644 index 9255ac177..000000000 --- a/kclvm/loader/src/snapshots/kclvm_loader__tests__import_stmt_1.snap +++ /dev/null @@ -1,87 +0,0 @@ ---- -source: loader/src/tests.rs -expression: "format! (\"{:#?}\", p.symbols.values())" -snapshot_kind: text ---- -[ - SymbolInfo { - ty: Type { - kind: Any, - is_type_alias: false, - flags: ANY, - }, - name: "a", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 0, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 1, - ), - }, - ), - owner: Some( - SymbolRef { - id: Index { - index: 16, - generation: 0, - }, - kind: Package, - }, - ), - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Value, - }, - ), - attrs: [], - is_global: true, - }, - SymbolInfo { - ty: Type { - kind: Any, - is_type_alias: false, - flags: ANY, - }, - name: "@IdentifierExpression", - range: ( - Position { - filename: "test.k", - line: 3, - column: Some( - 9, - ), - }, - Position { - filename: "test.k", - line: 3, - column: Some( - 9, - ), - }, - ), - owner: None, - def: Some( - SymbolRef { - id: Index { - index: 0, - generation: 0, - }, - kind: Expression, - }, - ), - attrs: [], - is_global: false, - }, -] diff --git a/kclvm/loader/src/snapshots/kclvm_loader__tests__list_options_0.snap b/kclvm/loader/src/snapshots/kclvm_loader__tests__list_options_0.snap deleted file mode 100644 index 91d15361f..000000000 --- a/kclvm/loader/src/snapshots/kclvm_loader__tests__list_options_0.snap +++ /dev/null @@ -1,13 +0,0 @@ ---- -source: loader/src/tests.rs -expression: "format!(\"{:#?}\", options)" ---- -[ - OptionHelp { - name: "key", - ty: "int", - required: false, - default_value: "", - help: "", - }, -] diff --git a/kclvm/loader/src/snapshots/kclvm_loader__tests__list_options_1.snap b/kclvm/loader/src/snapshots/kclvm_loader__tests__list_options_1.snap deleted file mode 100644 index 2fbb45c5d..000000000 --- a/kclvm/loader/src/snapshots/kclvm_loader__tests__list_options_1.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: loader/src/tests.rs -expression: "format!(\"{:#?}\", options)" ---- -[ - OptionHelp { - name: "key1", - ty: "str", - required: true, - default_value: "", - help: "", - }, - OptionHelp { - name: "key2", - ty: "int", - required: false, - default_value: "", - help: "", - }, -] diff --git a/kclvm/loader/src/snapshots/kclvm_loader__tests__list_options_2.snap b/kclvm/loader/src/snapshots/kclvm_loader__tests__list_options_2.snap deleted file mode 100644 index df9e327c3..000000000 --- a/kclvm/loader/src/snapshots/kclvm_loader__tests__list_options_2.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: loader/src/tests.rs -expression: "format!(\"{:#?}\", options)" ---- -[ - OptionHelp { - name: "key1", - ty: "str", - required: true, - default_value: "\"value\"", - help: "help me", - }, - OptionHelp { - name: "key2", - ty: "", - required: false, - default_value: "", - help: "", - }, -] diff --git a/kclvm/loader/src/snapshots/kclvm_loader__tests__list_options_3.snap b/kclvm/loader/src/snapshots/kclvm_loader__tests__list_options_3.snap deleted file mode 100644 index 74b6ab044..000000000 --- a/kclvm/loader/src/snapshots/kclvm_loader__tests__list_options_3.snap +++ /dev/null @@ -1,13 +0,0 @@ ---- -source: loader/src/tests.rs -expression: "format!(\"{:#?}\", options)" ---- -[ - OptionHelp { - name: "key1", - ty: "int", - required: false, - default_value: "123", - help: "help me", - }, -] diff --git a/kclvm/loader/src/tests.rs b/kclvm/loader/src/tests.rs deleted file mode 100644 index 363d115cc..000000000 --- a/kclvm/loader/src/tests.rs +++ /dev/null @@ -1,76 +0,0 @@ -use crate::option::list_options; -use crate::{load_packages, LoadPackageOptions}; -use kclvm_parser::LoadProgramOptions; - -#[macro_export] -macro_rules! load_package_snapshot { - ($name:ident, $src:expr) => { - #[test] - fn $name() { - let p = load_packages(&LoadPackageOptions { - paths: vec!["test.k".to_string()], - load_opts: Some(LoadProgramOptions { - k_code_list: vec![$src.to_string()], - ..Default::default() - }), - load_builtin: false, - ..Default::default() - }) - .unwrap(); - insta::assert_snapshot!(format!("{:#?}", p.symbols.values())); - } - }; -} - -load_package_snapshot! {assign_stmt_0, "a = 1"} -load_package_snapshot! {assign_stmt_1, "a = 1 + 1"} -load_package_snapshot! {assign_stmt_2, "a = (1 + 1)"} - -load_package_snapshot! {import_stmt_0, r#"import math - -a = math.log(10) -"#} -load_package_snapshot! {import_stmt_1, r#"import pkg - -a = pkg.a -"#} -load_package_snapshot! {builtin_call_0, r#"print("hello world")"#} -load_package_snapshot! {builtin_call_1, r#"a = option("key", type="str", required=True)"#} -load_package_snapshot! {builtin_call_2, r#"opt = option - -a = opt("key", type="str", required=True) -"#} - -#[macro_export] -macro_rules! list_options_snapshot { - ($name:ident, $src:expr) => { - #[test] - fn $name() { - let options = list_options(&LoadPackageOptions { - paths: vec!["test.k".to_string()], - load_opts: Some(LoadProgramOptions { - k_code_list: vec![$src.to_string()], - ..Default::default() - }), - load_builtin: false, - ..Default::default() - }) - .unwrap(); - insta::assert_snapshot!(format!("{:#?}", options)); - } - }; -} -list_options_snapshot! {list_options_0, r#"a = option("key", type="int")"#} -list_options_snapshot! {list_options_1, r#"opt = option - -a = opt("key1", type="str", required=True) -b = option("key2", type="int") -"#} -list_options_snapshot! {list_options_2, r#" -a = option("key1", type="str", required=True, default="value", help="help me") -if True: - b = option("key2") -"#} -list_options_snapshot! {list_options_3, r#" -a = option("key1", type="int", required=False, default=123, help="help me") -"#} diff --git a/kclvm/loader/src/util.rs b/kclvm/loader/src/util.rs deleted file mode 100644 index c890b6aa5..000000000 --- a/kclvm/loader/src/util.rs +++ /dev/null @@ -1,68 +0,0 @@ -use std::collections::HashMap; - -use kclvm_ast::ast; -use kclvm_ast_pretty::{print_ast_node, ASTNode}; -use kclvm_sema::eval::str_literal_eval; - -pub(crate) fn get_call_args_bool( - call_expr: &ast::CallExpr, - index: usize, - key: Option<&str>, -) -> bool { - let val = get_call_args_string(call_expr, index, key); - val == "True" || val == "true" -} - -pub(crate) fn get_call_args_strip_string( - call_expr: &ast::CallExpr, - index: usize, - key: Option<&str>, -) -> String { - let value = get_call_args_string(call_expr, index, key); - match str_literal_eval(&value, false, false) { - Some(value) => value, - None => value, - } -} - -pub(crate) fn get_call_args_string( - call_expr: &ast::CallExpr, - index: usize, - key: Option<&str>, -) -> String { - let (args, kwargs) = arguments_to_string(&call_expr.args, &call_expr.keywords); - if let Some(key) = key { - if let Some(val) = kwargs.get(key) { - return val.to_string(); - } - } - if index < args.len() { - return args[index].to_string(); - } - "".to_string() -} - -/// Print call arguments to argument vector and keyword mapping. -pub fn arguments_to_string( - args: &[ast::NodeRef], - kwargs: &[ast::NodeRef], -) -> (Vec, HashMap) { - ( - args.iter() - .map(|a| print_ast_node(ASTNode::Expr(a))) - .collect(), - kwargs - .iter() - .map(|a| { - ( - a.node.arg.node.get_name(), - a.node - .value - .as_ref() - .map(|v| print_ast_node(ASTNode::Expr(v))) - .unwrap_or_default(), - ) - }) - .collect(), - ) -} diff --git a/kclvm/macros/Cargo.lock b/kclvm/macros/Cargo.lock deleted file mode 100644 index 109f22417..000000000 --- a/kclvm/macros/Cargo.lock +++ /dev/null @@ -1,60 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "kclvm-macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "proc-macro2" -version = "1.0.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "quote" -version = "1.0.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "632d02bff7f874a36f33ea8bb416cd484b90cc66c1194b1a1110d067a7013f58" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "syn" -version = "1.0.90" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "704df27628939572cd88d33f171cd6f896f4eaca85252c6e0a72d8d8287ee86f" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "synstructure" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "unicode-xid", -] - -[[package]] -name = "unicode-xid" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" diff --git a/kclvm/macros/Cargo.toml b/kclvm/macros/Cargo.toml deleted file mode 100644 index 0c0732d9c..000000000 --- a/kclvm/macros/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "kclvm-macros" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[lib] -proc-macro = true - -[dependencies] -synstructure = "0.12.1" -syn = { version = "1", features = ["full"] } -proc-macro2 = "1" -quote = "1" diff --git a/kclvm/makefile b/kclvm/makefile deleted file mode 100644 index 8d822e05d..000000000 --- a/kclvm/makefile +++ /dev/null @@ -1,102 +0,0 @@ -default: run - -PWD:=$(shell pwd) -COVER_REPORT_FILE_PATH:=$(PWD)/target/llvm-cov/html/index.html - -# ------------------------ -# Building and tesing deps -# ------------------------ - -# Generate runtime libraries when the runtime code is changed. -gen-runtime-api: - make -C ./runtime gen-api-spec - make fmt - -# Install the wasm32-unknown-unknown target -install-rustc-wasm: - rustup target add wasm32-unknown-unknown - -# Install the wasm-wasi target -install-rustc-wasm-wasi: - rustup target add wasm32-wasip1 - -# Install python3 pytest -install-test-deps: - python3 -mpip install --user -U pytest pytest-html pytest-xdist ruamel.yaml - -# ------------------------ -# Compile and run -# ------------------------ - -# E2E compile and run -run: - cd .. && make build && cd kclvm - kclvm_cli run ../samples/hello.k - -# Cargo check all packages -check: - cargo check --release - -# Cargo fmt all packages -fmt: - cargo fmt --all - -# Cargo clippy all packages -lint: - cargo clippy - -# Cargo clippy all packages -lint-all: - cargo clippy --workspace --all-features --benches --examples --tests - -# Cargo clippy all packages witj auto ix -fix: - cargo clippy --fix --allow-dirty - -build-wasm: - cargo build --target=wasm32-wasip1 --release - -build-lsp: - cargo build --release --manifest-path tools/src/LSP/Cargo.toml - -# ------------------------ -# Tests -# ------------------------ - -# Unit tests without code cov -test: - cargo test --workspace -r -- --nocapture - -# Unit tests with code cov (Requires rust 1.60+) -codecov: - rustup component add llvm-tools-preview - cargo install cargo-llvm-cov@0.6.15 - cargo llvm-cov --workspace --ignore-filename-regex gpyrpc.rs --html --open -- --nocapture - -# Unit tests with code cov and output the lcov file (Requires rust 1.60+) -codecov-lcov: - rustup component add llvm-tools-preview - cargo install cargo-llvm-cov@0.6.15 - rm -rf $(PWD)/.kclvm_cov - mkdir $(PWD)/.kclvm_cov - cargo llvm-cov --lcov --output-path $(PWD)/.kclvm_cov/lcov.info -r --workspace --ignore-filename-regex gpyrpc.rs -- --nocapture - -# Test runtime libaries using python functions -test-runtime: install-test-deps - cd ./tests/test_units && PYTHONPATH=./../../tests/test_units/runtime python3 -m pytest -vv || { echo 'kclvm/tests/test_units failed' ; exit 1; } - -# E2E grammar tests. -test-grammar: install-test-deps - cd tests/integration/grammar && python3 -m pytest -v -n 5 - -# E2E grammar tests with the fast evaluator -test-grammar-evaluator: install-test-deps - cd tests/integration/grammar && KCL_FAST_EVAL=1 python3 -m pytest -v -n 5 - -# E2E konfig tests. -test-konfig: install-test-deps - cd tests/integration/konfig && python3 -m pytest -v -n 5 - -# Parser fuzz. -fuzz-parser: - cd tests && cargo fuzz run fuzz_parser diff --git a/kclvm/parser/Cargo.lock b/kclvm/parser/Cargo.lock deleted file mode 100644 index 1a5811e00..000000000 --- a/kclvm/parser/Cargo.lock +++ /dev/null @@ -1,1489 +0,0 @@ -# This file is automatically @generated by Cargo. -# It is not intended for manual editing. -version = 3 - -[[package]] -name = "ahash" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" -dependencies = [ - "getrandom", - "once_cell", - "version_check", -] - -[[package]] -name = "aho-corasick" -version = "0.7.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" -dependencies = [ - "memchr", -] - -[[package]] -name = "annotate-snippets" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d78ea013094e5ea606b1c05fe35f1dd7ea1eb1ea259908d040b25bd5ec677ee5" - -[[package]] -name = "arrayvec" -version = "0.7.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" - -[[package]] -name = "atty" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" -dependencies = [ - "hermit-abi", - "libc", - "winapi", -] - -[[package]] -name = "autocfg" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" - -[[package]] -name = "base64" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" - -[[package]] -name = "bit-set" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e11e16035ea35e4e5997b393eacbf6f63983188f7a2ad25bfb13465f5ad59de" -dependencies = [ - "bit-vec", -] - -[[package]] -name = "bit-vec" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "349f9b6a179ed607305526ca489b34ad0a41aed5f7980fa90eb03160b69598fb" - -[[package]] -name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "block-buffer" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" -dependencies = [ - "generic-array", -] - -[[package]] -name = "block-buffer" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324" -dependencies = [ - "generic-array", -] - -[[package]] -name = "bstr" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba3569f383e8f1598449f1a423e72e99569137b47740b1da11ef19af3d5c3223" -dependencies = [ - "lazy_static", - "memchr", - "regex-automata", -] - -[[package]] -name = "cc" -version = "1.0.73" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" - -[[package]] -name = "cfg-if" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" - -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - -[[package]] -name = "chrono" -version = "0.4.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" -dependencies = [ - "libc", - "num-integer", - "num-traits", - "time", - "winapi", -] - -[[package]] -name = "cpufeatures" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b" -dependencies = [ - "libc", -] - -[[package]] -name = "crossbeam-deque" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6455c0ca19f0d2fbf751b908d5c55c1f5cbc65e03c4225427254b46890bdde1e" -dependencies = [ - "cfg-if 1.0.0", - "crossbeam-epoch", - "crossbeam-utils", -] - -[[package]] -name = "crossbeam-epoch" -version = "0.9.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1145cf131a2c6ba0615079ab6a638f7e1973ac9c2634fcbeaaad6114246efe8c" -dependencies = [ - "autocfg", - "cfg-if 1.0.0", - "crossbeam-utils", - "lazy_static", - "memoffset", - "scopeguard", -] - -[[package]] -name = "crossbeam-utils" -version = "0.8.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf124c720b7686e3c2663cf54062ab0f68a88af2fb6a030e87e30bf721fcb38" -dependencies = [ - "cfg-if 1.0.0", - "lazy_static", -] - -[[package]] -name = "crypto-common" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "digest" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" -dependencies = [ - "generic-array", -] - -[[package]] -name = "digest" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506" -dependencies = [ - "block-buffer 0.10.2", - "crypto-common", -] - -[[package]] -name = "dissimilar" -version = "1.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31ad93652f40969dead8d4bf897a41e9462095152eb21c56e5830537e41179dd" - -[[package]] -name = "either" -version = "1.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e78d4f1cc4ae33bbfc157ed5d5a5ef3bc29227303d595861deb238fcec4e9457" - -[[package]] -name = "ena" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7402b94a93c24e742487327a7cd839dc9d36fec9de9fb25b09f2dae459f36c3" -dependencies = [ - "log", -] - -[[package]] -name = "enquote" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06c36cb11dbde389f4096111698d8b567c0720e3452fd5ac3e6b4e47e1939932" -dependencies = [ - "thiserror", -] - -[[package]] -name = "expect-test" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3e6b28dccda91d8742195c71fbda412112c0c77febf56bf3d895d68b19db16" -dependencies = [ - "dissimilar", - "once_cell", -] - -[[package]] -name = "fancy-regex" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d6b8560a05112eb52f04b00e5d3790c0dd75d9d980eb8a122fb23b92a623ccf" -dependencies = [ - "bit-set", - "regex", -] - -[[package]] -name = "fastrand" -version = "1.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf" -dependencies = [ - "instant", -] - -[[package]] -name = "fixedbitset" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "279fb028e20b3c4c320317955b77c5e0c9701f05a1d309905d6fc702cdc5053e" - -[[package]] -name = "fslock" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04412b8935272e3a9bae6f48c7bfff74c2911f60525404edfdd28e49884c3bfb" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "fuchsia-cprng" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba" - -[[package]] -name = "gcc" -version = "0.3.55" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2" - -[[package]] -name = "generic-array" -version = "0.14.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "wasi", -] - -[[package]] -name = "glob" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" - -[[package]] -name = "hashbrown" -version = "0.11.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" - -[[package]] -name = "hermit-abi" -version = "0.1.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" -dependencies = [ - "libc", -] - -[[package]] -name = "indexmap" -version = "1.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" -dependencies = [ - "autocfg", - "hashbrown", - "rustc-rayon", -] - -[[package]] -name = "instant" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "itertools" -version = "0.10.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3" -dependencies = [ - "either", -] - -[[package]] -name = "itoa" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" - -[[package]] -name = "jobserver" -version = "0.1.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af25a77299a7f711a01975c35a6a424eb6862092cc2d6c72c4ed6cbc56dfc1fa" -dependencies = [ - "libc", -] - -[[package]] -name = "json_minimal" -version = "0.1.3" - -[[package]] -name = "kclvm-ast" -version = "0.1.0" -dependencies = [ - "kclvm-span", - "rustc_span", - "serde", - "serde_json", -] - -[[package]] -name = "kclvm-config" -version = "0.1.0" -dependencies = [ - "ahash", - "chrono", - "fslock", - "glob", - "indexmap", - "kclvm-version", - "pathdiff", - "ron", - "rust-crypto", - "serde", - "serde_yaml", - "toml", -] - -[[package]] -name = "kclvm-error" -version = "0.1.0" -dependencies = [ - "annotate-snippets", - "atty", - "indexmap", - "kclvm-runtime", - "kclvm-span", - "rustc_span", - "termcolor", - "termize", - "tracing", -] - -[[package]] -name = "kclvm-lexer" -version = "0.1.0" -dependencies = [ - "kclvm-error", - "rustc_lexer", - "unic-emoji-char", -] - -[[package]] -name = "kclvm-macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "kclvm-parser" -version = "0.1.0" -dependencies = [ - "bstr", - "either", - "enquote", - "expect-test", - "kclvm-ast", - "kclvm-config", - "kclvm-error", - "kclvm-lexer", - "kclvm-runtime", - "kclvm-sema", - "kclvm-span", - "num-bigint", - "rustc_data_structures", - "rustc_lexer", - "rustc_span", - "serde", - "serde_json", - "tracing", - "unicode_names2", -] - -[[package]] -name = "kclvm-runtime" -version = "0.1.0" -dependencies = [ - "ahash", - "base64", - "bstr", - "chrono", - "fancy-regex", - "indexmap", - "itertools", - "json_minimal", - "kclvm_runtime_internal_macros", - "libc", - "md5", - "num-integer", - "phf", - "regex", - "serde", - "serde_json", - "serde_yaml", - "sha1", - "sha2 0.9.9", - "unic-ucd-bidi", - "unic-ucd-category", - "unicode-casing", -] - -[[package]] -name = "kclvm-sema" -version = "0.1.0" -dependencies = [ - "ahash", - "bit-set", - "bitflags", - "fancy-regex", - "indexmap", - "kclvm-ast", - "kclvm-error", - "kclvm-runtime", - "kclvm-span", - "once_cell", - "petgraph", - "phf", - "unicode_names2", -] - -[[package]] -name = "kclvm-span" -version = "0.1.0" -dependencies = [ - "kclvm-macros", - "rustc_span", - "scoped-tls", -] - -[[package]] -name = "kclvm-version" -version = "0.1.0" - -[[package]] -name = "kclvm_runtime_internal_macros" -version = "0.1.0" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "lazy_static" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" - -[[package]] -name = "libc" -version = "0.2.123" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb691a747a7ab48abc15c5b42066eaafde10dc427e3b6ee2a1cf43db04c763bd" - -[[package]] -name = "linked-hash-map" -version = "0.5.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3" - -[[package]] -name = "lock_api" -version = "0.4.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" -dependencies = [ - "autocfg", - "scopeguard", -] - -[[package]] -name = "log" -version = "0.4.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6389c490849ff5bc16be905ae24bc913a9c8892e19b2341dbc175e14c341c2b8" -dependencies = [ - "cfg-if 1.0.0", -] - -[[package]] -name = "matches" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" - -[[package]] -name = "md-5" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "658646b21e0b72f7866c7038ab086d3d5e1cd6271f060fd37defb241949d0582" -dependencies = [ - "digest 0.10.3", -] - -[[package]] -name = "md5" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771" - -[[package]] -name = "memchr" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" - -[[package]] -name = "memmap2" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "723e3ebdcdc5c023db1df315364573789f8857c11b631a2fdfad7c00f5c046b4" -dependencies = [ - "libc", -] - -[[package]] -name = "memoffset" -version = "0.6.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num-bigint" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f93ab6289c7b344a8a9f60f88d80aa20032336fe78da341afc91c8a2341fc75f" -dependencies = [ - "autocfg", - "num-integer", - "num-traits", -] - -[[package]] -name = "num-integer" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db" -dependencies = [ - "autocfg", - "num-traits", -] - -[[package]] -name = "num-traits" -version = "0.2.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" -dependencies = [ - "autocfg", -] - -[[package]] -name = "num_cpus" -version = "1.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" -dependencies = [ - "hermit-abi", - "libc", -] - -[[package]] -name = "once_cell" -version = "1.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9" - -[[package]] -name = "opaque-debug" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" - -[[package]] -name = "parking_lot" -version = "0.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87f5ec2493a61ac0506c0f4199f99070cbe83857b0337006a30f3e6719b8ef58" -dependencies = [ - "lock_api", - "parking_lot_core", -] - -[[package]] -name = "parking_lot_core" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "995f667a6c822200b0433ac218e05582f0e2efa1b922a3fd2fbaadc5f87bab37" -dependencies = [ - "cfg-if 1.0.0", - "libc", - "redox_syscall", - "smallvec", - "windows-sys", -] - -[[package]] -name = "pathdiff" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd" - -[[package]] -name = "petgraph" -version = "0.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a13a2fa9d0b63e5f22328828741e523766fff0ee9e779316902290dff3f824f" -dependencies = [ - "fixedbitset", - "indexmap", -] - -[[package]] -name = "phf" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2ac8b67553a7ca9457ce0e526948cad581819238f4a9d1ea74545851fa24f37" -dependencies = [ - "phf_macros", - "phf_shared", - "proc-macro-hack", -] - -[[package]] -name = "phf_generator" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d43f3220d96e0080cc9ea234978ccd80d904eafb17be31bb0f76daaea6493082" -dependencies = [ - "phf_shared", - "rand 0.8.5", -] - -[[package]] -name = "phf_macros" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b706f5936eb50ed880ae3009395b43ed19db5bff2ebd459c95e7bf013a89ab86" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro-hack", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "phf_shared" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a68318426de33640f02be62b4ae8eb1261be2efbc337b60c54d845bf4484e0d9" -dependencies = [ - "siphasher", -] - -[[package]] -name = "pin-project-lite" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e280fbe77cc62c91527259e9442153f4688736748d24660126286329742b4c6c" - -[[package]] -name = "ppv-lite86" -version = "0.2.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" - -[[package]] -name = "proc-macro-hack" -version = "0.5.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5" - -[[package]] -name = "proc-macro2" -version = "1.0.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9f5105d4fdaab20335ca9565e106a5d9b82b6219b5ba735731124ac6711d23d" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "psm" -version = "0.1.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "871372391786ccec00d3c5d3d6608905b3d4db263639cfe075d3b60a736d115a" -dependencies = [ - "cc", -] - -[[package]] -name = "quote" -version = "1.0.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38bc8cc6a5f2e3655e0899c1b848643b2562f853f114bfec7be120678e3ace05" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "rand" -version = "0.3.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "64ac302d8f83c0c1974bf758f6b041c6c8ada916fbb44a609158ca8b064cc76c" -dependencies = [ - "libc", - "rand 0.4.6", -] - -[[package]] -name = "rand" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293" -dependencies = [ - "fuchsia-cprng", - "libc", - "rand_core 0.3.1", - "rdrand", - "winapi", -] - -[[package]] -name = "rand" -version = "0.8.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" -dependencies = [ - "libc", - "rand_chacha", - "rand_core 0.6.3", -] - -[[package]] -name = "rand_chacha" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" -dependencies = [ - "ppv-lite86", - "rand_core 0.6.3", -] - -[[package]] -name = "rand_core" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b" -dependencies = [ - "rand_core 0.4.2", -] - -[[package]] -name = "rand_core" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc" - -[[package]] -name = "rand_core" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" -dependencies = [ - "getrandom", -] - -[[package]] -name = "rdrand" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2" -dependencies = [ - "rand_core 0.3.1", -] - -[[package]] -name = "redox_syscall" -version = "0.2.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" -dependencies = [ - "bitflags", -] - -[[package]] -name = "regex" -version = "1.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132" - -[[package]] -name = "regex-syntax" -version = "0.6.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" - -[[package]] -name = "remove_dir_all" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" -dependencies = [ - "winapi", -] - -[[package]] -name = "ron" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b861ecaade43ac97886a512b360d01d66be9f41f3c61088b42cedf92e03d678" -dependencies = [ - "base64", - "bitflags", - "serde", -] - -[[package]] -name = "rust-crypto" -version = "0.2.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f76d05d3993fd5f4af9434e8e436db163a12a9d40e1a58a726f27a01dfd12a2a" -dependencies = [ - "gcc", - "libc", - "rand 0.3.23", - "rustc-serialize", - "time", -] - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - -[[package]] -name = "rustc-rayon" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9974ab223660e61c1b4e7b43b827379df286736ca988308ce7e16f59f2d89246" -dependencies = [ - "crossbeam-deque", - "either", - "rustc-rayon-core", -] - -[[package]] -name = "rustc-rayon-core" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "564bfd27be8db888d0fa76aa4335e7851aaed0c2c11ad1e93aeb9349f6b88500" -dependencies = [ - "crossbeam-deque", - "crossbeam-utils", - "lazy_static", - "num_cpus", -] - -[[package]] -name = "rustc-serialize" -version = "0.3.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda" - -[[package]] -name = "rustc_data_structures" -version = "0.0.0" -dependencies = [ - "arrayvec", - "bitflags", - "cfg-if 0.1.10", - "ena", - "indexmap", - "jobserver", - "libc", - "memmap2", - "parking_lot", - "rustc-hash", - "rustc-rayon", - "rustc-rayon-core", - "stable_deref_trait", - "stacker", - "tempfile", - "tracing", - "winapi", -] - -[[package]] -name = "rustc_lexer" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c86aae0c77166108c01305ee1a36a1e77289d7dc6ca0a3cd91ff4992de2d16a5" -dependencies = [ - "unicode-xid", -] - -[[package]] -name = "rustc_span" -version = "0.0.0" -dependencies = [ - "cfg-if 0.1.10", - "md-5", - "rustc_data_structures", - "scoped-tls", - "sha-1", - "sha2 0.10.2", - "tracing", - "unicode-width", -] - -[[package]] -name = "ryu" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" - -[[package]] -name = "scoped-tls" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea6a9290e3c9cf0f18145ef7ffa62d68ee0bf5fcd651017e586dc7fd5da448c2" - -[[package]] -name = "scopeguard" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" - -[[package]] -name = "serde" -version = "1.0.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f12d06de37cf59146fbdecab66aa99f9fe4f78722e3607577a5375d66bd0c913" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.130" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7bc1a1ab1961464eae040d96713baa5a724a8152c1222492465b54322ec508b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.79" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e8d9fa5c3b304765ce1fd9c4c8a3de2c8db365a5b91be52f186efc675681d95" -dependencies = [ - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "serde_yaml" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4a521f2940385c165a24ee286aa8599633d162077a54bdcae2a6fd5a7bfa7a0" -dependencies = [ - "indexmap", - "ryu", - "serde", - "yaml-rust", -] - -[[package]] -name = "sha-1" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.3", -] - -[[package]] -name = "sha1" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" -dependencies = [ - "sha1_smol", -] - -[[package]] -name = "sha1_smol" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" - -[[package]] -name = "sha2" -version = "0.9.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800" -dependencies = [ - "block-buffer 0.9.0", - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.9.0", - "opaque-debug", -] - -[[package]] -name = "sha2" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676" -dependencies = [ - "cfg-if 1.0.0", - "cpufeatures", - "digest 0.10.3", -] - -[[package]] -name = "siphasher" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bd3e3206899af3f8b12af284fafc038cc1dc2b41d1b89dd17297221c5d225de" - -[[package]] -name = "smallvec" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83" - -[[package]] -name = "stable_deref_trait" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" - -[[package]] -name = "stacker" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90939d5171a4420b3ff5fbc8954d641e7377335454c259dcb80786f3f21dc9b4" -dependencies = [ - "cc", - "cfg-if 1.0.0", - "libc", - "psm", - "winapi", -] - -[[package]] -name = "syn" -version = "1.0.80" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d010a1623fbd906d51d650a9916aaefc05ffa0e4053ff7fe601167f3e715d194" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "synstructure" -version = "0.12.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "unicode-xid", -] - -[[package]] -name = "tempfile" -version = "3.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" -dependencies = [ - "cfg-if 1.0.0", - "fastrand", - "libc", - "redox_syscall", - "remove_dir_all", - "winapi", -] - -[[package]] -name = "termcolor" -version = "1.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "termize" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1706be6b564323ce7092f5f7e6b118a14c8ef7ed0e69c8c5329c914a9f101295" -dependencies = [ - "libc", - "winapi", -] - -[[package]] -name = "thiserror" -version = "1.0.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "854babe52e4df1653706b98fcfc05843010039b406875930a70e4d9644e5c417" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "1.0.30" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "time" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" -dependencies = [ - "libc", - "wasi", - "winapi", -] - -[[package]] -name = "toml" -version = "0.5.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" -dependencies = [ - "serde", -] - -[[package]] -name = "tracing" -version = "0.1.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a1bdf54a7c28a2bbf701e1d2233f6c77f473486b94bee4f9678da5a148dca7f" -dependencies = [ - "cfg-if 1.0.0", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e65ce065b4b5c53e73bb28912318cb8c9e9ad3921f1d669eb0e68b4c8143a2b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tracing-core" -version = "0.1.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa31669fa42c09c34d94d8165dd2012e8ff3c66aca50f3bb226b68f216f2706c" -dependencies = [ - "lazy_static", -] - -[[package]] -name = "typenum" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" - -[[package]] -name = "unic-char-property" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8c57a407d9b6fa02b4795eb81c5b6652060a15a7903ea981f3d723e6c0be221" -dependencies = [ - "unic-char-range", -] - -[[package]] -name = "unic-char-range" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0398022d5f700414f6b899e10b8348231abf9173fa93144cbc1a43b9793c1fbc" - -[[package]] -name = "unic-common" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" - -[[package]] -name = "unic-emoji-char" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b07221e68897210270a38bde4babb655869637af0f69407f96053a34f76494d" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-bidi" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1d568b51222484e1f8209ce48caa6b430bf352962b877d592c29ab31fb53d8c" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-category" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b8d4591f5fcfe1bd4453baaf803c40e1b1e69ff8455c47620440b46efef91c0" -dependencies = [ - "matches", - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - -[[package]] -name = "unic-ucd-version" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96bd2f2237fe450fcd0a1d2f5f4e91711124f7857ba2e964247776ebeeb7b0c4" -dependencies = [ - "unic-common", -] - -[[package]] -name = "unicode-casing" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "623f59e6af2a98bdafeb93fa277ac8e1e40440973001ca15cf4ae1541cd16d56" - -[[package]] -name = "unicode-width" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973" - -[[package]] -name = "unicode-xid" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" - -[[package]] -name = "unicode_names2" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "87d6678d7916394abad0d4b19df4d3802e1fd84abd7d701f39b75ee71b9e8cf1" - -[[package]] -name = "version_check" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" - -[[package]] -name = "wasi" -version = "0.10.0+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" - -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - -[[package]] -name = "winapi-util" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" -dependencies = [ - "winapi", -] - -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - -[[package]] -name = "windows-sys" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5acdd78cb4ba54c0045ac14f62d8f94a03d10047904ae2a40afa1e99d8f70825" -dependencies = [ - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17cffbe740121affb56fad0fc0e421804adf0ae00891205213b5cecd30db881d" - -[[package]] -name = "windows_i686_gnu" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2564fde759adb79129d9b4f54be42b32c89970c18ebf93124ca8870a498688ed" - -[[package]] -name = "windows_i686_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cd9d32ba70453522332c14d38814bceeb747d80b3958676007acadd7e166956" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfce6deae227ee8d356d19effc141a509cc503dfd1f850622ec4b0f84428e1f4" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d19538ccc21819d01deaf88d6a17eae6596a12e9aafdbb97916fb49896d89de9" - -[[package]] -name = "yaml-rust" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" -dependencies = [ - "linked-hash-map", -] diff --git a/kclvm/parser/Cargo.toml b/kclvm/parser/Cargo.toml deleted file mode 100644 index d0a7e89c3..000000000 --- a/kclvm/parser/Cargo.toml +++ /dev/null @@ -1,40 +0,0 @@ -[package] -name = "kclvm-parser" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -compiler_base_span = "0.1.2" -compiler_base_session = "0.1.3" -compiler_base_error = "0.1.6" -compiler_base_macros = "0.1.1" -tracing = "0.1" -serde = { version = "1", features = ["derive"] } -serde_json = "1.0" -rustc_lexer = "0.1.0" -either = "1.1.0" -enquote = "1.1.0" -unicode_names2 = "0.4" -bstr = "0.2.16" -petgraph = "0.6.0" -num-bigint = "0.4" -regex = "1.7.0" -anyhow = "1.0" -parking_lot = "0.12.3" -glob = "0.3.1" - -kclvm-lexer = { path = "../lexer" } -kclvm-ast = { path = "../ast" } -kclvm-span = { path = "../span" } -kclvm-error = { path = "../error" } -kclvm-config = { path = "../config" } -kclvm-sema = { path = "../sema" } -kclvm-utils = { path = "../utils" } -kclvm-primitives = { path = "../primitives" } -walkdir = "2" - -[dev-dependencies] -expect-test = "1.0" -insta = "1.8.0" diff --git a/kclvm/parser/src/lexer/mod.rs b/kclvm/parser/src/lexer/mod.rs deleted file mode 100644 index 4ec4dc5eb..000000000 --- a/kclvm/parser/src/lexer/mod.rs +++ /dev/null @@ -1,763 +0,0 @@ -//! A KCL lexer. -//! -//! The lexer is built on the low level [`kclvm_lexer`] -//! -//! It's main responsibilities: -//! 1. Mapping low level [`kclvm_lexer::Token`] tokens into [`kclvm_ast::Token`] tokens, -//! and provide TokenStream to downstream [`kclvm_parser::parser`]. -//! 2. Validations on Literals(String, Int, Float). -//! 3. Validations on closure of delim tokens. -//! 4. Validations on indent and dedent. -//! -//! The main differences of tokens between ast and lexer is: -//! 1. AST Affinity, based on unary, binary and other operations. -//! 2. Has Indent and dedent. -//! 3. Don't have some tokens(such as ';', '..', '..=', '<-') - -mod indent; -mod string; - -#[cfg(test)] -mod tests; - -use compiler_base_macros::bug; -use compiler_base_span::{self, span::new_byte_pos, BytePos, Span}; -use kclvm_ast::ast::NumberBinarySuffix; -use kclvm_ast::token::VALID_SPACES_LENGTH; -use kclvm_ast::token::{self, BinOpToken, CommentKind, Token, TokenKind}; -use kclvm_ast::token_stream::TokenStream; -use kclvm_error::ParseErrorMessage; -use kclvm_lexer::Base; -use kclvm_span::symbol::Symbol; -pub(crate) use string::str_content_eval; - -use self::indent::IndentLevel; -use crate::session::ParseSession; - -/// EntryPoint of the lexer. -/// Parse token streams from an input raw string and a fixed start point. -/// Return an iterable token stream. -pub fn parse_token_streams(sess: &ParseSession, src: &str, start_pos: BytePos) -> TokenStream { - Lexer { - sess, - start_pos, - pos: start_pos, - tok_start_pos: start_pos, - end_src_index: src.len(), - src, - token: TokenWithIndents::Token { - token: Token::dummy(), - }, - indent_cxt: IndentContext { - delims: Vec::new(), - tabs: 0, - spaces: 0, - new_line_beginning: false, - indents: vec![Default::default()], - }, - } - .into_tokens() -} - -/// A token or a token with indent. -enum TokenWithIndents { - Token { - token: Token, - }, - WithIndent { - token: Token, - indent: IndentOrDedents, - }, -} - -/// A indent or a fixed count of dedents. -enum IndentOrDedents { - Indent { token: Token }, - Dedents { tokens: Vec }, -} - -impl TokenWithIndents { - pub(crate) fn is_eof(&self) -> bool { - match self { - TokenWithIndents::Token { token } => *token == token::Eof, - TokenWithIndents::WithIndent { token, indent: _ } => *token == token::Eof, - } - } - - pub(crate) fn append_to(&self, buf: &mut TokenStreamBuilder) { - match self { - TokenWithIndents::Token { token } => { - buf.push(*token); - } - TokenWithIndents::WithIndent { token, indent } => { - match indent { - IndentOrDedents::Indent { token } => { - buf.push(*token); - } - IndentOrDedents::Dedents { tokens } => { - for dedent in tokens { - buf.push(*dedent); - } - } - } - - buf.push(*token); - } - } - } -} - -struct Lexer<'a> { - /// Initial position, read-only. - start_pos: BytePos, - - /// The absolute offset within the source_map of the current character. - pos: BytePos, - - /// The start position of the current token. - tok_start_pos: BytePos, - - /// Stop reading src at this index. - end_src_index: usize, - - /// Source text to tokenize. - src: &'a str, - - /// Token - token: TokenWithIndents, - - /// A on-going context to handle indent/dedents - indent_cxt: IndentContext, - - /// parse-time session - pub sess: &'a ParseSession, -} - -struct IndentContext { - /// A new line flag - new_line_beginning: bool, - - /// Delim stack - delims: Vec, - - /// tab counter - tabs: usize, - - /// space counter - spaces: usize, - - /// Indents stack - indents: Vec, -} - -impl<'a> Lexer<'a> { - fn into_tokens(mut self) -> TokenStream { - let mut buf = TokenStreamBuilder::default(); - // In the process of look-behind lexing, it is necessary to check the type of the previous token in 'buf', - // If the previous token and the current token can form a multi-character token, - // then the previous token will be popped from 'buf'. - // - // Therefore, the method 'self.token()' needs to take the mutable reference of 'buf' as an incoming argument. - self.token = self.token(&mut buf); - - while !self.token.is_eof() { - self.token.append_to(&mut buf); - self.token = self.token(&mut buf); - } - - self.eof(&mut buf); - buf.into_token_stream() - } - - fn token(&mut self, tok_stream_builder: &mut TokenStreamBuilder) -> TokenWithIndents { - loop { - let start_src_index = self.src_index(self.pos); - let text: &str = &self.src[start_src_index..self.end_src_index]; - - if text.is_empty() { - return TokenWithIndents::Token { - token: Token::new(token::Eof, self.span(self.pos, self.pos)), - }; - } - - // fetch next token - let token = kclvm_lexer::first_token(text); - - // Detect and handle indent cases before lexing on-going token - let indent = self.lex_indent_context(token.kind); - - // Because of the 'look-behind', the 'start' of the current token becomes a two-way cursor, - // which can not only move forward, but also move backward when 'look-behind'. - // Therefore, the value of 'self.tok_start_pos' can be changed in 'self.lex_token()'. - self.tok_start_pos = self.pos; - // update pos after token and indent handling - self.pos = self.pos + new_byte_pos(token.len as u32); - - // In the process of look-behind lexing, it is necessary to check the type of the previous token in 'tok_stream_builder', - // If the previous token and the current token can form a multi-character token, - // then the previous token will be popped from 'tok_stream_builder'. - // Therefore, the method 'self.lex_token()' needs to take the mutable reference of 'tok_stream_builder' as an incoming argument. - if let Some(kind) = self.lex_token(token, self.tok_start_pos, tok_stream_builder) { - let span = self.span(self.tok_start_pos, self.pos); - - match indent { - Some(iord) => { - // return the token with the leading indent/dedents - return TokenWithIndents::WithIndent { - token: Token::new(kind, span), - indent: iord, - }; - } - None => { - // return the token itself - return TokenWithIndents::Token { - token: Token::new(kind, span), - }; - } - } - } - } - } - - /// Turns `kclvm_lexer::TokenKind` into a rich `kclvm_ast::TokenKind`. - fn lex_token( - &mut self, - token: kclvm_lexer::Token, - start: BytePos, - tok_stream_builder: &mut TokenStreamBuilder, - ) -> Option { - Some(match token.kind { - kclvm_lexer::TokenKind::LineComment { doc_style: _ } => { - let s = self.str_from(start); - token::DocComment(CommentKind::Line(Symbol::intern(s))) - } - // Whitespace - kclvm_lexer::TokenKind::Newline => { - self.indent_cxt.new_line_beginning = true; - token::Newline - } - kclvm_lexer::TokenKind::Tab - | kclvm_lexer::TokenKind::Space - | kclvm_lexer::TokenKind::CarriageReturn - | kclvm_lexer::TokenKind::Whitespace => return None, - // Identifier - kclvm_lexer::TokenKind::Ident => { - let s = self.str_from(start); - token::Ident(Symbol::intern(s)) - } - // Literal - kclvm_lexer::TokenKind::Literal { kind, suffix_start } => { - let suffix_start = start + new_byte_pos(suffix_start as u32); - let (kind, symbol, suffix, raw) = self.lex_literal(start, suffix_start, kind); - token::Literal(token::Lit { - kind, - symbol, - suffix, - raw, - }) - } - // Unary op - kclvm_lexer::TokenKind::Tilde => token::UnaryOp(token::UTilde), - kclvm_lexer::TokenKind::Bang => { - self.sess.struct_message_error_with_suggestions( - ParseErrorMessage::InvalidTokenNot, - self.span(start, self.pos), - Some(vec!["not ".to_string()]), - ); - token::UnaryOp(token::UNot) - } - // Binary op - kclvm_lexer::TokenKind::Plus => token::BinOp(token::Plus), - kclvm_lexer::TokenKind::Minus => token::BinOp(token::Minus), - kclvm_lexer::TokenKind::Star => token::BinOp(token::Star), - kclvm_lexer::TokenKind::Slash => token::BinOp(token::Slash), - kclvm_lexer::TokenKind::Percent => token::BinOp(token::Percent), - kclvm_lexer::TokenKind::StarStar => token::BinOp(token::StarStar), - kclvm_lexer::TokenKind::SlashSlash => token::BinOp(token::SlashSlash), - kclvm_lexer::TokenKind::Caret => token::BinOp(token::Caret), - kclvm_lexer::TokenKind::And => token::BinOp(token::And), - kclvm_lexer::TokenKind::Or => token::BinOp(token::Or), - kclvm_lexer::TokenKind::LtLt => token::BinOp(token::Shl), - kclvm_lexer::TokenKind::GtGt => token::BinOp(token::Shr), - // Binary op eq - kclvm_lexer::TokenKind::PlusEq => token::BinOpEq(token::Plus), - kclvm_lexer::TokenKind::MinusEq => token::BinOpEq(token::Minus), - kclvm_lexer::TokenKind::StarEq => token::BinOpEq(token::Star), - kclvm_lexer::TokenKind::SlashEq => token::BinOpEq(token::Slash), - kclvm_lexer::TokenKind::PercentEq => token::BinOpEq(token::Percent), - kclvm_lexer::TokenKind::StarStarEq => token::BinOpEq(token::StarStar), - kclvm_lexer::TokenKind::SlashSlashEq => token::BinOpEq(token::SlashSlash), - kclvm_lexer::TokenKind::CaretEq => token::BinOpEq(token::Caret), - kclvm_lexer::TokenKind::AndEq => token::BinOpEq(token::And), - kclvm_lexer::TokenKind::OrEq => token::BinOpEq(token::Or), - kclvm_lexer::TokenKind::LtLtEq => token::BinOpEq(token::Shl), - kclvm_lexer::TokenKind::GtGtEq => token::BinOpEq(token::Shr), - // Binary cmp - kclvm_lexer::TokenKind::EqEq => token::BinCmp(token::Eq), - kclvm_lexer::TokenKind::BangEq => token::BinCmp(token::NotEq), - kclvm_lexer::TokenKind::Lt => token::BinCmp(token::Lt), - kclvm_lexer::TokenKind::LtEq => token::BinCmp(token::LtEq), - // If the current token is '>', - // then lexer need to check whether the previous token is '-', - // if yes, return token '->', if not return token '>'. - kclvm_lexer::TokenKind::Gt => match self.look_behind(&token, tok_stream_builder) { - Some(tok_kind) => tok_kind, - None => token::BinCmp(token::Gt), - }, - kclvm_lexer::TokenKind::GtEq => token::BinCmp(token::GtEq), - // Structural symbols - kclvm_lexer::TokenKind::At => token::At, - kclvm_lexer::TokenKind::Dot => token::Dot, - kclvm_lexer::TokenKind::DotDotDot => token::DotDotDot, - kclvm_lexer::TokenKind::Comma => token::Comma, - kclvm_lexer::TokenKind::Colon => token::Colon, - kclvm_lexer::TokenKind::Dollar => token::Dollar, - kclvm_lexer::TokenKind::Question => token::Question, - kclvm_lexer::TokenKind::Eq => token::Assign, - // Delim tokens - kclvm_lexer::TokenKind::OpenParen => { - self.indent_cxt.delims.push(token::OpenDelim(token::Paren)); - token::OpenDelim(token::Paren) - } - kclvm_lexer::TokenKind::CloseParen => match self.indent_cxt.delims.pop() { - // check delim stack - Some(delim) => match delim { - // expected case - token::OpenDelim(token::Paren) => token::CloseDelim(token::Paren), - // error recovery - token::OpenDelim(token::Brace) => { - self.sess.struct_span_error( - "error nesting on close paren", - self.span(start, self.pos), - ); - token::CloseDelim(token::Brace) - } - // error recovery - token::OpenDelim(token::Bracket) => { - self.sess.struct_span_error( - "error nesting on close paren", - self.span(start, self.pos), - ); - token::CloseDelim(token::Bracket) - } - // impossible case - _ => bug!("Impossible!"), - }, - // error recovery - None => { - self.sess.struct_span_error( - "error nesting on close paren", - self.span(start, self.pos), - ); - token::CloseDelim(token::Paren) - } - }, - kclvm_lexer::TokenKind::OpenBrace => { - self.indent_cxt.delims.push(token::OpenDelim(token::Brace)); - token::OpenDelim(token::Brace) - } - kclvm_lexer::TokenKind::CloseBrace => match self.indent_cxt.delims.pop() { - // check delim stack - Some(delim) => match delim { - // expected case - token::OpenDelim(token::Brace) => token::CloseDelim(token::Brace), - // error recovery - token::OpenDelim(token::Paren) => { - self.sess.struct_span_error( - "error nesting on close brace", - self.span(start, self.pos), - ); - token::CloseDelim(token::Paren) - } - // error recovery - token::OpenDelim(token::Bracket) => { - self.sess.struct_span_error( - "error nesting on close brace", - self.span(start, self.pos), - ); - token::CloseDelim(token::Bracket) - } - // impossible case - _ => bug!("Impossible!"), - }, - // error recovery - None => { - self.sess.struct_span_error( - "error nesting on close brace", - self.span(start, self.pos), - ); - token::CloseDelim(token::Brace) - } - }, - kclvm_lexer::TokenKind::OpenBracket => { - self.indent_cxt - .delims - .push(token::OpenDelim(token::Bracket)); - token::OpenDelim(token::Bracket) - } - kclvm_lexer::TokenKind::CloseBracket => match self.indent_cxt.delims.pop() { - // check delim stack - Some(delim) => match delim { - // expected case - token::OpenDelim(token::Bracket) => token::CloseDelim(token::Bracket), - // error recovery - token::OpenDelim(token::Brace) => { - self.sess.struct_span_error( - "mismatched closing delimiter", - self.span(start, self.pos), - ); - token::CloseDelim(token::Brace) - } - // error recovery - token::OpenDelim(token::Paren) => { - self.sess.struct_span_error( - "mismatched closing delimiter", - self.span(start, self.pos), - ); - token::CloseDelim(token::Paren) - } - // impossible case - _ => bug!("Impossible!"), - }, - // error recovery - None => { - self.sess.struct_span_error( - "mismatched closing delimiter", - self.span(start, self.pos), - ); - token::CloseDelim(token::Bracket) - } - }, - kclvm_lexer::TokenKind::LineContinue => return None, - kclvm_lexer::TokenKind::InvalidLineContinue => { - // If we encounter an illegal line continuation character, - // we will restore it to a normal line continuation character. - self.sess.struct_message_error_with_suggestions( - ParseErrorMessage::CharAfterLineContinuationToken, - self.span(start, self.pos), - None, - ); - return None; - } - kclvm_lexer::TokenKind::Semi => { - // If we encounter an illegal semi token ';', raise a friendly error. - self.sess.struct_message_error_with_suggestions( - ParseErrorMessage::RedundantSemicolon, - self.span(start, self.pos), - Some(vec!["".to_string()]), - ); - return None; - } - _ => { - self.sess - .struct_span_error("unknown start of token", self.span(start, self.pos)); - return None; - } - }) - } - - /// From the lexed tokens stack, check whether the token at the top of the stack and the current character can combine a new token. - /// If yes, lexer will pop the token at the top of the stack and return a new token combined with the token poped and the current character. - /// If not, return None. - fn look_behind( - &mut self, - tok: &kclvm_lexer::Token, - tok_stream_builder: &mut TokenStreamBuilder, - ) -> Option { - match tok.kind { - // Most multi-character tokens are lexed in ['kclvm-lexer'], - // and the multi-character tokens that need to be lexed in ['kclvm-parser/lexer'] are only token '->'. - // If a new multi-character token is added later, the corresponding operation can be added here. - kclvm_lexer::TokenKind::Gt => { - if tok_stream_builder - .pop_if_tok_kind(&TokenKind::BinOp(BinOpToken::Minus)) - .is_some() - { - // After the previous token pops up, 'self.tok_start_pos' needs to be updated. - if self.tok_start_pos >= new_byte_pos(1) { - self.tok_start_pos = self.tok_start_pos - new_byte_pos(1); - return Some(TokenKind::RArrow); - } else { - bug!("Internal Bugs: Please connect us to fix it, invalid token start pos") - } - } - } - _ => return None, - } - None - } - - fn lex_literal( - &self, - start: BytePos, - suffix_start: BytePos, - kind: kclvm_lexer::LiteralKind, - ) -> (token::LitKind, Symbol, Option, Option) { - match kind { - kclvm_lexer::LiteralKind::Str { - terminated, - triple_quoted, - } => { - let start_char = self.char_from(start); - let (is_raw, quote_char_pos, quote_char) = match start_char { - 'r' | 'R' => { - let pos = start + new_byte_pos(1); - (true, pos, self.char_from(pos)) - } - _ => (false, start, start_char), - }; - if !terminated { - self.sess.struct_span_error( - "unterminated string", - self.span(quote_char_pos, self.pos), - ); - } - // Cut offset before validation. - let offset: u32 = if triple_quoted { - if is_raw { - 4 - } else { - 3 - } - } else if is_raw { - 2 - } else { - 1 - }; - - let content_start = start + new_byte_pos(offset); - let mut content_end = suffix_start - new_byte_pos(offset); - if is_raw { - content_end = content_end + new_byte_pos(1); - } - // For unclosed quote string, cut offset of the string content. - if !terminated { - content_end = content_end + new_byte_pos(if triple_quoted { 3 } else { 1 }) - } - // If start > end, it is a invalid string content. - let value = if content_start > content_end { - // If get an error string from the eval process, - // directly return an empty string. - self.sess.struct_span_error( - "invalid string syntax", - self.span(content_start, self.pos), - ); - "".to_string() - } else { - let string_content = self.str_from_to(content_start, content_end); - match str_content_eval(string_content, quote_char, triple_quoted, false, is_raw) - { - Some(v) => v, - None => { - // If get an error string from the eval process, - // directly return an empty string. - self.sess.struct_span_error( - "invalid string syntax", - self.span(content_start, self.pos), - ); - "".to_string() - } - } - }; - - ( - token::Str { - is_long_string: triple_quoted, - is_raw, - }, - Symbol::intern(&value), - None, - Some(self.symbol_from_to(start, suffix_start)), - ) - } - kclvm_lexer::LiteralKind::Int { base, empty_int } => { - if empty_int { - self.sess.struct_span_error( - "no valid digits found for number", - self.span(start, self.pos), - ); - // If it is a empty int, returns number 0. - (token::Integer, Symbol::intern("0"), None, None) - } else { - let symbol = if self.validate_literal_int(base, start, suffix_start) { - self.symbol_from_to(start, suffix_start) - } else { - Symbol::intern("0") - }; - - let suffix = if suffix_start < self.pos { - let suffix_str = self.str_from(suffix_start); - // int binary suffix - if !NumberBinarySuffix::all_names().contains(&suffix_str) { - self.sess.struct_span_error( - "invalid int binary suffix", - self.span(start, self.pos), - ); - None - } else { - Some(Symbol::intern(suffix_str)) - } - } else { - None - }; - - (token::Integer, symbol, suffix, None) - } - } - - kclvm_lexer::LiteralKind::Float { - base, - empty_exponent, - } => { - let symbol = if self.validate_literal_float(base, start, empty_exponent) { - self.symbol_from_to(start, suffix_start) - } else { - Symbol::intern("0") - }; - (token::Float, symbol, None, None) - } - kclvm_lexer::LiteralKind::Bool { terminated: _ } => ( - token::Bool, - self.symbol_from_to(start, suffix_start), - None, - None, - ), - } - } - - fn validate_literal_int( - &self, - base: Base, - content_start: BytePos, - content_end: BytePos, - ) -> bool { - let base = match base { - Base::Binary => 2, - Base::Octal => 8, - Base::Hexadecimal => 16, - Base::Decimal => return true, - }; - let s = self.str_from_to(content_start + new_byte_pos(2), content_end); - for (idx, c) in s.char_indices() { - let idx = idx as u32; - if c != '_' && c.to_digit(base).is_none() { - let lo = content_start + new_byte_pos(2 + idx); - let hi = content_start + new_byte_pos(2 + idx + c.len_utf8() as u32); - - self.sess.struct_span_error( - &format!("invalid digit for a base {base} literal, start: {lo}, stop: {hi}"), - self.span(lo, self.pos), - ); - return false; - } - } - true - } - - fn validate_literal_float(&self, base: Base, start: BytePos, empty_exponent: bool) -> bool { - if empty_exponent { - self.sess.struct_span_error( - "expected at least one digit in exponent", - self.span(start, self.pos), - ); - false - } else { - match base { - kclvm_lexer::Base::Hexadecimal - | kclvm_lexer::Base::Octal - | kclvm_lexer::Base::Binary => { - self.sess.struct_span_error( - &format!("{} float literal is not supported", base.describe()), - self.span(start, self.pos), - ); - false - } - _ => true, - } - } - } - - fn span(&self, lo: BytePos, hi: BytePos) -> Span { - Span::new(lo, hi) - } - - #[inline] - fn src_index(&self, pos: BytePos) -> usize { - (pos - self.start_pos).0 as usize - } - - /// Char at `pos` in the source - fn char_from(&self, pos: BytePos) -> char { - self.src.as_bytes()[self.src_index(pos)] as char - } - - /// Slice of the source text from `start` up to but excluding `self.pos`, - /// meaning the slice does not include the character `self.ch`. - fn str_from(&self, start: BytePos) -> &str { - self.str_from_to(start, self.pos) - } - - /// Slice of the source text spanning from `start` up to but excluding `end`. - fn str_from_to(&self, start: BytePos, end: BytePos) -> &str { - &self.src[self.src_index(start)..self.src_index(end)] - } - - fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol { - Symbol::intern(self.str_from_to(start, end)) - } - - fn eof(&mut self, buf: &mut TokenStreamBuilder) { - if !self.indent_cxt.new_line_beginning { - self.indent_cxt.new_line_beginning = true; - buf.push(Token::new(token::Newline, self.span(self.pos, self.pos))); - } - - while self.indent_cxt.indents.len() > 1 { - self.indent_cxt.indents.pop(); - buf.push(Token::new( - token::Dedent(VALID_SPACES_LENGTH), - self.span(self.pos, self.pos), - )); - } - - buf.push(Token::new(token::Eof, self.span(self.pos, self.pos))); - } -} - -#[derive(Default)] -struct TokenStreamBuilder { - buf: Vec, -} - -impl TokenStreamBuilder { - fn push(&mut self, token: Token) { - self.buf.push(token) - } - - fn into_token_stream(self) -> TokenStream { - TokenStream::new(self.buf) - } - - /// Pop the token at the top of the stack, and return None if the stack is empty. - fn pop(&mut self) -> Option { - self.buf.pop() - } - - /// If the token kind at the top of the stack is 'expected_tok_kind', - /// pop the token and return it, otherwise do nothing and return None. - fn pop_if_tok_kind(&mut self, expected_tok_kind: &TokenKind) -> Option { - if self.peek_tok_kind() == expected_tok_kind { - self.pop() - } else { - None - } - } - - /// Peek the kind of the token on the top of the stack. - fn peek_tok_kind(&self) -> &TokenKind { - match self.buf.last() { - Some(tok) => &tok.kind, - None => &TokenKind::Dummy, - } - } -} diff --git a/kclvm/parser/src/lexer/tests.rs b/kclvm/parser/src/lexer/tests.rs deleted file mode 100644 index bda1cc021..000000000 --- a/kclvm/parser/src/lexer/tests.rs +++ /dev/null @@ -1,851 +0,0 @@ -use super::*; -use crate::lexer::str_content_eval; -use crate::session::ParseSession; -use compiler_base_error::diagnostic_handler::DiagnosticHandler; -use compiler_base_session::Session; -use compiler_base_span::{span::new_byte_pos, FilePathMapping, SourceMap}; -use expect_test::{expect, Expect}; -use kclvm_error::Handler; -use kclvm_span::create_session_globals_then; -use parking_lot::RwLock; -use std::path::PathBuf; -use std::sync::Arc; - -impl ParseSession { - #[inline] - pub(crate) fn with_source_map(sm: Arc) -> Self { - Self( - Arc::new(Session::new(sm, Arc::new(DiagnosticHandler::default()))), - RwLock::new(Handler::default()), - ) - } -} - -/// lexing the 'src'. -fn lex(src: &str) -> (String, String) { - let sm = SourceMap::new(FilePathMapping::empty()); - sm.new_source_file(PathBuf::from("").into(), src.to_string()); - let sess = &ParseSession::with_source_map(Arc::new(sm)); - - // preprocess the input str by [`SourceFile`] - let sf = sess - .0 - .sm - .new_source_file(PathBuf::from("").into(), src.to_string()); - - let src_from_sf = match sf.src.as_ref() { - Some(src) => src, - None => { - panic!("Unreachable code") - } - }; - - let res = create_session_globals_then(|| { - parse_token_streams(sess, src_from_sf, new_byte_pos(0)) - .iter() - .map(|token| format!("{:?}\n", token)) - .collect() - }); - - let err_msgs = sess - .0 - .emit_all_diags_into_string() - .unwrap() - .iter() - .map(|err| err.as_ref().unwrap().to_string()) - .collect(); - - (res, err_msgs) -} - -/// check the invalid panic message. -fn check_lexing_with_err_msg(src: &str, expect: Expect, expect_err_msg: Expect) { - let (got, got_err) = lex(src); - expect.assert_eq(&got); - expect_err_msg.assert_eq(&got_err); -} - -fn check_lexing(src: &str, expect: Expect) { - expect.assert_eq(&lex(src).0); -} - -// Get the code snippets from 'src' by token.span, and compare with expect. -fn check_span(src: &str, expect: Expect) { - let sm = SourceMap::new(FilePathMapping::empty()); - sm.new_source_file(PathBuf::from("").into(), src.to_string()); - let sess = &ParseSession::with_source_map(Arc::new(SourceMap::new(FilePathMapping::empty()))); - - create_session_globals_then(move || { - let actual: String = parse_token_streams(sess, src, new_byte_pos(0)) - .iter() - .map(|token| format!("{:?}\n", sm.span_to_snippet(token.span).unwrap())) - .collect(); - expect.assert_eq(&actual) - }); -} - -#[test] -fn test_str_content_eval() { - let cases = [ - // true cases - (("1", '\'', false, false, false), Some("1".to_string())), - (("1", '"', false, false, false), Some("1".to_string())), - ( - ("1\\n2", '"', false, false, false), - Some("1\n2".to_string()), - ), - ( - ("1\\n2", '"', false, false, true), - Some("1\\n2".to_string()), - ), - (("1\\2", '"', false, false, true), Some("1\\2".to_string())), - (("1", '\'', true, false, false), Some("1".to_string())), - (("1", '"', true, false, false), Some("1".to_string())), - (("1\n2", '"', true, false, false), Some("1\n2".to_string())), - ]; - for ((input, quote_char, triple_quoted, is_bytes, is_raw), expected) in cases { - assert_eq!( - str_content_eval(input, quote_char, triple_quoted, is_bytes, is_raw), - expected, - "test failed, input: {input}" - ) - } -} - -#[test] -fn smoke_test() { - check_lexing( - "lambda { println(\"kclvm\") }\n", - expect![[r#" - Token { kind: Ident(Symbol(SymbolIndex { idx: 18 })), span: Span { base_or_index: 0, len_or_tag: 6 } } - Token { kind: OpenDelim(Brace), span: Span { base_or_index: 7, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 9, len_or_tag: 7 } } - Token { kind: OpenDelim(Paren), span: Span { base_or_index: 16, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 43 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 44 })) }), span: Span { base_or_index: 17, len_or_tag: 7 } } - Token { kind: CloseDelim(Paren), span: Span { base_or_index: 24, len_or_tag: 1 } } - Token { kind: CloseDelim(Brace), span: Span { base_or_index: 26, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 27, len_or_tag: 1 } } - Token { kind: Eof, span: Span { base_or_index: 28, len_or_tag: 0 } } - "#]], - ) -} - -#[test] -fn comment_flavors() { - check_lexing( - r" -# line -", - expect![[r#" - Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: DocComment(Line(Symbol(SymbolIndex { idx: 42 }))), span: Span { base_or_index: 1, len_or_tag: 6 } } - Token { kind: Newline, span: Span { base_or_index: 7, len_or_tag: 1 } } - Token { kind: Eof, span: Span { base_or_index: 8, len_or_tag: 0 } } -"#]], - ) -} - -#[test] -fn simple_tokens() { - check_lexing( - r####" -, -. -( -) -{ -} -[ -] -@ -# -~ -? -: -$ -= -! -< -> -== -!= ->= -<= -- -& -| -+ -* -/ -^ -% -** -// -<< ->> -... -+= --= -*= -/= -%= -&= -|= -^= -**= -//= -<<= ->>= --> -"####, - expect![[r#" - Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: Comma, span: Span { base_or_index: 1, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 2, len_or_tag: 1 } } - Token { kind: Dot, span: Span { base_or_index: 3, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 4, len_or_tag: 1 } } - Token { kind: OpenDelim(Paren), span: Span { base_or_index: 5, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 6, len_or_tag: 1 } } - Token { kind: CloseDelim(Paren), span: Span { base_or_index: 7, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 8, len_or_tag: 1 } } - Token { kind: OpenDelim(Brace), span: Span { base_or_index: 9, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 10, len_or_tag: 1 } } - Token { kind: CloseDelim(Brace), span: Span { base_or_index: 11, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 12, len_or_tag: 1 } } - Token { kind: OpenDelim(Bracket), span: Span { base_or_index: 13, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 14, len_or_tag: 1 } } - Token { kind: CloseDelim(Bracket), span: Span { base_or_index: 15, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 16, len_or_tag: 1 } } - Token { kind: At, span: Span { base_or_index: 17, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 18, len_or_tag: 1 } } - Token { kind: DocComment(Line(Symbol(SymbolIndex { idx: 42 }))), span: Span { base_or_index: 19, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 20, len_or_tag: 1 } } - Token { kind: UnaryOp(UTilde), span: Span { base_or_index: 21, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 22, len_or_tag: 1 } } - Token { kind: Question, span: Span { base_or_index: 23, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 24, len_or_tag: 1 } } - Token { kind: Colon, span: Span { base_or_index: 25, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 26, len_or_tag: 1 } } - Token { kind: Dollar, span: Span { base_or_index: 27, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 28, len_or_tag: 1 } } - Token { kind: Assign, span: Span { base_or_index: 29, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 30, len_or_tag: 1 } } - Token { kind: UnaryOp(UNot), span: Span { base_or_index: 31, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 32, len_or_tag: 1 } } - Token { kind: BinCmp(Lt), span: Span { base_or_index: 33, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 34, len_or_tag: 1 } } - Token { kind: BinCmp(Gt), span: Span { base_or_index: 35, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 36, len_or_tag: 1 } } - Token { kind: BinCmp(Eq), span: Span { base_or_index: 37, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 39, len_or_tag: 1 } } - Token { kind: BinCmp(NotEq), span: Span { base_or_index: 40, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 42, len_or_tag: 1 } } - Token { kind: BinCmp(GtEq), span: Span { base_or_index: 43, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 45, len_or_tag: 1 } } - Token { kind: BinCmp(LtEq), span: Span { base_or_index: 46, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 48, len_or_tag: 1 } } - Token { kind: BinOp(Minus), span: Span { base_or_index: 49, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 50, len_or_tag: 1 } } - Token { kind: BinOp(And), span: Span { base_or_index: 51, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 52, len_or_tag: 1 } } - Token { kind: BinOp(Or), span: Span { base_or_index: 53, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 54, len_or_tag: 1 } } - Token { kind: BinOp(Plus), span: Span { base_or_index: 55, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 56, len_or_tag: 1 } } - Token { kind: BinOp(Star), span: Span { base_or_index: 57, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 58, len_or_tag: 1 } } - Token { kind: BinOp(Slash), span: Span { base_or_index: 59, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 60, len_or_tag: 1 } } - Token { kind: BinOp(Caret), span: Span { base_or_index: 61, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 62, len_or_tag: 1 } } - Token { kind: BinOp(Percent), span: Span { base_or_index: 63, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 64, len_or_tag: 1 } } - Token { kind: BinOp(StarStar), span: Span { base_or_index: 65, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 67, len_or_tag: 1 } } - Token { kind: BinOp(SlashSlash), span: Span { base_or_index: 68, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 70, len_or_tag: 1 } } - Token { kind: BinOp(Shl), span: Span { base_or_index: 71, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 73, len_or_tag: 1 } } - Token { kind: BinOp(Shr), span: Span { base_or_index: 74, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 76, len_or_tag: 1 } } - Token { kind: DotDotDot, span: Span { base_or_index: 77, len_or_tag: 3 } } - Token { kind: Newline, span: Span { base_or_index: 80, len_or_tag: 1 } } - Token { kind: BinOpEq(Plus), span: Span { base_or_index: 81, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 83, len_or_tag: 1 } } - Token { kind: BinOpEq(Minus), span: Span { base_or_index: 84, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 86, len_or_tag: 1 } } - Token { kind: BinOpEq(Star), span: Span { base_or_index: 87, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 89, len_or_tag: 1 } } - Token { kind: BinOpEq(Slash), span: Span { base_or_index: 90, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 92, len_or_tag: 1 } } - Token { kind: BinOpEq(Percent), span: Span { base_or_index: 93, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 95, len_or_tag: 1 } } - Token { kind: BinOpEq(And), span: Span { base_or_index: 96, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 98, len_or_tag: 1 } } - Token { kind: BinOpEq(Or), span: Span { base_or_index: 99, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 101, len_or_tag: 1 } } - Token { kind: BinOpEq(Caret), span: Span { base_or_index: 102, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 104, len_or_tag: 1 } } - Token { kind: BinOpEq(StarStar), span: Span { base_or_index: 105, len_or_tag: 3 } } - Token { kind: Newline, span: Span { base_or_index: 108, len_or_tag: 1 } } - Token { kind: BinOpEq(SlashSlash), span: Span { base_or_index: 109, len_or_tag: 3 } } - Token { kind: Newline, span: Span { base_or_index: 112, len_or_tag: 1 } } - Token { kind: BinOpEq(Shl), span: Span { base_or_index: 113, len_or_tag: 3 } } - Token { kind: Newline, span: Span { base_or_index: 116, len_or_tag: 1 } } - Token { kind: BinOpEq(Shr), span: Span { base_or_index: 117, len_or_tag: 3 } } - Token { kind: Newline, span: Span { base_or_index: 120, len_or_tag: 1 } } - Token { kind: RArrow, span: Span { base_or_index: 121, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 123, len_or_tag: 1 } } - Token { kind: Eof, span: Span { base_or_index: 124, len_or_tag: 0 } } - "#]], - ) -} - -#[test] -fn nonstring_literal() { - check_lexing( - r####" -1234 -0b101 -0xABC -1.0 -1.0e10 -0777 -0077 -1Ki -"####, - expect![[r#" - Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: None }), span: Span { base_or_index: 1, len_or_tag: 4 } } - Token { kind: Newline, span: Span { base_or_index: 5, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 43 }), suffix: None, raw: None }), span: Span { base_or_index: 6, len_or_tag: 5 } } - Token { kind: Newline, span: Span { base_or_index: 11, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 44 }), suffix: None, raw: None }), span: Span { base_or_index: 12, len_or_tag: 5 } } - Token { kind: Newline, span: Span { base_or_index: 17, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Float, symbol: Symbol(SymbolIndex { idx: 45 }), suffix: None, raw: None }), span: Span { base_or_index: 18, len_or_tag: 3 } } - Token { kind: Newline, span: Span { base_or_index: 21, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Float, symbol: Symbol(SymbolIndex { idx: 46 }), suffix: None, raw: None }), span: Span { base_or_index: 22, len_or_tag: 6 } } - Token { kind: Newline, span: Span { base_or_index: 28, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 47 }), suffix: None, raw: None }), span: Span { base_or_index: 29, len_or_tag: 4 } } - Token { kind: Newline, span: Span { base_or_index: 33, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 48 }), suffix: None, raw: None }), span: Span { base_or_index: 34, len_or_tag: 4 } } - Token { kind: Newline, span: Span { base_or_index: 38, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 33 }), suffix: Some(Symbol(SymbolIndex { idx: 49 })), raw: None }), span: Span { base_or_index: 39, len_or_tag: 3 } } - Token { kind: Newline, span: Span { base_or_index: 42, len_or_tag: 1 } } - Token { kind: Eof, span: Span { base_or_index: 43, len_or_tag: 0 } } - "#]], - ) -} - -#[test] -fn string_literal() { - check_lexing( - r####" -'a' -"a" -'''a''' -"""a""" -r'a' -r"a" -r'''a''' -r"""a""" -R'a' -R"a" -R'''a''' -R"""a""" -"####, - expect![[r#" - Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 43 })) }), span: Span { base_or_index: 1, len_or_tag: 3 } } - Token { kind: Newline, span: Span { base_or_index: 4, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 44 })) }), span: Span { base_or_index: 5, len_or_tag: 3 } } - Token { kind: Newline, span: Span { base_or_index: 8, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: true, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 45 })) }), span: Span { base_or_index: 9, len_or_tag: 7 } } - Token { kind: Newline, span: Span { base_or_index: 16, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: true, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 46 })) }), span: Span { base_or_index: 17, len_or_tag: 7 } } - Token { kind: Newline, span: Span { base_or_index: 24, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 47 })) }), span: Span { base_or_index: 25, len_or_tag: 4 } } - Token { kind: Newline, span: Span { base_or_index: 29, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 48 })) }), span: Span { base_or_index: 30, len_or_tag: 4 } } - Token { kind: Newline, span: Span { base_or_index: 34, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: true, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 49 })) }), span: Span { base_or_index: 35, len_or_tag: 8 } } - Token { kind: Newline, span: Span { base_or_index: 43, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: true, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 50 })) }), span: Span { base_or_index: 44, len_or_tag: 8 } } - Token { kind: Newline, span: Span { base_or_index: 52, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 51 })) }), span: Span { base_or_index: 53, len_or_tag: 4 } } - Token { kind: Newline, span: Span { base_or_index: 57, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 52 })) }), span: Span { base_or_index: 58, len_or_tag: 4 } } - Token { kind: Newline, span: Span { base_or_index: 62, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: true, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 53 })) }), span: Span { base_or_index: 63, len_or_tag: 8 } } - Token { kind: Newline, span: Span { base_or_index: 71, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: true, is_raw: true }, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 54 })) }), span: Span { base_or_index: 72, len_or_tag: 8 } } - Token { kind: Newline, span: Span { base_or_index: 80, len_or_tag: 1 } } - Token { kind: Eof, span: Span { base_or_index: 81, len_or_tag: 0 } } - "#]], - ) -} - -#[test] -fn indents() { - check_lexing( - r####" -if test0: - if test1: - println("true true") - else: - println("true false") -println("end") -"####, - expect![[r#" - Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 10 })), span: Span { base_or_index: 1, len_or_tag: 2 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 4, len_or_tag: 5 } } - Token { kind: Colon, span: Span { base_or_index: 9, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 10, len_or_tag: 1 } } - Token { kind: Indent(0), span: Span { base_or_index: 15, len_or_tag: 0 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 10 })), span: Span { base_or_index: 15, len_or_tag: 2 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 18, len_or_tag: 5 } } - Token { kind: Colon, span: Span { base_or_index: 23, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 24, len_or_tag: 1 } } - Token { kind: Indent(0), span: Span { base_or_index: 33, len_or_tag: 0 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 44 })), span: Span { base_or_index: 33, len_or_tag: 7 } } - Token { kind: OpenDelim(Paren), span: Span { base_or_index: 40, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 45 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 46 })) }), span: Span { base_or_index: 41, len_or_tag: 11 } } - Token { kind: CloseDelim(Paren), span: Span { base_or_index: 52, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 53, len_or_tag: 1 } } - Token { kind: Dedent(0), span: Span { base_or_index: 58, len_or_tag: 0 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 12 })), span: Span { base_or_index: 58, len_or_tag: 4 } } - Token { kind: Colon, span: Span { base_or_index: 62, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 63, len_or_tag: 1 } } - Token { kind: Indent(0), span: Span { base_or_index: 72, len_or_tag: 0 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 44 })), span: Span { base_or_index: 72, len_or_tag: 7 } } - Token { kind: OpenDelim(Paren), span: Span { base_or_index: 79, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 47 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 48 })) }), span: Span { base_or_index: 80, len_or_tag: 12 } } - Token { kind: CloseDelim(Paren), span: Span { base_or_index: 92, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 93, len_or_tag: 1 } } - Token { kind: Dedent(0), span: Span { base_or_index: 94, len_or_tag: 0 } } - Token { kind: Dedent(0), span: Span { base_or_index: 94, len_or_tag: 0 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 44 })), span: Span { base_or_index: 94, len_or_tag: 7 } } - Token { kind: OpenDelim(Paren), span: Span { base_or_index: 101, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 49 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 50 })) }), span: Span { base_or_index: 102, len_or_tag: 5 } } - Token { kind: CloseDelim(Paren), span: Span { base_or_index: 107, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 108, len_or_tag: 1 } } - Token { kind: Eof, span: Span { base_or_index: 109, len_or_tag: 0 } } - "#]], - ) -} - -#[test] -fn binary_expr_0() { - check_lexing( - r####"1 + a or b"####, - expect![[r#" - Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 33 }), suffix: None, raw: None }), span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: BinOp(Plus), span: Span { base_or_index: 2, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 4, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 13 })), span: Span { base_or_index: 6, len_or_tag: 2 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 9, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 10, len_or_tag: 0 } } - Token { kind: Eof, span: Span { base_or_index: 10, len_or_tag: 0 } } - "#]], - ); -} - -#[test] -fn schema_expr_0() { - check_lexing( - r####" -Schema (1, 2) { - k=v -} -"####, - expect![[r#" - Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 1, len_or_tag: 6 } } - Token { kind: OpenDelim(Paren), span: Span { base_or_index: 8, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 33 }), suffix: None, raw: None }), span: Span { base_or_index: 9, len_or_tag: 1 } } - Token { kind: Comma, span: Span { base_or_index: 10, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 34 }), suffix: None, raw: None }), span: Span { base_or_index: 12, len_or_tag: 1 } } - Token { kind: CloseDelim(Paren), span: Span { base_or_index: 13, len_or_tag: 1 } } - Token { kind: OpenDelim(Brace), span: Span { base_or_index: 15, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 16, len_or_tag: 1 } } - Token { kind: Indent(0), span: Span { base_or_index: 21, len_or_tag: 0 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 21, len_or_tag: 1 } } - Token { kind: Assign, span: Span { base_or_index: 22, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 44 })), span: Span { base_or_index: 23, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 24, len_or_tag: 1 } } - Token { kind: Dedent(0), span: Span { base_or_index: 25, len_or_tag: 0 } } - Token { kind: CloseDelim(Brace), span: Span { base_or_index: 25, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 26, len_or_tag: 1 } } - Token { kind: Eof, span: Span { base_or_index: 27, len_or_tag: 0 } } - "#]], - ); -} - -#[test] -fn schema_expr_1() { - check_lexing( - r####"Schema (1, 2) { - k=v -}"####, - expect![[r#" - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 0, len_or_tag: 6 } } - Token { kind: OpenDelim(Paren), span: Span { base_or_index: 7, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 33 }), suffix: None, raw: None }), span: Span { base_or_index: 8, len_or_tag: 1 } } - Token { kind: Comma, span: Span { base_or_index: 9, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 34 }), suffix: None, raw: None }), span: Span { base_or_index: 11, len_or_tag: 1 } } - Token { kind: CloseDelim(Paren), span: Span { base_or_index: 12, len_or_tag: 1 } } - Token { kind: OpenDelim(Brace), span: Span { base_or_index: 14, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 15, len_or_tag: 1 } } - Token { kind: Indent(0), span: Span { base_or_index: 20, len_or_tag: 0 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 20, len_or_tag: 1 } } - Token { kind: Assign, span: Span { base_or_index: 21, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 44 })), span: Span { base_or_index: 22, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 23, len_or_tag: 1 } } - Token { kind: Dedent(0), span: Span { base_or_index: 24, len_or_tag: 0 } } - Token { kind: CloseDelim(Brace), span: Span { base_or_index: 24, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 25, len_or_tag: 0 } } - Token { kind: Eof, span: Span { base_or_index: 25, len_or_tag: 0 } } - "#]], - ); -} - -#[test] -fn test_peek() { - let src = "\na=1"; - let sm = SourceMap::new(FilePathMapping::empty()); - sm.new_source_file(PathBuf::from("").into(), src.to_string()); - let sess = ParseSession::with_source_map(Arc::new(sm)); - - create_session_globals_then(|| { - let stream = parse_token_streams(&sess, src, new_byte_pos(0)); - let mut cursor = stream.cursor(); - - let tok0 = cursor.next(); - assert_eq!( - format!("{tok0:?}"), - "Some(Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } })" - ); - - let peek = cursor.peek(); - assert_eq!( - format!("{peek:?}"), - "Some(Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 1, len_or_tag: 1 } })" - ); - }); -} - -#[test] -fn test_assign_stmt() { - check_lexing( - r####" -a=1 -"####, - expect![[r#" - Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 1, len_or_tag: 1 } } - Token { kind: Assign, span: Span { base_or_index: 2, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 33 }), suffix: None, raw: None }), span: Span { base_or_index: 3, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 4, len_or_tag: 1 } } - Token { kind: Eof, span: Span { base_or_index: 5, len_or_tag: 0 } } - "#]], - ) -} - -#[test] -fn test_token_span() { - let src = r#" -schema Person: - name: str = "kcl" - -x0 = Person {} - "#; - check_span( - src, - expect![ - r#""\n" -"schema" -"Person" -":" -"\n" -"" -"name" -":" -"str" -"=" -"\"kcl\"" -"\n" -"\n" -"" -"x0" -"=" -"Person" -"{" -"}" -"\n" -"" -"# - ], - ) -} - -#[test] -fn test_source_file() { - let src = "\r\n\r\n\r\r\n\n\n\r".to_string(); - let sm = kclvm_span::SourceMap::new(FilePathMapping::empty()); - let sf = sm.new_source_file(PathBuf::from("").into(), src); - match sf.src.as_ref() { - Some(src_from_sf) => { - assert_eq!(src_from_sf.as_str(), "\n\n\r\n\n\n\r"); - } - None => { - unreachable!(); - } - }; -} - -#[test] -fn test_parse_token_stream() { - check_lexing( - "\n\r\n\r\n\r\r\n", - expect![[r#" - Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 1, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 2, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 4, len_or_tag: 1 } } - Token { kind: Eof, span: Span { base_or_index: 5, len_or_tag: 0 } } - "#]], - ); -} - -#[cfg(target_os = "windows")] -#[test] -fn test_parse_token_stream_on_win() { - use std::{fs, path::Path}; - let src = fs::read_to_string( - Path::new(".") - .join("testdata") - .join("hello_win.k") - .display() - .to_string(), - ) - .unwrap(); - assert_eq!( - src, - "\r\nschema Person:\r\n name: str = \"kcl\"\r\n\r\nx0 = Person {}\r\n" - ); - - check_lexing( - &src, - expect![[r#" - Token { kind: Newline, span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 4 })), span: Span { base_or_index: 1, len_or_tag: 6 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 8, len_or_tag: 6 } } - Token { kind: Colon, span: Span { base_or_index: 14, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 15, len_or_tag: 1 } } - Token { kind: Indent(0), span: Span { base_or_index: 20, len_or_tag: 0 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 20, len_or_tag: 4 } } - Token { kind: Colon, span: Span { base_or_index: 24, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 31 })), span: Span { base_or_index: 26, len_or_tag: 3 } } - Token { kind: Assign, span: Span { base_or_index: 30, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Str { is_long_string: false, is_raw: false }, symbol: Symbol(SymbolIndex { idx: 44 }), suffix: None, raw: Some(Symbol(SymbolIndex { idx: 45 })) }), span: Span { base_or_index: 32, len_or_tag: 5 } } - Token { kind: Newline, span: Span { base_or_index: 37, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 38, len_or_tag: 1 } } - Token { kind: Dedent(0), span: Span { base_or_index: 39, len_or_tag: 0 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 46 })), span: Span { base_or_index: 39, len_or_tag: 2 } } - Token { kind: Assign, span: Span { base_or_index: 42, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 44, len_or_tag: 6 } } - Token { kind: OpenDelim(Brace), span: Span { base_or_index: 51, len_or_tag: 1 } } - Token { kind: CloseDelim(Brace), span: Span { base_or_index: 52, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 53, len_or_tag: 1 } } - Token { kind: Eof, span: Span { base_or_index: 54, len_or_tag: 0 } } - "#]], - ); -} - -#[test] -fn test_rarrow() { - check_lexing( - "lambda x: int, y: int -> int { x + y }\n", - expect![[r#" - Token { kind: Ident(Symbol(SymbolIndex { idx: 18 })), span: Span { base_or_index: 0, len_or_tag: 6 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 7, len_or_tag: 1 } } - Token { kind: Colon, span: Span { base_or_index: 8, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 10, len_or_tag: 3 } } - Token { kind: Comma, span: Span { base_or_index: 13, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 15, len_or_tag: 1 } } - Token { kind: Colon, span: Span { base_or_index: 16, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 18, len_or_tag: 3 } } - Token { kind: RArrow, span: Span { base_or_index: 22, len_or_tag: 2 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 25, len_or_tag: 3 } } - Token { kind: OpenDelim(Brace), span: Span { base_or_index: 29, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 31, len_or_tag: 1 } } - Token { kind: BinOp(Plus), span: Span { base_or_index: 33, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 35, len_or_tag: 1 } } - Token { kind: CloseDelim(Brace), span: Span { base_or_index: 37, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 38, len_or_tag: 1 } } - Token { kind: Eof, span: Span { base_or_index: 39, len_or_tag: 0 } } - "#]], - ); -} - -#[test] -fn test_minus_unicode_gt_invalid() { - check_lexing_with_err_msg( - "lambda x: int, y: int -\u{feff}> int { x + y }\n", - expect![[r#" - Token { kind: Ident(Symbol(SymbolIndex { idx: 18 })), span: Span { base_or_index: 0, len_or_tag: 6 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 7, len_or_tag: 1 } } - Token { kind: Colon, span: Span { base_or_index: 8, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 10, len_or_tag: 3 } } - Token { kind: Comma, span: Span { base_or_index: 13, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 15, len_or_tag: 1 } } - Token { kind: Colon, span: Span { base_or_index: 16, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 18, len_or_tag: 3 } } - Token { kind: RArrow, span: Span { base_or_index: 25, len_or_tag: 2 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 28, len_or_tag: 3 } } - Token { kind: OpenDelim(Brace), span: Span { base_or_index: 32, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 34, len_or_tag: 1 } } - Token { kind: BinOp(Plus), span: Span { base_or_index: 36, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 38, len_or_tag: 1 } } - Token { kind: CloseDelim(Brace), span: Span { base_or_index: 40, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 41, len_or_tag: 1 } } - Token { kind: Eof, span: Span { base_or_index: 42, len_or_tag: 0 } } - "#]], - expect![["error[E1001]: InvalidSyntax\nunknown start of token\n\n"]], - ); -} - -#[test] -fn test_unicode_minus_gt_invalid() { - check_lexing_with_err_msg( - "lambda x: int, y: int \u{feff}-> int { x + y }\n", - expect![[r#" - Token { kind: Ident(Symbol(SymbolIndex { idx: 18 })), span: Span { base_or_index: 0, len_or_tag: 6 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 7, len_or_tag: 1 } } - Token { kind: Colon, span: Span { base_or_index: 8, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 10, len_or_tag: 3 } } - Token { kind: Comma, span: Span { base_or_index: 13, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 15, len_or_tag: 1 } } - Token { kind: Colon, span: Span { base_or_index: 16, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 18, len_or_tag: 3 } } - Token { kind: RArrow, span: Span { base_or_index: 25, len_or_tag: 2 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 28, len_or_tag: 3 } } - Token { kind: OpenDelim(Brace), span: Span { base_or_index: 32, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 34, len_or_tag: 1 } } - Token { kind: BinOp(Plus), span: Span { base_or_index: 36, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 38, len_or_tag: 1 } } - Token { kind: CloseDelim(Brace), span: Span { base_or_index: 40, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 41, len_or_tag: 1 } } - Token { kind: Eof, span: Span { base_or_index: 42, len_or_tag: 0 } } - "#]], - expect![["error[E1001]: InvalidSyntax\nunknown start of token\n\n"]], - ); -} - -#[test] -fn test_minus_gt_unicode_invalid() { - check_lexing_with_err_msg( - "lambda x: int, y: int ->\u{feff} int { x + y }\n", - expect![[r#" - Token { kind: Ident(Symbol(SymbolIndex { idx: 18 })), span: Span { base_or_index: 0, len_or_tag: 6 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 7, len_or_tag: 1 } } - Token { kind: Colon, span: Span { base_or_index: 8, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 10, len_or_tag: 3 } } - Token { kind: Comma, span: Span { base_or_index: 13, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 15, len_or_tag: 1 } } - Token { kind: Colon, span: Span { base_or_index: 16, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 18, len_or_tag: 3 } } - Token { kind: RArrow, span: Span { base_or_index: 22, len_or_tag: 2 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 30 })), span: Span { base_or_index: 28, len_or_tag: 3 } } - Token { kind: OpenDelim(Brace), span: Span { base_or_index: 32, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 34, len_or_tag: 1 } } - Token { kind: BinOp(Plus), span: Span { base_or_index: 36, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 43 })), span: Span { base_or_index: 38, len_or_tag: 1 } } - Token { kind: CloseDelim(Brace), span: Span { base_or_index: 40, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 41, len_or_tag: 1 } } - Token { kind: Eof, span: Span { base_or_index: 42, len_or_tag: 0 } } - "#]], - expect![["error[E1001]: InvalidSyntax\nunknown start of token\n\n"]], - ); -} - -#[test] -fn test_only_minus() { - check_lexing( - "-", - expect![[r#" - Token { kind: BinOp(Minus), span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 1, len_or_tag: 0 } } - Token { kind: Eof, span: Span { base_or_index: 1, len_or_tag: 0 } } - "#]], - ); -} - -#[test] -fn test_begin_with_minus() { - check_lexing( - "-123", - expect![[r#" - Token { kind: BinOp(Minus), span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: Literal(Lit { kind: Integer, symbol: Symbol(SymbolIndex { idx: 42 }), suffix: None, raw: None }), span: Span { base_or_index: 1, len_or_tag: 3 } } - Token { kind: Newline, span: Span { base_or_index: 4, len_or_tag: 0 } } - Token { kind: Eof, span: Span { base_or_index: 4, len_or_tag: 0 } } - "#]], - ); -} - -#[test] -fn test_only_gt() { - check_lexing( - ">", - expect![[r#" - Token { kind: BinCmp(Gt), span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: Newline, span: Span { base_or_index: 1, len_or_tag: 0 } } - Token { kind: Eof, span: Span { base_or_index: 1, len_or_tag: 0 } } - "#]], - ); -} - -#[test] -fn test_begin_with_gt() { - check_lexing( - ">sdjkd + ==", - expect![[r#" - Token { kind: BinCmp(Gt), span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: Ident(Symbol(SymbolIndex { idx: 42 })), span: Span { base_or_index: 1, len_or_tag: 5 } } - Token { kind: BinOp(Plus), span: Span { base_or_index: 7, len_or_tag: 1 } } - Token { kind: BinCmp(Eq), span: Span { base_or_index: 9, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 11, len_or_tag: 0 } } - Token { kind: Eof, span: Span { base_or_index: 11, len_or_tag: 0 } } - "#]], - ); -} - -#[test] -fn test_double_rarrow() { - check_lexing( - "->->", - expect![[r#" - Token { kind: RArrow, span: Span { base_or_index: 0, len_or_tag: 2 } } - Token { kind: RArrow, span: Span { base_or_index: 2, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 4, len_or_tag: 0 } } - Token { kind: Eof, span: Span { base_or_index: 4, len_or_tag: 0 } } - "#]], - ); -} - -#[test] -fn test_mess_rarrow() { - check_lexing( - "-->>->", - expect![[r#" - Token { kind: BinOp(Minus), span: Span { base_or_index: 0, len_or_tag: 1 } } - Token { kind: BinOp(Minus), span: Span { base_or_index: 1, len_or_tag: 1 } } - Token { kind: BinOp(Shr), span: Span { base_or_index: 2, len_or_tag: 2 } } - Token { kind: RArrow, span: Span { base_or_index: 4, len_or_tag: 2 } } - Token { kind: Newline, span: Span { base_or_index: 6, len_or_tag: 0 } } - Token { kind: Eof, span: Span { base_or_index: 6, len_or_tag: 0 } } - "#]], - ); -} diff --git a/kclvm/parser/src/lib.rs b/kclvm/parser/src/lib.rs deleted file mode 100644 index 4d33d9b52..000000000 --- a/kclvm/parser/src/lib.rs +++ /dev/null @@ -1,1312 +0,0 @@ -//! Copyright The KCL Authors. All rights reserved. - -pub mod entry; -pub mod file_graph; -mod lexer; -mod parser; -mod session; - -#[cfg(test)] -mod tests; - -extern crate kclvm_error; - -use crate::entry::get_compile_entries_from_paths; -pub use crate::session::{ParseSession, ParseSessionRef}; -use compiler_base_macros::bug; -use compiler_base_session::Session; -use compiler_base_span::span::new_byte_pos; -use file_graph::{toposort, Pkg, PkgFile, PkgFileGraph, PkgMap}; -use kclvm_ast::ast::Module; -use kclvm_ast::{ast, MAIN_PKG}; -use kclvm_config::modfile::{get_vendor_home, KCL_FILE_EXTENSION, KCL_FILE_SUFFIX, KCL_MOD_FILE}; -use kclvm_error::diagnostic::{Errors, Range}; -use kclvm_error::{ErrorKind, Message, Position, Style}; -use kclvm_primitives::IndexMap; -use kclvm_sema::plugin::PLUGIN_MODULE_PREFIX; -use kclvm_utils::path::PathPrefix; -use kclvm_utils::pkgpath::parse_external_pkg_name; -use kclvm_utils::pkgpath::rm_external_pkg_name; - -use anyhow::Result; -use lexer::parse_token_streams; -use parser::Parser; -use std::collections::{HashMap, HashSet, VecDeque}; -use std::path::{Path, PathBuf}; -use std::sync::{Arc, RwLock}; - -use kclvm_span::create_session_globals_then; - -#[derive(Default, Debug)] -/// [`PkgInfo`] is some basic information about a kcl package. -pub(crate) struct PkgInfo { - /// the name of the kcl package. - pkg_name: String, - /// path to save the package locally. e.g. /usr/xxx - pkg_root: String, - /// package path. e.g. konfig.base.xxx - pkg_path: String, - /// The kcl files that need to be compiled in this package. - k_files: Vec, -} - -impl PkgInfo { - /// New a [`PkgInfo`]. - pub(crate) fn new( - pkg_name: String, - pkg_root: String, - pkg_path: String, - k_files: Vec, - ) -> Self { - PkgInfo { - pkg_name, - pkg_root, - pkg_path, - k_files, - } - } -} - -/// parser mode -#[derive(Debug, Clone)] -pub enum ParseMode { - Null, - ParseComments, -} - -/// LoadProgramResult denotes the result of the whole program and a topological -/// ordering of all known files, -#[derive(Debug, Clone)] -pub struct LoadProgramResult { - /// Program AST - pub program: ast::Program, - /// Parse errors - pub errors: Errors, - /// The topological ordering of all known files. - pub paths: Vec, -} - -/// ParseFileResult denotes the result of a single file including AST, -/// errors and import dependencies. -#[derive(Debug, Clone)] -pub struct ParseFileResult { - /// Module AST - pub module: ast::Module, - /// Parse errors - pub errors: Errors, - /// Dependency paths. - pub deps: Vec, -} - -/// Parse a KCL file to the AST module with parse errors. -pub fn parse_single_file(filename: &str, code: Option) -> Result { - let filename = filename.adjust_canonicalization(); - let sess = Arc::new(ParseSession::default()); - let mut loader = Loader::new( - sess, - &[&filename], - Some(LoadProgramOptions { - load_packages: false, - k_code_list: if let Some(code) = code { - vec![code] - } else { - vec![] - }, - ..Default::default() - }), - None, - ); - let result = loader.load_main()?; - let module = match result.program.get_main_package_first_module() { - Some(module) => module.clone(), - None => ast::Module::default(), - }; - let file_graph = match loader.file_graph.read() { - Ok(file_graph) => file_graph, - Err(e) => { - return Err(anyhow::anyhow!( - "Failed to read KCL file graph. Because '{e}'" - )) - } - }; - let file = PkgFile::new(PathBuf::from(filename), MAIN_PKG.to_string()); - let deps = if file_graph.contains_file(&file) { - file_graph.dependencies_of(&file).into_iter().collect() - } else { - vec![] - }; - Ok(ParseFileResult { - module, - errors: result.errors.clone(), - deps, - }) -} - -/// Parse a KCL file to the AST module and return errors when meets parse errors as result. -pub fn parse_file_force_errors(filename: &str, code: Option) -> Result { - let sess = Arc::new(ParseSession::default()); - let result = parse_file_with_global_session(sess.clone(), filename, code); - if sess.0.diag_handler.has_errors()? { - let err = sess - .0 - .emit_nth_diag_into_string(0)? - .unwrap_or(Ok(ErrorKind::InvalidSyntax.name()))?; - Err(anyhow::anyhow!(err)) - } else { - result - } -} - -/// Parse a KCL file to the AST module with the parse session . -pub fn parse_file_with_session( - sess: ParseSessionRef, - filename: &str, - code: Option, -) -> Result { - // Code source. - let src = if let Some(s) = code { - s - } else { - match std::fs::read_to_string(filename) { - Ok(src) => src, - Err(err) => { - return Err(anyhow::anyhow!( - "Failed to load KCL file '{filename}'. Because '{err}'" - )); - } - } - }; - - // Build a source map to store file sources. - let sf = sess - .0 - .sm - .new_source_file(PathBuf::from(filename).into(), src); - - let src_from_sf = match sf.src.as_ref() { - Some(src) => src, - None => { - return Err(anyhow::anyhow!( - "Internal Bug: Failed to load KCL file '{filename}'." - )); - } - }; - - // Lexer - let stream = lexer::parse_token_streams(&sess, src_from_sf.as_str(), sf.start_pos); - // Parser - let mut p = parser::Parser::new(&sess, stream); - let mut m = p.parse_module(); - m.filename = filename.to_string().adjust_canonicalization(); - - Ok(m) -} - -/// Parse a KCL file to the AST module with the parse session and the global session -#[inline] -pub fn parse_file_with_global_session( - sess: ParseSessionRef, - filename: &str, - code: Option, -) -> Result { - create_session_globals_then(move || parse_file_with_session(sess, filename, code)) -} - -/// Parse a source string to a expression. When input empty string, it will return [None]. -/// -/// # Examples -/// ``` -/// use kclvm_ast::ast; -/// use kclvm_parser::parse_expr; -/// -/// let expr = parse_expr("'alice'").unwrap(); -/// assert!(matches!(expr.node, ast::Expr::StringLit(_))); -/// let expr = parse_expr(""); -/// assert!(matches!(expr, None)); -/// ``` -pub fn parse_expr(src: &str) -> Option> { - if src.is_empty() { - None - } else { - let sess = Arc::new(Session::default()); - let sf = sess - .sm - .new_source_file(PathBuf::from("").into(), src.to_string()); - let src_from_sf = match sf.src.as_ref() { - Some(src) => src, - None => { - bug!("Internal Bug: Failed to load KCL file."); - } - }; - - let sess = &&ParseSession::with_session(sess); - - let expr: Option> = Some(create_session_globals_then(|| { - let stream = parse_token_streams(sess, src_from_sf.as_str(), new_byte_pos(0)); - let mut parser = Parser::new(sess, stream); - parser.parse_expr() - })); - expr - } -} - -#[derive(Debug, Clone)] -pub struct LoadProgramOptions { - pub work_dir: String, - pub k_code_list: Vec, - pub vendor_dirs: Vec, - pub package_maps: HashMap, - /// The parser mode. - pub mode: ParseMode, - /// Whether to load packages. - pub load_packages: bool, - /// Whether to load plugins - pub load_plugins: bool, -} - -impl Default for LoadProgramOptions { - fn default() -> Self { - Self { - work_dir: Default::default(), - k_code_list: Default::default(), - vendor_dirs: vec![get_vendor_home()], - package_maps: Default::default(), - mode: ParseMode::ParseComments, - load_packages: true, - load_plugins: false, - } - } -} - -/// Load the KCL program by paths and options, -/// "module_cache" is used to cache parsed asts to support incremental parse, -/// if it is None, module caching will be disabled -/// -/// # Examples -/// -/// ``` -/// use kclvm_parser::{load_program, ParseSession}; -/// use kclvm_parser::KCLModuleCache; -/// use kclvm_ast::ast::Program; -/// use std::sync::Arc; -/// -/// // Create sessions -/// let sess = Arc::new(ParseSession::default()); -/// // Create module cache -/// let module_cache = KCLModuleCache::default(); -/// -/// // Parse kcl file -/// let kcl_path = "./testdata/import-01.k"; -/// let prog = load_program(sess.clone(), &[kcl_path], None, Some(module_cache.clone())).unwrap(); -/// -/// ``` -pub fn load_program( - sess: ParseSessionRef, - paths: &[&str], - opts: Option, - module_cache: Option, -) -> Result { - Loader::new(sess, paths, opts, module_cache).load_main() -} - -pub type KCLModuleCache = Arc>; - -#[derive(Default, Debug)] -pub struct ModuleCache { - /// File ast cache - pub ast_cache: IndexMap>>, - /// Which pkgs the file belongs to. Sometimes a file is not only contained in the pkg in the file system directory, but may also be in the main package. - pub file_pkg: IndexMap>, - /// File dependency cache - pub dep_cache: IndexMap, - /// File source code - pub source_code: IndexMap, - - pub last_compile_input: (Vec, Option), -} - -impl ModuleCache { - pub fn clear(&mut self, path: &PathBuf) { - self.ast_cache.swap_remove(path); - self.source_code.swap_remove(path); - if let Some(pkgs) = self.file_pkg.swap_remove(path) { - for pkg in &pkgs { - self.dep_cache.swap_remove(pkg); - } - } - } -} -struct Loader { - sess: ParseSessionRef, - paths: Vec, - opts: LoadProgramOptions, - module_cache: KCLModuleCache, - file_graph: FileGraphCache, - pkgmap: PkgMap, - parsed_file: HashSet, -} - -impl Loader { - fn new( - sess: ParseSessionRef, - paths: &[&str], - opts: Option, - module_cache: Option, - ) -> Self { - Self { - sess, - paths: paths - .iter() - .map(|s| kclvm_utils::path::convert_windows_drive_letter(s)) - .collect(), - opts: opts.unwrap_or_default(), - module_cache: module_cache.unwrap_or_default(), - file_graph: FileGraphCache::default(), - pkgmap: Default::default(), - parsed_file: HashSet::new(), - } - } - - #[inline] - fn load_main(&mut self) -> Result { - create_session_globals_then(move || self._load_main()) - } - - fn _load_main(&mut self) -> Result { - parse_program( - self.sess.clone(), - self.paths.clone(), - self.module_cache.clone(), - self.file_graph.clone(), - &mut self.pkgmap, - &mut self.parsed_file, - &self.opts, - ) - } -} - -fn fix_rel_import_path_with_file( - pkgroot: &str, - m: &mut ast::Module, - file: &PkgFile, - pkgmap: &PkgMap, - opts: &LoadProgramOptions, - sess: ParseSessionRef, -) { - for stmt in &mut m.body { - let pos = stmt.pos().clone(); - if let ast::Stmt::Import(ref mut import_spec) = &mut stmt.node { - let fix_path = kclvm_config::vfs::fix_import_path( - pkgroot, - &m.filename, - import_spec.path.node.as_str(), - ); - import_spec.path.node = fix_path.clone(); - - let pkg = pkgmap.get(file).expect("file not in pkgmap"); - import_spec.pkg_name = pkg.pkg_name.clone(); - // Load the import package source code and compile. - let pkg_info = find_packages( - pos.into(), - &pkg.pkg_name, - &pkg.pkg_root, - &fix_path, - opts, - sess.clone(), - ) - .unwrap_or(None); - if let Some(pkg_info) = &pkg_info { - // Add the external package name as prefix of the [`kclvm_ast::ImportStmt`]'s member [`path`]. - import_spec.path.node = pkg_info.pkg_path.to_string(); - import_spec.pkg_name = pkg_info.pkg_name.clone(); - } - } - } -} - -fn is_plugin_pkg(pkgpath: &str) -> bool { - pkgpath.starts_with(PLUGIN_MODULE_PREFIX) -} - -fn is_builtin_pkg(pkgpath: &str) -> bool { - let system_modules = kclvm_sema::builtin::system_module::STANDARD_SYSTEM_MODULES; - system_modules.contains(&pkgpath) -} - -fn find_packages( - pos: ast::Pos, - pkg_name: &str, - pkg_root: &str, - pkg_path: &str, - opts: &LoadProgramOptions, - sess: ParseSessionRef, -) -> Result> { - if pkg_path.is_empty() { - return Ok(None); - } - - // plugin pkgs - if is_plugin_pkg(pkg_path) { - if !opts.load_plugins { - sess.1.write().add_error( - ErrorKind::CannotFindModule, - &[Message { - range: Into::::into(pos), - style: Style::Line, - message: format!("the plugin package `{}` is not found, please confirm if plugin mode is enabled", pkg_path), - note: None, - suggested_replacement: None, - }], - ); - } - return Ok(None); - } - - // builtin pkgs - if is_builtin_pkg(pkg_path) { - return Ok(None); - } - - // 1. Look for in the current package's directory. - let is_internal = is_internal_pkg(pkg_name, pkg_root, pkg_path)?; - // 2. Look for in the vendor path. - let is_external = is_external_pkg(pkg_path, opts)?; - - // 3. Internal and external packages cannot be duplicated - if is_external.is_some() && is_internal.is_some() { - sess.1.write().add_error( - ErrorKind::CannotFindModule, - &[Message { - range: Into::::into(pos), - style: Style::Line, - message: format!( - "the `{}` is found multiple times in the current package and vendor package", - pkg_path - ), - note: None, - suggested_replacement: None, - }], - ); - return Ok(None); - } - - // 4. Get package information based on whether the package is internal or external. - - match is_internal.or(is_external) { - Some(pkg_info) => Ok(Some(pkg_info)), - None => { - sess.1.write().add_error( - ErrorKind::CannotFindModule, - &[Message { - range: Into::::into(pos), - style: Style::Line, - message: format!("pkgpath {} not found in the program", pkg_path), - note: None, - suggested_replacement: None, - }], - ); - let mut suggestions = vec![format!("browse more packages at 'https://artifacthub.io'")]; - - if let Ok(pkg_name) = parse_external_pkg_name(pkg_path) { - suggestions.insert( - 0, - format!( - "try 'kcl mod add {}' to download the missing package", - pkg_name - ), - ); - } - sess.1.write().add_suggestions(suggestions); - Ok(None) - } - } -} - -/// Search [`pkgpath`] among all the paths in [`pkgroots`]. -/// -/// # Notes -/// -/// All paths in [`pkgpath`] must contain the kcl.mod file. -/// It returns the parent directory of kcl.mod if present, or none if not. -fn pkg_exists(pkgroots: &[String], pkgpath: &str) -> Option { - pkgroots - .into_iter() - .find(|root| pkg_exists_in_path(root, pkgpath)) - .cloned() -} - -/// Search for [`pkgpath`] under [`path`]. -/// It only returns [`true`] if [`path`]/[`pkgpath`] or [`path`]/[`pkgpath.k`] exists. -fn pkg_exists_in_path(path: &str, pkgpath: &str) -> bool { - let mut pathbuf = PathBuf::from(path); - pkgpath.split('.').for_each(|s| pathbuf.push(s)); - pathbuf.exists() || pathbuf.with_extension(KCL_FILE_EXTENSION).exists() -} - -/// Look for [`pkgpath`] in the current package's [`pkgroot`]. -/// If found, return to the [`PkgInfo`], else return [`None`] -/// -/// # Error -/// -/// [`is_internal_pkg`] will return an error if the package's source files cannot be found. -fn is_internal_pkg(pkg_name: &str, pkg_root: &str, pkg_path: &str) -> Result> { - match pkg_exists(&[pkg_root.to_string()], pkg_path) { - Some(internal_pkg_root) => { - let fullpath = if pkg_name == kclvm_ast::MAIN_PKG { - pkg_path.to_string() - } else { - format!("{}.{}", pkg_name, pkg_path) - }; - let k_files = get_pkg_kfile_list(pkg_root, pkg_path)?; - Ok(Some(PkgInfo::new( - pkg_name.to_string(), - internal_pkg_root, - fullpath, - k_files, - ))) - } - None => Ok(None), - } -} - -fn get_pkg_kfile_list(pkgroot: &str, pkgpath: &str) -> Result> { - // plugin pkgs - if is_plugin_pkg(pkgpath) { - return Ok(Vec::new()); - } - - // builtin pkgs - if is_builtin_pkg(pkgpath) { - return Ok(Vec::new()); - } - - if pkgroot.is_empty() { - return Err(anyhow::anyhow!(format!("pkgroot not found: {:?}", pkgpath))); - } - - let mut pathbuf = std::path::PathBuf::new(); - pathbuf.push(pkgroot); - - for s in pkgpath.split('.') { - pathbuf.push(s); - } - - let abspath = match pathbuf.canonicalize() { - Ok(p) => p.to_str().unwrap().to_string(), - Err(_) => pathbuf.as_path().to_str().unwrap().to_string(), - }; - if std::path::Path::new(abspath.as_str()).exists() { - return get_dir_files(abspath.as_str()); - } - - let as_k_path = abspath + KCL_FILE_SUFFIX; - if std::path::Path::new((as_k_path).as_str()).exists() { - return Ok(vec![as_k_path]); - } - - Ok(Vec::new()) -} - -/// Get file list in the directory. -fn get_dir_files(dir: &str) -> Result> { - if !std::path::Path::new(dir).exists() { - return Ok(Vec::new()); - } - - let mut list = Vec::new(); - for path in std::fs::read_dir(dir)? { - let path = path?; - if !path - .file_name() - .to_str() - .unwrap() - .ends_with(KCL_FILE_SUFFIX) - { - continue; - } - if path.file_name().to_str().unwrap().ends_with("_test.k") { - continue; - } - if path.file_name().to_str().unwrap().starts_with('_') { - continue; - } - - let s = format!("{}", path.path().display()); - list.push(s); - } - - list.sort(); - Ok(list) -} - -/// Look for [`pkgpath`] in the external package's home. -/// If found, return to the [`PkgInfo`], else return [`None`] -/// -/// # Error -/// -/// - [`is_external_pkg`] will return an error if the package's source files cannot be found. -/// - The name of the external package could not be resolved from [`pkg_path`]. -fn is_external_pkg(pkg_path: &str, opts: &LoadProgramOptions) -> Result> { - let pkg_name = parse_external_pkg_name(pkg_path)?; - let external_pkg_root = if let Some(root) = opts.package_maps.get(&pkg_name) { - PathBuf::from(root).join(KCL_MOD_FILE) - } else { - match pkg_exists(&opts.vendor_dirs, pkg_path) { - Some(path) => PathBuf::from(path).join(&pkg_name).join(KCL_MOD_FILE), - None => return Ok(None), - } - }; - - if external_pkg_root.exists() { - return Ok(Some(match external_pkg_root.parent() { - Some(root) => { - let abs_root: String = match root.canonicalize() { - Ok(p) => p.to_str().unwrap().to_string(), - Err(_) => root.display().to_string(), - }; - let k_files = get_pkg_kfile_list(&abs_root, &rm_external_pkg_name(pkg_path)?)?; - PkgInfo::new( - pkg_name.to_string(), - abs_root, - pkg_path.to_string(), - k_files, - ) - } - None => return Ok(None), - })); - } else { - Ok(None) - } -} - -pub type ASTCache = Arc>>>; -pub type FileGraphCache = Arc>; - -pub fn parse_file( - sess: ParseSessionRef, - file: PkgFile, - src: Option, - module_cache: KCLModuleCache, - pkgs: &mut HashMap>, - pkgmap: &mut PkgMap, - file_graph: FileGraphCache, - opts: &LoadProgramOptions, -) -> Result> { - let src = match src { - Some(src) => Some(src), - None => match &module_cache.read() { - Ok(cache) => cache.source_code.get(file.get_path()), - Err(_) => None, - } - .cloned(), - }; - let m = parse_file_with_session(sess.clone(), file.get_path().to_str().unwrap(), src)?; - let deps = get_deps(&file, &m, pkgs, pkgmap, opts, sess)?; - let dep_files = deps.keys().map(|f| f.clone()).collect(); - pkgmap.extend(deps.clone()); - match &mut module_cache.write() { - Ok(module_cache) => { - module_cache - .ast_cache - .insert(file.get_path().clone(), Arc::new(RwLock::new(m))); - match module_cache.file_pkg.get_mut(&file.get_path().clone()) { - Some(s) => { - s.insert(file.clone()); - } - None => { - let mut s = HashSet::new(); - s.insert(file.clone()); - module_cache.file_pkg.insert(file.get_path().clone(), s); - } - } - module_cache.dep_cache.insert(file.clone(), deps); - } - Err(e) => return Err(anyhow::anyhow!("Parse file failed: {e}")), - } - - match &mut file_graph.write() { - Ok(file_graph) => { - file_graph.update_file(&file, &dep_files); - } - Err(e) => return Err(anyhow::anyhow!("Parse file failed: {e}")), - } - - Ok(dep_files) -} - -pub fn get_deps( - file: &PkgFile, - m: &Module, - pkgs: &mut HashMap>, - pkgmap: &PkgMap, - opts: &LoadProgramOptions, - sess: ParseSessionRef, -) -> Result { - let mut deps = PkgMap::default(); - for stmt in &m.body { - let pos = stmt.pos().clone(); - let pkg = pkgmap.get(file).expect("file not in pkgmap").clone(); - if let ast::Stmt::Import(import_spec) = &stmt.node { - let fix_path = kclvm_config::vfs::fix_import_path( - &pkg.pkg_root, - &m.filename, - import_spec.path.node.as_str(), - ); - let pkg_info = find_packages( - pos.into(), - &pkg.pkg_name, - &pkg.pkg_root, - &fix_path, - opts, - sess.clone(), - )?; - if let Some(pkg_info) = &pkg_info { - // If k_files is empty, the pkg information will not be found in the file graph. - // Record the empty pkg to prevent loss. After the parse file is completed, fill in the modules - if pkg_info.k_files.is_empty() { - pkgs.insert(pkg_info.pkg_path.clone(), vec![]); - } - - pkg_info.k_files.iter().for_each(|p| { - let file = PkgFile::new(p.into(), pkg_info.pkg_path.clone()); - deps.insert( - file.clone(), - file_graph::Pkg { - pkg_name: pkg_info.pkg_name.clone(), - pkg_root: pkg_info.pkg_root.clone().into(), - }, - ); - }); - } - } - } - Ok(deps) -} - -pub fn parse_pkg( - sess: ParseSessionRef, - files: Vec<(PkgFile, Option)>, - module_cache: KCLModuleCache, - pkgs: &mut HashMap>, - pkgmap: &mut PkgMap, - file_graph: FileGraphCache, - opts: &LoadProgramOptions, -) -> Result> { - let mut dependent = vec![]; - for (file, src) in files { - let deps = parse_file( - sess.clone(), - file.clone(), - src, - module_cache.clone(), - pkgs, - pkgmap, - file_graph.clone(), - opts, - )?; - dependent.extend(deps); - } - Ok(dependent) -} - -pub fn parse_entry( - sess: ParseSessionRef, - entry: &entry::Entry, - module_cache: KCLModuleCache, - pkgs: &mut HashMap>, - pkgmap: &mut PkgMap, - file_graph: FileGraphCache, - opts: &LoadProgramOptions, - parsed_file: &mut HashSet, -) -> Result> { - let k_files = entry.get_k_files(); - let maybe_k_codes = entry.get_k_codes(); - let mut files = vec![]; - let mut new_files = HashSet::new(); - for (i, f) in k_files.iter().enumerate() { - let file = PkgFile::new(f.adjust_canonicalization().into(), MAIN_PKG.to_string()); - files.push((file.clone(), maybe_k_codes.get(i).unwrap_or(&None).clone())); - new_files.insert(file.clone()); - pkgmap.insert( - file, - Pkg { - pkg_name: entry.name().clone(), - pkg_root: entry.path().into(), - }, - ); - } - let dependent_paths = parse_pkg( - sess.clone(), - files, - module_cache.clone(), - pkgs, - pkgmap, - file_graph.clone(), - opts, - )?; - let mut unparsed_file: VecDeque = dependent_paths.into(); - - // Bfs unparsed and import files - while let Some(file) = unparsed_file.pop_front() { - match &mut module_cache.write() { - Ok(m_cache) => match m_cache.file_pkg.get_mut(file.get_path()) { - Some(s) => { - // The module ast has been parsed, but does not belong to the same package - if s.insert(file.clone()) { - new_files.insert(file.clone()); - } - } - None => { - let mut s = HashSet::new(); - s.insert(file.clone()); - m_cache.file_pkg.insert(file.get_path().clone(), s); - new_files.insert(file.clone()); - } - }, - Err(e) => return Err(anyhow::anyhow!("Parse file failed: {e}")), - } - - let module_cache_read = module_cache.read(); - match &module_cache_read { - Ok(m_cache) => match m_cache.ast_cache.get(file.get_path()) { - Some(m) => { - let deps = m_cache.dep_cache.get(&file).cloned().unwrap_or_else(|| { - get_deps(&file, &m.read().unwrap(), pkgs, pkgmap, opts, sess.clone()) - .unwrap() - }); - let dep_files: Vec = deps.keys().map(|f| f.clone()).collect(); - pkgmap.extend(deps.clone()); - - match &mut file_graph.write() { - Ok(file_graph) => { - file_graph.update_file(&file, &dep_files); - - for dep in dep_files { - if parsed_file.insert(dep.clone()) { - unparsed_file.push_back(dep.clone()); - } - } - - continue; - } - Err(e) => return Err(anyhow::anyhow!("Parse entry failed: {e}")), - } - } - None => { - new_files.insert(file.clone()); - drop(module_cache_read); - let deps = parse_file( - sess.clone(), - file, - None, - module_cache.clone(), - pkgs, - pkgmap, - file_graph.clone(), - &opts, - )?; - for dep in deps { - if parsed_file.insert(dep.clone()) { - unparsed_file.push_back(dep.clone()); - } - } - } - }, - Err(e) => return Err(anyhow::anyhow!("Parse entry failed: {e}")), - }; - } - Ok(new_files) -} - -pub fn parse_program( - sess: ParseSessionRef, - paths: Vec, - module_cache: KCLModuleCache, - file_graph: FileGraphCache, - pkgmap: &mut PkgMap, - parsed_file: &mut HashSet, - opts: &LoadProgramOptions, -) -> Result { - let compile_entries = get_compile_entries_from_paths(&paths, &opts)?; - let workdir = compile_entries - .get_root_path() - .to_string() - .adjust_canonicalization(); - let mut pkgs: HashMap> = HashMap::new(); - let mut new_files = HashSet::new(); - for entry in compile_entries.iter() { - new_files.extend(parse_entry( - sess.clone(), - entry, - module_cache.clone(), - &mut pkgs, - pkgmap, - file_graph.clone(), - &opts, - parsed_file, - )?); - } - - let files = match file_graph.read() { - Ok(file_graph) => { - let files = match file_graph.toposort() { - Ok(files) => files, - Err(_) => file_graph.paths(), - }; - - let file_path_graph = file_graph.file_path_graph().0; - if let Err(cycle) = toposort(&file_path_graph) { - let formatted_cycle = cycle - .iter() - .map(|file| format!("- {}\n", file.to_string_lossy())) - .collect::(); - - sess.1.write().add_error( - ErrorKind::RecursiveLoad, - &[Message { - range: (Position::dummy_pos(), Position::dummy_pos()), - style: Style::Line, - message: format!( - "Could not compiles due to cyclic import statements\n{}", - formatted_cycle.trim_end() - ), - note: None, - suggested_replacement: None, - }], - ); - } - files - } - Err(e) => return Err(anyhow::anyhow!("Parse program failed: {e}")), - }; - - let mut modules: HashMap>> = HashMap::new(); - for file in files.iter() { - let filename = file.get_path().to_str().unwrap().to_string(); - let m_ref = match module_cache.read() { - Ok(module_cache) => module_cache - .ast_cache - .get(file.get_path()) - .expect(&format!( - "Module not found in module: {:?}", - file.get_path() - )) - .clone(), - Err(e) => return Err(anyhow::anyhow!("Parse program failed: {e}")), - }; - if new_files.contains(file) { - let pkg = pkgmap.get(file).expect("file not in pkgmap"); - let mut m = m_ref.write().unwrap(); - fix_rel_import_path_with_file(&pkg.pkg_root, &mut m, file, &pkgmap, opts, sess.clone()); - } - modules.insert(filename.clone(), m_ref); - match pkgs.get_mut(&file.pkg_path) { - Some(pkg_modules) => { - pkg_modules.push(filename.clone()); - } - None => { - pkgs.insert(file.pkg_path.clone(), vec![filename]); - } - } - } - let program = ast::Program { - root: workdir, - pkgs, - pkgs_not_imported: HashMap::new(), - modules, - modules_not_imported: HashMap::new(), - }; - - Ok(LoadProgramResult { - program, - errors: sess.1.read().diagnostics.clone(), - paths: files.iter().map(|file| file.get_path().clone()).collect(), - }) -} - -/// If there are too many files in the directory, it will affect the performance of lsp. Set a maximum number of files -const MAX_SCAN_FILES: usize = 1000; - -/// Parse all kcl files under path and dependencies from opts. -/// Different from `load_program`, this function will compile files that are not imported. -pub fn load_all_files_under_paths( - sess: ParseSessionRef, - paths: &[&str], - opts: Option, - module_cache: Option, -) -> Result { - let mut loader = Loader::new(sess.clone(), paths, opts.clone(), module_cache.clone()); - create_session_globals_then(move || { - match parse_program( - loader.sess.clone(), - loader.paths.clone(), - loader.module_cache.clone(), - loader.file_graph.clone(), - &mut loader.pkgmap, - &mut loader.parsed_file, - &loader.opts, - ) { - Ok(res) => { - let diag = sess.1.read().diagnostics.clone(); - let mut res = res.clone(); - let k_files_from_import = res.paths.clone(); - let mut paths = paths.to_vec(); - paths.push(&res.program.root); - let module_cache = loader.module_cache.clone(); - let mut module_cache_write = module_cache.write(); - match &mut module_cache_write { - Ok(m_cache) => { - let paths: Vec = paths.iter().map(|p| p.to_string()).collect(); - let paths_is_cached = paths == m_cache.last_compile_input.0; - let opt_is_cached = match (&m_cache.last_compile_input.1, &opts) { - (None, None) => true, - (Some(old), Some(new)) => old.package_maps == new.package_maps, - _ => false, - }; - if paths_is_cached && opt_is_cached { - return Ok(res); - } else { - m_cache.last_compile_input = (paths, opts.clone()) - } - } - Err(e) => return Err(anyhow::anyhow!("Parse entry failed: {e}")), - } - drop(module_cache_write); - - let (k_files_under_path, pkgmap) = - get_files_from_path(&res.program.root, &paths, opts)?; - - if k_files_under_path.len() > MAX_SCAN_FILES { - return Ok(res); - } - - loader.pkgmap.extend(pkgmap); - - // Filter unparsed file - let mut unparsed_file: VecDeque = VecDeque::new(); - for (pkg, paths) in &k_files_under_path { - for p in paths { - if !k_files_from_import.contains(p) { - let pkgfile = PkgFile::new(p.clone(), pkg.clone()); - let module_cache_read = module_cache.read(); - match &module_cache_read { - Ok(m_cache) => match m_cache.ast_cache.get(pkgfile.get_path()) { - Some(_) => continue, - None => { - unparsed_file.push_back(pkgfile); - } - }, - _ => {} - } - } - } - } - - let pkgs_not_imported = &mut res.program.pkgs_not_imported; - - let mut new_files = HashSet::new(); - // Bfs unparsed and import files - loader.parsed_file.extend(unparsed_file.clone()); - while let Some(file) = unparsed_file.pop_front() { - new_files.insert(file.clone()); - let module_cache_read = module_cache.read(); - match &module_cache_read { - Ok(m_cache) => match m_cache.ast_cache.get(file.get_path()) { - Some(_) => continue, - None => { - drop(module_cache_read); - let deps = parse_file( - sess.clone(), - file.clone(), - None, - module_cache.clone(), - pkgs_not_imported, - &mut loader.pkgmap, - loader.file_graph.clone(), - &loader.opts, - )?; - - let m_ref = match module_cache.read() { - Ok(module_cache) => module_cache - .ast_cache - .get(file.get_path()) - .expect(&format!( - "Module not found in module: {:?}", - file.get_path() - )) - .clone(), - Err(e) => { - return Err(anyhow::anyhow!("Parse program failed: {e}")) - } - }; - - let pkg = loader.pkgmap.get(&file).expect("file not in pkgmap"); - let mut m = m_ref.write().unwrap(); - fix_rel_import_path_with_file( - &pkg.pkg_root, - &mut m, - &file, - &loader.pkgmap, - &loader.opts, - sess.clone(), - ); - - for dep in deps { - if loader.parsed_file.insert(dep.clone()) { - unparsed_file.push_back(dep.clone()); - } - } - } - }, - Err(e) => return Err(anyhow::anyhow!("Parse entry failed: {e}")), - } - } - - // Merge unparsed module into res - let modules_not_imported = &mut res.program.modules_not_imported; - for file in &new_files { - let filename = file.get_path().to_str().unwrap().to_string(); - let m_ref = match module_cache.read() { - Ok(module_cache) => module_cache - .ast_cache - .get(file.get_path()) - .expect(&format!( - "Module not found in module: {:?}", - file.get_path() - )) - .clone(), - Err(e) => return Err(anyhow::anyhow!("Parse program failed: {e}")), - }; - modules_not_imported.insert(filename.clone(), m_ref); - match pkgs_not_imported.get_mut(&file.pkg_path) { - Some(pkg_modules) => { - pkg_modules.push(filename.clone()); - } - None => { - pkgs_not_imported.insert(file.pkg_path.clone(), vec![filename]); - } - } - } - sess.1.write().diagnostics = diag; - return Ok(res); - } - e => return e, - } - }) -} - -/// Get all kcl files under path and dependencies from opts, regardless of whether they are imported or not -pub fn get_files_from_path( - root: &str, - paths: &[&str], - opts: Option, -) -> Result<(HashMap>, HashMap)> { - let mut k_files_under_path = HashMap::new(); - let mut pkgmap = HashMap::new(); - - // get files from config - if let Some(opt) = &opts { - for (name, path) in &opt.package_maps { - let path_buf = PathBuf::from(path.clone()); - if path_buf.is_dir() { - let all_k_files_under_path = get_kcl_files(path.clone(), true)?; - for f in &all_k_files_under_path { - let p = PathBuf::from(f); - let fix_path = { - match p.parent().unwrap().strip_prefix(Path::new(&path)) { - Ok(p) => Path::new(&name).join(p), - Err(_) => match p.parent().unwrap().strip_prefix(Path::new(&path)) { - Ok(p) => Path::new(&name).join(p), - Err(_) => Path::new(&name).to_path_buf(), - }, - } - } - .to_str() - .unwrap() - .to_string(); - let mut fix_path = fix_path - .replace(['/', '\\'], ".") - .trim_end_matches('.') - .to_string(); - - if fix_path.is_empty() { - fix_path = MAIN_PKG.to_string(); - } - - let pkgfile = PkgFile::new(p.clone(), fix_path.clone()); - pkgmap.insert( - pkgfile, - Pkg { - pkg_name: name.clone(), - pkg_root: path.clone(), - }, - ); - k_files_under_path - .entry(fix_path) - .or_insert(Vec::new()) - .push(p); - } - } - } - } - - // get files from input paths - for path in paths { - let path_buf = PathBuf::from(path); - if path_buf.is_dir() { - let all_k_files_under_path = get_kcl_files(path, true)?; - for f in &all_k_files_under_path { - let p = PathBuf::from(f.adjust_canonicalization()); - let fix_path = p - .parent() - .unwrap() - .strip_prefix(root) - .unwrap() - .to_str() - .unwrap() - .to_string(); - - let fix_path = fix_path - .replace(['/', '\\'], ".") - .trim_end_matches('.') - .to_string(); - - let pkgfile = PkgFile::new(p.clone(), fix_path.clone()); - pkgmap.insert( - pkgfile, - Pkg { - pkg_name: MAIN_PKG.to_owned(), - pkg_root: path.to_string(), - }, - ); - k_files_under_path - .entry(fix_path) - .or_insert(Vec::new()) - .push(p); - } - } - } - - Ok((k_files_under_path, pkgmap)) -} - -/// Get kcl files from path. -pub fn get_kcl_files>(path: P, recursively: bool) -> Result> { - let mut files = vec![]; - let walkdir = if recursively { - walkdir::WalkDir::new(path) - } else { - walkdir::WalkDir::new(path).max_depth(1) - }; - for entry in walkdir.into_iter().filter_map(|e| e.ok()) { - let path = entry.path(); - if path.is_file() { - let file = path.to_str().unwrap(); - if file.ends_with(KCL_FILE_SUFFIX) { - files.push(file.to_string()) - } - } - } - files.sort(); - Ok(files) -} diff --git a/kclvm/parser/src/parser/mod.rs b/kclvm/parser/src/parser/mod.rs deleted file mode 100644 index 3e635f976..000000000 --- a/kclvm/parser/src/parser/mod.rs +++ /dev/null @@ -1,230 +0,0 @@ -//! A KCL Parser. -//! -//! The parser is built on top of the [`kclvm_parser::lexer`], and ordering KCL tokens -//! [`kclvm_ast::token`] to KCL ast nodes [`kclvm_ast::ast`]. -//! -//! The parser follows a LL1 parsing method, which constantly looking for -//! left-side derivation until a terminal token found. Since we hand-written the parser, -//! there is more flexibility in dealing with deduction priorities. -//! -//! KCL syntax elements can be simply divided into statements, expressions and tokens, -//! in which statement consists of expressions and tokens. In expression, operand is the most -//! complex part to enable all kinds of ident, constant, list, dict, config exprs. -//! -//! The parser error recovery strategy design is [here](https://github.com/kcl-lang/kcl/issues/420). - -#![macro_use] - -mod expr; -mod int; -mod module; -mod precedence; -mod stmt; -#[cfg(test)] -mod tests; -mod ty; - -use crate::session::ParseSession; - -use compiler_base_span::span::{new_byte_pos, BytePos}; -use kclvm_ast::ast::{Comment, NodeRef, PosTuple}; -use kclvm_ast::token::{CommentKind, Token, TokenKind}; -use kclvm_ast::token_stream::{Cursor, TokenStream}; -use kclvm_error::ParseErrorMessage; -use kclvm_span::symbol::Symbol; -use kclvm_utils::path::PathPrefix; - -/// The parser is built on top of the [`kclvm_parser::lexer`], and ordering KCL tokens -/// [`kclvm_ast::token`] to KCL ast nodes [`kclvm_ast::ast`]. -pub struct Parser<'a> { - /// The current token. - pub token: Token, - /// The previous token. - pub prev_token: Token, - /// Stream cursor - cursor: Cursor, - /// all comments. - comments: Vec>, - /// parse-time session - pub sess: &'a ParseSession, -} - -/// The DropMarker is used to mark whether to discard the token Mark whether to discard the token. -/// The principle is to store the index of the token in the token stream. When there is no index -/// change during the parse process, it is discarded and an error is output -#[derive(Debug, Default, Clone, Copy)] -pub(crate) struct DropMarker(usize); - -impl<'a> Parser<'a> { - pub fn new(sess: &'a ParseSession, stream: TokenStream) -> Self { - let (non_comment_tokens, comments) = Parser::split_token_stream(sess, stream); - - let mut parser = Parser { - token: Token::dummy(), - prev_token: Token::dummy(), - cursor: TokenStream::new(non_comment_tokens).cursor(), - comments, - sess, - }; - - // bump to the first token - parser.bump(); - - parser - } - - /// Get an AST position from the token pair (lo_tok, hi_tok). - #[inline] - pub(crate) fn token_span_pos(&mut self, lo_tok: Token, hi_tok: Token) -> PosTuple { - self.byte_pos_to_pos(lo_tok.span.lo(), hi_tok.span.hi()) - } - - /// Get an AST position from the byte pos pair (lo, hi). - pub(crate) fn byte_pos_to_pos(&mut self, lo: BytePos, hi: BytePos) -> PosTuple { - let lo = self.sess.lookup_char_pos(lo); - let hi = self.sess.lookup_char_pos(hi); - - let filename = kclvm_utils::path::convert_windows_drive_letter(&format!( - "{}", - lo.file.name.prefer_remapped() - )) - .adjust_canonicalization(); - - ( - filename, - lo.line as u64, - lo.col.0 as u64, - hi.line as u64, - hi.col.0 as u64, - ) - } - - pub(crate) fn bump(&mut self) { - self.prev_token = self.token; - let next = self.cursor.next(); - - if let Some(token) = next { - self.token = token - } - } - - /// Whether the parser has the next token in the token stream. - #[inline] - pub(crate) fn has_next(&mut self) -> bool { - self.cursor.next().is_some() - } - - #[inline] - /// Whether the parser has the next token in the token stream. - pub(crate) fn peek_has_next(&mut self) -> bool { - self.cursor.peek().is_some() - } - - pub(crate) fn bump_keyword(&mut self, kw: Symbol) { - if !self.token.is_keyword(kw) { - self.sess.struct_token_error(&[kw.into()], self.token); - } - self.bump(); - } - - pub(crate) fn bump_token(&mut self, kind: TokenKind) { - if self.token.kind != kind { - self.sess.struct_token_error(&[kind.into()], self.token); - } - self.bump(); - } - - pub(crate) fn skip_newlines(&mut self) { - while let TokenKind::Newline = self.token.kind { - self.bump(); - } - } - - /// Mark the token index. - pub(crate) fn mark(&mut self) -> DropMarker { - DropMarker(self.cursor.index()) - } - - /// Decide to discard token according to the current index. - pub(crate) fn drop(&mut self, marker: DropMarker) -> bool { - if marker.0 == self.cursor.index() { - let token_str: String = self.token.into(); - self.sess - .struct_message_error(ParseErrorMessage::ExpectExpr(token_str), self.token.span); - self.bump(); - true - } else { - false - } - } -} - -impl<'a> Parser<'a> { - fn split_token_stream( - sess: &'a ParseSession, - stream: TokenStream, - ) -> (Vec, Vec>) { - let mut comments = Vec::new(); - let mut non_comment_tokens = Vec::new(); - - for (i, tok) in stream.iter().enumerate() { - let prev_token = if i == 0 { - Token { - kind: TokenKind::Dummy, - span: kclvm_span::Span::new(new_byte_pos(0), new_byte_pos(0)), - } - } else { - stream[i - 1] - }; - - // eof: add newline - if tok.kind == TokenKind::Eof { - // append Newline - if prev_token.kind != TokenKind::Newline { - non_comment_tokens.push(Token { - kind: TokenKind::Newline, - span: tok.span, - }); - } - non_comment_tokens.push(*tok); - break; - } - - // split comments - if matches!(tok.kind, TokenKind::DocComment(_)) { - if let TokenKind::DocComment(comment_kind) = tok.kind { - match comment_kind { - CommentKind::Line(x) => { - let lo = sess.lookup_char_pos(tok.span.lo()); - let hi = sess.lookup_char_pos(tok.span.hi()); - let filename = kclvm_utils::path::convert_windows_drive_letter( - &format!("{}", lo.file.name.prefer_remapped()), - ) - .adjust_canonicalization(); - - let node = kclvm_ast::ast::Node { - id: kclvm_ast::ast::AstIndex::default(), - node: Comment { - text: x.as_str().to_string(), - }, - filename, - line: lo.line as u64, - column: lo.col.0 as u64, - end_line: hi.line as u64, - end_column: hi.col.0 as u64, - }; - - comments.push(NodeRef::new(node)); - } - } - } - continue; - } - - // normal tokens - non_comment_tokens.push(*tok); - } - - (non_comment_tokens, comments) - } -} diff --git a/kclvm/parser/src/parser/module.rs b/kclvm/parser/src/parser/module.rs deleted file mode 100644 index 28d0bf40b..000000000 --- a/kclvm/parser/src/parser/module.rs +++ /dev/null @@ -1,68 +0,0 @@ -use kclvm_ast::ast::*; -use kclvm_ast::node_ref; -use kclvm_ast::{token::LitKind, token::TokenKind}; - -use super::Parser; - -impl<'a> Parser<'a> { - /// Syntax: - /// start: (NEWLINE | statement)* - pub fn parse_module(&mut self) -> Module { - let doc = self.parse_doc(); - let body = self.parse_body(); - Module { - filename: "".to_string(), - doc, - comments: self.comments.clone(), - body, - } - } - - pub(crate) fn parse_doc(&mut self) -> Option> { - // doc string - match self.token.kind { - TokenKind::Literal(lit) => { - if let LitKind::Str { is_long_string, .. } = lit.kind { - if is_long_string { - let doc_expr = self.parse_str_expr(lit); - self.skip_newlines(); - match &doc_expr.node { - Expr::StringLit(str) => { - Some(node_ref!(str.raw_value.clone(), doc_expr.pos())) - } - Expr::JoinedString(str) => { - Some(node_ref!(str.raw_value.clone(), doc_expr.pos())) - } - _ => None, - } - } else { - None - } - } else { - None - } - } - _ => None, - } - } - - fn parse_body(&mut self) -> Vec> { - let mut stmts = Vec::new(); - loop { - if matches!(self.token.kind, TokenKind::Eof) { - self.bump(); - break; - } - - if let Some(stmt) = self.parse_stmt() { - stmts.push(stmt); - } else { - // Error recovery from panic mode: Once an error is detected (the statement is None), - // the symbols in the input are continuously discarded (one symbol at a time), until the - // "synchronous lexical unit" is found (the statement start token e.g., import, schema, etc). - self.bump(); - } - } - stmts - } -} diff --git a/kclvm/parser/src/parser/precedence.rs b/kclvm/parser/src/parser/precedence.rs deleted file mode 100644 index 2f31815ec..000000000 --- a/kclvm/parser/src/parser/precedence.rs +++ /dev/null @@ -1,89 +0,0 @@ -use kclvm_ast::token::{Token, TokenKind}; - -use kclvm_span::symbol::kw; - -#[repr(i32)] -#[derive(PartialEq, PartialOrd, Debug, Clone)] -pub enum Precedence { - /// lowest place holder - Lowest, - /// as - As, - /// logic or || - LogicOr, - /// logic and && - LogicAnd, - /// ==, != - Equals, - /// in, not it - InOrNotIn, - /// is, is not - IsOrIsNot, - /// >, <, >=, <= - LessGreater, - /// | - BitOr, - /// ^ - BitXor, - /// & - BitAnd, - /// >>, << - Shift, - /// +, - - Sum, - /// *, /, % // - Product, - /// ** - Power, - /// +X, -X, !X - Prefix, -} - -impl From for Precedence { - fn from(tok: Token) -> Self { - if tok.is_keyword(kw::As) { - return Precedence::As; - } - match tok.kind { - TokenKind::UnaryOp(_) => Precedence::Prefix, - TokenKind::BinOp(ot) => match ot { - kclvm_ast::token::BinOpToken::Plus | kclvm_ast::token::BinOpToken::Minus => { - Precedence::Sum - } - kclvm_ast::token::BinOpToken::Star - | kclvm_ast::token::BinOpToken::Slash - | kclvm_ast::token::BinOpToken::Percent - | kclvm_ast::token::BinOpToken::SlashSlash => Precedence::Product, - kclvm_ast::token::BinOpToken::StarStar => Precedence::Power, - kclvm_ast::token::BinOpToken::Caret => Precedence::BitXor, - kclvm_ast::token::BinOpToken::And => Precedence::BitAnd, - kclvm_ast::token::BinOpToken::Or => Precedence::BitOr, - kclvm_ast::token::BinOpToken::Shl | kclvm_ast::token::BinOpToken::Shr => { - Precedence::Shift - } - }, - TokenKind::BinCmp(ct) => match ct { - kclvm_ast::token::BinCmpToken::Eq | kclvm_ast::token::BinCmpToken::NotEq => { - Precedence::Equals - } - kclvm_ast::token::BinCmpToken::Lt - | kclvm_ast::token::BinCmpToken::LtEq - | kclvm_ast::token::BinCmpToken::Gt - | kclvm_ast::token::BinCmpToken::GtEq => Precedence::LessGreater, - }, - _ => { - if tok.is_keyword(kw::Or) { - Precedence::LogicOr - } else if tok.is_keyword(kw::And) { - Precedence::LogicAnd - } else if tok.is_keyword(kw::In) { - Precedence::InOrNotIn - } else if tok.is_keyword(kw::Is) { - Precedence::IsOrIsNot - } else { - Precedence::Lowest - } - } - } - } -} diff --git a/kclvm/parser/src/parser/ty.rs b/kclvm/parser/src/parser/ty.rs deleted file mode 100644 index c2fac8d19..000000000 --- a/kclvm/parser/src/parser/ty.rs +++ /dev/null @@ -1,291 +0,0 @@ -#![allow(dead_code)] - -use super::Parser; - -use kclvm_ast::ast::{Expr, Node, NodeRef, Type}; -use kclvm_ast::token; -use kclvm_ast::token::{BinOpToken, DelimToken, TokenKind}; -use kclvm_ast::{ast, expr_as}; -use kclvm_span::symbol::{kw, sym}; - -impl<'a> Parser<'a> { - /// Syntax: - /// - /// type: type_element (OR type_element)* - /// type_element: schema_type | function_type | basic_type | compound_type | literal_type - /// function_type: LEFT_PARENTHESES [type_element (COMMA type_element)*] RIGHT_PARENTHESES [RIGHT_ARROW type_element] - /// schema_type: identifier - /// basic_type: STRING_TYPE | INT_TYPE | FLOAT_TYPE | BOOL_TYPE | ANY_TYPE - /// compound_type: list_type | dict_type - /// list_type: LEFT_BRACKETS (type)? RIGHT_BRACKETS - /// dict_type: LEFT_BRACE (type)? COLON (type)? RIGHT_BRACE - /// literal_type: string | number | TRUE | FALSE - pub(crate) fn parse_type_annotation(&mut self) -> NodeRef { - let token = self.token; - let mut type_node_list = vec![self.parse_type_element()]; - - while let TokenKind::BinOp(BinOpToken::Or) = self.token.kind { - self.bump(); - let t = self.parse_type_element(); - type_node_list.push(t); - } - - if type_node_list.len() > 1 { - let mut union_type = ast::UnionType { - type_elements: Vec::new(), - }; - for v in type_node_list.iter_mut() { - union_type.type_elements.push(v.clone()); - } - - Box::new(Node::node( - Type::Union(union_type.clone()), - self.sess.struct_token_loc(token, self.prev_token), - )) - } else { - type_node_list[0].clone() - } - } - - fn parse_type_element(&mut self) -> NodeRef { - let token = self.token; - - // any - if self.token.is_keyword(kw::Any) { - let t = Type::Any; - self.bump_keyword(kw::Any); - return Box::new(Node::node( - t, - self.sess.struct_token_loc(token, self.prev_token), - )); - } - // lit: true/false - else if self.token.is_keyword(kw::True) { - self.bump_keyword(kw::True); - return Box::new(Node::node( - Type::Literal(ast::LiteralType::Bool(true)), - self.sess.struct_token_loc(token, self.prev_token), - )); - } else if self.token.is_keyword(kw::False) { - self.bump_keyword(kw::False); - return Box::new(Node::node( - Type::Literal(ast::LiteralType::Bool(false)), - self.sess.struct_token_loc(token, self.prev_token), - )); - } - // basic type - else if self.token.is_keyword(sym::bool) { - let t = Type::Basic(ast::BasicType::Bool); - self.bump_keyword(sym::bool); - return Box::new(Node::node( - t, - self.sess.struct_token_loc(token, self.prev_token), - )); - } else if self.token.is_keyword(sym::int) { - let t = Type::Basic(ast::BasicType::Int); - self.bump_keyword(sym::int); - return Box::new(Node::node( - t, - self.sess.struct_token_loc(token, self.prev_token), - )); - } else if self.token.is_keyword(sym::float) { - let t = Type::Basic(ast::BasicType::Float); - self.bump_keyword(sym::float); - return Box::new(Node::node( - t, - self.sess.struct_token_loc(token, self.prev_token), - )); - } else if self.token.is_keyword(sym::str) { - let t = Type::Basic(ast::BasicType::Str); - self.bump_keyword(sym::str); - return Box::new(Node::node( - t, - self.sess.struct_token_loc(token, self.prev_token), - )); - } - - // named type - if let TokenKind::Ident(_) = self.token.kind { - let ident = self.parse_identifier_expr(); - let ident = expr_as!(ident, Expr::Identifier).unwrap(); - let t = Type::Named(ident); - return Box::new(Node::node( - t, - self.sess.struct_token_loc(token, self.prev_token), - )); - } - // lit type - else if let TokenKind::Literal(lit) = self.token.kind { - let t = match lit.kind { - token::LitKind::Bool => { - if lit.symbol == kw::True { - ast::LiteralType::Bool(true) - } else if lit.symbol == kw::False { - ast::LiteralType::Bool(false) - } else { - self.sess - .struct_token_error(&[kw::True.into(), kw::False.into()], self.token); - ast::LiteralType::Bool(false) - } - } - token::LitKind::Integer => { - let v = lit.symbol.as_str().parse::().unwrap(); - if let Some(suffix) = lit.suffix { - let x = ast::NumberBinarySuffix::try_from(suffix.as_str().as_str()); - ast::LiteralType::Int(ast::IntLiteralType { - value: v, - suffix: Some(x.unwrap()), - }) - } else { - ast::LiteralType::Int(ast::IntLiteralType { - value: v, - suffix: None, - }) - } - } - token::LitKind::Float => { - let v = lit.symbol.as_str().parse::().unwrap(); - ast::LiteralType::Float(v) - } - token::LitKind::Str { .. } => ast::LiteralType::Str(lit.symbol.as_str()), - _ => { - if self.token.is_keyword(kw::True) { - ast::LiteralType::Bool(true) - } else if self.token.is_keyword(kw::False) { - ast::LiteralType::Bool(false) - } else { - self.sess - .struct_token_error(&[kw::True.into(), kw::False.into()], self.token); - ast::LiteralType::Bool(false) - } - } - }; - - let t = Type::Literal(t); - - self.bump(); - - return Box::new(Node::node( - t, - self.sess.struct_token_loc(token, self.prev_token), - )); - } - // [type] - else if let TokenKind::OpenDelim(DelimToken::Bracket) = self.token.kind { - self.bump_token(TokenKind::OpenDelim(DelimToken::Bracket)); - - if let TokenKind::CloseDelim(DelimToken::Bracket) = self.token.kind { - self.bump(); - let t = Type::List(ast::ListType { inner_type: None }); - - return Box::new(Node::node( - t, - self.sess.struct_token_loc(token, self.prev_token), - )); - } else { - let elem_type = self.parse_type_annotation(); - let t = Type::List(ast::ListType { - inner_type: Some(elem_type), - }); - - self.bump_token(TokenKind::CloseDelim(DelimToken::Bracket)); - - return Box::new(Node::node( - t, - self.sess.struct_token_loc(token, self.prev_token), - )); - } - } - // {key:value} - else if let TokenKind::OpenDelim(DelimToken::Brace) = self.token.kind { - self.bump_token(TokenKind::OpenDelim(DelimToken::Brace)); - - let key_type = if let TokenKind::Colon = self.token.kind { - None - } else { - Some(self.parse_type_annotation()) - }; - - self.bump_token(TokenKind::Colon); - - let value_type = if let TokenKind::CloseDelim(DelimToken::Brace) = self.token.kind { - None - } else { - Some(self.parse_type_annotation()) - }; - - let t = Type::Dict(ast::DictType { - key_type, - value_type, - }); - - self.bump_token(TokenKind::CloseDelim(DelimToken::Brace)); - - return Box::new(Node::node( - t, - self.sess.struct_token_loc(token, self.prev_token), - )); - } - // (type) -> type - else if let TokenKind::OpenDelim(DelimToken::Paren) = self.token.kind { - self.bump_token(TokenKind::OpenDelim(DelimToken::Paren)); - let mut params_type = vec![]; - // Parse all the params type until the params list end ')' - while self.token.kind != TokenKind::CloseDelim(DelimToken::Paren) - && self.peek_has_next() - { - params_type.push(self.parse_type_annotation()); - // All the params type should be separated by ',' - if let TokenKind::Comma = self.token.kind { - self.bump_token(TokenKind::Comma); - } - } - // If there is no params type, set it to None - let params_ty = if params_type.is_empty() { - None - } else { - Some(params_type) - }; - - self.bump_token(TokenKind::CloseDelim(DelimToken::Paren)); - // If there is a return type, parse it - // Return type start with '->' - let ret_ty = if let TokenKind::RArrow = self.token.kind { - self.bump_token(TokenKind::RArrow); - Some(self.parse_type_annotation()) - } else { - None - }; - - let t = Type::Function(ast::FunctionType { params_ty, ret_ty }); - - return Box::new(Node::node( - t, - self.sess.struct_token_loc(token, self.prev_token), - )); - } - // Expect type tokens - self.sess.struct_token_error( - &[ - kw::Any.into(), - sym::bool.into(), - sym::int.into(), - sym::float.into(), - sym::str.into(), - kw::True.into(), - kw::False.into(), - TokenKind::ident_value(), - TokenKind::literal_value(), - TokenKind::OpenDelim(DelimToken::Bracket).into(), - TokenKind::OpenDelim(DelimToken::Brace).into(), - TokenKind::CloseDelim(DelimToken::Paren).into(), - ], - self.token, - ); - self.bump(); - Box::new(Node::node( - Type::Any, - self.sess.struct_token_loc(token, self.prev_token), - )) - } -} diff --git a/kclvm/parser/src/session/mod.rs b/kclvm/parser/src/session/mod.rs deleted file mode 100644 index 9d8e14eef..000000000 --- a/kclvm/parser/src/session/mod.rs +++ /dev/null @@ -1,123 +0,0 @@ -use anyhow::Result; -use compiler_base_macros::bug; -use compiler_base_session::Session; -use kclvm_ast::token::Token; -use kclvm_error::{Diagnostic, Handler, ParseError, ParseErrorMessage}; -use kclvm_primitives::IndexSet; -use kclvm_span::{BytePos, Loc, Span}; -use parking_lot::RwLock; -use std::sync::Arc; - -pub type ParseSessionRef = Arc; - -/// ParseSession represents the data associated with a parse session such as the -/// source map and the error handler. -#[derive(Default)] -pub struct ParseSession(pub Arc, pub RwLock); - -impl ParseSession { - /// New a parse session with the global session. - #[inline] - pub fn with_session(sess: Arc) -> Self { - Self(sess, RwLock::new(Handler::default())) - } - - /// Lookup char pos from span. - #[inline] - pub(crate) fn lookup_char_pos(&self, pos: BytePos) -> Loc { - self.0.sm.lookup_char_pos(pos) - } - - /// Returns the source snippet as [String] corresponding to the given [Span]. - #[inline] - pub fn span_to_snippet(&self, span: Span) -> String { - self.0.sm.span_to_snippet(span).unwrap() - } - - /// Struct an loc of first and last valid tokens in an expr, returns a loc tuple - pub fn struct_token_loc(&self, lot: Token, hit: Token) -> (Loc, Loc) { - ( - self.lookup_char_pos(lot.span.lo()), - self.lookup_char_pos(hit.span.hi()), - ) - } - - /// Construct an loc of ont token. - pub fn token_loc(&self, tok: Token) -> (Loc, Loc) { - ( - self.lookup_char_pos(tok.span.lo()), - self.lookup_char_pos(tok.span.hi()), - ) - } - - /// Struct and report an error based on a token and not abort the compiler process. - #[inline] - pub fn struct_token_error(&self, expected: &[String], got: Token) { - self.add_parse_err(ParseError::UnexpectedToken { - expected: expected.iter().map(|tok| tok.into()).collect(), - got: got.into(), - span: got.span, - }); - } - - /// Struct and report an error based on a span and not abort the compiler process. - #[inline] - pub fn struct_span_error(&self, msg: &str, span: Span) { - self.add_parse_err(ParseError::String { - message: msg.to_string(), - span, - }); - } - - #[inline] - pub fn struct_message_error(&self, msg: ParseErrorMessage, span: Span) { - self.add_parse_err(ParseError::Message { - message: msg, - span, - suggestions: None, - }); - } - - #[inline] - pub fn struct_message_error_with_suggestions( - &self, - msg: ParseErrorMessage, - span: Span, - suggestions: Option>, - ) { - self.add_parse_err(ParseError::Message { - message: msg, - span, - suggestions, - }); - } - - /// Add a error into the session. - #[inline] - fn add_parse_err(&self, err: ParseError) { - let add_error = || -> Result<()> { - self.0.add_err(err.clone().into_diag(&self.0)?)?; - self.1.write().add_diagnostic(err.into_diag(&self.0)?); - Ok(()) - }; - if let Err(err) = add_error() { - bug!( - "compiler session internal error occurs: {}", - err.to_string() - ) - } - } - - /// Append diagnostics into the parse session. - pub fn append_diagnostic(&self, diagnostics: IndexSet) -> &Self { - for diagnostic in diagnostics { - self.1.write().add_diagnostic(diagnostic); - } - self - } - - /// Classify diagnostics into errors and warnings. - pub fn classification(&self) -> (IndexSet, IndexSet) { - self.1.read().classification() - } -} diff --git a/kclvm/parser/src/tests.rs b/kclvm/parser/src/tests.rs deleted file mode 100644 index b09c17829..000000000 --- a/kclvm/parser/src/tests.rs +++ /dev/null @@ -1,872 +0,0 @@ -use std::{ - env, - panic::{catch_unwind, set_hook}, - path::Path, -}; - -use compiler_base_span::{FilePathMapping, SourceMap}; -use entry::expand_input_files; -use kclvm_config::modfile::{get_vendor_home, KCL_PKG_PATH}; - -use crate::*; - -use core::any::Any; - -mod ast; -mod error_recovery; -mod expr; -mod file; -mod types; - -#[macro_export] -macro_rules! parse_expr_snapshot { - ($name:ident, $src:expr) => { - #[test] - fn $name() { - insta::assert_snapshot!($crate::tests::parsing_expr_string($src)); - } - }; -} - -#[macro_export] -macro_rules! parse_module_snapshot { - ($name:ident, $src:expr) => { - #[test] - fn $name() { - insta::assert_snapshot!($crate::tests::parsing_module_string($src)); - } - }; -} - -#[macro_export] -macro_rules! parse_type_snapshot { - ($name:ident, $src:expr) => { - #[test] - fn $name() { - insta::assert_snapshot!($crate::tests::parsing_type_string($src)); - } - }; -} - -#[macro_export] -macro_rules! parse_type_node_snapshot { - ($name:ident, $src:expr) => { - #[test] - fn $name() { - insta::assert_snapshot!($crate::tests::parsing_type_node_string($src)); - } - }; -} - -#[macro_export] -macro_rules! parse_file_ast_json_snapshot { - ($name:ident, $filename:expr, $src:expr) => { - #[test] - fn $name() { - insta::assert_snapshot!($crate::tests::parsing_file_ast_json($filename, $src)); - } - }; -} - -#[macro_export] -macro_rules! parse_file_snapshot { - ($name:ident, $filename:expr) => { - #[test] - fn $name() { - insta::assert_snapshot!($crate::tests::parsing_file_string($filename)); - } - }; -} - -pub(crate) fn parsing_expr_string(src: &str) -> String { - let sm = SourceMap::new(FilePathMapping::empty()); - let sf = sm.new_source_file(PathBuf::from("").into(), src.to_string()); - let sess = &ParseSession::with_source_map(Arc::new(sm)); - - match sf.src.as_ref() { - Some(src_from_sf) => create_session_globals_then(|| { - let stream = parse_token_streams(sess, src_from_sf.as_str(), new_byte_pos(0)); - let mut parser = Parser::new(sess, stream); - let expr = parser.parse_expr(); - format!("{expr:#?}\n") - }), - None => "".to_string(), - } -} - -pub(crate) fn parsing_module_string(src: &str) -> String { - let sm = SourceMap::new(FilePathMapping::empty()); - let sf = sm.new_source_file(PathBuf::from("").into(), src.to_string()); - let sess = &ParseSession::with_source_map(Arc::new(sm)); - - match sf.src.as_ref() { - Some(src_from_sf) => create_session_globals_then(|| { - let stream = parse_token_streams(sess, src_from_sf.as_str(), new_byte_pos(0)); - let mut parser = Parser::new(sess, stream); - let module = parser.parse_module(); - format!("{module:#?}\n") - }), - None => "".to_string(), - } -} - -pub(crate) fn parsing_type_string(src: &str) -> String { - let sm = SourceMap::new(FilePathMapping::empty()); - sm.new_source_file(PathBuf::from("").into(), src.to_string()); - let sess = &ParseSession::with_source_map(Arc::new(sm)); - - create_session_globals_then(|| { - let stream = parse_token_streams(sess, src, new_byte_pos(0)); - let mut parser = Parser::new(sess, stream); - let typ = parser.parse_type_annotation(); - format!("{typ:#?}\n") - }) -} - -pub(crate) fn parsing_type_node_string(src: &str) -> String { - let sm = SourceMap::new(FilePathMapping::empty()); - sm.new_source_file(PathBuf::from("").into(), src.to_string()); - let sess = &ParseSession::with_source_map(Arc::new(sm)); - - create_session_globals_then(|| { - let stream = parse_token_streams(sess, src, new_byte_pos(0)); - let mut parser = Parser::new(sess, stream); - let typ = parser.parse_type_annotation(); - typ.node.to_string() - }) -} - -pub(crate) fn parsing_file_ast_json(filename: &str, src: &str) -> String { - let m = crate::parse_file_with_global_session( - Arc::new(ParseSession::default()), - filename, - Some(src.into()), - ) - .unwrap(); - serde_json::ser::to_string_pretty(&m).unwrap() -} - -pub(crate) fn parsing_file_string(filename: &str) -> String { - let code = std::fs::read_to_string(filename).unwrap(); - let m = crate::parse_single_file(filename.trim_start_matches("testdata/"), Some(code)) - .expect(filename) - .module; - serde_json::ser::to_string_pretty(&m).unwrap() -} - -pub fn check_result_panic_info(result: Result<(), Box>) { - if let Err(e) = result { - assert!(e.downcast::().is_ok()); - }; -} - -const PARSE_EXPR_INVALID_TEST_CASES: &[&str] = - &["fs1_i1re1~s", "fh==-h==-", "8_________i", "1MM", "0x00x"]; - -#[test] -pub fn test_parse_expr_invalid() { - for case in PARSE_EXPR_INVALID_TEST_CASES { - set_hook(Box::new(|_| {})); - let result = catch_unwind(|| { - parse_expr(case); - }); - check_result_panic_info(result); - } -} - -const PARSE_FILE_INVALID_TEST_CASES: &[&str] = &[ - "a: int", // No initial value error - "a -", // Invalid binary expression error - "a?: int", // Invalid optional annotation error - "if a not is not b: a = 1", // Logic operator error - "if True:\n a=1\n b=2", // Indent error with recovery - "a[1::::]", // List slice error - "a[1 a]", // List index error - "{a ++ 1}", // Config attribute operator error - "func(a=1,b)", // Call argument error - "'${}'", // Empty string interpolation error - "'${a: jso}'", // Invalid string interpolation format spec error -]; - -#[test] -pub fn test_parse_file_invalid() { - for case in PARSE_FILE_INVALID_TEST_CASES { - let result = parse_file_force_errors("test.k", Some((&case).to_string())); - assert!(result.is_err(), "case: {case}, result {result:?}"); - } -} - -pub fn test_vendor_home() { - let vendor = &PathBuf::from(".") - .join("testdata") - .join("test_vendor") - .canonicalize() - .unwrap() - .display() - .to_string() - .adjust_canonicalization(); - env::set_var(KCL_PKG_PATH, vendor); - assert_eq!(get_vendor_home(), vendor.to_string()); -} - -fn set_vendor_home() -> String { - // set env vendor - let vendor = &PathBuf::from(".") - .join("testdata") - .join("test_vendor") - .canonicalize() - .unwrap() - .display() - .to_string() - .adjust_canonicalization(); - env::set_var(KCL_PKG_PATH, vendor); - debug_assert_eq!(get_vendor_home(), vendor.to_string()); - vendor.to_string() -} - -#[test] -/// The testing will set environment variables, -/// so can not to execute test cases concurrently. -fn test_in_order() { - test_import_vendor_by_external_arguments(); - println!("{:?} PASS", "test_import_vendor_by_external_arguments"); - test_import_vendor_without_vendor_home(); - println!("{:?} PASS", "test_import_vendor_without_vendor_home"); - test_import_vendor_without_kclmod(); - println!("{:?} PASS", "test_import_vendor_without_kclmod"); - test_import_vendor(); - println!("{:?} PASS", "test_import_vendor"); - test_import_vendor_with_same_internal_pkg(); - println!("{:?} PASS", "test_import_vendor_with_same_internal_pkg"); - test_import_vendor_without_kclmod_and_same_name(); - println!( - "{:?} PASS", - "test_import_vendor_without_kclmod_and_same_name" - ); - test_vendor_home(); - println!("{:?} PASS", "test_vendor_home"); - test_pkg_not_found_suggestion(); - println!("{:?} PASS", "test_pkg_not_found_suggestion"); -} - -pub fn test_import_vendor() { - let module_cache = KCLModuleCache::default(); - let vendor = set_vendor_home(); - let sm = SourceMap::new(FilePathMapping::empty()); - let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); - - let test_cases = vec![ - ("assign.k", vec!["__main__", "assign", "assign.assign"]), - ( - "config_expr.k", - vec!["__main__", "config_expr", "config_expr.config_expr_02"], - ), - ( - "nested_vendor.k", - vec![ - "__main__", - "nested_vendor", - "nested_vendor.nested_vendor", - "vendor_subpkg", - "vendor_subpkg.sub.sub1", - "vendor_subpkg.sub.sub2", - "vendor_subpkg.sub.sub", - "vendor_subpkg.sub", - ], - ), - ( - "subpkg.k", - vec![ - "__main__", - "vendor_subpkg", - "vendor_subpkg.sub.sub1", - "vendor_subpkg.sub.sub", - "vendor_subpkg.sub.sub2", - "vendor_subpkg.sub", - ], - ), - ]; - - let dir = &PathBuf::from(".") - .join("testdata") - .join("import_vendor") - .canonicalize() - .unwrap(); - - let test_fn = - |test_case_name: &&str, pkgs: &Vec<&str>, module_cache: Option| { - let test_case_path = dir - .join(test_case_name) - .display() - .to_string() - .adjust_canonicalization(); - let m = load_program(sess.clone(), &[&test_case_path], None, module_cache) - .unwrap() - .program; - assert_eq!(m.pkgs.len(), pkgs.len()); - m.pkgs.clone().into_iter().for_each(|(name, modules)| { - println!("{:?} - {:?}", test_case_name, name); - assert!(pkgs.contains(&name.as_str())); - for pkg in pkgs.clone() { - if name == pkg { - if name == "__main__" { - assert_eq!(modules.len(), 1); - let module = m.get_module(modules.get(0).unwrap()).unwrap().unwrap(); - assert_eq!(module.filename, test_case_path); - } else { - modules.into_iter().for_each(|module| { - let module = m.get_module(&module).unwrap().unwrap(); - assert!(module.filename.contains(&vendor)); - }); - } - break; - } - } - }); - }; - - test_cases - .iter() - .for_each(|(test_case_name, pkgs)| test_fn(test_case_name, pkgs, None)); - - test_cases.iter().for_each(|(test_case_name, pkgs)| { - test_fn(test_case_name, pkgs, Some(module_cache.clone())) - }); -} - -pub fn test_import_vendor_without_kclmod() { - let vendor = set_vendor_home(); - let sm = SourceMap::new(FilePathMapping::empty()); - let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); - - let test_cases = vec![("import_vendor.k", vec!["__main__", "assign.assign"])]; - - let dir = &PathBuf::from(".") - .join("testdata_without_kclmod") - .canonicalize() - .unwrap(); - - test_cases.into_iter().for_each(|(test_case_name, pkgs)| { - let test_case_path = dir - .join(test_case_name) - .display() - .to_string() - .adjust_canonicalization(); - let m = load_program(sess.clone(), &[&test_case_path], None, None) - .unwrap() - .program; - assert_eq!(m.pkgs.len(), pkgs.len()); - m.pkgs.clone().into_iter().for_each(|(name, modules)| { - assert!(pkgs.contains(&name.as_str())); - for pkg in pkgs.clone() { - if name == pkg { - if name == "__main__" { - assert_eq!(modules.len(), 1); - let module = m.get_module(modules.get(0).unwrap()).unwrap().unwrap(); - assert_eq!(module.filename, test_case_path); - } else { - modules.into_iter().for_each(|module| { - let module = m.get_module(&module).unwrap().unwrap(); - assert!(module.filename.contains(&vendor)); - }); - } - break; - } - } - }); - }); -} - -pub fn test_import_vendor_without_vendor_home() { - env::set_var(KCL_PKG_PATH, ""); - let sm = SourceMap::new(FilePathMapping::empty()); - let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); - let dir = &PathBuf::from(".") - .join("testdata") - .join("import_vendor") - .canonicalize() - .unwrap(); - let test_case_path = dir.join("assign.k").display().to_string(); - match load_program(sess.clone(), &[&test_case_path], None, None) { - Ok(_) => { - let errors = sess.classification().0; - let msgs = [ - "pkgpath assign not found in the program", - "try 'kcl mod add assign' to download the missing package", - "browse more packages at 'https://artifacthub.io'", - "pkgpath assign.assign not found in the program", - ]; - assert_eq!(errors.len(), msgs.len()); - for (diag, m) in errors.iter().zip(msgs.iter()) { - assert_eq!(diag.messages[0].message, m.to_string()); - } - } - Err(_) => { - panic!("Unreachable code.") - } - } - - match load_program( - sess.clone(), - &[&test_case_path], - None, - Some(KCLModuleCache::default()), - ) { - Ok(_) => { - let errors = sess.classification().0; - let msgs = [ - "pkgpath assign not found in the program", - "try 'kcl mod add assign' to download the missing package", - "browse more packages at 'https://artifacthub.io'", - "pkgpath assign.assign not found in the program", - ]; - assert_eq!(errors.len(), msgs.len()); - for (diag, m) in errors.iter().zip(msgs.iter()) { - assert_eq!(diag.messages[0].message, m.to_string()); - } - } - Err(_) => { - panic!("Unreachable code.") - } - } -} - -fn test_import_vendor_with_same_internal_pkg() { - set_vendor_home(); - let sm = SourceMap::new(FilePathMapping::empty()); - let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); - let dir = &PathBuf::from(".") - .join("testdata") - .join("import_vendor") - .canonicalize() - .unwrap(); - let test_case_path = dir.join("same_name.k").display().to_string(); - match load_program(sess.clone(), &[&test_case_path], None, None) { - Ok(_) => { - let errors = sess.classification().0; - let msgs = [ - "the `same_vendor` is found multiple times in the current package and vendor package" - ]; - assert_eq!(errors.len(), msgs.len()); - for (diag, m) in errors.iter().zip(msgs.iter()) { - assert_eq!(diag.messages[0].message, m.to_string()); - } - } - Err(_) => { - panic!("Unreachable code.") - } - } - match load_program( - sess.clone(), - &[&test_case_path], - None, - Some(KCLModuleCache::default()), - ) { - Ok(_) => { - let errors = sess.classification().0; - let msgs = [ - "the `same_vendor` is found multiple times in the current package and vendor package" - ]; - assert_eq!(errors.len(), msgs.len()); - for (diag, m) in errors.iter().zip(msgs.iter()) { - assert_eq!(diag.messages[0].message, m.to_string()); - } - } - Err(_) => { - panic!("Unreachable code.") - } - } -} - -fn test_import_vendor_without_kclmod_and_same_name() { - set_vendor_home(); - let sm = SourceMap::new(FilePathMapping::empty()); - let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); - let dir = &PathBuf::from(".") - .join("testdata_without_kclmod") - .join("same_name") - .canonicalize() - .unwrap(); - let test_case_path = dir.join("assign.k").display().to_string(); - match load_program(sess.clone(), &[&test_case_path], None, None) { - Ok(_) => { - let errors = sess.classification().0; - let msgs = [ - "the `assign` is found multiple times in the current package and vendor package", - ]; - assert_eq!(errors.len(), msgs.len()); - for (diag, m) in errors.iter().zip(msgs.iter()) { - assert_eq!(diag.messages[0].message, m.to_string()); - } - } - Err(_) => { - panic!("Unreachable code.") - } - } - - match load_program( - sess.clone(), - &[&test_case_path], - None, - Some(KCLModuleCache::default()), - ) { - Ok(_) => { - let errors = sess.classification().0; - let msgs = [ - "the `assign` is found multiple times in the current package and vendor package", - ]; - assert_eq!(errors.len(), msgs.len()); - for (diag, m) in errors.iter().zip(msgs.iter()) { - assert_eq!(diag.messages[0].message, m.to_string()); - } - } - Err(_) => { - panic!("Unreachable code.") - } - } -} - -fn test_import_vendor_by_external_arguments() { - let vendor = set_vendor_home(); - let sm = SourceMap::new(FilePathMapping::empty()); - let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); - let module_cache = KCLModuleCache::default(); - let external_dir = &PathBuf::from(".") - .join("testdata") - .join("test_vendor") - .canonicalize() - .unwrap(); - - let test_cases = vec![ - ( - "import_by_external_assign.k", - "assign", - vec!["__main__", "assign"], - ), - ( - "import_by_external_config_expr.k", - "config_expr", - vec!["__main__", "config_expr"], - ), - ( - "import_by_external_nested_vendor.k", - "nested_vendor", - vec![ - "__main__", - "nested_vendor", - "vendor_subpkg", - "vendor_subpkg.sub.sub2", - "vendor_subpkg.sub.sub1", - "vendor_subpkg.sub.sub", - "vendor_subpkg.sub", - ], - ), - ( - "import_by_external_vendor_subpkg.k", - "vendor_subpkg", - vec![ - "__main__", - "vendor_subpkg", - "vendor_subpkg.sub.sub1", - "vendor_subpkg.sub.sub2", - "vendor_subpkg.sub.sub", - "vendor_subpkg.sub", - ], - ), - ]; - - let dir = &PathBuf::from(".") - .join("testdata_without_kclmod") - .canonicalize() - .unwrap(); - - let test_fn = |test_case_name: &&str, - dep_name: &&str, - pkgs: &Vec<&str>, - module_cache: Option| { - let mut opts = LoadProgramOptions::default(); - opts.package_maps.insert( - dep_name.to_string(), - external_dir.join(dep_name).display().to_string(), - ); - let test_case_path = dir - .join(test_case_name) - .display() - .to_string() - .adjust_canonicalization(); - let m = load_program(sess.clone(), &[&test_case_path], None, module_cache) - .unwrap() - .program; - assert_eq!(m.pkgs.len(), pkgs.len()); - m.pkgs.clone().into_iter().for_each(|(name, modules)| { - assert!(pkgs.contains(&name.as_str())); - for pkg in pkgs.clone() { - if name == pkg { - if name == "__main__" { - assert_eq!(modules.len(), 1); - let module = m.get_module(modules.get(0).unwrap()).unwrap().unwrap(); - assert_eq!(module.filename, test_case_path); - } else { - modules.into_iter().for_each(|module| { - let module = m.get_module(&module).unwrap().unwrap(); - assert!(module.filename.contains(&vendor)); - }); - } - break; - } - } - }); - }; - - test_cases - .iter() - .for_each(|(test_case_name, dep_name, pkgs)| test_fn(test_case_name, dep_name, pkgs, None)); - - test_cases - .iter() - .for_each(|(test_case_name, dep_name, pkgs)| { - test_fn(test_case_name, dep_name, pkgs, Some(module_cache.clone())) - }); -} - -#[test] -fn test_get_compile_entries_from_paths() { - let testpath = PathBuf::from("./src/testdata/multimods") - .canonicalize() - .unwrap(); - - // [`kcl1_path`] is a normal path of the package [`kcl1`] root directory. - // It looks like `/xxx/xxx/xxx`. - let kcl1_path = testpath.join("kcl1"); - - // [`kcl2_path`] is a mod relative path of the packege [`kcl2`] root directory. - // It looks like `${kcl2:KCL_MOD}/xxx/xxx` - let kcl2_path = PathBuf::from("${kcl2:KCL_MOD}/main.k"); - - // [`kcl3_path`] is a mod relative path of the [`__main__`] packege. - let kcl3_path = PathBuf::from("${KCL_MOD}/main.k"); - - // [`package_maps`] is a map to show the real path of the mod relative path [`kcl2`]. - let mut opts = LoadProgramOptions::default(); - opts.package_maps.insert( - "kcl2".to_string(), - testpath.join("kcl2").to_str().unwrap().to_string(), - ); - - // [`get_compile_entries_from_paths`] will return the map of package name to package root real path. - let entries = get_compile_entries_from_paths( - &[ - kcl1_path.to_str().unwrap().to_string(), - kcl2_path.display().to_string(), - kcl3_path.display().to_string(), - ], - &opts, - ) - .unwrap(); - - assert_eq!(entries.len(), 3); - - assert_eq!(entries.get_nth_entry(0).unwrap().name(), "__main__"); - assert_eq!( - PathBuf::from(entries.get_nth_entry(0).unwrap().path()) - .canonicalize() - .unwrap() - .display() - .to_string(), - kcl1_path.canonicalize().unwrap().to_str().unwrap() - ); - - assert_eq!(entries.get_nth_entry(1).unwrap().name(), "kcl2"); - assert_eq!( - PathBuf::from(entries.get_nth_entry(1).unwrap().path()) - .canonicalize() - .unwrap() - .display() - .to_string(), - testpath - .join("kcl2") - .canonicalize() - .unwrap() - .to_str() - .unwrap() - ); - - assert_eq!(entries.get_nth_entry(2).unwrap().name(), "__main__"); - assert_eq!( - PathBuf::from(entries.get_nth_entry(2).unwrap().path()) - .canonicalize() - .unwrap() - .to_str() - .unwrap(), - kcl1_path.canonicalize().unwrap().to_str().unwrap() - ); -} - -#[test] -fn test_dir_with_k_code_list() { - let sm = SourceMap::new(FilePathMapping::empty()); - let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); - let testpath = PathBuf::from("./src/testdata/test_k_code_list") - .canonicalize() - .unwrap(); - - let mut opts = LoadProgramOptions::default(); - opts.k_code_list = vec!["test_code = 1".to_string()]; - - match load_program( - sess.clone(), - &[&testpath.display().to_string()], - Some(opts.clone()), - None, - ) { - Ok(_) => panic!("unreachable code"), - Err(err) => assert!(err.to_string().contains("Invalid code list")), - } - - match load_program( - sess.clone(), - &[&testpath.display().to_string()], - Some(opts), - Some(KCLModuleCache::default()), - ) { - Ok(_) => panic!("unreachable code"), - Err(err) => assert!(err.to_string().contains("Invalid code list")), - } -} - -pub fn test_pkg_not_found_suggestion() { - let sm = SourceMap::new(FilePathMapping::empty()); - let sess = Arc::new(ParseSession::with_source_map(Arc::new(sm))); - let dir = &PathBuf::from("./src/testdata/pkg_not_found") - .canonicalize() - .unwrap(); - let test_case_path = dir.join("suggestions.k").display().to_string(); - match load_program(sess.clone(), &[&test_case_path], None, None) { - Ok(_) => { - let errors = sess.classification().0; - let msgs = [ - "pkgpath k9s not found in the program", - "try 'kcl mod add k9s' to download the missing package", - "browse more packages at 'https://artifacthub.io'", - ]; - assert_eq!(errors.len(), msgs.len()); - for (diag, m) in errors.iter().zip(msgs.iter()) { - assert_eq!(diag.messages[0].message, m.to_string()); - } - } - Err(_) => { - panic!("Unreachable code.") - } - } -} - -#[test] -fn test_expand_input_files_with_kcl_mod() { - let path = PathBuf::from("testdata/expand_file_pattern"); - let input_files = vec![ - path.join("**").join("main.k").to_string_lossy().to_string(), - "${KCL_MOD}/testdata/expand_file_pattern/KCL_MOD".to_string(), - ]; - let expected_files = vec![ - path.join("kcl1/kcl2/main.k").to_string_lossy().to_string(), - path.join("kcl1/kcl4/main.k").to_string_lossy().to_string(), - path.join("kcl1/main.k").to_string_lossy().to_string(), - path.join("kcl3/main.k").to_string_lossy().to_string(), - path.join("main.k").to_string_lossy().to_string(), - "${KCL_MOD}/testdata/expand_file_pattern/KCL_MOD".to_string(), - ]; - let got_paths: Vec = expand_input_files(&input_files) - .iter() - .map(|s| s.replace(['/', '\\'], "")) - .collect(); - let expect_paths: Vec = expected_files - .iter() - .map(|s| s.replace(['/', '\\'], "")) - .collect(); - assert_eq!(got_paths, expect_paths); -} - -#[test] -#[cfg(not(windows))] -fn test_expand_input_files() { - let input_files = vec!["./testdata/expand_file_pattern/**/main.k".to_string()]; - let mut expected_files = vec![ - Path::new("testdata/expand_file_pattern/kcl1/kcl2/main.k") - .to_string_lossy() - .to_string(), - Path::new("testdata/expand_file_pattern/kcl3/main.k") - .to_string_lossy() - .to_string(), - Path::new("testdata/expand_file_pattern/main.k") - .to_string_lossy() - .to_string(), - Path::new("testdata/expand_file_pattern/kcl1/main.k") - .to_string_lossy() - .to_string(), - Path::new("testdata/expand_file_pattern/kcl1/kcl4/main.k") - .to_string_lossy() - .to_string(), - ]; - expected_files.sort(); - let mut input = expand_input_files(&input_files); - input.sort(); - assert_eq!(input, expected_files); - - let input_files = vec![ - "./testdata/expand_file_pattern/kcl1/main.k".to_string(), - "./testdata/expand_file_pattern/**/main.k".to_string(), - ]; - let mut expected_files = vec![ - Path::new("testdata/expand_file_pattern/kcl1/main.k") - .to_string_lossy() - .to_string(), - Path::new("testdata/expand_file_pattern/kcl1/main.k") - .to_string_lossy() - .to_string(), - Path::new("testdata/expand_file_pattern/kcl1/kcl2/main.k") - .to_string_lossy() - .to_string(), - Path::new("testdata/expand_file_pattern/kcl1/kcl4/main.k") - .to_string_lossy() - .to_string(), - Path::new("testdata/expand_file_pattern/kcl3/main.k") - .to_string_lossy() - .to_string(), - Path::new("testdata/expand_file_pattern/main.k") - .to_string_lossy() - .to_string(), - ]; - expected_files.sort(); - let mut input = expand_input_files(&input_files); - input.sort(); - assert_eq!(input, expected_files); -} - -#[test] -fn parse_all_file_under_path() { - let testpath = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("testdata") - .join("parse_all_modules"); - - let main = testpath.join("a"); - let main = main.to_str().unwrap(); - let helloworld = testpath.join("helloworld_0.0.1"); - let b = testpath.join("b"); - - let sess = ParseSessionRef::default(); - let mut opt = LoadProgramOptions::default(); - opt.vendor_dirs = vec![get_vendor_home()]; - opt.package_maps - .insert("b".to_string(), b.to_str().unwrap().to_string()); - opt.package_maps.insert( - "helloworld".to_string(), - helloworld.to_str().unwrap().to_string(), - ); - - let res = load_all_files_under_paths(sess.clone(), &[main], Some(opt), None).unwrap(); - - assert_eq!(res.program.pkgs.keys().len(), 1); - assert_eq!(res.program.pkgs_not_imported.keys().len(), 3); - - assert_eq!(res.paths.len(), 1); -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__assign_stmt.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__assign_stmt.snap deleted file mode 100644 index 25c93ab3e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__assign_stmt.snap +++ /dev/null @@ -1,58 +0,0 @@ ---- -source: parser/src/tests/ast.rs -expression: "crate::tests::parsing_file_ast_json(\"hello.k\", r####\"a=123\"####)" ---- -{ - "filename": "hello.k", - "doc": null, - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "a", - "filename": "hello.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 1 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "hello.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 1 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 123 - } - }, - "filename": "hello.k", - "line": 1, - "column": 2, - "end_line": 1, - "end_column": 5 - }, - "ty": null - }, - "filename": "hello.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 5 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__basic_stmt.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__basic_stmt.snap deleted file mode 100644 index 79fe9b520..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__basic_stmt.snap +++ /dev/null @@ -1,193 +0,0 @@ ---- -source: parser/src/tests/ast.rs -expression: "crate::tests::parsing_file_ast_json(\"hello.k\",\n r####\"\n# comment1\na = 1\n# comment22\nb = 2\n# comment333\nc = 3 # comment4444\n \"####)" ---- -{ - "filename": "hello.k", - "doc": null, - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "a", - "filename": "hello.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 1 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "hello.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 1 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "hello.k", - "line": 3, - "column": 4, - "end_line": 3, - "end_column": 5 - }, - "ty": null - }, - "filename": "hello.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 5 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "b", - "filename": "hello.k", - "line": 5, - "column": 0, - "end_line": 5, - "end_column": 1 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "hello.k", - "line": 5, - "column": 0, - "end_line": 5, - "end_column": 1 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 2 - } - }, - "filename": "hello.k", - "line": 5, - "column": 4, - "end_line": 5, - "end_column": 5 - }, - "ty": null - }, - "filename": "hello.k", - "line": 5, - "column": 0, - "end_line": 5, - "end_column": 5 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "c", - "filename": "hello.k", - "line": 7, - "column": 0, - "end_line": 7, - "end_column": 1 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "hello.k", - "line": 7, - "column": 0, - "end_line": 7, - "end_column": 1 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 3 - } - }, - "filename": "hello.k", - "line": 7, - "column": 4, - "end_line": 7, - "end_column": 5 - }, - "ty": null - }, - "filename": "hello.k", - "line": 7, - "column": 0, - "end_line": 7, - "end_column": 5 - } - ], - "comments": [ - { - "node": { - "text": "# comment1" - }, - "filename": "hello.k", - "line": 2, - "column": 0, - "end_line": 2, - "end_column": 10 - }, - { - "node": { - "text": "# comment22" - }, - "filename": "hello.k", - "line": 4, - "column": 0, - "end_line": 4, - "end_column": 11 - }, - { - "node": { - "text": "# comment333" - }, - "filename": "hello.k", - "line": 6, - "column": 0, - "end_line": 6, - "end_column": 12 - }, - { - "node": { - "text": "# comment4444" - }, - "filename": "hello.k", - "line": 7, - "column": 6, - "end_line": 7, - "end_column": 19 - } - ] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__if_stmt_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__if_stmt_0.snap deleted file mode 100644 index 63e1e6b78..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__if_stmt_0.snap +++ /dev/null @@ -1,557 +0,0 @@ ---- -source: parser/src/tests/ast.rs -expression: "crate::tests::parsing_file_ast_json(\"hello.k\",\n r####\"\na = 10\nb = 12\n_condition = 0\nif a == 11 or b == 13: _condition = 1\nelif a == 10 and b == 12: _condition = 2\ncondition = _condition\n \"####)" ---- -{ - "filename": "hello.k", - "doc": null, - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "a", - "filename": "hello.k", - "line": 2, - "column": 0, - "end_line": 2, - "end_column": 1 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "hello.k", - "line": 2, - "column": 0, - "end_line": 2, - "end_column": 1 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 10 - } - }, - "filename": "hello.k", - "line": 2, - "column": 4, - "end_line": 2, - "end_column": 6 - }, - "ty": null - }, - "filename": "hello.k", - "line": 2, - "column": 0, - "end_line": 2, - "end_column": 6 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "b", - "filename": "hello.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 1 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "hello.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 1 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 12 - } - }, - "filename": "hello.k", - "line": 3, - "column": 4, - "end_line": 3, - "end_column": 6 - }, - "ty": null - }, - "filename": "hello.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 6 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "_condition", - "filename": "hello.k", - "line": 4, - "column": 0, - "end_line": 4, - "end_column": 10 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "hello.k", - "line": 4, - "column": 0, - "end_line": 4, - "end_column": 10 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 0 - } - }, - "filename": "hello.k", - "line": 4, - "column": 13, - "end_line": 4, - "end_column": 14 - }, - "ty": null - }, - "filename": "hello.k", - "line": 4, - "column": 0, - "end_line": 4, - "end_column": 14 - }, - { - "node": { - "type": "If", - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "_condition", - "filename": "hello.k", - "line": 5, - "column": 23, - "end_line": 5, - "end_column": 33 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "hello.k", - "line": 5, - "column": 23, - "end_line": 5, - "end_column": 33 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "hello.k", - "line": 5, - "column": 36, - "end_line": 5, - "end_column": 37 - }, - "ty": null - }, - "filename": "hello.k", - "line": 5, - "column": 23, - "end_line": 5, - "end_column": 37 - } - ], - "cond": { - "node": { - "type": "Binary", - "left": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "a", - "filename": "hello.k", - "line": 5, - "column": 3, - "end_line": 5, - "end_column": 4 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 5, - "column": 3, - "end_line": 5, - "end_column": 4 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 11 - } - }, - "filename": "hello.k", - "line": 5, - "column": 8, - "end_line": 5, - "end_column": 10 - } - ] - }, - "filename": "hello.k", - "line": 5, - "column": 3, - "end_line": 5, - "end_column": 21 - }, - "op": "Or", - "right": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "b", - "filename": "hello.k", - "line": 5, - "column": 14, - "end_line": 5, - "end_column": 15 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 5, - "column": 14, - "end_line": 5, - "end_column": 15 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 13 - } - }, - "filename": "hello.k", - "line": 5, - "column": 19, - "end_line": 5, - "end_column": 21 - } - ] - }, - "filename": "hello.k", - "line": 5, - "column": 14, - "end_line": 5, - "end_column": 21 - } - }, - "filename": "hello.k", - "line": 5, - "column": 3, - "end_line": 5, - "end_column": 21 - }, - "orelse": [ - { - "node": { - "type": "If", - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "_condition", - "filename": "hello.k", - "line": 6, - "column": 26, - "end_line": 6, - "end_column": 36 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "hello.k", - "line": 6, - "column": 26, - "end_line": 6, - "end_column": 36 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 2 - } - }, - "filename": "hello.k", - "line": 6, - "column": 39, - "end_line": 6, - "end_column": 40 - }, - "ty": null - }, - "filename": "hello.k", - "line": 6, - "column": 26, - "end_line": 6, - "end_column": 40 - } - ], - "cond": { - "node": { - "type": "Binary", - "left": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "a", - "filename": "hello.k", - "line": 6, - "column": 5, - "end_line": 6, - "end_column": 6 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 6, - "column": 5, - "end_line": 6, - "end_column": 6 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 10 - } - }, - "filename": "hello.k", - "line": 6, - "column": 10, - "end_line": 6, - "end_column": 12 - } - ] - }, - "filename": "hello.k", - "line": 6, - "column": 5, - "end_line": 6, - "end_column": 24 - }, - "op": "And", - "right": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "b", - "filename": "hello.k", - "line": 6, - "column": 17, - "end_line": 6, - "end_column": 18 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 6, - "column": 17, - "end_line": 6, - "end_column": 18 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 12 - } - }, - "filename": "hello.k", - "line": 6, - "column": 22, - "end_line": 6, - "end_column": 24 - } - ] - }, - "filename": "hello.k", - "line": 6, - "column": 17, - "end_line": 6, - "end_column": 24 - } - }, - "filename": "hello.k", - "line": 6, - "column": 5, - "end_line": 6, - "end_column": 24 - }, - "orelse": [] - }, - "filename": "hello.k", - "line": 6, - "column": 0, - "end_line": 7, - "end_column": 0 - } - ] - }, - "filename": "hello.k", - "line": 5, - "column": 0, - "end_line": 7, - "end_column": 0 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "condition", - "filename": "hello.k", - "line": 7, - "column": 0, - "end_line": 7, - "end_column": 9 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "hello.k", - "line": 7, - "column": 0, - "end_line": 7, - "end_column": 9 - } - ], - "value": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "_condition", - "filename": "hello.k", - "line": 7, - "column": 12, - "end_line": 7, - "end_column": 22 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 7, - "column": 12, - "end_line": 7, - "end_column": 22 - }, - "ty": null - }, - "filename": "hello.k", - "line": 7, - "column": 0, - "end_line": 7, - "end_column": 22 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__if_stmt_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__if_stmt_1.snap deleted file mode 100644 index ebb01527c..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__if_stmt_1.snap +++ /dev/null @@ -1,320 +0,0 @@ ---- -source: parser/src/tests/ast.rs -expression: "crate::tests::parsing_file_ast_json(\"hello.k\",\n r####\"\ndata2 = {\n **{key = \"value1\"}\n if a == 123: if b == 456: key = \"value2\"\n}\n \"####)" ---- -{ - "filename": "hello.k", - "doc": null, - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "data2", - "filename": "hello.k", - "line": 2, - "column": 0, - "end_line": 2, - "end_column": 5 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "hello.k", - "line": 2, - "column": 0, - "end_line": 2, - "end_column": 5 - } - ], - "value": { - "node": { - "type": "Config", - "items": [ - { - "node": { - "key": null, - "value": { - "node": { - "type": "Config", - "items": [ - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "key", - "filename": "hello.k", - "line": 3, - "column": 7, - "end_line": 3, - "end_column": 10 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 3, - "column": 7, - "end_line": 3, - "end_column": 10 - }, - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"value1\"", - "value": "value1" - }, - "filename": "hello.k", - "line": 3, - "column": 13, - "end_line": 3, - "end_column": 21 - }, - "operation": "Override" - }, - "filename": "hello.k", - "line": 3, - "column": 7, - "end_line": 3, - "end_column": 21 - } - ] - }, - "filename": "hello.k", - "line": 3, - "column": 6, - "end_line": 3, - "end_column": 22 - }, - "operation": "Union" - }, - "filename": "hello.k", - "line": 3, - "column": 4, - "end_line": 3, - "end_column": 22 - }, - { - "node": { - "key": null, - "value": { - "node": { - "type": "ConfigIfEntry", - "if_cond": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "a", - "filename": "hello.k", - "line": 4, - "column": 7, - "end_line": 4, - "end_column": 8 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 4, - "column": 7, - "end_line": 4, - "end_column": 8 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 123 - } - }, - "filename": "hello.k", - "line": 4, - "column": 12, - "end_line": 4, - "end_column": 15 - } - ] - }, - "filename": "hello.k", - "line": 4, - "column": 7, - "end_line": 4, - "end_column": 15 - }, - "items": [ - { - "node": { - "key": null, - "value": { - "node": { - "type": "ConfigIfEntry", - "if_cond": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "b", - "filename": "hello.k", - "line": 4, - "column": 20, - "end_line": 4, - "end_column": 21 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 4, - "column": 20, - "end_line": 4, - "end_column": 21 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 456 - } - }, - "filename": "hello.k", - "line": 4, - "column": 25, - "end_line": 4, - "end_column": 28 - } - ] - }, - "filename": "hello.k", - "line": 4, - "column": 20, - "end_line": 4, - "end_column": 28 - }, - "items": [ - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "key", - "filename": "hello.k", - "line": 4, - "column": 30, - "end_line": 4, - "end_column": 33 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 4, - "column": 30, - "end_line": 4, - "end_column": 33 - }, - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"value2\"", - "value": "value2" - }, - "filename": "hello.k", - "line": 4, - "column": 36, - "end_line": 4, - "end_column": 44 - }, - "operation": "Override" - }, - "filename": "hello.k", - "line": 4, - "column": 30, - "end_line": 4, - "end_column": 44 - } - ], - "orelse": null - }, - "filename": "hello.k", - "line": 4, - "column": 17, - "end_line": 5, - "end_column": 0 - }, - "operation": "Override" - }, - "filename": "hello.k", - "line": 4, - "column": 17, - "end_line": 5, - "end_column": 0 - } - ], - "orelse": null - }, - "filename": "hello.k", - "line": 4, - "column": 4, - "end_line": 5, - "end_column": 0 - }, - "operation": "Union" - }, - "filename": "hello.k", - "line": 4, - "column": 4, - "end_line": 5, - "end_column": 0 - } - ] - }, - "filename": "hello.k", - "line": 2, - "column": 8, - "end_line": 5, - "end_column": 1 - }, - "ty": null - }, - "filename": "hello.k", - "line": 2, - "column": 0, - "end_line": 5, - "end_column": 1 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__schema_stmt.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__schema_stmt.snap deleted file mode 100644 index c780457af..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__ast__schema_stmt.snap +++ /dev/null @@ -1,913 +0,0 @@ ---- -source: parser/src/tests/ast.rs -expression: "crate::tests::parsing_file_ast_json(\"hello.k\",\n r####\"\nschema TestBool:\n []\n [str ]: int\n [a: str]: int\n [a: ...str]: int\n [...str]: int\n a: int\n b?: str\n c: int = 0\n d?: str = \"\"\n\n [a]\n [a, b, c]\n [\n 1\n ]\n [\n a\n ]\n [a for a in [1, 2, 3]]\n [\n a for a in [1, 2, 3]\n ]\n\n check:\n a > 1, \"msg\"\n name not None, \"we fail here\"\n \"####)" ---- -{ - "filename": "hello.k", - "doc": null, - "body": [ - { - "node": { - "type": "Schema", - "doc": null, - "name": { - "node": "TestBool", - "filename": "hello.k", - "line": 2, - "column": 7, - "end_line": 2, - "end_column": 15 - }, - "parent_name": null, - "for_host_name": null, - "is_mixin": false, - "is_protocol": false, - "args": null, - "mixins": [], - "body": [ - { - "node": { - "type": "Expr", - "exprs": [ - { - "node": { - "type": "List", - "elts": [], - "ctx": "Load" - }, - "filename": "hello.k", - "line": 3, - "column": 4, - "end_line": 3, - "end_column": 6 - } - ] - }, - "filename": "hello.k", - "line": 3, - "column": 4, - "end_line": 3, - "end_column": 6 - }, - { - "node": { - "type": "SchemaAttr", - "doc": "", - "name": { - "node": "a", - "filename": "hello.k", - "line": 8, - "column": 4, - "end_line": 8, - "end_column": 5 - }, - "op": null, - "value": null, - "is_optional": false, - "decorators": [], - "ty": { - "node": { - "type": "Basic", - "value": "Int" - }, - "filename": "hello.k", - "line": 8, - "column": 7, - "end_line": 8, - "end_column": 10 - } - }, - "filename": "hello.k", - "line": 8, - "column": 4, - "end_line": 8, - "end_column": 10 - }, - { - "node": { - "type": "SchemaAttr", - "doc": "", - "name": { - "node": "b", - "filename": "hello.k", - "line": 9, - "column": 4, - "end_line": 9, - "end_column": 5 - }, - "op": null, - "value": null, - "is_optional": true, - "decorators": [], - "ty": { - "node": { - "type": "Basic", - "value": "Str" - }, - "filename": "hello.k", - "line": 9, - "column": 8, - "end_line": 9, - "end_column": 11 - } - }, - "filename": "hello.k", - "line": 9, - "column": 4, - "end_line": 10, - "end_column": 0 - }, - { - "node": { - "type": "SchemaAttr", - "doc": "", - "name": { - "node": "c", - "filename": "hello.k", - "line": 10, - "column": 4, - "end_line": 10, - "end_column": 5 - }, - "op": "Assign", - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 0 - } - }, - "filename": "hello.k", - "line": 10, - "column": 13, - "end_line": 10, - "end_column": 14 - }, - "is_optional": false, - "decorators": [], - "ty": { - "node": { - "type": "Basic", - "value": "Int" - }, - "filename": "hello.k", - "line": 10, - "column": 7, - "end_line": 10, - "end_column": 10 - } - }, - "filename": "hello.k", - "line": 10, - "column": 4, - "end_line": 10, - "end_column": 14 - }, - { - "node": { - "type": "SchemaAttr", - "doc": "", - "name": { - "node": "d", - "filename": "hello.k", - "line": 11, - "column": 4, - "end_line": 11, - "end_column": 5 - }, - "op": "Assign", - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"\"", - "value": "" - }, - "filename": "hello.k", - "line": 11, - "column": 14, - "end_line": 11, - "end_column": 16 - }, - "is_optional": true, - "decorators": [], - "ty": { - "node": { - "type": "Basic", - "value": "Str" - }, - "filename": "hello.k", - "line": 11, - "column": 8, - "end_line": 11, - "end_column": 11 - } - }, - "filename": "hello.k", - "line": 11, - "column": 4, - "end_line": 13, - "end_column": 0 - }, - { - "node": { - "type": "Expr", - "exprs": [ - { - "node": { - "type": "List", - "elts": [ - { - "node": { - "type": "Identifier", - "names": [ - { - "node": "a", - "filename": "hello.k", - "line": 13, - "column": 5, - "end_line": 13, - "end_column": 6 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 13, - "column": 5, - "end_line": 13, - "end_column": 6 - } - ], - "ctx": "Load" - }, - "filename": "hello.k", - "line": 13, - "column": 4, - "end_line": 13, - "end_column": 7 - } - ] - }, - "filename": "hello.k", - "line": 13, - "column": 4, - "end_line": 13, - "end_column": 7 - }, - { - "node": { - "type": "Expr", - "exprs": [ - { - "node": { - "type": "List", - "elts": [ - { - "node": { - "type": "Identifier", - "names": [ - { - "node": "a", - "filename": "hello.k", - "line": 14, - "column": 5, - "end_line": 14, - "end_column": 6 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 14, - "column": 5, - "end_line": 14, - "end_column": 6 - }, - { - "node": { - "type": "Identifier", - "names": [ - { - "node": "b", - "filename": "hello.k", - "line": 14, - "column": 8, - "end_line": 14, - "end_column": 9 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 14, - "column": 8, - "end_line": 14, - "end_column": 9 - }, - { - "node": { - "type": "Identifier", - "names": [ - { - "node": "c", - "filename": "hello.k", - "line": 14, - "column": 11, - "end_line": 14, - "end_column": 12 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 14, - "column": 11, - "end_line": 14, - "end_column": 12 - } - ], - "ctx": "Load" - }, - "filename": "hello.k", - "line": 14, - "column": 4, - "end_line": 14, - "end_column": 13 - } - ] - }, - "filename": "hello.k", - "line": 14, - "column": 4, - "end_line": 14, - "end_column": 13 - }, - { - "node": { - "type": "Expr", - "exprs": [ - { - "node": { - "type": "List", - "elts": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "hello.k", - "line": 16, - "column": 8, - "end_line": 16, - "end_column": 9 - } - ], - "ctx": "Load" - }, - "filename": "hello.k", - "line": 15, - "column": 4, - "end_line": 17, - "end_column": 5 - } - ] - }, - "filename": "hello.k", - "line": 15, - "column": 4, - "end_line": 17, - "end_column": 5 - }, - { - "node": { - "type": "Expr", - "exprs": [ - { - "node": { - "type": "List", - "elts": [ - { - "node": { - "type": "Identifier", - "names": [ - { - "node": "a", - "filename": "hello.k", - "line": 19, - "column": 8, - "end_line": 19, - "end_column": 9 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 19, - "column": 8, - "end_line": 19, - "end_column": 9 - } - ], - "ctx": "Load" - }, - "filename": "hello.k", - "line": 18, - "column": 4, - "end_line": 20, - "end_column": 5 - } - ] - }, - "filename": "hello.k", - "line": 18, - "column": 4, - "end_line": 20, - "end_column": 5 - }, - { - "node": { - "type": "Expr", - "exprs": [ - { - "node": { - "type": "ListComp", - "elt": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "a", - "filename": "hello.k", - "line": 21, - "column": 5, - "end_line": 21, - "end_column": 6 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 21, - "column": 5, - "end_line": 21, - "end_column": 6 - }, - "generators": [ - { - "node": { - "targets": [ - { - "node": { - "names": [ - { - "node": "a", - "filename": "hello.k", - "line": 21, - "column": 11, - "end_line": 21, - "end_column": 12 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 21, - "column": 11, - "end_line": 21, - "end_column": 12 - } - ], - "iter": { - "node": { - "type": "List", - "elts": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "hello.k", - "line": 21, - "column": 17, - "end_line": 21, - "end_column": 18 - }, - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 2 - } - }, - "filename": "hello.k", - "line": 21, - "column": 20, - "end_line": 21, - "end_column": 21 - }, - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 3 - } - }, - "filename": "hello.k", - "line": 21, - "column": 23, - "end_line": 21, - "end_column": 24 - } - ], - "ctx": "Load" - }, - "filename": "hello.k", - "line": 21, - "column": 16, - "end_line": 21, - "end_column": 25 - }, - "ifs": [] - }, - "filename": "hello.k", - "line": 21, - "column": 7, - "end_line": 21, - "end_column": 25 - } - ] - }, - "filename": "hello.k", - "line": 21, - "column": 4, - "end_line": 21, - "end_column": 26 - } - ] - }, - "filename": "hello.k", - "line": 21, - "column": 4, - "end_line": 21, - "end_column": 26 - }, - { - "node": { - "type": "Expr", - "exprs": [ - { - "node": { - "type": "ListComp", - "elt": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "a", - "filename": "hello.k", - "line": 23, - "column": 8, - "end_line": 23, - "end_column": 9 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 23, - "column": 8, - "end_line": 23, - "end_column": 9 - }, - "generators": [ - { - "node": { - "targets": [ - { - "node": { - "names": [ - { - "node": "a", - "filename": "hello.k", - "line": 23, - "column": 14, - "end_line": 23, - "end_column": 15 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 23, - "column": 14, - "end_line": 23, - "end_column": 15 - } - ], - "iter": { - "node": { - "type": "List", - "elts": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "hello.k", - "line": 23, - "column": 20, - "end_line": 23, - "end_column": 21 - }, - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 2 - } - }, - "filename": "hello.k", - "line": 23, - "column": 23, - "end_line": 23, - "end_column": 24 - }, - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 3 - } - }, - "filename": "hello.k", - "line": 23, - "column": 26, - "end_line": 23, - "end_column": 27 - } - ], - "ctx": "Load" - }, - "filename": "hello.k", - "line": 23, - "column": 19, - "end_line": 23, - "end_column": 28 - }, - "ifs": [] - }, - "filename": "hello.k", - "line": 23, - "column": 10, - "end_line": 24, - "end_column": 0 - } - ] - }, - "filename": "hello.k", - "line": 22, - "column": 4, - "end_line": 24, - "end_column": 5 - } - ] - }, - "filename": "hello.k", - "line": 22, - "column": 4, - "end_line": 24, - "end_column": 5 - } - ], - "decorators": [], - "checks": [ - { - "node": { - "test": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "a", - "filename": "hello.k", - "line": 27, - "column": 8, - "end_line": 27, - "end_column": 9 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 27, - "column": 8, - "end_line": 27, - "end_column": 9 - }, - "ops": [ - "Gt" - ], - "comparators": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "hello.k", - "line": 27, - "column": 12, - "end_line": 27, - "end_column": 13 - } - ] - }, - "filename": "hello.k", - "line": 27, - "column": 8, - "end_line": 27, - "end_column": 13 - }, - "if_cond": null, - "msg": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"msg\"", - "value": "msg" - }, - "filename": "hello.k", - "line": 27, - "column": 15, - "end_line": 27, - "end_column": 20 - } - }, - "filename": "hello.k", - "line": 27, - "column": 8, - "end_line": 27, - "end_column": 20 - }, - { - "node": { - "test": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "name", - "filename": "hello.k", - "line": 28, - "column": 8, - "end_line": 28, - "end_column": 12 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello.k", - "line": 28, - "column": 8, - "end_line": 28, - "end_column": 12 - }, - "if_cond": null, - "msg": null - }, - "filename": "hello.k", - "line": 28, - "column": 8, - "end_line": 28, - "end_column": 12 - }, - { - "node": { - "test": { - "node": { - "type": "Unary", - "op": "Not", - "operand": { - "node": { - "type": "NameConstantLit", - "value": "None" - }, - "filename": "hello.k", - "line": 28, - "column": 17, - "end_line": 28, - "end_column": 21 - } - }, - "filename": "hello.k", - "line": 28, - "column": 13, - "end_line": 28, - "end_column": 21 - }, - "if_cond": null, - "msg": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"we fail here\"", - "value": "we fail here" - }, - "filename": "hello.k", - "line": 28, - "column": 23, - "end_line": 28, - "end_column": 37 - } - }, - "filename": "hello.k", - "line": 28, - "column": 13, - "end_line": 28, - "end_column": 37 - } - ], - "index_signature": { - "node": { - "key_name": null, - "value": null, - "any_other": true, - "key_ty": { - "node": { - "type": "Basic", - "value": "Str" - }, - "filename": "hello.k", - "line": 7, - "column": 8, - "end_line": 7, - "end_column": 11 - }, - "value_ty": { - "node": { - "type": "Basic", - "value": "Int" - }, - "filename": "hello.k", - "line": 7, - "column": 14, - "end_line": 7, - "end_column": 17 - } - }, - "filename": "hello.k", - "line": 7, - "column": 4, - "end_line": 8, - "end_column": 0 - } - }, - "filename": "hello.k", - "line": 2, - "column": 0, - "end_line": 29, - "end_column": 8 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assert_stmt_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assert_stmt_recovery_0.snap deleted file mode 100644 index 9c09f887d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assert_stmt_recovery_0.snap +++ /dev/null @@ -1,34 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"assert\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assert( - AssertStmt { - test: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - if_cond: None, - msg: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assert_stmt_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assert_stmt_recovery_1.snap deleted file mode 100644 index bc5b75397..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assert_stmt_recovery_1.snap +++ /dev/null @@ -1,55 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"assert a.\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assert( - AssertStmt { - test: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - Node { - node: "", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 9, - }, - if_cond: None, - msg: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assert_stmt_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assert_stmt_recovery_2.snap deleted file mode 100644 index bbda939cc..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assert_stmt_recovery_2.snap +++ /dev/null @@ -1,74 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"assert True,,, 'msg'\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assert( - AssertStmt { - test: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 11, - }, - if_cond: None, - msg: Some( - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 13, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'msg'", - value: "msg", - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 20, - }, - ], - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 20, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assert_stmt_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assert_stmt_recovery_3.snap deleted file mode 100644 index cd30623eb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assert_stmt_recovery_3.snap +++ /dev/null @@ -1,123 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"assert True if data else 'msg'\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assert( - AssertStmt { - test: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 11, - }, - if_cond: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "data", - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 19, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 19, - }, - ), - msg: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 19, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "else", - filename: "", - line: 1, - column: 20, - end_line: 1, - end_column: 24, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 20, - end_line: 1, - end_column: 24, - }, - ], - }, - ), - filename: "", - line: 1, - column: 20, - end_line: 1, - end_column: 24, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'msg'", - value: "msg", - }, - ), - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 30, - }, - ], - }, - ), - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 30, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_0.snap deleted file mode 100644 index 6951e9b94..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_0.snap +++ /dev/null @@ -1,54 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a = \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_1.snap deleted file mode 100644 index 5c468008e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_1.snap +++ /dev/null @@ -1,39 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\" = 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_10.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_10.snap deleted file mode 100644 index 2f4e3439a..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_10.snap +++ /dev/null @@ -1,75 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a[0] -= 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: AugAssign( - AugAssignStmt { - target: Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [ - Index( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - ], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, - }, - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - op: Sub, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_11.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_11.snap deleted file mode 100644 index a645f9dcb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_11.snap +++ /dev/null @@ -1,85 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a[0].b -= 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: AugAssign( - AugAssignStmt { - target: Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [ - Index( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - Member( - Node { - node: "b", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ), - ], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - op: Sub, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_12.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_12.snap deleted file mode 100644 index 5a184e372..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_12.snap +++ /dev/null @@ -1,87 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a.b[0] = 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [ - Member( - Node { - node: "b", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - Index( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - ], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 10, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_13.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_13.snap deleted file mode 100644 index edc868d44..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_13.snap +++ /dev/null @@ -1,39 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a().b = 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_14.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_14.snap deleted file mode 100644 index 2f7c2a746..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_14.snap +++ /dev/null @@ -1,39 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a.b[1:2] = 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 12, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_15.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_15.snap deleted file mode 100644 index e078d719c..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_15.snap +++ /dev/null @@ -1,39 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a.b[1::2].c = 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 15, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 15, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_16.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_16.snap deleted file mode 100644 index 194969bad..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_16.snap +++ /dev/null @@ -1,113 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a.b[c.d].e = 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [ - Member( - Node { - node: "b", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - Index( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "c", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - Node { - node: "d", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ), - Member( - Node { - node: "e", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - ), - ], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 10, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 14, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_17.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_17.snap deleted file mode 100644 index 0e86e730d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_17.snap +++ /dev/null @@ -1,124 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a.b[1 + 1].e = 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [ - Member( - Node { - node: "b", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - Index( - Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 9, - }, - ), - Member( - Node { - node: "e", - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 12, - }, - ), - ], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 16, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 16, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_18.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_18.snap deleted file mode 100644 index 357af11a9..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_18.snap +++ /dev/null @@ -1,118 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a.b[f()].e = 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [ - Member( - Node { - node: "b", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - Index( - Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "f", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - args: [], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ), - Member( - Node { - node: "e", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - ), - ], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 10, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 14, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_2.snap deleted file mode 100644 index 53e11fbb5..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_2.snap +++ /dev/null @@ -1,65 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a: int =\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 8, - }, - ty: Some( - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_3.snap deleted file mode 100644 index 07cdee130..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_3.snap +++ /dev/null @@ -1,83 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a: a = 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ty: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_4.snap deleted file mode 100644 index a57200e48..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_4.snap +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 2, - }, - ty: Some( - Node { - node: Any, - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 2, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_5.snap deleted file mode 100644 index 9086a33ef..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_5.snap +++ /dev/null @@ -1,73 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a = b = \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - Node { - node: Target { - name: Node { - node: "b", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 8, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_6.snap deleted file mode 100644 index edd7b68e7..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_6.snap +++ /dev/null @@ -1,78 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a() = b. = c\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "b", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - paths: [ - Member( - Node { - node: "", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 9, - }, - ), - ], - pkgpath: "", - }, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 8, - }, - ], - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "c", - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 12, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 12, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_7.snap deleted file mode 100644 index 027ddcbd3..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_7.snap +++ /dev/null @@ -1,73 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a: () = 0\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: None, - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 5, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_8.snap deleted file mode 100644 index 027ddcbd3..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_8.snap +++ /dev/null @@ -1,73 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a: () = 0\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: None, - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 5, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_9.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_9.snap deleted file mode 100644 index fdca2e151..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__assign_stmt_recovery_9.snap +++ /dev/null @@ -1,10 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a ++= 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_0.snap deleted file mode 100644 index bd7c6ee1d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_0.snap +++ /dev/null @@ -1,28 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a not is b\"#)" ---- -Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_1.snap deleted file mode 100644 index c216df331..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_1.snap +++ /dev/null @@ -1,67 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a is is not b\"#)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ops: [ - Is, - ], - comparators: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "is", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_2.snap deleted file mode 100644 index 977b93b43..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_2.snap +++ /dev/null @@ -1,28 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a not b\"#)" ---- -Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_3.snap deleted file mode 100644 index bf68b34e3..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_3.snap +++ /dev/null @@ -1,28 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a not is in b\"#)" ---- -Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_4.snap deleted file mode 100644 index d4b9948ff..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_4.snap +++ /dev/null @@ -1,67 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a in in b\"#)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ops: [ - In, - ], - comparators: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "in", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_5.snap deleted file mode 100644 index c597b6281..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_5.snap +++ /dev/null @@ -1,75 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a ++ b\"#)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - op: Add, - right: Node { - node: Unary( - UnaryExpr { - op: UAdd, - operand: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_6.snap deleted file mode 100644 index ad0ad2629..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_6.snap +++ /dev/null @@ -1,97 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a -not- b\"#)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - op: Sub, - right: Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - op: Sub, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_7.snap deleted file mode 100644 index 1f0594d49..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_7.snap +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a +is b\"#)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - op: Add, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "is", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 5, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_8.snap deleted file mode 100644 index e76e3f815..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__binary_recovery_8.snap +++ /dev/null @@ -1,28 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a +=+ b\"#)" ---- -Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_0.snap deleted file mode 100644 index dea4d3cfd..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_0.snap +++ /dev/null @@ -1,40 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a(\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_1.snap deleted file mode 100644 index bdfd9fb5a..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_1.snap +++ /dev/null @@ -1,41 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a(]\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_10.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_10.snap deleted file mode 100644 index 431ffacfc..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_10.snap +++ /dev/null @@ -1,71 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a(\n 1,\n 2\n)\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - ], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_11.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_11.snap deleted file mode 100644 index 1cb2cce40..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_11.snap +++ /dev/null @@ -1,71 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a(\n 1,\n2,\n)\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 3, - column: 0, - end_line: 3, - end_column: 1, - }, - ], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_12.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_12.snap deleted file mode 100644 index 1cb2cce40..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_12.snap +++ /dev/null @@ -1,71 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a(\n 1,\n2,\n)\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 3, - column: 0, - end_line: 3, - end_column: 1, - }, - ], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_13.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_13.snap deleted file mode 100644 index c3099f749..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_13.snap +++ /dev/null @@ -1,71 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a(\n 1,,\n2,\n)\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 3, - column: 0, - end_line: 3, - end_column: 1, - }, - ], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_14.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_14.snap deleted file mode 100644 index 1e37e5050..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_14.snap +++ /dev/null @@ -1,71 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a(\n 1,\n 2,\n]\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - ], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_2.snap deleted file mode 100644 index 80b7358cc..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_2.snap +++ /dev/null @@ -1,64 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a(a,,)\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_3.snap deleted file mode 100644 index e853ca663..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_3.snap +++ /dev/null @@ -1,113 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a.b(a=1,2)\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - Node { - node: "b", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ], - keywords: [ - Node { - node: Keyword { - arg: Node { - node: Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - value: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ), - }, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 10, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_4.snap deleted file mode 100644 index 174c24666..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_4.snap +++ /dev/null @@ -1,113 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a(a.ba=1,2)\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - ], - keywords: [ - Node { - node: Keyword { - arg: Node { - node: Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - Node { - node: "ba", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 6, - }, - value: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ), - }, - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 8, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_5.snap deleted file mode 100644 index b279a496b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_5.snap +++ /dev/null @@ -1,96 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a(a.b+a=1,2)\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - ], - keywords: [ - Node { - node: Keyword { - arg: Node { - node: Identifier { - names: [], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 7, - }, - value: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ), - }, - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 9, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_6.snap deleted file mode 100644 index 0b7e629f4..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_6.snap +++ /dev/null @@ -1,80 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a(a-1.b=1)\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [], - keywords: [ - Node { - node: Keyword { - arg: Node { - node: Identifier { - names: [], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 7, - }, - value: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ), - }, - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 9, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 10, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_7.snap deleted file mode 100644 index 064b56799..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_7.snap +++ /dev/null @@ -1,103 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a(type=\"list\", \"key\")\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"key\"", - value: "key", - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 20, - }, - ], - keywords: [ - Node { - node: Keyword { - arg: Node { - node: Identifier { - names: [ - Node { - node: "type", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 6, - }, - value: Some( - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"list\"", - value: "list", - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 13, - }, - ), - }, - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 13, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 21, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_8.snap deleted file mode 100644 index 3451c9c7c..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_8.snap +++ /dev/null @@ -1,71 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a(\n 1,2\n)\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 2, - column: 6, - end_line: 2, - end_column: 7, - }, - ], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 3, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_9.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_9.snap deleted file mode 100644 index 7610c0fe1..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__call_recovery_9.snap +++ /dev/null @@ -1,71 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a(1,2\n)\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_0.snap deleted file mode 100644 index 8a232b432..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_0.snap +++ /dev/null @@ -1,133 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"[i for i in [1,2,3]]\")" ---- -Node { - node: ListComp( - ListComp { - elt: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - generators: [ - Node { - node: CompClause { - targets: [ - Node { - node: Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - iter: Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 16, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 17, - end_line: 1, - end_column: 18, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 19, - }, - ifs: [], - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 19, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 20, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_1.snap deleted file mode 100644 index 4d07d7700..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_1.snap +++ /dev/null @@ -1,133 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"[i, j for i in [1,2,3]]\")" ---- -Node { - node: ListComp( - ListComp { - elt: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - generators: [ - Node { - node: CompClause { - targets: [ - Node { - node: Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - ], - iter: Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 17, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 18, - end_line: 1, - end_column: 19, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 20, - end_line: 1, - end_column: 21, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 22, - }, - ifs: [], - }, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 22, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 23, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_2.snap deleted file mode 100644 index ff66fec1f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_2.snap +++ /dev/null @@ -1,19 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 73 -expression: "crate::tests::parsing_expr_string(\"[for i in [1,2,3]]\")" ---- -Node { - node: List( - ListExpr { - elts: [], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 18, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_3.snap deleted file mode 100644 index 37b66105d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_3.snap +++ /dev/null @@ -1,150 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{i for i in [1,2,3]}\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ), - value: Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ops: [ - In, - ], - comparators: [ - Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 16, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 17, - end_line: 1, - end_column: 18, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 19, - }, - ], - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 19, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 19, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 20, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_4.snap deleted file mode 100644 index d70188e8f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_4.snap +++ /dev/null @@ -1,195 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{i: for i in [1,2,3]}\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ), - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "for", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - operation: Union, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 7, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ops: [ - In, - ], - comparators: [ - Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 15, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 17, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 18, - end_line: 1, - end_column: 19, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 20, - }, - ], - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 20, - }, - ), - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 21, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 21, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 21, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_5.snap deleted file mode 100644 index be499bccb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_5.snap +++ /dev/null @@ -1,200 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{i: 1, j for i in [1,2,3]}\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - operation: Union, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 5, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "j", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ), - value: Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - ops: [ - In, - ], - comparators: [ - Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 19, - end_line: 1, - end_column: 20, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 22, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 23, - end_line: 1, - end_column: 24, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 18, - end_line: 1, - end_column: 25, - }, - ], - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 25, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 25, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 26, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_6.snap deleted file mode 100644 index 12c72821e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__comp_clause_recovery_6.snap +++ /dev/null @@ -1,18 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 77 -expression: "crate::tests::parsing_expr_string(\"{for i in [1,2,3]}\")" ---- -Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 18, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_0.snap deleted file mode 100644 index a64d0b4e7..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_0.snap +++ /dev/null @@ -1,78 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a <> b\"#)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ops: [ - Lt, - Gt, - ], - comparators: [ - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_1.snap deleted file mode 100644 index d75e31cfd..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_1.snap +++ /dev/null @@ -1,107 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a < !b >!1\"#)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ops: [ - Lt, - Gt, - ], - comparators: [ - Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 6, - }, - Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 10, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 10, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_2.snap deleted file mode 100644 index d75e31cfd..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_2.snap +++ /dev/null @@ -1,107 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a < !b >!1\"#)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ops: [ - Lt, - Gt, - ], - comparators: [ - Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 6, - }, - Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 10, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 10, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_3.snap deleted file mode 100644 index d7b4ce34f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_3.snap +++ /dev/null @@ -1,89 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a <<< b\"#)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - op: LShift, - right: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, - }, - ops: [ - Lt, - ], - comparators: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_4.snap deleted file mode 100644 index 180757482..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_4.snap +++ /dev/null @@ -1,90 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a <+< b\"#)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ops: [ - Lt, - Lt, - ], - comparators: [ - Node { - node: Unary( - UnaryExpr { - op: UAdd, - operand: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_5.snap deleted file mode 100644 index 3b231aeec..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_5.snap +++ /dev/null @@ -1,79 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a >+ b\"#)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ops: [ - Gt, - ], - comparators: [ - Node { - node: Unary( - UnaryExpr { - op: UAdd, - operand: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_6.snap deleted file mode 100644 index d0df0d26a..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__compare_recovery_6.snap +++ /dev/null @@ -1,90 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"+ b\"#)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ops: [ - Lt, - Gt, - ], - comparators: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - Node { - node: Unary( - UnaryExpr { - op: UAdd, - operand: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_0.snap deleted file mode 100644 index cfe32a67b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_0.snap +++ /dev/null @@ -1,18 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 14 -expression: "crate::tests::parsing_expr_string(\"{\")" ---- -Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_1.snap deleted file mode 100644 index df71197c7..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_1.snap +++ /dev/null @@ -1,67 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{a = 1\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 6, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_10.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_10.snap deleted file mode 100644 index 3d0af9815..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_10.snap +++ /dev/null @@ -1,118 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{**a, *b}\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: None, - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - operation: Union, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 4, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Binary( - BinaryExpr { - left: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - op: Mul, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 8, - }, - ), - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 9, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 9, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_11.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_11.snap deleted file mode 100644 index 166a1b7b4..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_11.snap +++ /dev/null @@ -1,149 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{if True: a = , b = 2}\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: None, - value: Node { - node: ConfigIfEntry( - ConfigIfEntryExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 8, - }, - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - ), - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 15, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 15, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 15, - }, - operation: Union, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 15, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 17, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 17, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 20, - end_line: 1, - end_column: 21, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 21, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 22, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_12.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_12.snap deleted file mode 100644 index 8d7da0285..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_12.snap +++ /dev/null @@ -1,171 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{if True: *a, b = 2}\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: None, - value: Node { - node: ConfigIfEntry( - ConfigIfEntryExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 8, - }, - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Binary( - BinaryExpr { - left: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - op: Mul, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 12, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 12, - }, - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 12, - }, - ), - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 13, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 13, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 13, - }, - operation: Union, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 13, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 15, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 15, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 18, - end_line: 1, - end_column: 19, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 19, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 20, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_13.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_13.snap deleted file mode 100644 index 4510d3d24..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_13.snap +++ /dev/null @@ -1,101 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{if True: key: {}}\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: None, - value: Node { - node: ConfigIfEntry( - ConfigIfEntryExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 8, - }, - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "key", - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 13, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 13, - }, - ), - value: Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 17, - }, - operation: Union, - }, - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 17, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 18, - }, - operation: Union, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 17, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 18, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_14.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_14.snap deleted file mode 100644 index 3a2992a34..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_14.snap +++ /dev/null @@ -1,102 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{if True: key: []}\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: None, - value: Node { - node: ConfigIfEntry( - ConfigIfEntryExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 8, - }, - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "key", - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 13, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 13, - }, - ), - value: Node { - node: List( - ListExpr { - elts: [], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 17, - }, - operation: Union, - }, - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 17, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 18, - }, - operation: Union, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 17, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 18, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_15.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_15.snap deleted file mode 100644 index e988ccd02..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_15.snap +++ /dev/null @@ -1,62 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{你好\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "你好", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 3, - }, - ), - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 3, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_2.snap deleted file mode 100644 index 949af7663..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_2.snap +++ /dev/null @@ -1,117 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{a = 1, b = 2\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 6, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 13, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 13, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 13, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_3.snap deleted file mode 100644 index 16b95f5ca..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_3.snap +++ /dev/null @@ -1,115 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{a = {a = 1}\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ), - value: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 11, - }, - ], - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 12, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 12, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_4.snap deleted file mode 100644 index 1e5f38fe7..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_4.snap +++ /dev/null @@ -1,115 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{a = {a = 1\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ), - value: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 11, - }, - ], - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 11, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 11, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_5.snap deleted file mode 100644 index 99f796475..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_5.snap +++ /dev/null @@ -1,149 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"{\n a = 1\n b = 2\n \"#)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 2, - column: 8, - end_line: 2, - end_column: 9, - }, - operation: Override, - }, - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 9, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - operation: Override, - }, - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 9, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 4, - column: 4, - end_line: 4, - end_column: 4, - }, - ), - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 4, - column: 4, - end_line: 4, - end_column: 4, - }, - operation: Override, - }, - filename: "", - line: 4, - column: 4, - end_line: 4, - end_column: 4, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 4, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_6.snap deleted file mode 100644 index 25154a89d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_6.snap +++ /dev/null @@ -1,117 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{a = 1 b = 2}\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 6, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 12, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 12, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 13, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_7.snap deleted file mode 100644 index 7d94e620c..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_7.snap +++ /dev/null @@ -1,149 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{a = 1,, b = 2}\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 6, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ), - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 10, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 12, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 14, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 15, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_8.snap deleted file mode 100644 index c3412c7c5..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_8.snap +++ /dev/null @@ -1,129 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{a = 1 ~ b = 2}\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 6, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Unary( - UnaryExpr { - op: Invert, - operand: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 10, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 14, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 15, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_9.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_9.snap deleted file mode 100644 index eadd2be4e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__config_recovery_9.snap +++ /dev/null @@ -1,119 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"{*a, **b}\")" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Binary( - BinaryExpr { - left: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - op: Mul, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 3, - }, - ), - value: Node { - node: Binary( - BinaryExpr { - left: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 7, - }, - op: Pow, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 8, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 8, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_0.snap deleted file mode 100644 index 289fe85e0..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_0.snap +++ /dev/null @@ -1,79 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:(\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Any, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_1.snap deleted file mode 100644 index 9890a5d4b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_1.snap +++ /dev/null @@ -1,102 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:(i\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Named( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - Node { - node: Any, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 4, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_10.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_10.snap deleted file mode 100644 index 21f1b312e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_10.snap +++ /dev/null @@ -1,102 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:({\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Dict( - DictType { - key_type: Some( - Node { - node: Any, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - ), - value_type: Some( - Node { - node: Any, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 4, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_11.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_11.snap deleted file mode 100644 index 646edab6d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_11.snap +++ /dev/null @@ -1,117 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:({i\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 5, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Dict( - DictType { - key_type: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - value_type: Some( - Node { - node: Any, - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 5, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 5, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 5, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_12.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_12.snap deleted file mode 100644 index 3ae60363b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_12.snap +++ /dev/null @@ -1,117 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:({i:\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Dict( - DictType { - key_type: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - value_type: Some( - Node { - node: Any, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 6, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_13.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_13.snap deleted file mode 100644 index 60c402b80..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_13.snap +++ /dev/null @@ -1,132 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:({i:i\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 7, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Dict( - DictType { - key_type: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - value_type: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 7, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 7, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_14.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_14.snap deleted file mode 100644 index a1900d5b1..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_14.snap +++ /dev/null @@ -1,119 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:({i:int\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 9, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Dict( - DictType { - key_type: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - value_type: Some( - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 9, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 9, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_15.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_15.snap deleted file mode 100644 index f259cc0be..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_15.snap +++ /dev/null @@ -1,127 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:({i:int]\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 10, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Dict( - DictType { - key_type: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - value_type: Some( - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 9, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 10, - }, - Node { - node: Any, - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 10, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 10, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_16.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_16.snap deleted file mode 100644 index d4f7e0baf..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_16.snap +++ /dev/null @@ -1,114 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:({str:int]\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 12, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Dict( - DictType { - key_type: Some( - Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ), - value_type: Some( - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 11, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 12, - }, - Node { - node: Any, - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 12, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 12, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_17.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_17.snap deleted file mode 100644 index 3f62171eb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_17.snap +++ /dev/null @@ -1,114 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:({str:int}\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 12, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Dict( - DictType { - key_type: Some( - Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ), - value_type: Some( - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 11, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 12, - }, - Node { - node: Any, - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 12, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 12, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_18.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_18.snap deleted file mode 100644 index 55d4ac98e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_18.snap +++ /dev/null @@ -1,122 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:({str:int} ->\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 15, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Dict( - DictType { - key_type: Some( - Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ), - value_type: Some( - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 11, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 12, - }, - Node { - node: Any, - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 15, - }, - Node { - node: Any, - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 15, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 15, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_19.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_19.snap deleted file mode 100644 index c12213574..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_19.snap +++ /dev/null @@ -1,130 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:({str:int}) -> i\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 18, - end_line: 1, - end_column: 18, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Dict( - DictType { - key_type: Some( - Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ), - value_type: Some( - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 11, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 12, - }, - ], - ), - ret_ty: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 17, - end_line: 1, - end_column: 18, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 17, - end_line: 1, - end_column: 18, - }, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 18, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_2.snap deleted file mode 100644 index 0623e3c2f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_2.snap +++ /dev/null @@ -1,89 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:(int\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - Node { - node: Any, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 6, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_20.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_20.snap deleted file mode 100644 index 4a9bd1289..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_20.snap +++ /dev/null @@ -1,128 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:(str|int) -> i\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 16, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Union( - UnionType { - type_elements: [ - Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 10, - }, - ], - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 10, - }, - ], - ), - ret_ty: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 16, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 16, - }, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 16, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_21.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_21.snap deleted file mode 100644 index 9443f5d0c..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_21.snap +++ /dev/null @@ -1,138 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:(str|int, int) -> i\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 21, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Union( - UnionType { - type_elements: [ - Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 10, - }, - ], - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 10, - }, - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 15, - }, - ], - ), - ret_ty: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 20, - end_line: 1, - end_column: 21, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 20, - end_line: 1, - end_column: 21, - }, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 21, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_22.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_22.snap deleted file mode 100644 index 4e0f08952..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_22.snap +++ /dev/null @@ -1,135 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:(str|int, int|\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 16, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Union( - UnionType { - type_elements: [ - Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 10, - }, - ], - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 10, - }, - Node { - node: Union( - UnionType { - type_elements: [ - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 15, - }, - Node { - node: Any, - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 16, - }, - ], - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 16, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 16, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_23.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_23.snap deleted file mode 100644 index a04ea182f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_23.snap +++ /dev/null @@ -1,151 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:(str|int, int|) ->\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 20, - end_line: 1, - end_column: 20, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Union( - UnionType { - type_elements: [ - Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 10, - }, - ], - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 10, - }, - Node { - node: Union( - UnionType { - type_elements: [ - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 15, - }, - Node { - node: Any, - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 17, - }, - ], - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 17, - }, - Node { - node: Any, - filename: "", - line: 1, - column: 18, - end_line: 1, - end_column: 20, - }, - Node { - node: Any, - filename: "", - line: 1, - column: 20, - end_line: 1, - end_column: 20, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 20, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_3.snap deleted file mode 100644 index 4abeae807..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_3.snap +++ /dev/null @@ -1,78 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:i)\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ty: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_4.snap deleted file mode 100644 index d14d5c78c..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_4.snap +++ /dev/null @@ -1,107 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:([i\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 5, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: List( - ListType { - inner_type: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 5, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 5, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_5.snap deleted file mode 100644 index ce5eb974f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_5.snap +++ /dev/null @@ -1,115 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:([i:\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: List( - ListType { - inner_type: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - Node { - node: Any, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 6, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_6.snap deleted file mode 100644 index 8cfed4657..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_6.snap +++ /dev/null @@ -1,115 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:([i]\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: List( - ListType { - inner_type: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - Node { - node: Any, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 6, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_7.snap deleted file mode 100644 index fe51302d7..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_7.snap +++ /dev/null @@ -1,102 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:([int]\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 8, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: List( - ListType { - inner_type: Some( - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 8, - }, - Node { - node: Any, - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 8, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 8, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_8.snap deleted file mode 100644 index b2a05a64a..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_8.snap +++ /dev/null @@ -1,94 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:([int\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 7, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: List( - ListType { - inner_type: Some( - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 7, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 7, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_9.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_9.snap deleted file mode 100644 index f4d31fa19..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__fn_ty_annotation_recovery_9.snap +++ /dev/null @@ -1,102 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"a:({}\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 5, - }, - ty: Some( - Node { - node: Function( - FunctionType { - params_ty: Some( - [ - Node { - node: Dict( - DictType { - key_type: Some( - Node { - node: Any, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - value_type: Some( - Node { - node: Any, - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 5, - }, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 5, - }, - ], - ), - ret_ty: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 5, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_0.snap deleted file mode 100644 index 528d37531..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_0.snap +++ /dev/null @@ -1,51 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"1 if\"#)" ---- -Node { - node: If( - IfExpr { - body: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - cond: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - orelse: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_1.snap deleted file mode 100644 index 528d37531..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_1.snap +++ /dev/null @@ -1,51 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"1 if\"#)" ---- -Node { - node: If( - IfExpr { - body: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - cond: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - orelse: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_2.snap deleted file mode 100644 index 49690bc2f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_2.snap +++ /dev/null @@ -1,53 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"1 if True\"#)" ---- -Node { - node: If( - IfExpr { - body: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 9, - }, - orelse: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 9, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_3.snap deleted file mode 100644 index db389259e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_3.snap +++ /dev/null @@ -1,53 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"1 if True else\"#)" ---- -Node { - node: If( - IfExpr { - body: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 9, - }, - orelse: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 14, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 14, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_4.snap deleted file mode 100644 index ccc877766..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_recovery_4.snap +++ /dev/null @@ -1,28 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"if True else\"#)" ---- -Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "if", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_0.snap deleted file mode 100644 index 2fa082d3d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_0.snap +++ /dev/null @@ -1,65 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"if True a = 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: If( - IfStmt { - body: [ - Node { - node: Assign( - AssignStmt { - targets: [], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 13, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 13, - }, - ], - cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 7, - }, - orelse: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 13, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_1.snap deleted file mode 100644 index b39f4363f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_1.snap +++ /dev/null @@ -1,114 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"if True: a = 1 else if b = 2\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: If( - IfStmt { - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 14, - }, - ], - cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 7, - }, - orelse: [ - Node { - node: Assign( - AssignStmt { - targets: [], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 27, - end_line: 1, - end_column: 28, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 28, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 28, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_2.snap deleted file mode 100644 index 1396ed4fd..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_2.snap +++ /dev/null @@ -1,83 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"if : a = 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: If( - IfStmt { - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 10, - }, - ], - cond: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - orelse: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 10, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_3.snap deleted file mode 100644 index e225daff1..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_3.snap +++ /dev/null @@ -1,114 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"if True: a = 1 else b = 2\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: If( - IfStmt { - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 14, - }, - ], - cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 7, - }, - orelse: [ - Node { - node: Assign( - AssignStmt { - targets: [], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 24, - end_line: 1, - end_column: 25, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 22, - end_line: 1, - end_column: 25, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 25, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_4.snap deleted file mode 100644 index 4b5684a72..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_4.snap +++ /dev/null @@ -1,109 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"if True: else: b = 2\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: If( - IfStmt { - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "else", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 13, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 13, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 19, - end_line: 1, - end_column: 20, - }, - ty: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 16, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 16, - }, - ), - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 20, - }, - ], - cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 7, - }, - orelse: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 20, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_5.snap deleted file mode 100644 index 206bf3133..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_5.snap +++ /dev/null @@ -1,58 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"if\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: If( - IfStmt { - body: [ - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 2, - }, - ], - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 2, - }, - ], - cond: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 2, - }, - orelse: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_6.snap deleted file mode 100644 index 90c99d7cb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_6.snap +++ /dev/null @@ -1,71 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"if else\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: If( - IfStmt { - body: [ - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 7, - }, - ], - cond: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "else", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 7, - }, - orelse: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_7.snap deleted file mode 100644 index 3435267c8..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_7.snap +++ /dev/null @@ -1,36 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"if True:\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: If( - IfStmt { - body: [], - cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 7, - }, - orelse: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_8.snap deleted file mode 100644 index 64253742f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_8.snap +++ /dev/null @@ -1,138 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"if True: a = 1\nelse if False: b = 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: If( - IfStmt { - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 14, - }, - ], - cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 7, - }, - orelse: [ - Node { - node: Assign( - AssignStmt { - targets: [], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 2, - column: 19, - end_line: 2, - end_column: 20, - }, - ty: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 2, - column: 15, - end_line: 2, - end_column: 16, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 15, - end_line: 2, - end_column: 16, - }, - ), - }, - ), - filename: "", - line: 2, - column: 13, - end_line: 2, - end_column: 20, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 20, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_9.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_9.snap deleted file mode 100644 index 045b89545..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__if_stmt_recovery_9.snap +++ /dev/null @@ -1,138 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"if True: a = 1\nelse False: b = 1\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: If( - IfStmt { - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - ty: None, - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 14, - }, - ], - cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 7, - }, - orelse: [ - Node { - node: Assign( - AssignStmt { - targets: [], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 2, - column: 16, - end_line: 2, - end_column: 17, - }, - ty: Some( - Node { - node: Named( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 2, - column: 12, - end_line: 2, - end_column: 13, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 12, - end_line: 2, - end_column: 13, - }, - ), - }, - ), - filename: "", - line: 2, - column: 10, - end_line: 2, - end_column: 17, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 17, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_recovery_0.snap deleted file mode 100644 index 5b34ce992..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_recovery_0.snap +++ /dev/null @@ -1,34 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"import json as j.a\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Import( - ImportStmt { - path: Node { - node: "json", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 11, - }, - rawpath: "json", - name: "json", - asname: None, - pkg_name: "", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 18, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_0.snap deleted file mode 100644 index cb7f681b5..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_0.snap +++ /dev/null @@ -1,34 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"import\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Import( - ImportStmt { - path: Node { - node: "", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - rawpath: "", - name: "", - asname: None, - pkg_name: "", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_1.snap deleted file mode 100644 index a69bc5079..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_1.snap +++ /dev/null @@ -1,61 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"import 'pkg_path'\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Import( - ImportStmt { - path: Node { - node: "", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 6, - }, - rawpath: "", - name: "", - asname: None, - pkg_name: "", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'pkg_path'", - value: "pkg_path", - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 17, - }, - ], - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 17, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_2.snap deleted file mode 100644 index 6b6986b97..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_2.snap +++ /dev/null @@ -1,34 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"import pkg_path.\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Import( - ImportStmt { - path: Node { - node: "pkg_path.", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 16, - }, - rawpath: "pkg_path.", - name: "", - asname: None, - pkg_name: "", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 16, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_3.snap deleted file mode 100644 index 94512d4be..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_3.snap +++ /dev/null @@ -1,76 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"import pkg_path[0]\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Import( - ImportStmt { - path: Node { - node: "pkg_path", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 15, - }, - rawpath: "pkg_path", - name: "pkg_path", - asname: None, - pkg_name: "", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 15, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 17, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 18, - }, - ], - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 18, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_4.snap deleted file mode 100644 index 33fe9d47f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_4.snap +++ /dev/null @@ -1,34 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"import .pkg_path.\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Import( - ImportStmt { - path: Node { - node: ".pkg_path.", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 17, - }, - rawpath: ".pkg_path.", - name: "", - asname: None, - pkg_name: "", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 17, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_5.snap deleted file mode 100644 index da09f18cc..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_5.snap +++ /dev/null @@ -1,43 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"import pkg_path as \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Import( - ImportStmt { - path: Node { - node: "pkg_path", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 15, - }, - rawpath: "pkg_path", - name: "", - asname: Some( - Node { - node: "", - filename: "", - line: 1, - column: 19, - end_line: 1, - end_column: 19, - }, - ), - pkg_name: "", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 18, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_6.snap deleted file mode 100644 index 21ec43038..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__import_stmt_recovery_6.snap +++ /dev/null @@ -1,70 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"import pkg_path as 'data'\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Import( - ImportStmt { - path: Node { - node: "pkg_path", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 15, - }, - rawpath: "pkg_path", - name: "", - asname: Some( - Node { - node: "", - filename: "", - line: 1, - column: 19, - end_line: 1, - end_column: 19, - }, - ), - pkg_name: "", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 18, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'data'", - value: "data", - }, - ), - filename: "", - line: 1, - column: 19, - end_line: 1, - end_column: 25, - }, - ], - }, - ), - filename: "", - line: 1, - column: 19, - end_line: 1, - end_column: 25, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_0.snap deleted file mode 100644 index d65592149..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_0.snap +++ /dev/null @@ -1,44 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 151 -expression: "crate::tests::parsing_expr_string(r#\"'${}'\"#)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: false, - values: [ - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - format_spec: None, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - ], - raw_value: "'${}'", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_1.snap deleted file mode 100644 index 9e1a8683e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_1.snap +++ /dev/null @@ -1,78 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"'${a +}'\"#)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: false, - values: [ - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - op: Add, - right: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - format_spec: None, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - ], - raw_value: "'${a +}'", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_10.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_10.snap deleted file mode 100644 index 3aca424a4..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_10.snap +++ /dev/null @@ -1,83 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"\"\"\"\n ${CC}\n\"\"\"\"#)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: true, - values: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\n ", - value: "\n ", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "CC", - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 6, - }, - format_spec: None, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 6, - }, - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\n", - value: "\n", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - ], - raw_value: "\"\"\"\n ${CC}\n\"\"\"", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 3, - end_column: 3, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_11.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_11.snap deleted file mode 100644 index 8343e4ae8..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_11.snap +++ /dev/null @@ -1,143 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"'\\\"false\\\" ${item.kind}: ${item.metadata.name}'\"#)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: false, - values: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\\\"false\\\" ", - value: "\"false\" ", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "item", - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 17, - }, - Node { - node: "kind", - filename: "", - line: 1, - column: 18, - end_line: 1, - end_column: 22, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 22, - }, - format_spec: None, - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 22, - }, - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: ": ", - value: ": ", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "item", - filename: "", - line: 1, - column: 27, - end_line: 1, - end_column: 31, - }, - Node { - node: "metadata", - filename: "", - line: 1, - column: 32, - end_line: 1, - end_column: 40, - }, - Node { - node: "name", - filename: "", - line: 1, - column: 41, - end_line: 1, - end_column: 45, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 27, - end_line: 1, - end_column: 45, - }, - format_spec: None, - }, - ), - filename: "", - line: 1, - column: 27, - end_line: 1, - end_column: 45, - }, - ], - raw_value: "'\\\"false\\\" ${item.kind}: ${item.metadata.name}'", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 47, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_12.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_12.snap deleted file mode 100644 index 235648fa5..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_12.snap +++ /dev/null @@ -1,207 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"'\\\"false\\\" ${item.kind}: ${item.metadata.name} \\\"true\\\" ${item} '\"#)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: false, - values: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\\\"false\\\" ", - value: "\"false\" ", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "item", - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 17, - }, - Node { - node: "kind", - filename: "", - line: 1, - column: 18, - end_line: 1, - end_column: 22, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 22, - }, - format_spec: None, - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 22, - }, - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: ": ", - value: ": ", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "item", - filename: "", - line: 1, - column: 27, - end_line: 1, - end_column: 31, - }, - Node { - node: "metadata", - filename: "", - line: 1, - column: 32, - end_line: 1, - end_column: 40, - }, - Node { - node: "name", - filename: "", - line: 1, - column: 41, - end_line: 1, - end_column: 45, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 27, - end_line: 1, - end_column: 45, - }, - format_spec: None, - }, - ), - filename: "", - line: 1, - column: 27, - end_line: 1, - end_column: 45, - }, - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: " \\\"true\\\" ", - value: " \"true\" ", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "item", - filename: "", - line: 1, - column: 58, - end_line: 1, - end_column: 62, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 58, - end_line: 1, - end_column: 62, - }, - format_spec: None, - }, - ), - filename: "", - line: 1, - column: 58, - end_line: 1, - end_column: 62, - }, - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: " ", - value: " ", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - ], - raw_value: "'\\\"false\\\" ${item.kind}: ${item.metadata.name} \\\"true\\\" ${item} '", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 65, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_13.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_13.snap deleted file mode 100644 index cb1becd17..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_13.snap +++ /dev/null @@ -1,127 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"'\\\"false\\\" \\${item.kind}: a${item.metadata.name} \\\"true\\\" \\${item} '\"#)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: false, - values: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\\\"false\\\" \\${item.kind}", - value: "\"false\" ${item.kind}", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: ": a", - value: ": a", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "item", - filename: "", - line: 1, - column: 29, - end_line: 1, - end_column: 33, - }, - Node { - node: "metadata", - filename: "", - line: 1, - column: 34, - end_line: 1, - end_column: 42, - }, - Node { - node: "name", - filename: "", - line: 1, - column: 43, - end_line: 1, - end_column: 47, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 29, - end_line: 1, - end_column: 47, - }, - format_spec: None, - }, - ), - filename: "", - line: 1, - column: 29, - end_line: 1, - end_column: 47, - }, - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: " \\\"true\\\" \\${item}", - value: " \"true\" ${item}", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: " ", - value: " ", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - ], - raw_value: "'\\\"false\\\" \\${item.kind}: a${item.metadata.name} \\\"true\\\" \\${item} '", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 68, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_2.snap deleted file mode 100644 index 7bdb64047..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_2.snap +++ /dev/null @@ -1,89 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"'${(a +}'\"#)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: false, - values: [ - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Paren( - ParenExpr { - expr: Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - op: Add, - right: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 7, - }, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 7, - }, - format_spec: None, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 7, - }, - ], - raw_value: "'${(a +}'", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_3.snap deleted file mode 100644 index fb84a2866..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_3.snap +++ /dev/null @@ -1,35 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 129 -expression: "crate::tests::parsing_expr_string(r#\"'${a'\"#)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: false, - values: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "${a", - value: "${a", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - ], - raw_value: "'${a'", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_5.snap deleted file mode 100644 index c974dedbf..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_5.snap +++ /dev/null @@ -1,83 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"'${a + 1 = }'\"#)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: false, - values: [ - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 8, - }, - format_spec: None, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 11, - }, - ], - raw_value: "'${a + 1 = }'", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 13, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_6.snap deleted file mode 100644 index 466ccce34..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_6.snap +++ /dev/null @@ -1,56 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"'${a: json}'\"#)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: false, - values: [ - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - format_spec: None, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 10, - }, - ], - raw_value: "'${a: json}'", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_7.snap deleted file mode 100644 index 60205c006..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_7.snap +++ /dev/null @@ -1,71 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"'\\n${a: #json}'\"#)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: false, - values: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\\n", - value: "\n", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - format_spec: Some( - "#json", - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 13, - }, - ], - raw_value: "'\\n${a: #json}'", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 15, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_8.snap deleted file mode 100644 index c679d1782..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_8.snap +++ /dev/null @@ -1,85 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"'a\\nb${a: #json}\\n'\"#)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: false, - values: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "a\\nb", - value: "a\nb", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - format_spec: Some( - "#json", - ), - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 15, - }, - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\\n", - value: "\n", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - ], - raw_value: "'a\\nb${a: #json}\\n'", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 19, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_9.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_9.snap deleted file mode 100644 index d93090334..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__joined_string_recovery_9.snap +++ /dev/null @@ -1,83 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"'''\\\n ${CC}\n'''\"#)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: true, - values: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\\\n ", - value: " ", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "CC", - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 6, - }, - format_spec: None, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 6, - }, - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\n", - value: "\n", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - ], - raw_value: "'''\\\n ${CC}\n'''", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 3, - end_column: 3, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_0.snap deleted file mode 100644 index 72e7e6216..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_0.snap +++ /dev/null @@ -1,33 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 161 -expression: "crate::tests::parsing_expr_string(r#\"lambda\"#)" ---- -Node { - node: Lambda( - LambdaExpr { - args: Some( - Node { - node: Arguments { - args: [], - defaults: [], - ty_list: [], - }, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - ), - body: [], - return_ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_1.snap deleted file mode 100644 index 01fc43f47..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_1.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 162 -expression: "crate::tests::parsing_expr_string(r#\"lambda {\"#)" ---- -Node { - node: Lambda( - LambdaExpr { - args: None, - body: [], - return_ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_2.snap deleted file mode 100644 index d591a8a1b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_2.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 163 -expression: "crate::tests::parsing_expr_string(r#\"lambda {}\"#)" ---- -Node { - node: Lambda( - LambdaExpr { - args: None, - body: [], - return_ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_3.snap deleted file mode 100644 index 1f7ff3bbb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_3.snap +++ /dev/null @@ -1,92 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"{lambda}\"#)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Lambda( - LambdaExpr { - args: Some( - Node { - node: Arguments { - args: [ - Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 7, - }, - ], - defaults: [ - None, - ], - ty_list: [ - None, - ], - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ), - body: [], - return_ty: None, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 8, - }, - ), - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 8, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 8, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_4.snap deleted file mode 100644 index 52080bd08..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_4.snap +++ /dev/null @@ -1,53 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"{lambda{}\"#)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Lambda( - LambdaExpr { - args: None, - body: [], - return_ty: None, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 9, - }, - ), - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 9, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 9, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_5.snap deleted file mode 100644 index 9c6d1b83e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__lambda_recovery_5.snap +++ /dev/null @@ -1,92 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"{lambda a{}\"#)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Lambda( - LambdaExpr { - args: Some( - Node { - node: Arguments { - args: [ - Node { - node: Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ], - defaults: [ - None, - ], - ty_list: [ - None, - ], - }, - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ), - body: [], - return_ty: None, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 11, - }, - ), - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 11, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 11, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__line_continue_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__line_continue_recovery_0.snap deleted file mode 100644 index c5759da50..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__line_continue_recovery_0.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 15 -expression: "crate::tests::parsing_expr_string(\"0x\\\\2\\n12\")" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__line_continue_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__line_continue_recovery_1.snap deleted file mode 100644 index 6a188859e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__line_continue_recovery_1.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 24 -expression: "crate::tests::parsing_expr_string(\"'abc\\\\ \\ndef\")" ---- -Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'abc\\ ", - value: "abc\\ ", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__line_continue_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__line_continue_recovery_2.snap deleted file mode 100644 index 90d980588..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__line_continue_recovery_2.snap +++ /dev/null @@ -1,45 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"'a' + \\\n'b'\n\"#)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'a'", - value: "a", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - op: Add, - right: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'b'", - value: "b", - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 3, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__line_continue_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__line_continue_recovery_3.snap deleted file mode 100644 index 560f44c0f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__line_continue_recovery_3.snap +++ /dev/null @@ -1,46 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"'a' + \\1\n'b'\n\"#)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'a'", - value: "a", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_0.snap deleted file mode 100644 index b9f33adb6..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_0.snap +++ /dev/null @@ -1,19 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 5 -expression: "crate::tests::parsing_expr_string(\"[\")" ---- -Node { - node: List( - ListExpr { - elts: [], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_1.snap deleted file mode 100644 index 620783e9c..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_1.snap +++ /dev/null @@ -1,35 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 6 -expression: "crate::tests::parsing_expr_string(\"[0\")" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_10.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_10.snap deleted file mode 100644 index 47087d246..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_10.snap +++ /dev/null @@ -1,99 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"[**a, *b\")" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: Binary( - BinaryExpr { - left: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 3, - }, - op: Pow, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 4, - }, - Node { - node: Starred( - StarredExpr { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 8, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_11.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_11.snap deleted file mode 100644 index 637195280..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_11.snap +++ /dev/null @@ -1,91 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"[if True: a, b]\")" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: ListIfItem( - ListIfItemExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 8, - }, - exprs: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 11, - }, - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 15, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_12.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_12.snap deleted file mode 100644 index 452d8d6fa..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_12.snap +++ /dev/null @@ -1,113 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"[if True: **a, b]\")" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: ListIfItem( - ListIfItemExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 8, - }, - exprs: [ - Node { - node: Binary( - BinaryExpr { - left: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 12, - }, - op: Pow, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 13, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 13, - }, - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 13, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 13, - }, - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 16, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 16, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 17, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_13.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_13.snap deleted file mode 100644 index 90b45fd76..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_13.snap +++ /dev/null @@ -1,90 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"[\n if True:\n b = []\n]\n\"#)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: ListIfItem( - ListIfItemExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 11, - }, - exprs: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 10, - end_line: 3, - end_column: 11, - }, - Node { - node: List( - ListExpr { - elts: [], - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 12, - end_line: 3, - end_column: 14, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 0, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_14.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_14.snap deleted file mode 100644 index fe6b45e6d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_14.snap +++ /dev/null @@ -1,87 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"[\n if True:\n b = \n]\n\"#)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: ListIfItem( - ListIfItemExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 11, - }, - exprs: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 10, - end_line: 3, - end_column: 11, - }, - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 12, - end_line: 4, - end_column: 0, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 0, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_15.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_15.snap deleted file mode 100644 index 4d35ef38b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_15.snap +++ /dev/null @@ -1,89 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"[\n if True:\n b -\n]\n\"#)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: ListIfItem( - ListIfItemExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 11, - }, - exprs: [ - Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - op: Sub, - right: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 11, - end_line: 4, - end_column: 0, - }, - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 11, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 0, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_16.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_16.snap deleted file mode 100644 index 6200e4a98..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_16.snap +++ /dev/null @@ -1,137 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"{\n if True:\n b = [] = []\n}\n\"#)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: None, - value: Node { - node: ConfigIfEntry( - ConfigIfEntryExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 11, - }, - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ), - value: Node { - node: List( - ListExpr { - elts: [], - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 12, - end_line: 3, - end_column: 14, - }, - operation: Override, - }, - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 14, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 15, - end_line: 3, - end_column: 16, - }, - ), - value: Node { - node: List( - ListExpr { - elts: [], - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 17, - end_line: 3, - end_column: 19, - }, - operation: Override, - }, - filename: "", - line: 3, - column: 15, - end_line: 3, - end_column: 19, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 0, - }, - operation: Union, - }, - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 0, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_17.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_17.snap deleted file mode 100644 index 8af297076..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_17.snap +++ /dev/null @@ -1,134 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"{\n if True:\n b = [] = \n}\n\"#)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: None, - value: Node { - node: ConfigIfEntry( - ConfigIfEntryExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 11, - }, - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ), - value: Node { - node: List( - ListExpr { - elts: [], - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 12, - end_line: 3, - end_column: 14, - }, - operation: Override, - }, - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 14, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 15, - end_line: 3, - end_column: 16, - }, - ), - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 17, - end_line: 4, - end_column: 0, - }, - operation: Override, - }, - filename: "", - line: 3, - column: 15, - end_line: 4, - end_column: 0, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 0, - }, - operation: Union, - }, - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 0, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_18.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_18.snap deleted file mode 100644 index a4ff6c2ce..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_18.snap +++ /dev/null @@ -1,124 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"{\n if True:\n b = [] -\n}\n\"#)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: None, - value: Node { - node: ConfigIfEntry( - ConfigIfEntryExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 11, - }, - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ), - value: Node { - node: Binary( - BinaryExpr { - left: Node { - node: List( - ListExpr { - elts: [], - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 12, - end_line: 3, - end_column: 14, - }, - op: Sub, - right: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 16, - end_line: 4, - end_column: 0, - }, - }, - ), - filename: "", - line: 3, - column: 12, - end_line: 3, - end_column: 16, - }, - operation: Override, - }, - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 16, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 0, - }, - operation: Union, - }, - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 0, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_2.snap deleted file mode 100644 index aced507ef..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_2.snap +++ /dev/null @@ -1,50 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 7 -expression: "crate::tests::parsing_expr_string(\"[0,1\")" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_3.snap deleted file mode 100644 index e5badc30f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_3.snap +++ /dev/null @@ -1,64 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 8 -expression: "crate::tests::parsing_expr_string(\"[[0,1]\")" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 6, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_4.snap deleted file mode 100644 index 85ef6c261..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_4.snap +++ /dev/null @@ -1,64 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 9 -expression: "crate::tests::parsing_expr_string(\"[[0,1\")" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 5, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_5.snap deleted file mode 100644 index 492a653ca..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_5.snap +++ /dev/null @@ -1,50 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 10 -expression: "crate::tests::parsing_expr_string(r#\"[\n 0,\n 1\n \"#)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_6.snap deleted file mode 100644 index 78c29602f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_6.snap +++ /dev/null @@ -1,50 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 48 -expression: "crate::tests::parsing_expr_string(\"[0 1]\")" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_7.snap deleted file mode 100644 index e715c89bc..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_7.snap +++ /dev/null @@ -1,50 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 49 -expression: "crate::tests::parsing_expr_string(\"[0,, 1\")" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_8.snap deleted file mode 100644 index 4d10dee6f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_8.snap +++ /dev/null @@ -1,62 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 50 -expression: "crate::tests::parsing_expr_string(\"[0 ~ 1\")" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - Node { - node: Unary( - UnaryExpr { - op: Invert, - operand: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_9.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_9.snap deleted file mode 100644 index 9d6ba6afb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__list_recovery_9.snap +++ /dev/null @@ -1,99 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"[*a, **b]\")" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: Starred( - StarredExpr { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 3, - }, - Node { - node: Binary( - BinaryExpr { - left: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 7, - }, - op: Pow, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 8, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_0.snap deleted file mode 100644 index a1e546300..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_0.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 8 -expression: "crate::tests::parsing_expr_string(\"00\")" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_1.snap deleted file mode 100644 index ac6b04397..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_1.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 9 -expression: "crate::tests::parsing_expr_string(\"00a\")" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_10.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_10.snap deleted file mode 100644 index 1fcdec63e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_10.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 20 -expression: "crate::tests::parsing_expr_string(\"100mm\")" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 100, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_2.snap deleted file mode 100644 index 8e11e6460..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_2.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 12 -expression: "crate::tests::parsing_expr_string(\"0x112.3\")" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Float( - 0.0, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_3.snap deleted file mode 100644 index a08c61788..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_3.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 11 -expression: "crate::tests::parsing_expr_string(\"0o\")" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_4.snap deleted file mode 100644 index 6db076205..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_4.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 12 -expression: "crate::tests::parsing_expr_string(\"0oA\")" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_5.snap deleted file mode 100644 index 9953c6cfd..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_5.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 13 -expression: "crate::tests::parsing_expr_string(\"0x\")" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_6.snap deleted file mode 100644 index 09b76ab4c..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_6.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 14 -expression: "crate::tests::parsing_expr_string(\"0xH\")" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_7.snap deleted file mode 100644 index 2eeebefbc..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_7.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 17 -expression: "crate::tests::parsing_expr_string(\"0e0\")" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Float( - 0.0, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_8.snap deleted file mode 100644 index 0c9228f75..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_8.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 18 -expression: "crate::tests::parsing_expr_string(\"0b333\")" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_9.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_9.snap deleted file mode 100644 index df346b367..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__number_literal_recovery_9.snap +++ /dev/null @@ -1,21 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 19 -expression: "crate::tests::parsing_expr_string(\"10KI\")" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 10, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_0.snap deleted file mode 100644 index 658e897e8..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_0.snap +++ /dev/null @@ -1,39 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"(a\")" ---- -Node { - node: Paren( - ParenExpr { - expr: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_1.snap deleted file mode 100644 index c5ab49249..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_1.snap +++ /dev/null @@ -1,66 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(\"(a + 1\")" ---- -Node { - node: Paren( - ParenExpr { - expr: Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_2.snap deleted file mode 100644 index 555d7f732..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_2.snap +++ /dev/null @@ -1,26 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"(\"#)" ---- -Node { - node: Paren( - ParenExpr { - expr: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_3.snap deleted file mode 100644 index 891fafced..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_3.snap +++ /dev/null @@ -1,26 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"(]\"#)" ---- -Node { - node: Paren( - ParenExpr { - expr: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_4.snap deleted file mode 100644 index 371a9181f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_4.snap +++ /dev/null @@ -1,39 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"(a\"#)" ---- -Node { - node: Paren( - ParenExpr { - expr: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_5.snap deleted file mode 100644 index de670e6df..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__paren_recovery_5.snap +++ /dev/null @@ -1,61 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"(a +\"#)" ---- -Node { - node: Paren( - ParenExpr { - expr: Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - op: Add, - right: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 4, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__parse_body_item.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__parse_body_item.snap deleted file mode 100644 index 8c7f02971..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__parse_body_item.snap +++ /dev/null @@ -1,93 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "$crate :: tests :: parsing_module_string(r#\"\nx = {\n if True\n}\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "x", - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - ], - value: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: None, - value: Node { - node: ConfigIfEntry( - ConfigIfEntryExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 3, - column: 7, - end_line: 3, - end_column: 11, - }, - items: [], - orelse: None, - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 4, - end_column: 0, - }, - operation: Union, - }, - filename: "", - line: 3, - column: 4, - end_line: 4, - end_column: 0, - }, - ], - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 1, - }, - ty: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 4, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_0.snap deleted file mode 100644 index 72222a840..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_0.snap +++ /dev/null @@ -1,36 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"rule\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Rule( - RuleStmt { - doc: None, - name: Node { - node: "", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - parent_rules: [], - decorators: [], - checks: [], - args: None, - for_host_name: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_1.snap deleted file mode 100644 index 690ccd1b8..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_1.snap +++ /dev/null @@ -1,36 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"rule A\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Rule( - RuleStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - parent_rules: [], - decorators: [], - checks: [], - args: None, - for_host_name: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_2.snap deleted file mode 100644 index 25924f88f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_2.snap +++ /dev/null @@ -1,49 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"rule A[\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Rule( - RuleStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - parent_rules: [], - decorators: [], - checks: [], - args: Some( - Node { - node: Arguments { - args: [], - defaults: [], - ty_list: [], - }, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ), - for_host_name: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_3.snap deleted file mode 100644 index 4b30e85b0..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_3.snap +++ /dev/null @@ -1,58 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"rule A::\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Rule( - RuleStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - parent_rules: [], - decorators: [], - checks: [ - Node { - node: CheckExpr { - test: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 8, - }, - if_cond: None, - msg: None, - }, - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 8, - }, - ], - args: None, - for_host_name: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_4.snap deleted file mode 100644 index d94506fa0..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_4.snap +++ /dev/null @@ -1,58 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"rule A:B\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Rule( - RuleStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - parent_rules: [], - decorators: [], - checks: [ - Node { - node: CheckExpr { - test: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 8, - }, - if_cond: None, - msg: None, - }, - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 8, - }, - ], - args: None, - for_host_name: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_5.snap deleted file mode 100644 index cc4c1f167..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_5.snap +++ /dev/null @@ -1,49 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"rule A(:\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Rule( - RuleStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - parent_rules: [ - Node { - node: Identifier { - names: [], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - decorators: [], - checks: [], - args: None, - for_host_name: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_6.snap deleted file mode 100644 index 6bf798b74..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_6.snap +++ /dev/null @@ -1,60 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nrule A:\n True \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Rule( - RuleStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 5, - end_line: 2, - end_column: 6, - }, - parent_rules: [], - decorators: [], - checks: [ - Node { - node: CheckExpr { - test: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 8, - }, - if_cond: None, - msg: None, - }, - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 8, - }, - ], - args: None, - for_host_name: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 3, - end_column: 9, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_7.snap deleted file mode 100644 index 5b1f5dd0d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__rule_stmt_recovery_7.snap +++ /dev/null @@ -1,79 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nrule A:\n @\n\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Rule( - RuleStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 5, - end_line: 2, - end_column: 6, - }, - parent_rules: [], - decorators: [], - checks: [ - Node { - node: CheckExpr { - test: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - if_cond: None, - msg: None, - }, - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 4, - }, - Node { - node: CheckExpr { - test: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 5, - end_line: 3, - end_column: 6, - }, - if_cond: None, - msg: None, - }, - filename: "", - line: 3, - column: 5, - end_line: 3, - end_column: 5, - }, - ], - args: None, - for_host_name: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 3, - end_column: 6, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_0.snap deleted file mode 100644 index 5f6e442ad..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_0.snap +++ /dev/null @@ -1,51 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"s {\"#)" ---- -Node { - node: Schema( - SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "s", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_1.snap deleted file mode 100644 index 89c8905aa..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_1.snap +++ /dev/null @@ -1,101 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"s {a=1\"#)" ---- -Node { - node: Schema( - SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "s", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - ], - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_2.snap deleted file mode 100644 index d601fb18f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_2.snap +++ /dev/null @@ -1,36 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"s.0 {a=1}\"#)" ---- -Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "s", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - Node { - node: "", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_3.snap deleted file mode 100644 index 3e5dc5123..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_3.snap +++ /dev/null @@ -1,62 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"s?.a {a=1}\"#)" ---- -Node { - node: Selector( - SelectorExpr { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "s", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ctx: Load, - has_question: true, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_4.snap deleted file mode 100644 index 2a0aad990..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_4.snap +++ /dev/null @@ -1,109 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"s. {a=1}\"#)" ---- -Node { - node: Schema( - SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "s", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - Node { - node: "", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - args: [], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 8, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_5.snap deleted file mode 100644 index 2f3c3ba6f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_5.snap +++ /dev/null @@ -1,104 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"s( {a=1}\"#)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "s", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [ - Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 8, - }, - ], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_6.snap deleted file mode 100644 index d61635ea6..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_recovery_6.snap +++ /dev/null @@ -1,101 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"s(] {a=1}\"#)" ---- -Node { - node: Schema( - SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "s", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - args: [], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 8, - }, - ], - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 9, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_0.snap deleted file mode 100644 index dfe7121ea..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_0.snap +++ /dev/null @@ -1,41 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_1.snap deleted file mode 100644 index 6f8bf3c3d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_1.snap +++ /dev/null @@ -1,41 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_10.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_10.snap deleted file mode 100644 index bc0fcc076..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_10.snap +++ /dev/null @@ -1,77 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A:\n[str:]: []\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 0, - }, - Node { - node: Assign( - AssignStmt { - targets: [], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 2, - column: 10, - end_line: 2, - end_column: 10, - }, - ty: Some( - Node { - node: List( - ListType { - inner_type: None, - }, - ), - filename: "", - line: 2, - column: 8, - end_line: 2, - end_column: 10, - }, - ), - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 6, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_11.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_11.snap deleted file mode 100644 index 97012da11..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_11.snap +++ /dev/null @@ -1,75 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A:\n[str]: str = \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 0, - }, - Node { - node: Assign( - AssignStmt { - targets: [], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 2, - column: 13, - end_line: 2, - end_column: 13, - }, - ty: Some( - Node { - node: Basic( - Str, - ), - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 10, - }, - ), - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 12, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_12.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_12.snap deleted file mode 100644 index c0d7f3461..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_12.snap +++ /dev/null @@ -1,73 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A:\n[str]: = \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 0, - }, - Node { - node: Assign( - AssignStmt { - targets: [], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 2, - column: 9, - end_line: 2, - end_column: 9, - }, - ty: Some( - Node { - node: Any, - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - ), - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 5, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_13.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_13.snap deleted file mode 100644 index e14c4f3f8..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_13.snap +++ /dev/null @@ -1,77 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A:\n[str]: ''= \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 0, - }, - Node { - node: Assign( - AssignStmt { - targets: [], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 2, - column: 11, - end_line: 2, - end_column: 11, - }, - ty: Some( - Node { - node: Literal( - Str( - "", - ), - ), - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 9, - }, - ), - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 10, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_14.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_14.snap deleted file mode 100644 index 631651b7a..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_14.snap +++ /dev/null @@ -1,113 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A:\na??: int \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 0, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - ], - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "int", - filename: "", - line: 2, - column: 5, - end_line: 2, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 5, - end_line: 2, - end_column: 8, - }, - ], - }, - ), - filename: "", - line: 2, - column: 5, - end_line: 2, - end_column: 8, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_15.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_15.snap deleted file mode 100644 index 7aa335109..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_15.snap +++ /dev/null @@ -1,148 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A:\na!: int \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 0, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - ], - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 2, - column: 2, - end_line: 2, - end_column: 3, - }, - }, - ), - filename: "", - line: 2, - column: 1, - end_line: 2, - end_column: 2, - }, - ], - }, - ), - filename: "", - line: 2, - column: 1, - end_line: 2, - end_column: 2, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "int", - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 7, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_16.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_16.snap deleted file mode 100644 index 6109806a8..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_16.snap +++ /dev/null @@ -1,183 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A:\na!!: int \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 0, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - ], - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 2, - column: 2, - end_line: 2, - end_column: 3, - }, - }, - ), - filename: "", - line: 2, - column: 1, - end_line: 2, - end_column: 2, - }, - ], - }, - ), - filename: "", - line: 2, - column: 1, - end_line: 2, - end_column: 2, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 2, - column: 3, - end_line: 2, - end_column: 4, - }, - }, - ), - filename: "", - line: 2, - column: 2, - end_line: 2, - end_column: 3, - }, - ], - }, - ), - filename: "", - line: 2, - column: 2, - end_line: 2, - end_column: 3, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "int", - filename: "", - line: 2, - column: 5, - end_line: 2, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 5, - end_line: 2, - end_column: 8, - }, - ], - }, - ), - filename: "", - line: 2, - column: 5, - end_line: 2, - end_column: 8, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_17.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_17.snap deleted file mode 100644 index 497f3d15e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_17.snap +++ /dev/null @@ -1,93 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A:\na: \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 0, - }, - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 2, - column: 3, - end_line: 2, - end_column: 3, - }, - ty: Some( - Node { - node: Any, - filename: "", - line: 2, - column: 3, - end_line: 2, - end_column: 3, - }, - ), - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_18.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_18.snap deleted file mode 100644 index 4b59b1b3c..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_18.snap +++ /dev/null @@ -1,88 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 210 -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n a: int\"#)" ---- -Module { - filename: "", - pkg: "", - doc: "", - name: "", - body: [ - Node { - node: Schema( - SchemaStmt { - doc: "", - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [ - Node { - node: SchemaAttr( - SchemaAttr { - doc: "", - name: Node { - node: "a", - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - type_str: Node { - node: "int", - filename: "", - line: 3, - column: 7, - end_line: 3, - end_column: 10, - }, - op: None, - value: None, - is_optional: false, - decorators: [], - ty: Node { - node: Basic( - Int, - ), - filename: "", - line: 3, - column: 7, - end_line: 3, - end_column: 10, - }, - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 10, - }, - ], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 3, - end_column: 10, - }, - ], - comments: [], -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_19.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_19.snap deleted file mode 100644 index 70c29f78e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_19.snap +++ /dev/null @@ -1,109 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"@deprecated\nschema A:\n a: \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [ - Node { - node: SchemaAttr( - SchemaAttr { - doc: "", - name: Node { - node: "a", - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - op: None, - value: None, - is_optional: false, - decorators: [], - ty: Node { - node: Any, - filename: "", - line: 3, - column: 7, - end_line: 3, - end_column: 7, - }, - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 7, - }, - ], - decorators: [ - Node { - node: CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "deprecated", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 11, - }, - args: [], - keywords: [], - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 11, - }, - ], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 3, - end_column: 7, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_2.snap deleted file mode 100644 index af0bbf8a4..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_2.snap +++ /dev/null @@ -1,54 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A[\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: Some( - Node { - node: Arguments { - args: [], - defaults: [], - ty_list: [], - }, - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ), - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_20.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_20.snap deleted file mode 100644 index 6889d2b02..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_20.snap +++ /dev/null @@ -1,10 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"@deprecated(\nschema A:\n a: \"#)" ---- -Module { - filename: "", - doc: None, - body: [], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_21.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_21.snap deleted file mode 100644 index 6889d2b02..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_21.snap +++ /dev/null @@ -1,10 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"@deprecated(\nschema A:\n a: \"#)" ---- -Module { - filename: "", - doc: None, - body: [], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_22.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_22.snap deleted file mode 100644 index 195cdc9c0..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_22.snap +++ /dev/null @@ -1,133 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"@deprecated(a\nschema A:\n a: \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [ - Node { - node: SchemaAttr( - SchemaAttr { - doc: "", - name: Node { - node: "a", - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - op: None, - value: None, - is_optional: false, - decorators: [], - ty: Node { - node: Any, - filename: "", - line: 3, - column: 7, - end_line: 3, - end_column: 7, - }, - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 7, - }, - ], - decorators: [ - Node { - node: CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "deprecated", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 11, - }, - args: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 13, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 13, - }, - ], - keywords: [], - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 13, - }, - ], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 3, - end_column: 7, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_23.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_23.snap deleted file mode 100644 index d915512c1..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_23.snap +++ /dev/null @@ -1,133 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"@deprecated(a,\nschema A:\n a: \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [ - Node { - node: SchemaAttr( - SchemaAttr { - doc: "", - name: Node { - node: "a", - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - op: None, - value: None, - is_optional: false, - decorators: [], - ty: Node { - node: Any, - filename: "", - line: 3, - column: 7, - end_line: 3, - end_column: 7, - }, - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 7, - }, - ], - decorators: [ - Node { - node: CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "deprecated", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 11, - }, - args: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 13, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 13, - }, - ], - keywords: [], - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 14, - }, - ], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 3, - end_column: 7, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_24.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_24.snap deleted file mode 100644 index 6b4165f99..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_24.snap +++ /dev/null @@ -1,131 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"@deprecated((),\nschema A:\n a: \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [ - Node { - node: SchemaAttr( - SchemaAttr { - doc: "", - name: Node { - node: "a", - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - op: None, - value: None, - is_optional: false, - decorators: [], - ty: Node { - node: Any, - filename: "", - line: 3, - column: 7, - end_line: 3, - end_column: 7, - }, - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 7, - }, - ], - decorators: [ - Node { - node: CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "deprecated", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 11, - }, - args: [ - Node { - node: Paren( - ParenExpr { - expr: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 14, - }, - ], - keywords: [], - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 15, - }, - ], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 3, - end_column: 7, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_25.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_25.snap deleted file mode 100644 index e857c6eef..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_25.snap +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n check: \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [ - Node { - node: CheckExpr { - test: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 11, - end_line: 3, - end_column: 11, - }, - if_cond: None, - msg: None, - }, - filename: "", - line: 3, - column: 11, - end_line: 3, - end_column: 11, - }, - ], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 4, - end_column: 0, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_26.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_26.snap deleted file mode 100644 index f95033e52..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_26.snap +++ /dev/null @@ -1,84 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n check: \n @\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [ - Node { - node: CheckExpr { - test: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 4, - column: 8, - end_line: 4, - end_column: 9, - }, - if_cond: None, - msg: None, - }, - filename: "", - line: 4, - column: 8, - end_line: 4, - end_column: 8, - }, - Node { - node: CheckExpr { - test: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 4, - column: 9, - end_line: 4, - end_column: 9, - }, - if_cond: None, - msg: None, - }, - filename: "", - line: 4, - column: 9, - end_line: 4, - end_column: 9, - }, - ], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 4, - end_column: 9, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_27.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_27.snap deleted file mode 100644 index 76f1085d3..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_27.snap +++ /dev/null @@ -1,145 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n [.str]: str \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [ - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Selector( - SelectorExpr { - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 5, - end_line: 3, - end_column: 6, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "str", - filename: "", - line: 3, - column: 6, - end_line: 3, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 3, - column: 6, - end_line: 3, - end_column: 9, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 3, - column: 5, - end_line: 3, - end_column: 9, - }, - ], - }, - ), - filename: "", - line: 3, - column: 5, - end_line: 3, - end_column: 9, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 9, - end_line: 3, - end_column: 10, - }, - ], - }, - ), - filename: "", - line: 3, - column: 9, - end_line: 3, - end_column: 10, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 16, - end_line: 3, - end_column: 16, - }, - ], - }, - ), - filename: "", - line: 3, - column: 16, - end_line: 3, - end_column: 16, - }, - ], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 4, - end_column: 0, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_28.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_28.snap deleted file mode 100644 index 5f479243b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_28.snap +++ /dev/null @@ -1,168 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n [....str]: str \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [ - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 5, - end_line: 3, - end_column: 8, - }, - ], - }, - ), - filename: "", - line: 3, - column: 5, - end_line: 3, - end_column: 8, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Selector( - SelectorExpr { - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "str", - filename: "", - line: 3, - column: 9, - end_line: 3, - end_column: 12, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 3, - column: 9, - end_line: 3, - end_column: 12, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 12, - }, - ], - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 12, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 12, - end_line: 3, - end_column: 13, - }, - ], - }, - ), - filename: "", - line: 3, - column: 12, - end_line: 3, - end_column: 13, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 19, - end_line: 3, - end_column: 19, - }, - ], - }, - ), - filename: "", - line: 3, - column: 19, - end_line: 3, - end_column: 19, - }, - ], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 4, - end_column: 0, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_29.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_29.snap deleted file mode 100644 index 62fc4f318..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_29.snap +++ /dev/null @@ -1,74 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n @\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [ - Node { - node: SchemaAttr( - SchemaAttr { - doc: "", - name: Node { - node: "", - filename: "", - line: 3, - column: 5, - end_line: 3, - end_column: 5, - }, - op: None, - value: None, - is_optional: false, - decorators: [], - ty: Node { - node: Any, - filename: "", - line: 3, - column: 5, - end_line: 3, - end_column: 5, - }, - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - ], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 4, - end_column: 0, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_3.snap deleted file mode 100644 index 81c47f096..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_3.snap +++ /dev/null @@ -1,41 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A::\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_30.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_30.snap deleted file mode 100644 index b16bcd28a..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_30.snap +++ /dev/null @@ -1,99 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n .\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [ - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Selector( - SelectorExpr { - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 3, - column: 5, - end_line: 3, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 3, - column: 5, - end_line: 3, - end_column: 5, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - ], - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - ], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 3, - end_column: 5, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_31.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_31.snap deleted file mode 100644 index 8b89cf890..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_31.snap +++ /dev/null @@ -1,87 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n [str]: str\n [str]: int\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: Some( - Node { - node: SchemaIndexSignature { - key_name: None, - value: None, - any_other: false, - key_ty: Node { - node: Named( - Identifier { - names: [ - Node { - node: "str", - filename: "", - line: 4, - column: 5, - end_line: 4, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 4, - column: 5, - end_line: 4, - end_column: 8, - }, - value_ty: Node { - node: Basic( - Int, - ), - filename: "", - line: 4, - column: 11, - end_line: 4, - end_column: 14, - }, - }, - filename: "", - line: 4, - column: 4, - end_line: 4, - end_column: 14, - }, - ), - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 4, - end_column: 14, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_32.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_32.snap deleted file mode 100644 index ecddecab0..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_32.snap +++ /dev/null @@ -1,76 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n \"attr\": str\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [ - Node { - node: SchemaAttr( - SchemaAttr { - doc: "", - name: Node { - node: "attr", - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 10, - }, - op: None, - value: None, - is_optional: false, - decorators: [], - ty: Node { - node: Basic( - Str, - ), - filename: "", - line: 3, - column: 12, - end_line: 3, - end_column: 15, - }, - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 15, - }, - ], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 3, - end_column: 15, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_33.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_33.snap deleted file mode 100644 index 94699965b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_33.snap +++ /dev/null @@ -1,85 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n \"\"\"Schema Doc\"\"\"\n \"attr\": str\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: Some( - Node { - node: "\"\"\"Schema Doc\"\"\"", - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 20, - }, - ), - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [ - Node { - node: SchemaAttr( - SchemaAttr { - doc: "", - name: Node { - node: "attr", - filename: "", - line: 4, - column: 4, - end_line: 4, - end_column: 10, - }, - op: None, - value: None, - is_optional: false, - decorators: [], - ty: Node { - node: Basic( - Str, - ), - filename: "", - line: 4, - column: 12, - end_line: 4, - end_column: 15, - }, - }, - ), - filename: "", - line: 4, - column: 4, - end_line: 4, - end_column: 15, - }, - ], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 4, - end_column: 15, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_34.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_34.snap deleted file mode 100644 index 25d475bb9..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_34.snap +++ /dev/null @@ -1,69 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n \"attr: str\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [ - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"attr: str", - value: "attr: str", - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 14, - }, - ], - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 14, - }, - ], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 3, - end_column: 14, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_35.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_35.snap deleted file mode 100644 index da25f67ba..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_35.snap +++ /dev/null @@ -1,74 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n \"attr\":\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [ - Node { - node: SchemaAttr( - SchemaAttr { - doc: "", - name: Node { - node: "attr", - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 10, - }, - op: None, - value: None, - is_optional: false, - decorators: [], - ty: Node { - node: Any, - filename: "", - line: 3, - column: 11, - end_line: 3, - end_column: 11, - }, - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 11, - }, - ], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 3, - end_column: 11, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_36.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_36.snap deleted file mode 100644 index f6a0910bb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_36.snap +++ /dev/null @@ -1,41 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n mixin: \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 4, - end_column: 0, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_37.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_37.snap deleted file mode 100644 index 4d014d978..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_37.snap +++ /dev/null @@ -1,84 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n mixin: [\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [ - Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 3, - column: 11, - end_line: 3, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 3, - column: 11, - end_line: 3, - end_column: 11, - }, - Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 3, - column: 12, - end_line: 3, - end_column: 12, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 3, - column: 12, - end_line: 3, - end_column: 12, - }, - ], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 4, - end_column: 0, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_38.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_38.snap deleted file mode 100644 index a664c289e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_38.snap +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n mixin: []\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [ - Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 3, - column: 11, - end_line: 3, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 3, - column: 11, - end_line: 3, - end_column: 11, - }, - ], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 3, - end_column: 13, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_39.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_39.snap deleted file mode 100644 index d063f1e0f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_39.snap +++ /dev/null @@ -1,41 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n mixin []\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 3, - end_column: 12, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_4.snap deleted file mode 100644 index 0d9173231..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_4.snap +++ /dev/null @@ -1,77 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A:B\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "B", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - ], - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 10, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_40.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_40.snap deleted file mode 100644 index 76f050c8a..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_40.snap +++ /dev/null @@ -1,41 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"\nschema A:\n mixin [\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 4, - end_column: 0, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_5.snap deleted file mode 100644 index c0f19a73e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_5.snap +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A(:\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: Some( - Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 9, - }, - ), - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 10, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_6.snap deleted file mode 100644 index f7d1e7d10..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_6.snap +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A():\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: Some( - Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 9, - }, - ), - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_7.snap deleted file mode 100644 index b79287b21..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_7.snap +++ /dev/null @@ -1,129 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A:\na:: int\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 0, - }, - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 7, - }, - ty: Some( - Node { - node: Any, - filename: "", - line: 2, - column: 2, - end_line: 2, - end_column: 3, - }, - ), - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "int", - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 7, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_8.snap deleted file mode 100644 index 696794612..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_8.snap +++ /dev/null @@ -1,95 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A:\na: int =\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 0, - }, - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "a", - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - ], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 2, - column: 8, - end_line: 2, - end_column: 8, - }, - ty: Some( - Node { - node: Basic( - Int, - ), - filename: "", - line: 2, - column: 3, - end_line: 2, - end_column: 6, - }, - ), - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 8, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_9.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_9.snap deleted file mode 100644 index b6722c4e9..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__schema_stmt_recovery_9.snap +++ /dev/null @@ -1,77 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"schema A:\n[]: []\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Schema( - SchemaStmt { - doc: None, - name: Node { - node: "A", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - parent_name: None, - for_host_name: None, - is_mixin: false, - is_protocol: false, - args: None, - mixins: [], - body: [], - decorators: [], - checks: [], - index_signature: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 0, - }, - Node { - node: Assign( - AssignStmt { - targets: [], - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 2, - column: 6, - end_line: 2, - end_column: 6, - }, - ty: Some( - Node { - node: List( - ListType { - inner_type: None, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 6, - }, - ), - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 2, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_0.snap deleted file mode 100644 index bbe003c51..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_0.snap +++ /dev/null @@ -1,36 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a.\"#)" ---- -Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - Node { - node: "", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_1.snap deleted file mode 100644 index 97847cd0c..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_1.snap +++ /dev/null @@ -1,44 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a.b.\"#)" ---- -Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - Node { - node: "b", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - Node { - node: "", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_10.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_10.snap deleted file mode 100644 index 35c0b2f28..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_10.snap +++ /dev/null @@ -1,62 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a?.b?\"#)" ---- -Node { - node: Selector( - SelectorExpr { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ctx: Load, - has_question: true, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_11.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_11.snap deleted file mode 100644 index 615b8a3db..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_11.snap +++ /dev/null @@ -1,96 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a?.b?.c?\"#)" ---- -Node { - node: Selector( - SelectorExpr { - value: Node { - node: Selector( - SelectorExpr { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ctx: Load, - has_question: true, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "c", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ctx: Load, - has_question: true, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_12.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_12.snap deleted file mode 100644 index 7deefffd2..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_12.snap +++ /dev/null @@ -1,36 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a.0\"#)" ---- -Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - Node { - node: "", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_13.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_13.snap deleted file mode 100644 index 0f7564c77..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_13.snap +++ /dev/null @@ -1,44 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a..0\"#)" ---- -Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - Node { - node: "", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 2, - }, - Node { - node: "", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_14.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_14.snap deleted file mode 100644 index 9a683650f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_14.snap +++ /dev/null @@ -1,28 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a...\"#)" ---- -Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_2.snap deleted file mode 100644 index ad5c2dd8d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_2.snap +++ /dev/null @@ -1,52 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a.b.c.\"#)" ---- -Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - Node { - node: "b", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - Node { - node: "c", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - Node { - node: "", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_3.snap deleted file mode 100644 index 992848968..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_3.snap +++ /dev/null @@ -1,53 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"''.\"#)" ---- -Node { - node: Selector( - SelectorExpr { - value: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "''", - value: "", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_4.snap deleted file mode 100644 index 45ff29d11..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_4.snap +++ /dev/null @@ -1,53 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"''.lower\"#)" ---- -Node { - node: Selector( - SelectorExpr { - value: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "''", - value: "", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "lower", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 8, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_5.snap deleted file mode 100644 index 484388876..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_5.snap +++ /dev/null @@ -1,100 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"''.lower().\"#)" ---- -Node { - node: Selector( - SelectorExpr { - value: Node { - node: Call( - CallExpr { - func: Node { - node: Selector( - SelectorExpr { - value: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "''", - value: "", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "lower", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 8, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, - }, - args: [], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 10, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 11, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_6.snap deleted file mode 100644 index 675b0e19b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_6.snap +++ /dev/null @@ -1,62 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a?.\"#)" ---- -Node { - node: Selector( - SelectorExpr { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - ctx: Load, - has_question: true, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_7.snap deleted file mode 100644 index 20d302127..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_7.snap +++ /dev/null @@ -1,96 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a?.b?.\"#)" ---- -Node { - node: Selector( - SelectorExpr { - value: Node { - node: Selector( - SelectorExpr { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ctx: Load, - has_question: true, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - ctx: Load, - has_question: true, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_8.snap deleted file mode 100644 index 202dd5709..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_8.snap +++ /dev/null @@ -1,130 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a?.b?.c?.\"#)" ---- -Node { - node: Selector( - SelectorExpr { - value: Node { - node: Selector( - SelectorExpr { - value: Node { - node: Selector( - SelectorExpr { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ctx: Load, - has_question: true, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "c", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ctx: Load, - has_question: true, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 9, - }, - ctx: Load, - has_question: true, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_9.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_9.snap deleted file mode 100644 index 25cc39e66..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__select_recovery_9.snap +++ /dev/null @@ -1,28 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a?\"#)" ---- -Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_0.snap deleted file mode 100644 index 25c936d5b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_0.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 3 -expression: "crate::tests::parsing_expr_string(\"'abc\")" ---- -Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'abc", - value: "abc", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_1.snap deleted file mode 100644 index ce6535974..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_1.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 4 -expression: "crate::tests::parsing_expr_string(\"r'abc\")" ---- -Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "r'abc", - value: "abc", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_2.snap deleted file mode 100644 index fce74020f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_2.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 5 -expression: "crate::tests::parsing_expr_string(\"'''abc\")" ---- -Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'''abc", - value: "''abc", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_3.snap deleted file mode 100644 index 03c0aa2e3..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_3.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 6 -expression: "crate::tests::parsing_expr_string(\"r'''abc\")" ---- -Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "r'''abc", - value: "''abc", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_4.snap deleted file mode 100644 index 55f2ad0c0..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_4.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 7 -expression: "crate::tests::parsing_expr_string(\"r''abc'\")" ---- -Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "r''", - value: "", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_5.snap deleted file mode 100644 index 83b1e9728..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_5.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 8 -expression: "crate::tests::parsing_expr_string(\"'\")" ---- -Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'", - value: "", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_6.snap deleted file mode 100644 index 2d74a5ec0..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_6.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 9 -expression: "crate::tests::parsing_expr_string(\"'''\")" ---- -Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'''", - value: "''", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_7.snap deleted file mode 100644 index 6f68ad175..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_7.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 10 -expression: "crate::tests::parsing_expr_string(\"'\\n\")" ---- -Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'\n", - value: "", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_8.snap deleted file mode 100644 index 5f96fc52f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__string_literal_recovery_8.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 11 -expression: "crate::tests::parsing_expr_string(\"r'abc\\n\")" ---- -Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "r'abc", - value: "abc", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_0.snap deleted file mode 100644 index 7acd7bdf8..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_0.snap +++ /dev/null @@ -1,61 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a[b 1]\"#)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_1.snap deleted file mode 100644 index 6877c8670..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_1.snap +++ /dev/null @@ -1,56 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a[1,b]\"#)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: Some( - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ), - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_10.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_10.snap deleted file mode 100644 index c0b5ac715..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_10.snap +++ /dev/null @@ -1,101 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"[0]?.[0]\"#)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Selector( - SelectorExpr { - value: Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 5, - }, - ctx: Load, - has_question: true, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, - }, - index: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ), - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_11.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_11.snap deleted file mode 100644 index 5ac61db4d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_11.snap +++ /dev/null @@ -1,35 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 95 -expression: "crate::tests::parsing_expr_string(r#\"[0]??[0]\"#)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_12.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_12.snap deleted file mode 100644 index d68841a4b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_12.snap +++ /dev/null @@ -1,101 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"[0].?[0]\"#)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Selector( - SelectorExpr { - value: Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, - }, - index: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ), - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: true, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_2.snap deleted file mode 100644 index 034165107..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_2.snap +++ /dev/null @@ -1,69 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a[b;;b]\"#)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ), - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_3.snap deleted file mode 100644 index 6e6a2f491..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_3.snap +++ /dev/null @@ -1,56 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a[b[b]\"#)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: Some( - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 6, - }, - ), - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_4.snap deleted file mode 100644 index 53b3104ed..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_4.snap +++ /dev/null @@ -1,45 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a[:::]\"#)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: None, - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_5.snap deleted file mode 100644 index 45d2cd7cc..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_5.snap +++ /dev/null @@ -1,77 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"a[:1:2:]\"#)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: None, - lower: None, - upper: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ), - step: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ), - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_6.snap deleted file mode 100644 index b250a5626..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_6.snap +++ /dev/null @@ -1,107 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"[][a:b:c:d]\"#)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: List( - ListExpr { - elts: [], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - index: None, - lower: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ), - upper: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ), - step: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "c", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ), - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_7.snap deleted file mode 100644 index f9a7d62fc..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_7.snap +++ /dev/null @@ -1,36 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 116 -expression: "crate::tests::parsing_expr_string(r#\"[][]\"#)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: List( - ListExpr { - elts: [], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - index: None, - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_8.snap deleted file mode 100644 index 5959e1822..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_8.snap +++ /dev/null @@ -1,53 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 117 -expression: "crate::tests::parsing_expr_string(r#\"[][][]\"#)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Subscript( - Subscript { - value: Node { - node: List( - ListExpr { - elts: [], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - index: None, - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, - }, - index: None, - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_9.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_9.snap deleted file mode 100644 index bd84fee9d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__subscript_recovery_9.snap +++ /dev/null @@ -1,36 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -assertion_line: 118 -expression: "crate::tests::parsing_expr_string(r#\"[]?[]\"#)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: List( - ListExpr { - elts: [], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - index: None, - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: true, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_0.snap deleted file mode 100644 index 47c1b7a74..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_0.snap +++ /dev/null @@ -1,50 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"type\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: TypeAlias( - TypeAliasStmt { - type_name: Node { - node: Identifier { - names: [], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - type_value: Node { - node: "any", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - ty: Node { - node: Any, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 4, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_1.snap deleted file mode 100644 index e7f6a3b7d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_1.snap +++ /dev/null @@ -1,50 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"type 'pkg_path'\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: TypeAlias( - TypeAliasStmt { - type_name: Node { - node: Identifier { - names: [], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 15, - }, - type_value: Node { - node: "any", - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 15, - }, - ty: Node { - node: Any, - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 15, - }, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 15, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_2.snap deleted file mode 100644 index df48fb9e0..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_2.snap +++ /dev/null @@ -1,67 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"type pkg_path.\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: TypeAlias( - TypeAliasStmt { - type_name: Node { - node: Identifier { - names: [ - Node { - node: "pkg_path", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 13, - }, - Node { - node: "", - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 14, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 14, - }, - type_value: Node { - node: "any", - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 14, - }, - ty: Node { - node: Any, - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 14, - }, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 14, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_3.snap deleted file mode 100644 index eec7060a9..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_3.snap +++ /dev/null @@ -1,50 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"type pkg_path[0]\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: TypeAlias( - TypeAliasStmt { - type_name: Node { - node: Identifier { - names: [], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 16, - }, - type_value: Node { - node: "any", - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 16, - }, - ty: Node { - node: Any, - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 16, - }, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 16, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_4.snap deleted file mode 100644 index bfb604958..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_4.snap +++ /dev/null @@ -1,50 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"type .pkg_path.\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: TypeAlias( - TypeAliasStmt { - type_name: Node { - node: Identifier { - names: [], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 15, - }, - type_value: Node { - node: "any", - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 15, - }, - ty: Node { - node: Any, - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 15, - }, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 15, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_5.snap deleted file mode 100644 index 897aa29b2..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_5.snap +++ /dev/null @@ -1,59 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"type pkg_path = \"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: TypeAlias( - TypeAliasStmt { - type_name: Node { - node: Identifier { - names: [ - Node { - node: "pkg_path", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 13, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 13, - }, - type_value: Node { - node: "any", - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 16, - }, - ty: Node { - node: Any, - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 16, - }, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 16, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_6.snap deleted file mode 100644 index 895de4613..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__type_alias_recovery_6.snap +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"type pkg_path = 'data'\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: TypeAlias( - TypeAliasStmt { - type_name: Node { - node: Identifier { - names: [ - Node { - node: "pkg_path", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 13, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 13, - }, - type_value: Node { - node: "\"data\"", - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 22, - }, - ty: Node { - node: Literal( - Str( - "data", - ), - ), - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 22, - }, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 22, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_0.snap deleted file mode 100644 index 82b3cdaa4..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_0.snap +++ /dev/null @@ -1,40 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"!a\"#)" ---- -Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_1.snap deleted file mode 100644 index 16dc359a3..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_1.snap +++ /dev/null @@ -1,27 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"!!a\"#)" ---- -Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_2.snap deleted file mode 100644 index dbe5ca25a..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_2.snap +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"not (!a)\"#)" ---- -Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: Paren( - ParenExpr { - expr: Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 7, - }, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 8, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_3.snap deleted file mode 100644 index c564377bc..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_3.snap +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"! (not a)\"#)" ---- -Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: Paren( - ParenExpr { - expr: Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 8, - }, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 9, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_5.snap deleted file mode 100644 index b81c0b0e6..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_5.snap +++ /dev/null @@ -1,62 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"++i\"#)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Unary( - UnaryExpr { - op: UAdd, - operand: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - op: Add, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_6.snap deleted file mode 100644 index 4d52ae56e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_6.snap +++ /dev/null @@ -1,62 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"--i\"#)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Unary( - UnaryExpr { - op: USub, - operand: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - op: Sub, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_7.snap deleted file mode 100644 index 986f87af6..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_7.snap +++ /dev/null @@ -1,62 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"-+i\"#)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Unary( - UnaryExpr { - op: USub, - operand: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - op: Add, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_8.snap deleted file mode 100644 index 35ca71f65..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unary_recovery_8.snap +++ /dev/null @@ -1,27 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_expr_string(r#\"~~i\"#)" ---- -Node { - node: Unary( - UnaryExpr { - op: Invert, - operand: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_0.snap deleted file mode 100644 index 14cf86ba4..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_0.snap +++ /dev/null @@ -1,87 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"s: Server {\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Unification( - UnificationStmt { - target: Node { - node: Identifier { - names: [ - Node { - node: "s", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Store, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - value: Node { - node: SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "Server", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - args: [], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_1.snap deleted file mode 100644 index 0349210c7..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_1.snap +++ /dev/null @@ -1,87 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"s: Server {}\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Unification( - UnificationStmt { - target: Node { - node: Identifier { - names: [ - Node { - node: "s", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Store, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - value: Node { - node: SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "Server", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - args: [], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 12, - }, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_2.snap deleted file mode 100644 index 1e45fa860..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_2.snap +++ /dev/null @@ -1,87 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"s: Server (\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Unification( - UnificationStmt { - target: Node { - node: Identifier { - names: [ - Node { - node: "s", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Store, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - value: Node { - node: SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "Server", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - args: [], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 11, - }, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_3.snap deleted file mode 100644 index a8c89921f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_3.snap +++ /dev/null @@ -1,87 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"s: Server ()\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Unification( - UnificationStmt { - target: Node { - node: Identifier { - names: [ - Node { - node: "s", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Store, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - value: Node { - node: SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "Server", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - args: [], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 12, - }, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_4.snap deleted file mode 100644 index dfa74cd5e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_4.snap +++ /dev/null @@ -1,87 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"s: Server () {\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Unification( - UnificationStmt { - target: Node { - node: Identifier { - names: [ - Node { - node: "s", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Store, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - value: Node { - node: SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "Server", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - args: [], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 14, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 14, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_5.snap deleted file mode 100644 index 1c71c2c1d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_5.snap +++ /dev/null @@ -1,100 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"s: Server ( {\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Unification( - UnificationStmt { - target: Node { - node: Identifier { - names: [ - Node { - node: "s", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Store, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - value: Node { - node: SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "Server", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - args: [ - Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 13, - }, - ], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 13, - }, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 13, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 13, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_6.snap deleted file mode 100644 index 91d45bb2d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__error_recovery__unification_stmt_recovery_6.snap +++ /dev/null @@ -1,87 +0,0 @@ ---- -source: parser/src/tests/error_recovery.rs -expression: "crate::tests::parsing_module_string(r#\"s: Server ( }\"#)" ---- -Module { - filename: "", - doc: None, - body: [ - Node { - node: Unification( - UnificationStmt { - target: Node { - node: Identifier { - names: [ - Node { - node: "s", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Store, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - value: Node { - node: SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "Server", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 9, - }, - args: [], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 13, - }, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 13, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 13, - }, - ], - comments: [], -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_0.snap deleted file mode 100644 index 5eff3ea53..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_0.snap +++ /dev/null @@ -1,74 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"1+2+3\"####)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_1.snap deleted file mode 100644 index 332c5dcc2..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_1.snap +++ /dev/null @@ -1,101 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"1+2*3-4\"####)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - op: Add, - right: Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - op: Mul, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 5, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, - }, - op: Sub, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 4, - ), - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_10.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_10.snap deleted file mode 100644 index 97c2bc28e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_10.snap +++ /dev/null @@ -1,90 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"1 + a and b\"####)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - op: Add, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, - }, - op: And, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_2.snap deleted file mode 100644 index d401b95d2..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_2.snap +++ /dev/null @@ -1,101 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"1+2*3/4\"####)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - op: Add, - right: Node { - node: Binary( - BinaryExpr { - left: Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - op: Mul, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 5, - }, - op: Div, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 4, - ), - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 7, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_3.snap deleted file mode 100644 index 90eafbf74..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_3.snap +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a or b\"####)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - op: Or, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_4.snap deleted file mode 100644 index 2f4355574..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_4.snap +++ /dev/null @@ -1,102 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"x == a or b\"####)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ops: [ - Eq, - ], - comparators: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, - }, - op: Or, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_5.snap deleted file mode 100644 index 390202c20..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_5.snap +++ /dev/null @@ -1,109 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"22 > 11 and 111 < 222\"####)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Compare( - Compare { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 22, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - ops: [ - Gt, - ], - comparators: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 11, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 21, - }, - op: And, - right: Node { - node: Compare( - Compare { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 111, - ), - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 15, - }, - ops: [ - Lt, - ], - comparators: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 222, - ), - }, - ), - filename: "", - line: 1, - column: 18, - end_line: 1, - end_column: 21, - }, - ], - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 21, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 21, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_6.snap deleted file mode 100644 index cd1469496..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_6.snap +++ /dev/null @@ -1,170 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"int(e.value) > 1 and i == 0\"####)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Compare( - Compare { - left: Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "int", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - args: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "e", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - Node { - node: "value", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 11, - }, - ], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, - }, - ops: [ - Gt, - ], - comparators: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 16, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 27, - }, - op: And, - right: Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 22, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 22, - }, - ops: [ - Eq, - ], - comparators: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 26, - end_line: 1, - end_column: 27, - }, - ], - }, - ), - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 27, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 27, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_7.snap deleted file mode 100644 index 7f48f3a65..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_7.snap +++ /dev/null @@ -1,72 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"key in ['key']\"####)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "key", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - ops: [ - In, - ], - comparators: [ - Node { - node: List( - ListExpr { - elts: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'key'", - value: "key", - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 13, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 14, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 14, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_8.snap deleted file mode 100644 index 1bb4f300a..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_8.snap +++ /dev/null @@ -1,72 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"key not in ['key']\"####)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "key", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - ops: [ - NotIn, - ], - comparators: [ - Node { - node: List( - ListExpr { - elts: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'key'", - value: "key", - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 17, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 18, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 18, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_9.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_9.snap deleted file mode 100644 index 416b34223..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_9.snap +++ /dev/null @@ -1,109 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"1 is 1 and 11 is not 22\"####)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Compare( - Compare { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ops: [ - Is, - ], - comparators: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 23, - }, - op: And, - right: Node { - node: Compare( - Compare { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 11, - ), - }, - ), - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 13, - }, - ops: [ - IsNot, - ], - comparators: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 22, - ), - }, - ), - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 23, - }, - ], - }, - ), - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 23, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 23, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_with_paren.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_with_paren.snap deleted file mode 100644 index b370c6def..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__binary_expr_with_paren.snap +++ /dev/null @@ -1,112 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"1*(2+3)-4\"####)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - op: Mul, - right: Node { - node: Paren( - ParenExpr { - expr: Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 7, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, - }, - op: Sub, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 4, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__call_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__call_expr_0.snap deleted file mode 100644 index 44b34d0df..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__call_expr_0.snap +++ /dev/null @@ -1,41 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"func0()\"####)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "func0", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, - }, - args: [], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__call_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__call_expr_1.snap deleted file mode 100644 index 7f53f5a9e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__call_expr_1.snap +++ /dev/null @@ -1,57 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"func1(1)\"####)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "func1", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__call_expr_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__call_expr_2.snap deleted file mode 100644 index 365a54fd2..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__call_expr_2.snap +++ /dev/null @@ -1,89 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"func2(x=2)\"####)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "func2", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, - }, - args: [], - keywords: [ - Node { - node: Keyword { - arg: Node { - node: Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - value: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ), - }, - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 9, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 10, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__call_expr_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__call_expr_3.snap deleted file mode 100644 index abe42a4cb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__call_expr_3.snap +++ /dev/null @@ -1,105 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"func3(1,x=2)\"####)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "func3", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - keywords: [ - Node { - node: Keyword { - arg: Node { - node: Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - value: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - ), - }, - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 11, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_expr_0.snap deleted file mode 100644 index 1a31b93d9..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_expr_0.snap +++ /dev/null @@ -1,136 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{\n \"name\" = {\n \"name\": \"alice\"\n },\n \"gender\" = \"female\"\n}\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"name\"", - value: "name", - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 10, - }, - ), - value: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"name\"", - value: "name", - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 14, - }, - ), - value: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"alice\"", - value: "alice", - }, - ), - filename: "", - line: 3, - column: 16, - end_line: 3, - end_column: 23, - }, - operation: Union, - }, - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 23, - }, - ], - }, - ), - filename: "", - line: 2, - column: 13, - end_line: 4, - end_column: 5, - }, - operation: Override, - }, - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 5, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"gender\"", - value: "gender", - }, - ), - filename: "", - line: 5, - column: 4, - end_line: 5, - end_column: 12, - }, - ), - value: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"female\"", - value: "female", - }, - ), - filename: "", - line: 5, - column: 15, - end_line: 5, - end_column: 23, - }, - operation: Override, - }, - filename: "", - line: 5, - column: 4, - end_line: 5, - end_column: 23, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 6, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_expr_1.snap deleted file mode 100644 index 20854a5cc..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_expr_1.snap +++ /dev/null @@ -1,136 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{\n \"name\" = {\n \"name\": \"alice\"\n }\n \"gender\" = \"female\",\n}\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"name\"", - value: "name", - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 10, - }, - ), - value: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"name\"", - value: "name", - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 14, - }, - ), - value: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"alice\"", - value: "alice", - }, - ), - filename: "", - line: 3, - column: 16, - end_line: 3, - end_column: 23, - }, - operation: Union, - }, - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 23, - }, - ], - }, - ), - filename: "", - line: 2, - column: 13, - end_line: 4, - end_column: 5, - }, - operation: Override, - }, - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 5, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"gender\"", - value: "gender", - }, - ), - filename: "", - line: 5, - column: 4, - end_line: 5, - end_column: 12, - }, - ), - value: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"female\"", - value: "female", - }, - ), - filename: "", - line: 5, - column: 15, - end_line: 5, - end_column: 23, - }, - operation: Override, - }, - filename: "", - line: 5, - column: 4, - end_line: 5, - end_column: 23, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 6, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_expr_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_expr_2.snap deleted file mode 100644 index 13be4b453..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_expr_2.snap +++ /dev/null @@ -1,136 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{\n \"name\" = {\n \"name\": \"alice\",\n }\n \"gender\" = \"female\"\n}\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"name\"", - value: "name", - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 10, - }, - ), - value: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"name\"", - value: "name", - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 14, - }, - ), - value: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"alice\"", - value: "alice", - }, - ), - filename: "", - line: 3, - column: 16, - end_line: 3, - end_column: 23, - }, - operation: Union, - }, - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 23, - }, - ], - }, - ), - filename: "", - line: 2, - column: 13, - end_line: 4, - end_column: 5, - }, - operation: Override, - }, - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 5, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"gender\"", - value: "gender", - }, - ), - filename: "", - line: 5, - column: 4, - end_line: 5, - end_column: 12, - }, - ), - value: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"female\"", - value: "female", - }, - ), - filename: "", - line: 5, - column: 15, - end_line: 5, - end_column: 23, - }, - operation: Override, - }, - filename: "", - line: 5, - column: 4, - end_line: 5, - end_column: 23, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 6, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_if_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_if_expr_0.snap deleted file mode 100644 index 2d85fa3c0..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_if_expr_0.snap +++ /dev/null @@ -1,104 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{\n if True:\n a = 1\n}\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: None, - value: Node { - node: ConfigIfEntry( - ConfigIfEntryExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 11, - }, - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 3, - column: 12, - end_line: 3, - end_column: 13, - }, - operation: Override, - }, - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 13, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 0, - }, - operation: Union, - }, - filename: "", - line: 2, - column: 4, - end_line: 4, - end_column: 0, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_if_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_if_expr_1.snap deleted file mode 100644 index af1795665..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_if_expr_1.snap +++ /dev/null @@ -1,168 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{\n if True:\n a = 1\n else:\n a = 2\n}\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: None, - value: Node { - node: ConfigIfEntry( - ConfigIfEntryExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 11, - }, - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 3, - column: 12, - end_line: 3, - end_column: 13, - }, - operation: Override, - }, - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 13, - }, - ], - orelse: Some( - Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 5, - column: 8, - end_line: 5, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 5, - column: 8, - end_line: 5, - end_column: 9, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 5, - column: 12, - end_line: 5, - end_column: 13, - }, - operation: Override, - }, - filename: "", - line: 5, - column: 8, - end_line: 5, - end_column: 13, - }, - ], - }, - ), - filename: "", - line: 4, - column: 4, - end_line: 6, - end_column: 0, - }, - ), - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 6, - end_column: 0, - }, - operation: Union, - }, - filename: "", - line: 2, - column: 4, - end_line: 6, - end_column: 0, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 6, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_if_expr_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_if_expr_2.snap deleted file mode 100644 index 8931e97bc..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_if_expr_2.snap +++ /dev/null @@ -1,287 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{\n if True:\n a = 1\n elif x > 1:\n a = 2\n else:\n a = 3\n}\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: None, - value: Node { - node: ConfigIfEntry( - ConfigIfEntryExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 11, - }, - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 9, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 3, - column: 12, - end_line: 3, - end_column: 13, - }, - operation: Override, - }, - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 13, - }, - ], - orelse: Some( - Node { - node: ConfigIfEntry( - ConfigIfEntryExpr { - if_cond: Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 4, - column: 9, - end_line: 4, - end_column: 10, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 4, - column: 9, - end_line: 4, - end_column: 10, - }, - ops: [ - Gt, - ], - comparators: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 4, - column: 13, - end_line: 4, - end_column: 14, - }, - ], - }, - ), - filename: "", - line: 4, - column: 9, - end_line: 4, - end_column: 14, - }, - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 5, - column: 8, - end_line: 5, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 5, - column: 8, - end_line: 5, - end_column: 9, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 5, - column: 12, - end_line: 5, - end_column: 13, - }, - operation: Override, - }, - filename: "", - line: 5, - column: 8, - end_line: 5, - end_column: 13, - }, - ], - orelse: Some( - Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 7, - column: 8, - end_line: 7, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 7, - column: 8, - end_line: 7, - end_column: 9, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 7, - column: 12, - end_line: 7, - end_column: 13, - }, - operation: Override, - }, - filename: "", - line: 7, - column: 8, - end_line: 7, - end_column: 13, - }, - ], - }, - ), - filename: "", - line: 6, - column: 4, - end_line: 8, - end_column: 0, - }, - ), - }, - ), - filename: "", - line: 4, - column: 4, - end_line: 6, - end_column: 4, - }, - ), - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 8, - end_column: 0, - }, - operation: Union, - }, - filename: "", - line: 2, - column: 4, - end_line: 8, - end_column: 0, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 8, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_if_expr_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_if_expr_3.snap deleted file mode 100644 index c110d9ea1..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__config_if_expr_3.snap +++ /dev/null @@ -1,141 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{\n if True:\n if False:\n a = 1\n}\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: None, - value: Node { - node: ConfigIfEntry( - ConfigIfEntryExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 11, - }, - items: [ - Node { - node: ConfigEntry { - key: None, - value: Node { - node: ConfigIfEntry( - ConfigIfEntryExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: False, - }, - ), - filename: "", - line: 3, - column: 11, - end_line: 3, - end_column: 16, - }, - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 4, - column: 12, - end_line: 4, - end_column: 13, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 4, - column: 12, - end_line: 4, - end_column: 13, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 4, - column: 16, - end_line: 4, - end_column: 17, - }, - operation: Override, - }, - filename: "", - line: 4, - column: 12, - end_line: 4, - end_column: 17, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 5, - end_column: 0, - }, - operation: Override, - }, - filename: "", - line: 3, - column: 8, - end_line: 5, - end_column: 0, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 5, - end_column: 0, - }, - operation: Union, - }, - filename: "", - line: 2, - column: 4, - end_line: 5, - end_column: 0, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 5, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__dict_comp_expr.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__dict_comp_expr.snap deleted file mode 100644 index a240ca07e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__dict_comp_expr.snap +++ /dev/null @@ -1,262 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{k: v + 1 for k, v in {k1 = 1, k2 = 2}}\"####)" ---- -Node { - node: DictComp( - DictComp { - entry: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "k", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ), - value: Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "v", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 9, - }, - operation: Union, - }, - generators: [ - Node { - node: CompClause { - targets: [ - Node { - node: Identifier { - names: [ - Node { - node: "k", - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 15, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 15, - }, - Node { - node: Identifier { - names: [ - Node { - node: "v", - filename: "", - line: 1, - column: 17, - end_line: 1, - end_column: 18, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 17, - end_line: 1, - end_column: 18, - }, - ], - iter: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "k1", - filename: "", - line: 1, - column: 23, - end_line: 1, - end_column: 25, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 23, - end_line: 1, - end_column: 25, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 28, - end_line: 1, - end_column: 29, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 23, - end_line: 1, - end_column: 29, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "k2", - filename: "", - line: 1, - column: 31, - end_line: 1, - end_column: 33, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 31, - end_line: 1, - end_column: 33, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 36, - end_line: 1, - end_column: 37, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 31, - end_line: 1, - end_column: 37, - }, - ], - }, - ), - filename: "", - line: 1, - column: 22, - end_line: 1, - end_column: 38, - }, - ifs: [], - }, - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 38, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 39, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__dict_expr.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__dict_expr.snap deleted file mode 100644 index f94a0e658..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__dict_expr.snap +++ /dev/null @@ -1,133 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{k0=v0, k1=v1}\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "k0", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 3, - }, - ), - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "v0", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 6, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 6, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "k1", - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 10, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 10, - }, - ), - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "v1", - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 13, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 13, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 13, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 14, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_brace_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_brace_0.snap deleted file mode 100644 index 487dd4827..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_brace_0.snap +++ /dev/null @@ -1,67 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{a=2}\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 4, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_brace_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_brace_1.snap deleted file mode 100644 index 10ebd495e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_brace_1.snap +++ /dev/null @@ -1,67 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{a=2}}\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 4, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_0.snap deleted file mode 100644 index 5f61ac170..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_0.snap +++ /dev/null @@ -1,49 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"[2,3]\"####)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_1.snap deleted file mode 100644 index 8540a6417..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_1.snap +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"[[2,3]\"####)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 6, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_2.snap deleted file mode 100644 index 974638b56..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_2.snap +++ /dev/null @@ -1,49 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"[2,3]]\"####)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_3.snap deleted file mode 100644 index f00b8be1a..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_3.snap +++ /dev/null @@ -1,49 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"[2,3\"####)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_4.snap deleted file mode 100644 index 1caf60fff..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_4.snap +++ /dev/null @@ -1,18 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"[\"####)" ---- -Node { - node: List( - ListExpr { - elts: [], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_5.snap deleted file mode 100644 index aa4f7fe96..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_5.snap +++ /dev/null @@ -1,49 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"[\n 1\n 2,\n]\n \"####)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 3, - column: 4, - end_line: 3, - end_column: 5, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_6.snap deleted file mode 100644 index ca20c1f26..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_6.snap +++ /dev/null @@ -1,49 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"[\n 1,2,\n]\n \"####)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 2, - column: 6, - end_line: 2, - end_column: 7, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 3, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_7.snap deleted file mode 100644 index 9ae683dfa..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_bracket_7.snap +++ /dev/null @@ -1,49 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"[\n 1,2,\n\n \"####)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 2, - column: 6, - end_line: 2, - end_column: 7, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 4, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_0.snap deleted file mode 100644 index c854743c8..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_0.snap +++ /dev/null @@ -1,78 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"({a=2}\"####)" ---- -Node { - node: Paren( - ParenExpr { - expr: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 5, - }, - ], - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_1.snap deleted file mode 100644 index a25037c77..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_1.snap +++ /dev/null @@ -1,89 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"({a=(2}\"####)" ---- -Node { - node: Paren( - ParenExpr { - expr: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - value: Node { - node: Paren( - ParenExpr { - expr: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 7, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_2.snap deleted file mode 100644 index 2f0a50261..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_2.snap +++ /dev/null @@ -1,81 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{a=[2]\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ), - value: Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 6, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_3.snap deleted file mode 100644 index 9758f62a5..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_3.snap +++ /dev/null @@ -1,81 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"[{a=2}\"####)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 5, - }, - ], - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 6, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_4.snap deleted file mode 100644 index c9e7a9b93..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_4.snap +++ /dev/null @@ -1,92 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"({a=[2}\"####)" ---- -Node { - node: Paren( - ParenExpr { - expr: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - value: Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 7, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_5.snap deleted file mode 100644 index e69e0ea93..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_5.snap +++ /dev/null @@ -1,17 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_6.snap deleted file mode 100644 index bda623e7f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_6.snap +++ /dev/null @@ -1,67 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{\n a = 1\n}\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 2, - column: 8, - end_line: 2, - end_column: 9, - }, - operation: Override, - }, - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 9, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 3, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_7.snap deleted file mode 100644 index fa26c7489..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_delim_7.snap +++ /dev/null @@ -1,99 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{\n a = 1\n\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - ), - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 2, - column: 8, - end_line: 2, - end_column: 9, - }, - operation: Override, - }, - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 9, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 2, - column: 10, - end_line: 2, - end_column: 10, - }, - ), - value: Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 2, - column: 10, - end_line: 2, - end_column: 10, - }, - operation: Override, - }, - filename: "", - line: 2, - column: 10, - end_line: 2, - end_column: 10, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 10, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_paren_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_paren_0.snap deleted file mode 100644 index 6c6715bc5..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_paren_0.snap +++ /dev/null @@ -1,58 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"(2+3)\"####)" ---- -Node { - node: Paren( - ParenExpr { - expr: Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 4, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_paren_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_paren_1.snap deleted file mode 100644 index 5a29b6407..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_paren_1.snap +++ /dev/null @@ -1,69 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"((2+3)\"####)" ---- -Node { - node: Paren( - ParenExpr { - expr: Node { - node: Paren( - ParenExpr { - expr: Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 5, - }, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_paren_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_paren_2.snap deleted file mode 100644 index c353720ce..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__expr_with_paren_2.snap +++ /dev/null @@ -1,58 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"(2+3))\"####)" ---- -Node { - node: Paren( - ParenExpr { - expr: Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 4, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__if_expr.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__if_expr.snap deleted file mode 100644 index 6d43c32c0..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__if_expr.snap +++ /dev/null @@ -1,69 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"1 if true else 2\"####)" ---- -Node { - node: If( - IfExpr { - body: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - cond: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "true", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 9, - }, - orelse: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 16, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 16, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__lambda_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__lambda_expr_0.snap deleted file mode 100644 index 0d919f9bc..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__lambda_expr_0.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/expr.rs -assertion_line: 79 -expression: "crate::tests::parsing_expr_string(r####\"lambda {}\"####)" ---- -Node { - node: Lambda( - LambdaExpr { - args: None, - body: [], - return_ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__lambda_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__lambda_expr_1.snap deleted file mode 100644 index f6415f382..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__lambda_expr_1.snap +++ /dev/null @@ -1,59 +0,0 @@ ---- -source: parser/src/tests/expr.rs -assertion_line: 80 -expression: "crate::tests::parsing_expr_string(r####\"lambda x {}\"####)" ---- -Node { - node: Lambda( - LambdaExpr { - args: Some( - Node { - node: Arguments { - args: [ - Node { - node: Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - defaults: [ - None, - ], - ty_list: [ - None, - ], - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ), - body: [], - return_ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__lambda_expr_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__lambda_expr_2.snap deleted file mode 100644 index 0364c43ef..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__lambda_expr_2.snap +++ /dev/null @@ -1,118 +0,0 @@ ---- -source: parser/src/tests/expr.rs -assertion_line: 81 -expression: "crate::tests::parsing_expr_string(r####\"lambda x: int -> int {x}\"####)" ---- -Node { - node: Lambda( - LambdaExpr { - args: Some( - Node { - node: Arguments { - args: [ - Node { - node: Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - defaults: [ - None, - ], - ty_list: [ - Some( - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 13, - }, - ), - ], - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 13, - }, - ), - body: [ - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 22, - end_line: 1, - end_column: 23, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 22, - end_line: 1, - end_column: 23, - }, - ], - }, - ), - filename: "", - line: 1, - column: 22, - end_line: 1, - end_column: 23, - }, - ], - return_ty: Some( - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 17, - end_line: 1, - end_column: 20, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 24, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__lambda_expr_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__lambda_expr_3.snap deleted file mode 100644 index e8f968626..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__lambda_expr_3.snap +++ /dev/null @@ -1,178 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"lambda {\n if True:\n _a = 1\n else:\n _a = 2\n _a\n}\"####)" ---- -Node { - node: Lambda( - LambdaExpr { - args: None, - body: [ - Node { - node: If( - IfStmt { - body: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "_a", - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 10, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 10, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 3, - column: 13, - end_line: 3, - end_column: 14, - }, - ty: None, - }, - ), - filename: "", - line: 3, - column: 8, - end_line: 3, - end_column: 14, - }, - ], - cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 2, - column: 7, - end_line: 2, - end_column: 11, - }, - orelse: [ - Node { - node: Assign( - AssignStmt { - targets: [ - Node { - node: Target { - name: Node { - node: "_a", - filename: "", - line: 5, - column: 8, - end_line: 5, - end_column: 10, - }, - paths: [], - pkgpath: "", - }, - filename: "", - line: 5, - column: 8, - end_line: 5, - end_column: 10, - }, - ], - value: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 5, - column: 13, - end_line: 5, - end_column: 14, - }, - ty: None, - }, - ), - filename: "", - line: 5, - column: 8, - end_line: 5, - end_column: 14, - }, - ], - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 6, - end_column: 4, - }, - Node { - node: Expr( - ExprStmt { - exprs: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "_a", - filename: "", - line: 6, - column: 4, - end_line: 6, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 6, - column: 4, - end_line: 6, - end_column: 6, - }, - ], - }, - ), - filename: "", - line: 6, - column: 4, - end_line: 6, - end_column: 6, - }, - ], - return_ty: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 7, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__line_continue.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__line_continue.snap deleted file mode 100644 index a563e4cd8..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__line_continue.snap +++ /dev/null @@ -1,47 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"1 + \\\n2\n\"####)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 2, - column: 0, - end_line: 2, - end_column: 1, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 2, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__list_comp_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__list_comp_expr_0.snap deleted file mode 100644 index c6f7cc855..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__list_comp_expr_0.snap +++ /dev/null @@ -1,160 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"[x ** 2 for x in [1, 2, 3]]\"####)" ---- -Node { - node: ListComp( - ListComp { - elt: Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - op: Pow, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 7, - }, - generators: [ - Node { - node: CompClause { - targets: [ - Node { - node: Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 13, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 13, - }, - ], - iter: Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 18, - end_line: 1, - end_column: 19, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 22, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 24, - end_line: 1, - end_column: 25, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 17, - end_line: 1, - end_column: 26, - }, - ifs: [], - }, - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 26, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 27, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__list_comp_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__list_comp_expr_1.snap deleted file mode 100644 index 724c18610..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__list_comp_expr_1.snap +++ /dev/null @@ -1,188 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"[i for i in [1, 2, 3] if i > 2]\"####)" ---- -Node { - node: ListComp( - ListComp { - elt: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - generators: [ - Node { - node: CompClause { - targets: [ - Node { - node: Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - iter: Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 17, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 19, - end_line: 1, - end_column: 20, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 21, - }, - ifs: [ - Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 26, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 26, - }, - ops: [ - Gt, - ], - comparators: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 29, - end_line: 1, - end_column: 30, - }, - ], - }, - ), - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 30, - }, - ], - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 30, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 31, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__list_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__list_expr_0.snap deleted file mode 100644 index 356ee9454..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__list_expr_0.snap +++ /dev/null @@ -1,64 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"[1, 2, 3]\"####)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__list_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__list_expr_1.snap deleted file mode 100644 index 3401d3c7f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__list_expr_1.snap +++ /dev/null @@ -1,90 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"[1, if True: 2, 3]\"####)" ---- -Node { - node: List( - ListExpr { - elts: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - Node { - node: ListIfItem( - ListIfItemExpr { - if_cond: Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 11, - }, - exprs: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - ], - orelse: None, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 14, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 16, - end_line: 1, - end_column: 17, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 18, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_0.snap deleted file mode 100644 index 6f3ba2059..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_0.snap +++ /dev/null @@ -1,75 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"0 < a < 100\"####)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ops: [ - Lt, - Lt, - ], - comparators: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 100, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 11, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_1.snap deleted file mode 100644 index a5f7197a3..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_1.snap +++ /dev/null @@ -1,110 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"0 < a < 100 + a\"####)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ops: [ - Lt, - Lt, - ], - comparators: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 100, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 11, - }, - op: Add, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 15, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 15, - }, - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 15, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 15, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_2.snap deleted file mode 100644 index b8df91bfb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_2.snap +++ /dev/null @@ -1,75 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"100 > a > 0\"####)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 100, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - ops: [ - Gt, - Gt, - ], - comparators: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_3.snap deleted file mode 100644 index 1116355bb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_3.snap +++ /dev/null @@ -1,110 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"100 + a > a > 0\"####)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 100, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - op: Add, - right: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, - }, - ops: [ - Gt, - Gt, - ], - comparators: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 15, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 15, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_4.snap deleted file mode 100644 index 4d1179f19..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_4.snap +++ /dev/null @@ -1,67 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a is b\"####)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ops: [ - Is, - ], - comparators: [ - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_5.snap deleted file mode 100644 index 45e278b7b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_5.snap +++ /dev/null @@ -1,56 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a is not True\"####)" ---- -Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ops: [ - IsNot, - ], - comparators: [ - Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 13, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 13, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_6.snap deleted file mode 100644 index b848314b7..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__logic_expr_6.snap +++ /dev/null @@ -1,158 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"not False or a > 0 and b is True\"####)" ---- -Node { - node: Binary( - BinaryExpr { - left: Node { - node: Unary( - UnaryExpr { - op: Not, - operand: Node { - node: NameConstantLit( - NameConstantLit { - value: False, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 9, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, - }, - op: Or, - right: Node { - node: Binary( - BinaryExpr { - left: Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - ops: [ - Gt, - ], - comparators: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 17, - end_line: 1, - end_column: 18, - }, - ], - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 32, - }, - op: And, - right: Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 23, - end_line: 1, - end_column: 24, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 23, - end_line: 1, - end_column: 24, - }, - ops: [ - Is, - ], - comparators: [ - Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 28, - end_line: 1, - end_column: 32, - }, - ], - }, - ), - filename: "", - line: 1, - column: 23, - end_line: 1, - end_column: 32, - }, - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 32, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 32, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__named_literal_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__named_literal_expr_0.snap deleted file mode 100644 index 7de5ef740..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__named_literal_expr_0.snap +++ /dev/null @@ -1,17 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(\"Undefined\")" ---- -Node { - node: NameConstantLit( - NameConstantLit { - value: Undefined, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__named_literal_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__named_literal_expr_1.snap deleted file mode 100644 index 7f5c7ef9d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__named_literal_expr_1.snap +++ /dev/null @@ -1,17 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(\"None\")" ---- -Node { - node: NameConstantLit( - NameConstantLit { - value: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__named_literal_expr_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__named_literal_expr_2.snap deleted file mode 100644 index 2da8eaa4c..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__named_literal_expr_2.snap +++ /dev/null @@ -1,17 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(\"True\")" ---- -Node { - node: NameConstantLit( - NameConstantLit { - value: True, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__named_literal_expr_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__named_literal_expr_3.snap deleted file mode 100644 index 2f6bf66cc..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__named_literal_expr_3.snap +++ /dev/null @@ -1,17 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(\"False\")" ---- -Node { - node: NameConstantLit( - NameConstantLit { - value: False, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__nonstring_literal_expr.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__nonstring_literal_expr.snap deleted file mode 100644 index 565de3ff4..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__nonstring_literal_expr.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"1234\"####)" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1234, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__number_bin_suffix_expr.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__number_bin_suffix_expr.snap deleted file mode 100644 index 5082423ff..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__number_bin_suffix_expr.snap +++ /dev/null @@ -1,22 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"1234Ki\"####)" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: Some( - Ki, - ), - value: Int( - 1234, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__parse_joined_string_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__parse_joined_string_0.snap deleted file mode 100644 index 9de6c12ec..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__parse_joined_string_0.snap +++ /dev/null @@ -1,75 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"'${123+200}'\"####)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: false, - values: [ - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Binary( - BinaryExpr { - left: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 123, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 6, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 200, - ), - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 10, - }, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 10, - }, - format_spec: None, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 10, - }, - ], - raw_value: "'${123+200}'", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__parse_joined_string_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__parse_joined_string_1.snap deleted file mode 100644 index 5fa01f670..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__parse_joined_string_1.snap +++ /dev/null @@ -1,111 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"'abc${a+1}cde'\"####)" ---- -Node { - node: JoinedString( - JoinedString { - is_long_string: false, - values: [ - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "abc", - value: "abc", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - Node { - node: FormattedValue( - FormattedValue { - is_long_string: false, - value: Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 9, - }, - format_spec: None, - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 9, - }, - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "cde", - value: "cde", - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 1, - }, - ], - raw_value: "'abc${a+1}cde'", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 14, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_0.snap deleted file mode 100644 index a028192b6..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_0.snap +++ /dev/null @@ -1,44 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a.b.c\"####)" ---- -Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - Node { - node: "b", - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - Node { - node: "c", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_1.snap deleted file mode 100644 index df2ad88f0..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_1.snap +++ /dev/null @@ -1,82 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"'{}'.format(1)\"####)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Selector( - SelectorExpr { - value: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'{}'", - value: "{}", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "format", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 11, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 11, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 13, - }, - ], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 14, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_2.snap deleted file mode 100644 index 45416f506..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_2.snap +++ /dev/null @@ -1,104 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"str(1).isdigit()\"####)" ---- -Node { - node: Call( - CallExpr { - func: Node { - node: Selector( - SelectorExpr { - value: Node { - node: Call( - CallExpr { - func: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "str", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "isdigit", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 14, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 14, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 14, - }, - args: [], - keywords: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 16, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_3.snap deleted file mode 100644 index 5485d0a48..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_3.snap +++ /dev/null @@ -1,50 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{}.a\"####)" ---- -Node { - node: Selector( - SelectorExpr { - value: Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_4.snap deleted file mode 100644 index 70bc3af4b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_4.snap +++ /dev/null @@ -1,84 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{}..a\"####)" ---- -Node { - node: Selector( - SelectorExpr { - value: Node { - node: Selector( - SelectorExpr { - value: Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_5.snap deleted file mode 100644 index c8ebf0ba3..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_5.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{}...a\"####)" ---- -Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_6.snap deleted file mode 100644 index a560d73fc..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_6.snap +++ /dev/null @@ -1,85 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"[]..a\"####)" ---- -Node { - node: Selector( - SelectorExpr { - value: Node { - node: Selector( - SelectorExpr { - value: Node { - node: List( - ListExpr { - elts: [], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "", - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 3, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - attr: Node { - node: Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_7.snap deleted file mode 100644 index c7674ed47..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__primary_expr_7.snap +++ /dev/null @@ -1,44 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"{}[[]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, - }, - index: Some( - Node { - node: Missing( - MissingExpr, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 5, - }, - ), - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_0.snap deleted file mode 100644 index 2da80a01e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_0.snap +++ /dev/null @@ -1,119 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"all x in collection {x > 0}\"####)" ---- -Node { - node: Quant( - QuantExpr { - target: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "collection", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 19, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 19, - }, - variables: [ - Node { - node: Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - op: All, - test: Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 22, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 22, - }, - ops: [ - Gt, - ], - comparators: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 26, - }, - ], - }, - ), - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 26, - }, - if_cond: None, - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 27, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_1.snap deleted file mode 100644 index 2191519ad..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_1.snap +++ /dev/null @@ -1,119 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"any y in collection {y < 0}\"####)" ---- -Node { - node: Quant( - QuantExpr { - target: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "collection", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 19, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 19, - }, - variables: [ - Node { - node: Identifier { - names: [ - Node { - node: "y", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - op: Any, - test: Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "y", - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 22, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 22, - }, - ops: [ - Lt, - ], - comparators: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 26, - }, - ], - }, - ), - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 26, - }, - if_cond: None, - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 27, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_2.snap deleted file mode 100644 index e969f0cc3..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_2.snap +++ /dev/null @@ -1,115 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"map x in collection {x + 1}\"####)" ---- -Node { - node: Quant( - QuantExpr { - target: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "collection", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 19, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 19, - }, - variables: [ - Node { - node: Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - op: Map, - test: Node { - node: Binary( - BinaryExpr { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 22, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 22, - }, - op: Add, - right: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 26, - }, - }, - ), - filename: "", - line: 1, - column: 21, - end_line: 1, - end_column: 26, - }, - if_cond: None, - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 27, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_3.snap deleted file mode 100644 index 272131f54..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_3.snap +++ /dev/null @@ -1,119 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"filter x in collection {x > 1}\"####)" ---- -Node { - node: Quant( - QuantExpr { - target: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "collection", - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 22, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 22, - }, - variables: [ - Node { - node: Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - op: Filter, - test: Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 24, - end_line: 1, - end_column: 25, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 24, - end_line: 1, - end_column: 25, - }, - ops: [ - Gt, - ], - comparators: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 28, - end_line: 1, - end_column: 29, - }, - ], - }, - ), - filename: "", - line: 1, - column: 24, - end_line: 1, - end_column: 29, - }, - if_cond: None, - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 30, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_4.snap deleted file mode 100644 index 272131f54..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_4.snap +++ /dev/null @@ -1,119 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"filter x in collection {x > 1}\"####)" ---- -Node { - node: Quant( - QuantExpr { - target: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "collection", - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 22, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 22, - }, - variables: [ - Node { - node: Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - op: Filter, - test: Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "x", - filename: "", - line: 1, - column: 24, - end_line: 1, - end_column: 25, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 24, - end_line: 1, - end_column: 25, - }, - ops: [ - Gt, - ], - comparators: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 28, - end_line: 1, - end_column: 29, - }, - ], - }, - ), - filename: "", - line: 1, - column: 24, - end_line: 1, - end_column: 29, - }, - if_cond: None, - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 30, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_5.snap deleted file mode 100644 index ee6e33686..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_5.snap +++ /dev/null @@ -1,210 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"map i, e in [{k1 = \"v1\", k2 = \"v2\"}] { e }\"####)" ---- -Node { - node: Quant( - QuantExpr { - target: Node { - node: List( - ListExpr { - elts: [ - Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "k1", - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 16, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 16, - }, - ), - value: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"v1\"", - value: "v1", - }, - ), - filename: "", - line: 1, - column: 19, - end_line: 1, - end_column: 23, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 23, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "k2", - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 27, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 27, - }, - ), - value: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"v2\"", - value: "v2", - }, - ), - filename: "", - line: 1, - column: 30, - end_line: 1, - end_column: 34, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 34, - }, - ], - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 35, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 36, - }, - variables: [ - Node { - node: Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - Node { - node: Identifier { - names: [ - Node { - node: "e", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - op: Map, - test: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "e", - filename: "", - line: 1, - column: 39, - end_line: 1, - end_column: 40, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 39, - end_line: 1, - end_column: 40, - }, - if_cond: None, - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 42, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_6.snap deleted file mode 100644 index 39e61cef4..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__quant_expr_6.snap +++ /dev/null @@ -1,265 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"map i, e in [{k1 = \"v1\", k2 = \"v2\"}] { e if i > 0 }\"####)" ---- -Node { - node: Quant( - QuantExpr { - target: Node { - node: List( - ListExpr { - elts: [ - Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "k1", - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 16, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 16, - }, - ), - value: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"v1\"", - value: "v1", - }, - ), - filename: "", - line: 1, - column: 19, - end_line: 1, - end_column: 23, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 23, - }, - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "k2", - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 27, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 27, - }, - ), - value: Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"v2\"", - value: "v2", - }, - ), - filename: "", - line: 1, - column: 30, - end_line: 1, - end_column: 34, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 25, - end_line: 1, - end_column: 34, - }, - ], - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 35, - }, - ], - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 36, - }, - variables: [ - Node { - node: Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - Node { - node: Identifier { - names: [ - Node { - node: "e", - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 8, - }, - ], - op: Map, - test: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "e", - filename: "", - line: 1, - column: 39, - end_line: 1, - end_column: 40, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 39, - end_line: 1, - end_column: 40, - }, - if_cond: Some( - Node { - node: Compare( - Compare { - left: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "i", - filename: "", - line: 1, - column: 44, - end_line: 1, - end_column: 45, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 44, - end_line: 1, - end_column: 45, - }, - ops: [ - Gt, - ], - comparators: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 48, - end_line: 1, - end_column: 49, - }, - ], - }, - ), - filename: "", - line: 1, - column: 44, - end_line: 1, - end_column: 49, - }, - ), - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 51, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_0.snap deleted file mode 100644 index ca2d929a2..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_0.snap +++ /dev/null @@ -1,51 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"Schema {}\"####)" ---- -Node { - node: Schema( - SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "Schema", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - args: [], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [], - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 9, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 9, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_1.snap deleted file mode 100644 index 553da53ed..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_1.snap +++ /dev/null @@ -1,109 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"Schema {k=v}\"####)" ---- -Node { - node: Schema( - SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "Schema", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - args: [], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "k", - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - ), - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "v", - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 11, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 11, - }, - ], - }, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 12, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 12, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_2.snap deleted file mode 100644 index 92dffcfc6..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_2.snap +++ /dev/null @@ -1,109 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"Schema () {k=v}\"####)" ---- -Node { - node: Schema( - SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "Schema", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - args: [], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "k", - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 12, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 12, - }, - ), - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "v", - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 13, - end_line: 1, - end_column: 14, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 14, - }, - ], - }, - ), - filename: "", - line: 1, - column: 10, - end_line: 1, - end_column: 15, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 15, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_3.snap deleted file mode 100644 index 921ac0dd1..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_3.snap +++ /dev/null @@ -1,140 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"Schema (1, 2) {k=v}\"####)" ---- -Node { - node: Schema( - SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "Schema", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 12, - }, - ], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "k", - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 16, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 16, - }, - ), - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "v", - filename: "", - line: 1, - column: 17, - end_line: 1, - end_column: 18, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 17, - end_line: 1, - end_column: 18, - }, - operation: Override, - }, - filename: "", - line: 1, - column: 15, - end_line: 1, - end_column: 18, - }, - ], - }, - ), - filename: "", - line: 1, - column: 14, - end_line: 1, - end_column: 19, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 19, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_4.snap deleted file mode 100644 index b0d50f05b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__schema_expr_4.snap +++ /dev/null @@ -1,140 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"Schema (1, 2) {\n k=v\n}\"####)" ---- -Node { - node: Schema( - SchemaExpr { - name: Node { - node: Identifier { - names: [ - Node { - node: "Schema", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - args: [ - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 8, - end_line: 1, - end_column: 9, - }, - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 11, - end_line: 1, - end_column: 12, - }, - ], - kwargs: [], - config: Node { - node: Config( - ConfigExpr { - items: [ - Node { - node: ConfigEntry { - key: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "k", - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 5, - }, - ), - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "v", - filename: "", - line: 2, - column: 6, - end_line: 2, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 2, - column: 6, - end_line: 2, - end_column: 7, - }, - operation: Override, - }, - filename: "", - line: 2, - column: 4, - end_line: 2, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 1, - column: 14, - end_line: 3, - end_column: 1, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 3, - end_column: 1, -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__smoke_test_parsing_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__smoke_test_parsing_expr_0.snap deleted file mode 100644 index 896509e1b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__smoke_test_parsing_expr_0.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(\"1\\n\")" ---- -Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__smoke_test_parsing_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__smoke_test_parsing_expr_1.snap deleted file mode 100644 index 2e7abca86..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__smoke_test_parsing_expr_1.snap +++ /dev/null @@ -1,19 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(\"\\\"1\\\"\\n\")" ---- -Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"1\"", - value: "1", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__string_literal_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__string_literal_expr_0.snap deleted file mode 100644 index 6c8c37538..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__string_literal_expr_0.snap +++ /dev/null @@ -1,19 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"'1234'\"####)" ---- -Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "'1234'", - value: "1234", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__string_literal_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__string_literal_expr_1.snap deleted file mode 100644 index 1f108e406..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__string_literal_expr_1.snap +++ /dev/null @@ -1,19 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"\"1234\"\"####)" ---- -Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"1234\"", - value: "1234", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__string_literal_expr_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__string_literal_expr_2.snap deleted file mode 100644 index a5f3e2e53..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__string_literal_expr_2.snap +++ /dev/null @@ -1,19 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"\"1234\\n\"\"####)" ---- -Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"1234\\n\"", - value: "1234\n", - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_0.snap deleted file mode 100644 index 3752cbeac..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_0.snap +++ /dev/null @@ -1,61 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a[0]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_1.snap deleted file mode 100644 index 9b32e231a..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_1.snap +++ /dev/null @@ -1,60 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"b[\"k\"]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "b", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: Some( - Node { - node: StringLit( - StringLit { - is_long_string: false, - raw_value: "\"k\"", - value: "k", - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 5, - }, - ), - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_10.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_10.snap deleted file mode 100644 index ce08b1682..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_10.snap +++ /dev/null @@ -1,73 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a[::-1]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: None, - lower: None, - upper: None, - step: Some( - Node { - node: Unary( - UnaryExpr { - op: USub, - operand: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 6, - }, - ), - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_11.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_11.snap deleted file mode 100644 index a5cc8ab34..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_11.snap +++ /dev/null @@ -1,77 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a[1::2]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: None, - lower: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - upper: None, - step: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ), - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_12.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_12.snap deleted file mode 100644 index f6cfe4beb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_12.snap +++ /dev/null @@ -1,77 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a[:2:1]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: None, - lower: None, - upper: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ), - step: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - ), - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_13.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_13.snap deleted file mode 100644 index 61b668cca..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_13.snap +++ /dev/null @@ -1,77 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a[1:2:]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: None, - lower: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - upper: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 2, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_14.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_14.snap deleted file mode 100644 index 001416f3a..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_14.snap +++ /dev/null @@ -1,93 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a[1:3:1]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: None, - lower: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - upper: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 3, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - ), - step: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 7, - }, - ), - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_2.snap deleted file mode 100644 index 1c4f15312..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_2.snap +++ /dev/null @@ -1,61 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"c?[1]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "c", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ), - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: true, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_3.snap deleted file mode 100644 index a288ead99..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_3.snap +++ /dev/null @@ -1,61 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a[1:]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: None, - lower: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_4.snap deleted file mode 100644 index d65b89649..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_4.snap +++ /dev/null @@ -1,73 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a[:-1]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: None, - lower: None, - upper: Some( - Node { - node: Unary( - UnaryExpr { - op: USub, - operand: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 5, - }, - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 5, - }, - ), - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_5.snap deleted file mode 100644 index d095deb1f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_5.snap +++ /dev/null @@ -1,85 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a[1:len]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: None, - lower: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - upper: Some( - Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "len", - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ), - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 8, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_6.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_6.snap deleted file mode 100644 index 16596547b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_6.snap +++ /dev/null @@ -1,89 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a[0:-1]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: None, - lower: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - upper: Some( - Node { - node: Unary( - UnaryExpr { - op: USub, - operand: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 6, - }, - }, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 6, - }, - ), - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_7.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_7.snap deleted file mode 100644 index efdc7b695..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_7.snap +++ /dev/null @@ -1,45 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a[::]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: None, - lower: None, - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_8.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_8.snap deleted file mode 100644 index 6a16c990c..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_8.snap +++ /dev/null @@ -1,61 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a[1::]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: None, - lower: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 3, - }, - ), - upper: None, - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_9.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_9.snap deleted file mode 100644 index 14164675c..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__subscript_expr_9.snap +++ /dev/null @@ -1,61 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"a[:0:]\"####)" ---- -Node { - node: Subscript( - Subscript { - value: Node { - node: Identifier( - Identifier { - names: [ - Node { - node: "a", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 1, - }, - index: None, - lower: None, - upper: Some( - Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 0, - ), - }, - ), - filename: "", - line: 1, - column: 3, - end_line: 1, - end_column: 4, - }, - ), - step: None, - ctx: Load, - has_question: false, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__unary_expr.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__unary_expr.snap deleted file mode 100644 index 174b7eeec..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__expr__unary_expr.snap +++ /dev/null @@ -1,32 +0,0 @@ ---- -source: parser/src/tests/expr.rs -expression: "crate::tests::parsing_expr_string(r####\"+1\"####)" ---- -Node { - node: Unary( - UnaryExpr { - op: UAdd, - operand: Node { - node: NumberLit( - NumberLit { - binary_suffix: None, - value: Int( - 1, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 2, - }, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_1.snap deleted file mode 100644 index 48d0bf21e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_1.snap +++ /dev/null @@ -1,100 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/assert-01.k\")" ---- -{ - "filename": "assert-01.k", - "doc": null, - "body": [ - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "assert-01.k", - "line": 1, - "column": 7, - "end_line": 1, - "end_column": 8 - }, - "if_cond": null, - "msg": null - }, - "filename": "assert-01.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 8 - }, - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 2 - } - }, - "filename": "assert-01.k", - "line": 2, - "column": 7, - "end_line": 2, - "end_column": 8 - }, - "if_cond": null, - "msg": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"msg\"", - "value": "msg" - }, - "filename": "assert-01.k", - "line": 2, - "column": 10, - "end_line": 2, - "end_column": 15 - } - }, - "filename": "assert-01.k", - "line": 2, - "column": 0, - "end_line": 2, - "end_column": 15 - }, - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "NameConstantLit", - "value": "True" - }, - "filename": "assert-01.k", - "line": 3, - "column": 7, - "end_line": 3, - "end_column": 11 - }, - "if_cond": null, - "msg": null - }, - "filename": "assert-01.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 11 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_2.snap deleted file mode 100644 index 499040813..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_2.snap +++ /dev/null @@ -1,198 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/assert-02.k\")" ---- -{ - "filename": "assert-02.k", - "doc": null, - "body": [ - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "NameConstantLit", - "value": "True" - }, - "filename": "assert-02.k", - "line": 1, - "column": 7, - "end_line": 1, - "end_column": 11 - }, - "if_cond": null, - "msg": null - }, - "filename": "assert-02.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 11 - }, - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "assert-02.k", - "line": 2, - "column": 7, - "end_line": 2, - "end_column": 8 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "assert-02.k", - "line": 2, - "column": 12, - "end_line": 2, - "end_column": 13 - } - ] - }, - "filename": "assert-02.k", - "line": 2, - "column": 7, - "end_line": 2, - "end_column": 13 - }, - "if_cond": null, - "msg": null - }, - "filename": "assert-02.k", - "line": 2, - "column": 0, - "end_line": 2, - "end_column": 13 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "_x", - "filename": "assert-02.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 2 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "assert-02.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 2 - } - ], - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"good case\"", - "value": "good case" - }, - "filename": "assert-02.k", - "line": 3, - "column": 5, - "end_line": 3, - "end_column": 16 - }, - "ty": null - }, - "filename": "assert-02.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 16 - }, - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "_x", - "filename": "assert-02.k", - "line": 4, - "column": 7, - "end_line": 4, - "end_column": 9 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "assert-02.k", - "line": 4, - "column": 7, - "end_line": 4, - "end_column": 9 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"good case\"", - "value": "good case" - }, - "filename": "assert-02.k", - "line": 4, - "column": 13, - "end_line": 4, - "end_column": 24 - } - ] - }, - "filename": "assert-02.k", - "line": 4, - "column": 7, - "end_line": 4, - "end_column": 24 - }, - "if_cond": null, - "msg": null - }, - "filename": "assert-02.k", - "line": 4, - "column": 0, - "end_line": 4, - "end_column": 24 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_3.snap deleted file mode 100644 index 5f7883c36..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_3.snap +++ /dev/null @@ -1,270 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/assert-03.k\")" ---- -{ - "filename": "assert-03.k", - "doc": null, - "body": [ - { - "node": { - "type": "If", - "body": [ - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "NameConstantLit", - "value": "True" - }, - "filename": "assert-03.k", - "line": 2, - "column": 11, - "end_line": 2, - "end_column": 15 - }, - "if_cond": null, - "msg": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"Error messgae\"", - "value": "Error messgae" - }, - "filename": "assert-03.k", - "line": 2, - "column": 17, - "end_line": 2, - "end_column": 32 - } - }, - "filename": "assert-03.k", - "line": 2, - "column": 4, - "end_line": 2, - "end_column": 32 - }, - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "assert-03.k", - "line": 3, - "column": 11, - "end_line": 3, - "end_column": 12 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "assert-03.k", - "line": 3, - "column": 16, - "end_line": 3, - "end_column": 17 - } - ] - }, - "filename": "assert-03.k", - "line": 3, - "column": 11, - "end_line": 3, - "end_column": 17 - }, - "if_cond": null, - "msg": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"\"", - "value": "" - }, - "filename": "assert-03.k", - "line": 3, - "column": 19, - "end_line": 3, - "end_column": 21 - } - }, - "filename": "assert-03.k", - "line": 3, - "column": 4, - "end_line": 3, - "end_column": 21 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "_x", - "filename": "assert-03.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 6 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "assert-03.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 6 - } - ], - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"good case\"", - "value": "good case" - }, - "filename": "assert-03.k", - "line": 4, - "column": 9, - "end_line": 4, - "end_column": 20 - }, - "ty": null - }, - "filename": "assert-03.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 20 - }, - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "_x", - "filename": "assert-03.k", - "line": 5, - "column": 11, - "end_line": 5, - "end_column": 13 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "assert-03.k", - "line": 5, - "column": 11, - "end_line": 5, - "end_column": 13 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"good case\"", - "value": "good case" - }, - "filename": "assert-03.k", - "line": 5, - "column": 17, - "end_line": 5, - "end_column": 28 - } - ] - }, - "filename": "assert-03.k", - "line": 5, - "column": 11, - "end_line": 5, - "end_column": 28 - }, - "if_cond": null, - "msg": null - }, - "filename": "assert-03.k", - "line": 5, - "column": 4, - "end_line": 5, - "end_column": 28 - } - ], - "cond": { - "node": { - "type": "NameConstantLit", - "value": "True" - }, - "filename": "assert-03.k", - "line": 1, - "column": 3, - "end_line": 1, - "end_column": 7 - }, - "orelse": [ - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "NameConstantLit", - "value": "False" - }, - "filename": "assert-03.k", - "line": 7, - "column": 11, - "end_line": 7, - "end_column": 16 - }, - "if_cond": null, - "msg": null - }, - "filename": "assert-03.k", - "line": 7, - "column": 4, - "end_line": 7, - "end_column": 16 - } - ] - }, - "filename": "assert-03.k", - "line": 1, - "column": 0, - "end_line": 8, - "end_column": 1 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_if_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_if_0.snap deleted file mode 100644 index 4362c79da..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_if_0.snap +++ /dev/null @@ -1,241 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/assert-if-0.k\")" ---- -{ - "filename": "assert-if-0.k", - "doc": null, - "body": [ - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "NameConstantLit", - "value": "True" - }, - "filename": "assert-if-0.k", - "line": 1, - "column": 7, - "end_line": 1, - "end_column": 11 - }, - "if_cond": null, - "msg": null - }, - "filename": "assert-if-0.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 11 - }, - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "assert-if-0.k", - "line": 2, - "column": 7, - "end_line": 2, - "end_column": 8 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "assert-if-0.k", - "line": 2, - "column": 12, - "end_line": 2, - "end_column": 13 - } - ] - }, - "filename": "assert-if-0.k", - "line": 2, - "column": 7, - "end_line": 2, - "end_column": 13 - }, - "if_cond": { - "node": { - "type": "NameConstantLit", - "value": "True" - }, - "filename": "assert-if-0.k", - "line": 2, - "column": 17, - "end_line": 2, - "end_column": 21 - }, - "msg": null - }, - "filename": "assert-if-0.k", - "line": 2, - "column": 0, - "end_line": 2, - "end_column": 21 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "_x", - "filename": "assert-if-0.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 2 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "assert-if-0.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 2 - } - ], - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"good case\"", - "value": "good case" - }, - "filename": "assert-if-0.k", - "line": 3, - "column": 5, - "end_line": 3, - "end_column": 16 - }, - "ty": null - }, - "filename": "assert-if-0.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 16 - }, - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "_x", - "filename": "assert-if-0.k", - "line": 4, - "column": 7, - "end_line": 4, - "end_column": 9 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "assert-if-0.k", - "line": 4, - "column": 7, - "end_line": 4, - "end_column": 9 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"good case\"", - "value": "good case" - }, - "filename": "assert-if-0.k", - "line": 4, - "column": 13, - "end_line": 4, - "end_column": 24 - } - ] - }, - "filename": "assert-if-0.k", - "line": 4, - "column": 7, - "end_line": 4, - "end_column": 24 - }, - "if_cond": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "_x", - "filename": "assert-if-0.k", - "line": 4, - "column": 28, - "end_line": 4, - "end_column": 30 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "assert-if-0.k", - "line": 4, - "column": 28, - "end_line": 4, - "end_column": 30 - }, - "msg": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"_x need to be 'good case'\"", - "value": "_x need to be 'good case'" - }, - "filename": "assert-if-0.k", - "line": 4, - "column": 32, - "end_line": 4, - "end_column": 59 - } - }, - "filename": "assert-if-0.k", - "line": 4, - "column": 0, - "end_line": 4, - "end_column": 59 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_if_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_if_1.snap deleted file mode 100644 index ccdaa2edb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_if_1.snap +++ /dev/null @@ -1,262 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/assert-if-1.k\")" ---- -{ - "filename": "assert-if-1.k", - "doc": null, - "body": [ - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "NameConstantLit", - "value": "True" - }, - "filename": "assert-if-1.k", - "line": 1, - "column": 7, - "end_line": 1, - "end_column": 11 - }, - "if_cond": { - "node": { - "type": "NameConstantLit", - "value": "False" - }, - "filename": "assert-if-1.k", - "line": 1, - "column": 15, - "end_line": 1, - "end_column": 20 - }, - "msg": null - }, - "filename": "assert-if-1.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 20 - }, - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "assert-if-1.k", - "line": 2, - "column": 7, - "end_line": 2, - "end_column": 8 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "assert-if-1.k", - "line": 2, - "column": 12, - "end_line": 2, - "end_column": 13 - } - ] - }, - "filename": "assert-if-1.k", - "line": 2, - "column": 7, - "end_line": 2, - "end_column": 13 - }, - "if_cond": { - "node": { - "type": "NameConstantLit", - "value": "False" - }, - "filename": "assert-if-1.k", - "line": 2, - "column": 17, - "end_line": 2, - "end_column": 22 - }, - "msg": null - }, - "filename": "assert-if-1.k", - "line": 2, - "column": 0, - "end_line": 2, - "end_column": 22 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "_x", - "filename": "assert-if-1.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 2 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "assert-if-1.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 2 - } - ], - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"good case\"", - "value": "good case" - }, - "filename": "assert-if-1.k", - "line": 3, - "column": 5, - "end_line": 3, - "end_column": 16 - }, - "ty": null - }, - "filename": "assert-if-1.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 16 - }, - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "_x", - "filename": "assert-if-1.k", - "line": 4, - "column": 7, - "end_line": 4, - "end_column": 9 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "assert-if-1.k", - "line": 4, - "column": 7, - "end_line": 4, - "end_column": 9 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"good case\"", - "value": "good case" - }, - "filename": "assert-if-1.k", - "line": 4, - "column": 13, - "end_line": 4, - "end_column": 24 - } - ] - }, - "filename": "assert-if-1.k", - "line": 4, - "column": 7, - "end_line": 4, - "end_column": 24 - }, - "if_cond": { - "node": { - "type": "Unary", - "op": "Not", - "operand": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "_x", - "filename": "assert-if-1.k", - "line": 4, - "column": 32, - "end_line": 4, - "end_column": 34 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "assert-if-1.k", - "line": 4, - "column": 32, - "end_line": 4, - "end_column": 34 - } - }, - "filename": "assert-if-1.k", - "line": 4, - "column": 28, - "end_line": 4, - "end_column": 34 - }, - "msg": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"_x need to be 'good case'\"", - "value": "_x need to be 'good case'" - }, - "filename": "assert-if-1.k", - "line": 4, - "column": 36, - "end_line": 4, - "end_column": 63 - } - }, - "filename": "assert-if-1.k", - "line": 4, - "column": 0, - "end_line": 4, - "end_column": 63 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_if_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_if_2.snap deleted file mode 100644 index 38a807578..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assert_if_2.snap +++ /dev/null @@ -1,368 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/assert-if-2.k\")" ---- -{ - "filename": "assert-if-2.k", - "doc": null, - "body": [ - { - "node": { - "type": "Schema", - "doc": null, - "name": { - "node": "Data", - "filename": "assert-if-2.k", - "line": 1, - "column": 7, - "end_line": 1, - "end_column": 11 - }, - "parent_name": null, - "for_host_name": null, - "is_mixin": false, - "is_protocol": false, - "args": null, - "mixins": [], - "body": [ - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "NameConstantLit", - "value": "True" - }, - "filename": "assert-if-2.k", - "line": 2, - "column": 11, - "end_line": 2, - "end_column": 15 - }, - "if_cond": { - "node": { - "type": "NameConstantLit", - "value": "False" - }, - "filename": "assert-if-2.k", - "line": 2, - "column": 19, - "end_line": 2, - "end_column": 24 - }, - "msg": null - }, - "filename": "assert-if-2.k", - "line": 2, - "column": 4, - "end_line": 2, - "end_column": 24 - }, - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "assert-if-2.k", - "line": 3, - "column": 11, - "end_line": 3, - "end_column": 12 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "assert-if-2.k", - "line": 3, - "column": 16, - "end_line": 3, - "end_column": 17 - } - ] - }, - "filename": "assert-if-2.k", - "line": 3, - "column": 11, - "end_line": 3, - "end_column": 17 - }, - "if_cond": { - "node": { - "type": "NameConstantLit", - "value": "False" - }, - "filename": "assert-if-2.k", - "line": 3, - "column": 21, - "end_line": 3, - "end_column": 26 - }, - "msg": null - }, - "filename": "assert-if-2.k", - "line": 3, - "column": 4, - "end_line": 3, - "end_column": 26 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "_x", - "filename": "assert-if-2.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 6 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "assert-if-2.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 6 - } - ], - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"good case\"", - "value": "good case" - }, - "filename": "assert-if-2.k", - "line": 4, - "column": 9, - "end_line": 4, - "end_column": 20 - }, - "ty": null - }, - "filename": "assert-if-2.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 20 - }, - { - "node": { - "type": "Assert", - "test": { - "node": { - "type": "Compare", - "left": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "_x", - "filename": "assert-if-2.k", - "line": 5, - "column": 11, - "end_line": 5, - "end_column": 13 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "assert-if-2.k", - "line": 5, - "column": 11, - "end_line": 5, - "end_column": 13 - }, - "ops": [ - "Eq" - ], - "comparators": [ - { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"good case\"", - "value": "good case" - }, - "filename": "assert-if-2.k", - "line": 5, - "column": 17, - "end_line": 5, - "end_column": 28 - } - ] - }, - "filename": "assert-if-2.k", - "line": 5, - "column": 11, - "end_line": 5, - "end_column": 28 - }, - "if_cond": { - "node": { - "type": "Unary", - "op": "Not", - "operand": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "_x", - "filename": "assert-if-2.k", - "line": 5, - "column": 36, - "end_line": 5, - "end_column": 38 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "assert-if-2.k", - "line": 5, - "column": 36, - "end_line": 5, - "end_column": 38 - } - }, - "filename": "assert-if-2.k", - "line": 5, - "column": 32, - "end_line": 5, - "end_column": 38 - }, - "msg": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"_x need to be 'good case'\"", - "value": "_x need to be 'good case'" - }, - "filename": "assert-if-2.k", - "line": 5, - "column": 40, - "end_line": 5, - "end_column": 67 - } - }, - "filename": "assert-if-2.k", - "line": 5, - "column": 4, - "end_line": 5, - "end_column": 67 - } - ], - "decorators": [], - "checks": [], - "index_signature": null - }, - "filename": "assert-if-2.k", - "line": 1, - "column": 0, - "end_line": 7, - "end_column": 0 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "data", - "filename": "assert-if-2.k", - "line": 7, - "column": 0, - "end_line": 7, - "end_column": 4 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "assert-if-2.k", - "line": 7, - "column": 0, - "end_line": 7, - "end_column": 4 - } - ], - "value": { - "node": { - "type": "Schema", - "name": { - "node": { - "names": [ - { - "node": "Data", - "filename": "assert-if-2.k", - "line": 7, - "column": 7, - "end_line": 7, - "end_column": 11 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "assert-if-2.k", - "line": 7, - "column": 7, - "end_line": 7, - "end_column": 11 - }, - "args": [], - "kwargs": [], - "config": { - "node": { - "type": "Config", - "items": [] - }, - "filename": "assert-if-2.k", - "line": 7, - "column": 12, - "end_line": 7, - "end_column": 14 - } - }, - "filename": "assert-if-2.k", - "line": 7, - "column": 7, - "end_line": 7, - "end_column": 14 - }, - "ty": null - }, - "filename": "assert-if-2.k", - "line": 7, - "column": 0, - "end_line": 7, - "end_column": 14 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assign_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assign_1.snap deleted file mode 100644 index de61728b9..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__assign_1.snap +++ /dev/null @@ -1,230 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/assign-01.k\")" ---- -{ - "filename": "assign-01.k", - "doc": null, - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "a", - "filename": "assign-01.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 1 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "assign-01.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 1 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "assign-01.k", - "line": 1, - "column": 2, - "end_line": 1, - "end_column": 3 - }, - "ty": null - }, - "filename": "assign-01.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 3 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "b", - "filename": "assign-01.k", - "line": 2, - "column": 0, - "end_line": 2, - "end_column": 1 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "assign-01.k", - "line": 2, - "column": 0, - "end_line": 2, - "end_column": 1 - } - ], - "value": { - "node": { - "type": "Binary", - "left": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "assign-01.k", - "line": 2, - "column": 4, - "end_line": 2, - "end_column": 5 - }, - "op": "Add", - "right": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 2 - } - }, - "filename": "assign-01.k", - "line": 2, - "column": 8, - "end_line": 2, - "end_column": 9 - } - }, - "filename": "assign-01.k", - "line": 2, - "column": 4, - "end_line": 2, - "end_column": 9 - }, - "ty": null - }, - "filename": "assign-01.k", - "line": 2, - "column": 0, - "end_line": 2, - "end_column": 9 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "c", - "filename": "assign-01.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 1 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "assign-01.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 1 - } - ], - "value": { - "node": { - "type": "Binary", - "left": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 2 - } - }, - "filename": "assign-01.k", - "line": 3, - "column": 4, - "end_line": 3, - "end_column": 5 - }, - "op": "Add", - "right": { - "node": { - "type": "Binary", - "left": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 2 - } - }, - "filename": "assign-01.k", - "line": 3, - "column": 8, - "end_line": 3, - "end_column": 9 - }, - "op": "Mul", - "right": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 3 - } - }, - "filename": "assign-01.k", - "line": 3, - "column": 10, - "end_line": 3, - "end_column": 11 - } - }, - "filename": "assign-01.k", - "line": 3, - "column": 8, - "end_line": 3, - "end_column": 11 - } - }, - "filename": "assign-01.k", - "line": 3, - "column": 4, - "end_line": 3, - "end_column": 11 - }, - "ty": null - }, - "filename": "assign-01.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 11 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__config_expr_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__config_expr_1.snap deleted file mode 100644 index f4162051e..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__config_expr_1.snap +++ /dev/null @@ -1,54 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/config_expr-01.k\")" ---- -{ - "filename": "config_expr-01.k", - "doc": null, - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "config", - "filename": "config_expr-01.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 6 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "config_expr-01.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 6 - } - ], - "value": { - "node": { - "type": "Config", - "items": [] - }, - "filename": "config_expr-01.k", - "line": 1, - "column": 9, - "end_line": 2, - "end_column": 1 - }, - "ty": null - }, - "filename": "config_expr-01.k", - "line": 1, - "column": 0, - "end_line": 2, - "end_column": 1 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__config_expr_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__config_expr_2.snap deleted file mode 100644 index dd2937192..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__config_expr_2.snap +++ /dev/null @@ -1,149 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/config_expr-02.k\")" ---- -{ - "filename": "config_expr-02.k", - "doc": null, - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "config", - "filename": "config_expr-02.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 6 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "config_expr-02.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 6 - } - ], - "value": { - "node": { - "type": "Config", - "items": [ - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "k1", - "filename": "config_expr-02.k", - "line": 2, - "column": 4, - "end_line": 2, - "end_column": 6 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-02.k", - "line": 2, - "column": 4, - "end_line": 2, - "end_column": 6 - }, - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 111 - } - }, - "filename": "config_expr-02.k", - "line": 2, - "column": 9, - "end_line": 2, - "end_column": 12 - }, - "operation": "Override" - }, - "filename": "config_expr-02.k", - "line": 2, - "column": 4, - "end_line": 2, - "end_column": 12 - }, - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "k2", - "filename": "config_expr-02.k", - "line": 3, - "column": 4, - "end_line": 3, - "end_column": 6 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-02.k", - "line": 3, - "column": 4, - "end_line": 3, - "end_column": 6 - }, - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 222 - } - }, - "filename": "config_expr-02.k", - "line": 3, - "column": 9, - "end_line": 3, - "end_column": 12 - }, - "operation": "Override" - }, - "filename": "config_expr-02.k", - "line": 3, - "column": 4, - "end_line": 3, - "end_column": 12 - } - ] - }, - "filename": "config_expr-02.k", - "line": 1, - "column": 9, - "end_line": 4, - "end_column": 1 - }, - "ty": null - }, - "filename": "config_expr-02.k", - "line": 1, - "column": 0, - "end_line": 4, - "end_column": 1 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__config_expr_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__config_expr_3.snap deleted file mode 100644 index 5a893eaca..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__config_expr_3.snap +++ /dev/null @@ -1,448 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/config_expr-03.k\")" ---- -{ - "filename": "config_expr-03.k", - "doc": null, - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "config", - "filename": "config_expr-03.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 6 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "config_expr-03.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 6 - } - ], - "value": { - "node": { - "type": "Config", - "items": [ - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "main", - "filename": "config_expr-03.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 8 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-03.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 8 - }, - "value": { - "node": { - "type": "Config", - "items": [ - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "env", - "filename": "config_expr-03.k", - "line": 5, - "column": 8, - "end_line": 5, - "end_column": 11 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-03.k", - "line": 5, - "column": 8, - "end_line": 5, - "end_column": 11 - }, - "value": { - "node": { - "type": "List", - "elts": [ - { - "node": { - "type": "Config", - "items": [ - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "name", - "filename": "config_expr-03.k", - "line": 6, - "column": 13, - "end_line": 6, - "end_column": 17 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-03.k", - "line": 6, - "column": 13, - "end_line": 6, - "end_column": 17 - }, - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"ENV_1\"", - "value": "ENV_1" - }, - "filename": "config_expr-03.k", - "line": 6, - "column": 19, - "end_line": 6, - "end_column": 26 - }, - "operation": "Union" - }, - "filename": "config_expr-03.k", - "line": 6, - "column": 13, - "end_line": 6, - "end_column": 26 - }, - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "value", - "filename": "config_expr-03.k", - "line": 6, - "column": 28, - "end_line": 6, - "end_column": 33 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-03.k", - "line": 6, - "column": 28, - "end_line": 6, - "end_column": 33 - }, - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"1\"", - "value": "1" - }, - "filename": "config_expr-03.k", - "line": 6, - "column": 35, - "end_line": 6, - "end_column": 38 - }, - "operation": "Union" - }, - "filename": "config_expr-03.k", - "line": 6, - "column": 28, - "end_line": 6, - "end_column": 38 - } - ] - }, - "filename": "config_expr-03.k", - "line": 6, - "column": 12, - "end_line": 6, - "end_column": 39 - } - ], - "ctx": "Load" - }, - "filename": "config_expr-03.k", - "line": 5, - "column": 13, - "end_line": 7, - "end_column": 9 - }, - "operation": "Union" - }, - "filename": "config_expr-03.k", - "line": 5, - "column": 8, - "end_line": 7, - "end_column": 9 - } - ] - }, - "filename": "config_expr-03.k", - "line": 4, - "column": 10, - "end_line": 8, - "end_column": 5 - }, - "operation": "Union" - }, - "filename": "config_expr-03.k", - "line": 4, - "column": 4, - "end_line": 8, - "end_column": 5 - }, - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "main", - "filename": "config_expr-03.k", - "line": 9, - "column": 4, - "end_line": 9, - "end_column": 8 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-03.k", - "line": 9, - "column": 4, - "end_line": 9, - "end_column": 8 - }, - "value": { - "node": { - "type": "Config", - "items": [ - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "env", - "filename": "config_expr-03.k", - "line": 10, - "column": 8, - "end_line": 10, - "end_column": 11 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-03.k", - "line": 10, - "column": 8, - "end_line": 10, - "end_column": 11 - }, - "value": { - "node": { - "type": "List", - "elts": [ - { - "node": { - "type": "Config", - "items": [ - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "name", - "filename": "config_expr-03.k", - "line": 11, - "column": 13, - "end_line": 11, - "end_column": 17 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-03.k", - "line": 11, - "column": 13, - "end_line": 11, - "end_column": 17 - }, - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"ENV_2\"", - "value": "ENV_2" - }, - "filename": "config_expr-03.k", - "line": 11, - "column": 19, - "end_line": 11, - "end_column": 26 - }, - "operation": "Union" - }, - "filename": "config_expr-03.k", - "line": 11, - "column": 13, - "end_line": 11, - "end_column": 26 - }, - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "value", - "filename": "config_expr-03.k", - "line": 11, - "column": 28, - "end_line": 11, - "end_column": 33 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-03.k", - "line": 11, - "column": 28, - "end_line": 11, - "end_column": 33 - }, - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"2\"", - "value": "2" - }, - "filename": "config_expr-03.k", - "line": 11, - "column": 35, - "end_line": 11, - "end_column": 38 - }, - "operation": "Union" - }, - "filename": "config_expr-03.k", - "line": 11, - "column": 28, - "end_line": 11, - "end_column": 38 - } - ] - }, - "filename": "config_expr-03.k", - "line": 11, - "column": 12, - "end_line": 11, - "end_column": 39 - } - ], - "ctx": "Load" - }, - "filename": "config_expr-03.k", - "line": 10, - "column": 15, - "end_line": 12, - "end_column": 9 - }, - "operation": "Insert" - }, - "filename": "config_expr-03.k", - "line": 10, - "column": 8, - "end_line": 12, - "end_column": 9 - } - ] - }, - "filename": "config_expr-03.k", - "line": 9, - "column": 10, - "end_line": 13, - "end_column": 5 - }, - "operation": "Union" - }, - "filename": "config_expr-03.k", - "line": 9, - "column": 4, - "end_line": 13, - "end_column": 5 - } - ] - }, - "filename": "config_expr-03.k", - "line": 3, - "column": 9, - "end_line": 14, - "end_column": 1 - }, - "ty": null - }, - "filename": "config_expr-03.k", - "line": 3, - "column": 0, - "end_line": 14, - "end_column": 1 - } - ], - "comments": [ - { - "node": { - "text": "# test/grammar/attr_operator/config_inside/insert/dict_0/main.k" - }, - "filename": "config_expr-03.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 63 - } - ] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__config_expr_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__config_expr_4.snap deleted file mode 100644 index 03043661b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__config_expr_4.snap +++ /dev/null @@ -1,865 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/config_expr-04.k\")" ---- -{ - "filename": "config_expr-04.k", - "doc": null, - "body": [ - { - "node": { - "type": "Schema", - "doc": null, - "name": { - "node": "Env", - "filename": "config_expr-04.k", - "line": 3, - "column": 7, - "end_line": 3, - "end_column": 10 - }, - "parent_name": null, - "for_host_name": null, - "is_mixin": false, - "is_protocol": false, - "args": null, - "mixins": [], - "body": [ - { - "node": { - "type": "SchemaAttr", - "doc": "", - "name": { - "node": "name", - "filename": "config_expr-04.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 8 - }, - "op": null, - "value": null, - "is_optional": false, - "decorators": [], - "ty": { - "node": { - "type": "Basic", - "value": "Str" - }, - "filename": "config_expr-04.k", - "line": 4, - "column": 10, - "end_line": 4, - "end_column": 13 - } - }, - "filename": "config_expr-04.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 13 - }, - { - "node": { - "type": "SchemaAttr", - "doc": "", - "name": { - "node": "value", - "filename": "config_expr-04.k", - "line": 5, - "column": 4, - "end_line": 5, - "end_column": 9 - }, - "op": null, - "value": null, - "is_optional": false, - "decorators": [], - "ty": { - "node": { - "type": "Basic", - "value": "Str" - }, - "filename": "config_expr-04.k", - "line": 5, - "column": 11, - "end_line": 5, - "end_column": 14 - } - }, - "filename": "config_expr-04.k", - "line": 5, - "column": 4, - "end_line": 5, - "end_column": 14 - } - ], - "decorators": [], - "checks": [], - "index_signature": null - }, - "filename": "config_expr-04.k", - "line": 3, - "column": 0, - "end_line": 7, - "end_column": 0 - }, - { - "node": { - "type": "Schema", - "doc": null, - "name": { - "node": "Main", - "filename": "config_expr-04.k", - "line": 7, - "column": 7, - "end_line": 7, - "end_column": 11 - }, - "parent_name": null, - "for_host_name": null, - "is_mixin": false, - "is_protocol": false, - "args": null, - "mixins": [], - "body": [ - { - "node": { - "type": "SchemaAttr", - "doc": "", - "name": { - "node": "env", - "filename": "config_expr-04.k", - "line": 8, - "column": 4, - "end_line": 8, - "end_column": 7 - }, - "op": null, - "value": null, - "is_optional": false, - "decorators": [], - "ty": { - "node": { - "type": "List", - "value": { - "inner_type": { - "node": { - "type": "Named", - "value": { - "names": [ - { - "node": "Env", - "filename": "config_expr-04.k", - "line": 8, - "column": 10, - "end_line": 8, - "end_column": 13 - } - ], - "pkgpath": "", - "ctx": "Load" - } - }, - "filename": "config_expr-04.k", - "line": 8, - "column": 10, - "end_line": 8, - "end_column": 13 - } - } - }, - "filename": "config_expr-04.k", - "line": 8, - "column": 9, - "end_line": 8, - "end_column": 14 - } - }, - "filename": "config_expr-04.k", - "line": 8, - "column": 4, - "end_line": 8, - "end_column": 14 - } - ], - "decorators": [], - "checks": [], - "index_signature": null - }, - "filename": "config_expr-04.k", - "line": 7, - "column": 0, - "end_line": 10, - "end_column": 0 - }, - { - "node": { - "type": "Schema", - "doc": null, - "name": { - "node": "Config", - "filename": "config_expr-04.k", - "line": 10, - "column": 7, - "end_line": 10, - "end_column": 13 - }, - "parent_name": null, - "for_host_name": null, - "is_mixin": false, - "is_protocol": false, - "args": null, - "mixins": [], - "body": [ - { - "node": { - "type": "SchemaAttr", - "doc": "", - "name": { - "node": "main", - "filename": "config_expr-04.k", - "line": 11, - "column": 4, - "end_line": 11, - "end_column": 8 - }, - "op": null, - "value": null, - "is_optional": false, - "decorators": [], - "ty": { - "node": { - "type": "Named", - "value": { - "names": [ - { - "node": "Main", - "filename": "config_expr-04.k", - "line": 11, - "column": 10, - "end_line": 11, - "end_column": 14 - } - ], - "pkgpath": "", - "ctx": "Load" - } - }, - "filename": "config_expr-04.k", - "line": 11, - "column": 10, - "end_line": 11, - "end_column": 14 - } - }, - "filename": "config_expr-04.k", - "line": 11, - "column": 4, - "end_line": 11, - "end_column": 14 - } - ], - "decorators": [], - "checks": [], - "index_signature": null - }, - "filename": "config_expr-04.k", - "line": 10, - "column": 0, - "end_line": 13, - "end_column": 0 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "_main", - "filename": "config_expr-04.k", - "line": 13, - "column": 0, - "end_line": 13, - "end_column": 5 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "config_expr-04.k", - "line": 13, - "column": 0, - "end_line": 13, - "end_column": 5 - } - ], - "value": { - "node": { - "type": "Schema", - "name": { - "node": { - "names": [ - { - "node": "Main", - "filename": "config_expr-04.k", - "line": 13, - "column": 8, - "end_line": 13, - "end_column": 12 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-04.k", - "line": 13, - "column": 8, - "end_line": 13, - "end_column": 12 - }, - "args": [], - "kwargs": [], - "config": { - "node": { - "type": "Config", - "items": [ - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "env", - "filename": "config_expr-04.k", - "line": 14, - "column": 4, - "end_line": 14, - "end_column": 7 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-04.k", - "line": 14, - "column": 4, - "end_line": 14, - "end_column": 7 - }, - "value": { - "node": { - "type": "List", - "elts": [ - { - "node": { - "type": "Config", - "items": [ - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "name", - "filename": "config_expr-04.k", - "line": 15, - "column": 9, - "end_line": 15, - "end_column": 13 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-04.k", - "line": 15, - "column": 9, - "end_line": 15, - "end_column": 13 - }, - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"ENV_1\"", - "value": "ENV_1" - }, - "filename": "config_expr-04.k", - "line": 15, - "column": 15, - "end_line": 15, - "end_column": 22 - }, - "operation": "Union" - }, - "filename": "config_expr-04.k", - "line": 15, - "column": 9, - "end_line": 15, - "end_column": 22 - }, - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "value", - "filename": "config_expr-04.k", - "line": 15, - "column": 24, - "end_line": 15, - "end_column": 29 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-04.k", - "line": 15, - "column": 24, - "end_line": 15, - "end_column": 29 - }, - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"1\"", - "value": "1" - }, - "filename": "config_expr-04.k", - "line": 15, - "column": 31, - "end_line": 15, - "end_column": 34 - }, - "operation": "Union" - }, - "filename": "config_expr-04.k", - "line": 15, - "column": 24, - "end_line": 15, - "end_column": 34 - } - ] - }, - "filename": "config_expr-04.k", - "line": 15, - "column": 8, - "end_line": 15, - "end_column": 35 - } - ], - "ctx": "Load" - }, - "filename": "config_expr-04.k", - "line": 14, - "column": 9, - "end_line": 16, - "end_column": 5 - }, - "operation": "Union" - }, - "filename": "config_expr-04.k", - "line": 14, - "column": 4, - "end_line": 16, - "end_column": 5 - } - ] - }, - "filename": "config_expr-04.k", - "line": 13, - "column": 13, - "end_line": 17, - "end_column": 1 - } - }, - "filename": "config_expr-04.k", - "line": 13, - "column": 8, - "end_line": 17, - "end_column": 1 - }, - "ty": null - }, - "filename": "config_expr-04.k", - "line": 13, - "column": 0, - "end_line": 17, - "end_column": 1 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "config", - "filename": "config_expr-04.k", - "line": 19, - "column": 0, - "end_line": 19, - "end_column": 6 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "config_expr-04.k", - "line": 19, - "column": 0, - "end_line": 19, - "end_column": 6 - } - ], - "value": { - "node": { - "type": "Schema", - "name": { - "node": { - "names": [ - { - "node": "Config", - "filename": "config_expr-04.k", - "line": 19, - "column": 9, - "end_line": 19, - "end_column": 15 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-04.k", - "line": 19, - "column": 9, - "end_line": 19, - "end_column": 15 - }, - "args": [], - "kwargs": [], - "config": { - "node": { - "type": "Config", - "items": [ - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "main", - "filename": "config_expr-04.k", - "line": 20, - "column": 4, - "end_line": 20, - "end_column": 8 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-04.k", - "line": 20, - "column": 4, - "end_line": 20, - "end_column": 8 - }, - "value": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "_main", - "filename": "config_expr-04.k", - "line": 20, - "column": 10, - "end_line": 20, - "end_column": 15 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-04.k", - "line": 20, - "column": 10, - "end_line": 20, - "end_column": 15 - }, - "operation": "Union" - }, - "filename": "config_expr-04.k", - "line": 20, - "column": 4, - "end_line": 20, - "end_column": 15 - }, - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "main", - "filename": "config_expr-04.k", - "line": 21, - "column": 4, - "end_line": 21, - "end_column": 8 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-04.k", - "line": 21, - "column": 4, - "end_line": 21, - "end_column": 8 - }, - "value": { - "node": { - "type": "Schema", - "name": { - "node": { - "names": [ - { - "node": "Main", - "filename": "config_expr-04.k", - "line": 21, - "column": 10, - "end_line": 21, - "end_column": 14 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-04.k", - "line": 21, - "column": 10, - "end_line": 21, - "end_column": 14 - }, - "args": [], - "kwargs": [], - "config": { - "node": { - "type": "Config", - "items": [ - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "env", - "filename": "config_expr-04.k", - "line": 22, - "column": 8, - "end_line": 22, - "end_column": 11 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-04.k", - "line": 22, - "column": 8, - "end_line": 22, - "end_column": 11 - }, - "value": { - "node": { - "type": "List", - "elts": [ - { - "node": { - "type": "Config", - "items": [ - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "name", - "filename": "config_expr-04.k", - "line": 23, - "column": 13, - "end_line": 23, - "end_column": 17 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-04.k", - "line": 23, - "column": 13, - "end_line": 23, - "end_column": 17 - }, - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"ENV_2\"", - "value": "ENV_2" - }, - "filename": "config_expr-04.k", - "line": 23, - "column": 19, - "end_line": 23, - "end_column": 26 - }, - "operation": "Union" - }, - "filename": "config_expr-04.k", - "line": 23, - "column": 13, - "end_line": 23, - "end_column": 26 - }, - { - "node": { - "key": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "value", - "filename": "config_expr-04.k", - "line": 23, - "column": 28, - "end_line": 23, - "end_column": 33 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "config_expr-04.k", - "line": 23, - "column": 28, - "end_line": 23, - "end_column": 33 - }, - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"2\"", - "value": "2" - }, - "filename": "config_expr-04.k", - "line": 23, - "column": 35, - "end_line": 23, - "end_column": 38 - }, - "operation": "Union" - }, - "filename": "config_expr-04.k", - "line": 23, - "column": 28, - "end_line": 23, - "end_column": 38 - } - ] - }, - "filename": "config_expr-04.k", - "line": 23, - "column": 12, - "end_line": 23, - "end_column": 39 - } - ], - "ctx": "Load" - }, - "filename": "config_expr-04.k", - "line": 22, - "column": 15, - "end_line": 24, - "end_column": 9 - }, - "operation": "Insert" - }, - "filename": "config_expr-04.k", - "line": 22, - "column": 8, - "end_line": 24, - "end_column": 9 - } - ] - }, - "filename": "config_expr-04.k", - "line": 21, - "column": 15, - "end_line": 25, - "end_column": 5 - } - }, - "filename": "config_expr-04.k", - "line": 21, - "column": 10, - "end_line": 25, - "end_column": 5 - }, - "operation": "Union" - }, - "filename": "config_expr-04.k", - "line": 21, - "column": 4, - "end_line": 25, - "end_column": 5 - } - ] - }, - "filename": "config_expr-04.k", - "line": 19, - "column": 16, - "end_line": 26, - "end_column": 1 - } - }, - "filename": "config_expr-04.k", - "line": 19, - "column": 9, - "end_line": 26, - "end_column": 1 - }, - "ty": null - }, - "filename": "config_expr-04.k", - "line": 19, - "column": 0, - "end_line": 26, - "end_column": 1 - } - ], - "comments": [ - { - "node": { - "text": "# test/grammar/attr_operator/config_inside/insert/schema_0/main.k" - }, - "filename": "config_expr-04.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 65 - } - ] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__hello_win.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__hello_win.snap deleted file mode 100644 index f5ad82a8f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__hello_win.snap +++ /dev/null @@ -1,163 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/hello_win.k\")" ---- -{ - "filename": "hello_win.k", - "doc": null, - "body": [ - { - "node": { - "type": "Schema", - "doc": null, - "name": { - "node": "Person", - "filename": "hello_win.k", - "line": 2, - "column": 7, - "end_line": 2, - "end_column": 13 - }, - "parent_name": null, - "for_host_name": null, - "is_mixin": false, - "is_protocol": false, - "args": null, - "mixins": [], - "body": [ - { - "node": { - "type": "SchemaAttr", - "doc": "", - "name": { - "node": "name", - "filename": "hello_win.k", - "line": 3, - "column": 4, - "end_line": 3, - "end_column": 8 - }, - "op": "Assign", - "value": { - "node": { - "type": "StringLit", - "is_long_string": false, - "raw_value": "\"kcl\"", - "value": "kcl" - }, - "filename": "hello_win.k", - "line": 3, - "column": 16, - "end_line": 3, - "end_column": 21 - }, - "is_optional": false, - "decorators": [], - "ty": { - "node": { - "type": "Basic", - "value": "Str" - }, - "filename": "hello_win.k", - "line": 3, - "column": 10, - "end_line": 3, - "end_column": 13 - } - }, - "filename": "hello_win.k", - "line": 3, - "column": 4, - "end_line": 3, - "end_column": 21 - } - ], - "decorators": [], - "checks": [], - "index_signature": null - }, - "filename": "hello_win.k", - "line": 2, - "column": 0, - "end_line": 5, - "end_column": 0 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "x0", - "filename": "hello_win.k", - "line": 5, - "column": 0, - "end_line": 5, - "end_column": 2 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "hello_win.k", - "line": 5, - "column": 0, - "end_line": 5, - "end_column": 2 - } - ], - "value": { - "node": { - "type": "Schema", - "name": { - "node": { - "names": [ - { - "node": "Person", - "filename": "hello_win.k", - "line": 5, - "column": 5, - "end_line": 5, - "end_column": 11 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "hello_win.k", - "line": 5, - "column": 5, - "end_line": 5, - "end_column": 11 - }, - "args": [], - "kwargs": [], - "config": { - "node": { - "type": "Config", - "items": [] - }, - "filename": "hello_win.k", - "line": 5, - "column": 12, - "end_line": 5, - "end_column": 14 - } - }, - "filename": "hello_win.k", - "line": 5, - "column": 5, - "end_line": 5, - "end_column": 14 - }, - "ty": null - }, - "filename": "hello_win.k", - "line": 5, - "column": 0, - "end_line": 5, - "end_column": 14 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__if_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__if_1.snap deleted file mode 100644 index 4621f8909..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__if_1.snap +++ /dev/null @@ -1,140 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/if-01.k\")" ---- -{ - "filename": "if-01.k", - "doc": null, - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "a", - "filename": "if-01.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 1 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "if-01.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 1 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "if-01.k", - "line": 1, - "column": 4, - "end_line": 1, - "end_column": 5 - }, - "ty": null - }, - "filename": "if-01.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 5 - }, - { - "node": { - "type": "If", - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "bbb", - "filename": "if-01.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 7 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "if-01.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 7 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 2 - } - }, - "filename": "if-01.k", - "line": 4, - "column": 10, - "end_line": 4, - "end_column": 11 - }, - "ty": null - }, - "filename": "if-01.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 11 - } - ], - "cond": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "a", - "filename": "if-01.k", - "line": 3, - "column": 3, - "end_line": 3, - "end_column": 4 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "if-01.k", - "line": 3, - "column": 3, - "end_line": 3, - "end_column": 4 - }, - "orelse": [] - }, - "filename": "if-01.k", - "line": 3, - "column": 0, - "end_line": 4, - "end_column": 12 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__if_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__if_2.snap deleted file mode 100644 index fa0d10abb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__if_2.snap +++ /dev/null @@ -1,453 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/if-02.k\")" ---- -{ - "filename": "if-02.k", - "doc": null, - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "a", - "filename": "if-02.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 1 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "if-02.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 1 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "if-02.k", - "line": 1, - "column": 4, - "end_line": 1, - "end_column": 5 - }, - "ty": null - }, - "filename": "if-02.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 5 - }, - { - "node": { - "type": "If", - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "bbb", - "filename": "if-02.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 7 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "if-02.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 7 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 2 - } - }, - "filename": "if-02.k", - "line": 4, - "column": 10, - "end_line": 4, - "end_column": 11 - }, - "ty": null - }, - "filename": "if-02.k", - "line": 4, - "column": 4, - "end_line": 4, - "end_column": 11 - } - ], - "cond": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "a", - "filename": "if-02.k", - "line": 3, - "column": 3, - "end_line": 3, - "end_column": 4 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "if-02.k", - "line": 3, - "column": 3, - "end_line": 3, - "end_column": 4 - }, - "orelse": [ - { - "node": { - "type": "If", - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "ccc", - "filename": "if-02.k", - "line": 6, - "column": 4, - "end_line": 6, - "end_column": 7 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "if-02.k", - "line": 6, - "column": 4, - "end_line": 6, - "end_column": 7 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 3 - } - }, - "filename": "if-02.k", - "line": 6, - "column": 10, - "end_line": 6, - "end_column": 11 - }, - "ty": null - }, - "filename": "if-02.k", - "line": 6, - "column": 4, - "end_line": 6, - "end_column": 11 - } - ], - "cond": { - "node": { - "type": "Binary", - "left": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "a", - "filename": "if-02.k", - "line": 5, - "column": 5, - "end_line": 5, - "end_column": 6 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "if-02.k", - "line": 5, - "column": 5, - "end_line": 5, - "end_column": 6 - }, - "op": "Add", - "right": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 10 - } - }, - "filename": "if-02.k", - "line": 5, - "column": 9, - "end_line": 5, - "end_column": 11 - } - }, - "filename": "if-02.k", - "line": 5, - "column": 5, - "end_line": 5, - "end_column": 11 - }, - "orelse": [ - { - "node": { - "type": "If", - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "ddd", - "filename": "if-02.k", - "line": 8, - "column": 4, - "end_line": 8, - "end_column": 7 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "if-02.k", - "line": 8, - "column": 4, - "end_line": 8, - "end_column": 7 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 4 - } - }, - "filename": "if-02.k", - "line": 8, - "column": 10, - "end_line": 8, - "end_column": 11 - }, - "ty": null - }, - "filename": "if-02.k", - "line": 8, - "column": 4, - "end_line": 8, - "end_column": 11 - } - ], - "cond": { - "node": { - "type": "Binary", - "left": { - "node": { - "type": "Identifier", - "names": [ - { - "node": "a", - "filename": "if-02.k", - "line": 7, - "column": 5, - "end_line": 7, - "end_column": 6 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "if-02.k", - "line": 7, - "column": 5, - "end_line": 7, - "end_column": 6 - }, - "op": "Add", - "right": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 100 - } - }, - "filename": "if-02.k", - "line": 7, - "column": 9, - "end_line": 7, - "end_column": 12 - } - }, - "filename": "if-02.k", - "line": 7, - "column": 5, - "end_line": 7, - "end_column": 12 - }, - "orelse": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "eee", - "filename": "if-02.k", - "line": 10, - "column": 4, - "end_line": 10, - "end_column": 7 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "if-02.k", - "line": 10, - "column": 4, - "end_line": 10, - "end_column": 7 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 5 - } - }, - "filename": "if-02.k", - "line": 10, - "column": 10, - "end_line": 10, - "end_column": 11 - }, - "ty": null - }, - "filename": "if-02.k", - "line": 10, - "column": 4, - "end_line": 10, - "end_column": 11 - }, - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "fff", - "filename": "if-02.k", - "line": 11, - "column": 4, - "end_line": 11, - "end_column": 7 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "if-02.k", - "line": 11, - "column": 4, - "end_line": 11, - "end_column": 7 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 6 - } - }, - "filename": "if-02.k", - "line": 11, - "column": 10, - "end_line": 11, - "end_column": 11 - }, - "ty": null - }, - "filename": "if-02.k", - "line": 11, - "column": 4, - "end_line": 11, - "end_column": 11 - } - ] - }, - "filename": "if-02.k", - "line": 7, - "column": 0, - "end_line": 11, - "end_column": 11 - } - ] - }, - "filename": "if-02.k", - "line": 5, - "column": 0, - "end_line": 11, - "end_column": 11 - } - ] - }, - "filename": "if-02.k", - "line": 3, - "column": 0, - "end_line": 11, - "end_column": 12 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__if_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__if_3.snap deleted file mode 100644 index 15b09c735..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__if_3.snap +++ /dev/null @@ -1,82 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/if-03.k\")" ---- -{ - "filename": "if-03.k", - "doc": null, - "body": [ - { - "node": { - "type": "If", - "body": [ - { - "node": { - "type": "Assign", - "targets": [ - { - "node": { - "name": { - "node": "a", - "filename": "if-03.k", - "line": 1, - "column": 9, - "end_line": 1, - "end_column": 10 - }, - "paths": [], - "pkgpath": "" - }, - "filename": "if-03.k", - "line": 1, - "column": 9, - "end_line": 1, - "end_column": 10 - } - ], - "value": { - "node": { - "type": "NumberLit", - "binary_suffix": null, - "value": { - "type": "Int", - "value": 1 - } - }, - "filename": "if-03.k", - "line": 1, - "column": 13, - "end_line": 1, - "end_column": 14 - }, - "ty": null - }, - "filename": "if-03.k", - "line": 1, - "column": 9, - "end_line": 1, - "end_column": 14 - } - ], - "cond": { - "node": { - "type": "NameConstantLit", - "value": "True" - }, - "filename": "if-03.k", - "line": 1, - "column": 3, - "end_line": 1, - "end_column": 7 - }, - "orelse": [] - }, - "filename": "if-03.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 15 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__import_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__import_1.snap deleted file mode 100644 index 3b95fac1a..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__import_1.snap +++ /dev/null @@ -1,106 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/import-01.k\")" ---- -{ - "filename": "import-01.k", - "doc": null, - "body": [ - { - "node": { - "type": "Import", - "path": { - "node": "a1", - "filename": "import-01.k", - "line": 1, - "column": 7, - "end_line": 1, - "end_column": 9 - }, - "rawpath": "a1", - "name": "a1", - "asname": null, - "pkg_name": "__main__" - }, - "filename": "import-01.k", - "line": 1, - "column": 0, - "end_line": 1, - "end_column": 9 - }, - { - "node": { - "type": "Import", - "path": { - "node": "a2", - "filename": "import-01.k", - "line": 3, - "column": 7, - "end_line": 3, - "end_column": 9 - }, - "rawpath": "a2", - "name": "a2_pkg", - "asname": { - "node": "a2_pkg", - "filename": "import-01.k", - "line": 3, - "column": 13, - "end_line": 3, - "end_column": 19 - }, - "pkg_name": "__main__" - }, - "filename": "import-01.k", - "line": 3, - "column": 0, - "end_line": 3, - "end_column": 19 - }, - { - "node": { - "type": "Import", - "path": { - "node": "subpkg.b1.c1", - "filename": "import-01.k", - "line": 5, - "column": 7, - "end_line": 5, - "end_column": 19 - }, - "rawpath": "subpkg.b1.c1", - "name": "c1", - "asname": null, - "pkg_name": "__main__" - }, - "filename": "import-01.k", - "line": 5, - "column": 0, - "end_line": 5, - "end_column": 19 - }, - { - "node": { - "type": "Import", - "path": { - "node": "a3", - "filename": "import-01.k", - "line": 7, - "column": 7, - "end_line": 7, - "end_column": 10 - }, - "rawpath": ".a3", - "name": "a3", - "asname": null, - "pkg_name": "__main__" - }, - "filename": "import-01.k", - "line": 7, - "column": 0, - "end_line": 7, - "end_column": 10 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__type_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__type_1.snap deleted file mode 100644 index e696e92c9..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__file__type_1.snap +++ /dev/null @@ -1,540 +0,0 @@ ---- -source: parser/src/tests/file.rs -expression: "crate::tests::parsing_file_string(\"testdata/type-01.k\")" ---- -{ - "filename": "type-01.k", - "doc": null, - "body": [ - { - "node": { - "type": "TypeAlias", - "type_name": { - "node": { - "names": [ - { - "node": "a", - "filename": "type-01.k", - "line": 1, - "column": 5, - "end_line": 1, - "end_column": 6 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "type-01.k", - "line": 1, - "column": 5, - "end_line": 1, - "end_column": 6 - }, - "type_value": { - "node": "any", - "filename": "type-01.k", - "line": 1, - "column": 9, - "end_line": 1, - "end_column": 12 - }, - "ty": { - "node": { - "type": "Any" - }, - "filename": "type-01.k", - "line": 1, - "column": 9, - "end_line": 1, - "end_column": 12 - } - }, - "filename": "type-01.k", - "line": 1, - "column": 5, - "end_line": 1, - "end_column": 12 - }, - { - "node": { - "type": "TypeAlias", - "type_name": { - "node": { - "names": [ - { - "node": "b", - "filename": "type-01.k", - "line": 3, - "column": 5, - "end_line": 3, - "end_column": 6 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "type-01.k", - "line": 3, - "column": 5, - "end_line": 3, - "end_column": 6 - }, - "type_value": { - "node": "bool", - "filename": "type-01.k", - "line": 3, - "column": 9, - "end_line": 3, - "end_column": 13 - }, - "ty": { - "node": { - "type": "Basic", - "value": "Bool" - }, - "filename": "type-01.k", - "line": 3, - "column": 9, - "end_line": 3, - "end_column": 13 - } - }, - "filename": "type-01.k", - "line": 3, - "column": 5, - "end_line": 3, - "end_column": 13 - }, - { - "node": { - "type": "TypeAlias", - "type_name": { - "node": { - "names": [ - { - "node": "c", - "filename": "type-01.k", - "line": 4, - "column": 5, - "end_line": 4, - "end_column": 6 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "type-01.k", - "line": 4, - "column": 5, - "end_line": 4, - "end_column": 6 - }, - "type_value": { - "node": "int", - "filename": "type-01.k", - "line": 4, - "column": 9, - "end_line": 4, - "end_column": 12 - }, - "ty": { - "node": { - "type": "Basic", - "value": "Int" - }, - "filename": "type-01.k", - "line": 4, - "column": 9, - "end_line": 4, - "end_column": 12 - } - }, - "filename": "type-01.k", - "line": 4, - "column": 5, - "end_line": 4, - "end_column": 12 - }, - { - "node": { - "type": "TypeAlias", - "type_name": { - "node": { - "names": [ - { - "node": "d", - "filename": "type-01.k", - "line": 5, - "column": 5, - "end_line": 5, - "end_column": 6 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "type-01.k", - "line": 5, - "column": 5, - "end_line": 5, - "end_column": 6 - }, - "type_value": { - "node": "float", - "filename": "type-01.k", - "line": 5, - "column": 9, - "end_line": 5, - "end_column": 14 - }, - "ty": { - "node": { - "type": "Basic", - "value": "Float" - }, - "filename": "type-01.k", - "line": 5, - "column": 9, - "end_line": 5, - "end_column": 14 - } - }, - "filename": "type-01.k", - "line": 5, - "column": 5, - "end_line": 5, - "end_column": 14 - }, - { - "node": { - "type": "TypeAlias", - "type_name": { - "node": { - "names": [ - { - "node": "e", - "filename": "type-01.k", - "line": 6, - "column": 5, - "end_line": 6, - "end_column": 6 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "type-01.k", - "line": 6, - "column": 5, - "end_line": 6, - "end_column": 6 - }, - "type_value": { - "node": "str", - "filename": "type-01.k", - "line": 6, - "column": 9, - "end_line": 6, - "end_column": 12 - }, - "ty": { - "node": { - "type": "Basic", - "value": "Str" - }, - "filename": "type-01.k", - "line": 6, - "column": 9, - "end_line": 6, - "end_column": 12 - } - }, - "filename": "type-01.k", - "line": 6, - "column": 5, - "end_line": 6, - "end_column": 12 - }, - { - "node": { - "type": "TypeAlias", - "type_name": { - "node": { - "names": [ - { - "node": "type_list1", - "filename": "type-01.k", - "line": 8, - "column": 5, - "end_line": 8, - "end_column": 15 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "type-01.k", - "line": 8, - "column": 5, - "end_line": 8, - "end_column": 15 - }, - "type_value": { - "node": "[]", - "filename": "type-01.k", - "line": 8, - "column": 18, - "end_line": 8, - "end_column": 20 - }, - "ty": { - "node": { - "type": "List", - "value": { - "inner_type": null - } - }, - "filename": "type-01.k", - "line": 8, - "column": 18, - "end_line": 8, - "end_column": 20 - } - }, - "filename": "type-01.k", - "line": 8, - "column": 5, - "end_line": 8, - "end_column": 20 - }, - { - "node": { - "type": "TypeAlias", - "type_name": { - "node": { - "names": [ - { - "node": "type_list2", - "filename": "type-01.k", - "line": 9, - "column": 5, - "end_line": 9, - "end_column": 15 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "type-01.k", - "line": 9, - "column": 5, - "end_line": 9, - "end_column": 15 - }, - "type_value": { - "node": "[[]]", - "filename": "type-01.k", - "line": 9, - "column": 18, - "end_line": 9, - "end_column": 22 - }, - "ty": { - "node": { - "type": "List", - "value": { - "inner_type": { - "node": { - "type": "List", - "value": { - "inner_type": null - } - }, - "filename": "type-01.k", - "line": 9, - "column": 19, - "end_line": 9, - "end_column": 21 - } - } - }, - "filename": "type-01.k", - "line": 9, - "column": 18, - "end_line": 9, - "end_column": 22 - } - }, - "filename": "type-01.k", - "line": 9, - "column": 5, - "end_line": 9, - "end_column": 22 - }, - { - "node": { - "type": "TypeAlias", - "type_name": { - "node": { - "names": [ - { - "node": "type_list3", - "filename": "type-01.k", - "line": 10, - "column": 5, - "end_line": 10, - "end_column": 15 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "type-01.k", - "line": 10, - "column": 5, - "end_line": 10, - "end_column": 15 - }, - "type_value": { - "node": "[int]", - "filename": "type-01.k", - "line": 10, - "column": 18, - "end_line": 10, - "end_column": 23 - }, - "ty": { - "node": { - "type": "List", - "value": { - "inner_type": { - "node": { - "type": "Basic", - "value": "Int" - }, - "filename": "type-01.k", - "line": 10, - "column": 19, - "end_line": 10, - "end_column": 22 - } - } - }, - "filename": "type-01.k", - "line": 10, - "column": 18, - "end_line": 10, - "end_column": 23 - } - }, - "filename": "type-01.k", - "line": 10, - "column": 5, - "end_line": 10, - "end_column": 23 - }, - { - "node": { - "type": "TypeAlias", - "type_name": { - "node": { - "names": [ - { - "node": "b", - "filename": "type-01.k", - "line": 12, - "column": 5, - "end_line": 12, - "end_column": 6 - } - ], - "pkgpath": "", - "ctx": "Load" - }, - "filename": "type-01.k", - "line": 12, - "column": 5, - "end_line": 12, - "end_column": 6 - }, - "type_value": { - "node": "int | str | [] | {:}", - "filename": "type-01.k", - "line": 12, - "column": 9, - "end_line": 12, - "end_column": 29 - }, - "ty": { - "node": { - "type": "Union", - "value": { - "type_elements": [ - { - "node": { - "type": "Basic", - "value": "Int" - }, - "filename": "type-01.k", - "line": 12, - "column": 9, - "end_line": 12, - "end_column": 12 - }, - { - "node": { - "type": "Basic", - "value": "Str" - }, - "filename": "type-01.k", - "line": 12, - "column": 15, - "end_line": 12, - "end_column": 18 - }, - { - "node": { - "type": "List", - "value": { - "inner_type": null - } - }, - "filename": "type-01.k", - "line": 12, - "column": 21, - "end_line": 12, - "end_column": 23 - }, - { - "node": { - "type": "Dict", - "value": { - "key_type": null, - "value_type": null - } - }, - "filename": "type-01.k", - "line": 12, - "column": 26, - "end_line": 12, - "end_column": 29 - } - ] - } - }, - "filename": "type-01.k", - "line": 12, - "column": 9, - "end_line": 12, - "end_column": 29 - } - }, - "filename": "type-01.k", - "line": 12, - "column": 5, - "end_line": 12, - "end_column": 29 - } - ], - "comments": [] -} diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__any_type.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__any_type.snap deleted file mode 100644 index 5e3e41d28..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__any_type.snap +++ /dev/null @@ -1,13 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"any\"####)" ---- -Node { - node: Any, - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__basic_type_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__basic_type_0.snap deleted file mode 100644 index d7a243058..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__basic_type_0.snap +++ /dev/null @@ -1,15 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"bool\"####)" ---- -Node { - node: Basic( - Bool, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__basic_type_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__basic_type_1.snap deleted file mode 100644 index 335b19217..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__basic_type_1.snap +++ /dev/null @@ -1,15 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"int\"####)" ---- -Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__basic_type_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__basic_type_2.snap deleted file mode 100644 index 7c6ee89d2..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__basic_type_2.snap +++ /dev/null @@ -1,15 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"float\"####)" ---- -Node { - node: Basic( - Float, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__basic_type_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__basic_type_3.snap deleted file mode 100644 index 9d7b59a4b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__basic_type_3.snap +++ /dev/null @@ -1,15 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"str\"####)" ---- -Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_0.snap deleted file mode 100644 index 7d0a2bf4b..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_0.snap +++ /dev/null @@ -1,18 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"{:}\"####)" ---- -Node { - node: Dict( - DictType { - key_type: None, - value_type: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_1.snap deleted file mode 100644 index 3b4667dcb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_1.snap +++ /dev/null @@ -1,29 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"{str:}\"####)" ---- -Node { - node: Dict( - DictType { - key_type: Some( - Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 4, - }, - ), - value_type: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_2.snap deleted file mode 100644 index 8165aaed5..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_2.snap +++ /dev/null @@ -1,31 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"{:[]}\"####)" ---- -Node { - node: Dict( - DictType { - key_type: None, - value_type: Some( - Node { - node: List( - ListType { - inner_type: None, - }, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 4, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_3.snap deleted file mode 100644 index c35fb6168..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_3.snap +++ /dev/null @@ -1,54 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"{str:{:float}}\"####)" ---- -Node { - node: Dict( - DictType { - key_type: Some( - Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 4, - }, - ), - value_type: Some( - Node { - node: Dict( - DictType { - key_type: None, - value_type: Some( - Node { - node: Basic( - Float, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 12, - }, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 13, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 14, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_4.snap deleted file mode 100644 index b98aafcde..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__dict_type_4.snap +++ /dev/null @@ -1,54 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"{str:{:float}, int:[]}\"####)" ---- -Node { - node: Dict( - DictType { - key_type: Some( - Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 4, - }, - ), - value_type: Some( - Node { - node: Dict( - DictType { - key_type: None, - value_type: Some( - Node { - node: Basic( - Float, - ), - filename: "", - line: 1, - column: 7, - end_line: 1, - end_column: 12, - }, - ), - }, - ), - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 13, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 14, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_0.snap deleted file mode 100644 index c473941af..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_0.snap +++ /dev/null @@ -1,17 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"[]\"####)" ---- -Node { - node: List( - ListType { - inner_type: None, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_1.snap deleted file mode 100644 index fd9988b84..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_1.snap +++ /dev/null @@ -1,28 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"[int]\"####)" ---- -Node { - node: List( - ListType { - inner_type: Some( - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 4, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_2.snap deleted file mode 100644 index 73e992119..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_2.snap +++ /dev/null @@ -1,26 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"[any]\"####)" ---- -Node { - node: List( - ListType { - inner_type: Some( - Node { - node: Any, - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 4, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_3.snap deleted file mode 100644 index a3b930896..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_3.snap +++ /dev/null @@ -1,30 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"[[]]\"####)" ---- -Node { - node: List( - ListType { - inner_type: Some( - Node { - node: List( - ListType { - inner_type: None, - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 3, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_4.snap deleted file mode 100644 index 518dd31b9..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__list_type_4.snap +++ /dev/null @@ -1,41 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"[[str]]\"####)" ---- -Node { - node: List( - ListType { - inner_type: Some( - Node { - node: List( - ListType { - inner_type: Some( - Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 2, - end_line: 1, - end_column: 5, - }, - ), - }, - ), - filename: "", - line: 1, - column: 1, - end_line: 1, - end_column: 6, - }, - ), - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_0.snap deleted file mode 100644 index d7ba0c795..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_0.snap +++ /dev/null @@ -1,17 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"True\"####)" ---- -Node { - node: Literal( - Bool( - true, - ), - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_1.snap deleted file mode 100644 index 79951d904..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_1.snap +++ /dev/null @@ -1,17 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"False\"####)" ---- -Node { - node: Literal( - Bool( - false, - ), - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_2.snap deleted file mode 100644 index fe221ef16..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_2.snap +++ /dev/null @@ -1,20 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"123\"####)" ---- -Node { - node: Literal( - Int( - IntLiteralType { - value: 123, - suffix: None, - }, - ), - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_3.snap deleted file mode 100644 index 7db780a7d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_3.snap +++ /dev/null @@ -1,17 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"123.0\"####)" ---- -Node { - node: Literal( - Float( - 123.0, - ), - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_4.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_4.snap deleted file mode 100644 index 9e368bc0d..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_4.snap +++ /dev/null @@ -1,17 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"\"abc\"\"####)" ---- -Node { - node: Literal( - Str( - "abc", - ), - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 5, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_5.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_5.snap deleted file mode 100644 index 886d9b0cb..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__literal_type_5.snap +++ /dev/null @@ -1,17 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"''\"####)" ---- -Node { - node: Literal( - Str( - "", - ), - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 2, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__named_type_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__named_type_0.snap deleted file mode 100644 index 9c2a9e0a9..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__named_type_0.snap +++ /dev/null @@ -1,28 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"Person\"####)" ---- -Node { - node: Named( - Identifier { - names: [ - Node { - node: "Person", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 6, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__named_type_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__named_type_1.snap deleted file mode 100644 index ea918caae..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__named_type_1.snap +++ /dev/null @@ -1,44 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"some.pkg.Person\"####)" ---- -Node { - node: Named( - Identifier { - names: [ - Node { - node: "some", - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 4, - }, - Node { - node: "pkg", - filename: "", - line: 1, - column: 5, - end_line: 1, - end_column: 8, - }, - Node { - node: "Person", - filename: "", - line: 1, - column: 9, - end_line: 1, - end_column: 15, - }, - ], - pkgpath: "", - ctx: Load, - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 15, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__type_str_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__type_str_0.snap deleted file mode 100644 index fe487c4ab..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__type_str_0.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_node_string(r####\"int\"####)" ---- -int diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__type_str_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__type_str_1.snap deleted file mode 100644 index b5d050c86..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__type_str_1.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_node_string(r####\" int \"####)" ---- -int diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__type_str_2.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__type_str_2.snap deleted file mode 100644 index f6ceb4f04..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__type_str_2.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_node_string(r####\"bool | True | int | str|str\"####)" ---- -bool | True | int | str | str diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__type_str_3.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__type_str_3.snap deleted file mode 100644 index 8d25e81de..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__type_str_3.snap +++ /dev/null @@ -1,5 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_node_string(r####\"[ [{str: float}] | int]\"####)" ---- -[[{str:float}] | int] diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__union_type_0.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__union_type_0.snap deleted file mode 100644 index d78b2e820..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__union_type_0.snap +++ /dev/null @@ -1,38 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"int|str\"####)" ---- -Node { - node: Union( - UnionType { - type_elements: [ - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 4, - end_line: 1, - end_column: 7, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 7, -} - diff --git a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__union_type_1.snap b/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__union_type_1.snap deleted file mode 100644 index 4a631d87f..000000000 --- a/kclvm/parser/src/tests/snapshots/kclvm_parser__tests__types__union_type_1.snap +++ /dev/null @@ -1,63 +0,0 @@ ---- -source: parser/src/tests/types.rs -expression: "crate::tests::parsing_type_string(r####\"int | str | [] | {:}\"####)" ---- -Node { - node: Union( - UnionType { - type_elements: [ - Node { - node: Basic( - Int, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 3, - }, - Node { - node: Basic( - Str, - ), - filename: "", - line: 1, - column: 6, - end_line: 1, - end_column: 9, - }, - Node { - node: List( - ListType { - inner_type: None, - }, - ), - filename: "", - line: 1, - column: 12, - end_line: 1, - end_column: 14, - }, - Node { - node: Dict( - DictType { - key_type: None, - value_type: None, - }, - ), - filename: "", - line: 1, - column: 17, - end_line: 1, - end_column: 20, - }, - ], - }, - ), - filename: "", - line: 1, - column: 0, - end_line: 1, - end_column: 20, -} - diff --git a/kclvm/primitives/Cargo.toml b/kclvm/primitives/Cargo.toml deleted file mode 100644 index 98b114bf0..000000000 --- a/kclvm/primitives/Cargo.toml +++ /dev/null @@ -1,8 +0,0 @@ -[package] -name = "kclvm-primitives" -version = "0.11.2" -edition = "2021" - -[dependencies] -indexmap = "2.9.0" -rustc-hash = "2.1.1" diff --git a/kclvm/query/Cargo.toml b/kclvm/query/Cargo.toml deleted file mode 100644 index 88d3f5a58..000000000 --- a/kclvm/query/Cargo.toml +++ /dev/null @@ -1,27 +0,0 @@ -[package] -name = "kclvm-query" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[dependencies] -anyhow = "1.0" -compiler_base_session = "0.1.3" -compiler_base_macros = "0.1.1" - -kclvm-ast = { path = "../ast" } -kclvm-ast-pretty = { path = "../ast_pretty" } -kclvm-parser = { path = "../parser" } -kclvm-sema = { path = "../sema" } -kclvm-error = { path = "../error" } -kclvm-utils = { path = "../utils" } -kclvm-primitives = { path = "../primitives" } -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" -fancy-regex = "0.7.1" -maplit = "1.0.2" - -[dev-dependencies] -pretty_assertions = "1.2.1" -insta = "1.8.0" diff --git a/kclvm/query/src/lib.rs b/kclvm/query/src/lib.rs deleted file mode 100644 index 88d25b3a8..000000000 --- a/kclvm/query/src/lib.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! This package is mainly the implementation of the KCL query tool, mainly including -//! KCL code modification `override` and other implementations. We can call the `override_file` -//! function to modify the file. The main principle is to parse the AST according to the -//! input file name, and according to the ast::OverrideSpec transforms the nodes in the -//! AST, recursively modifying or deleting the values of the nodes in the AST. -pub mod node; -pub mod r#override; -pub mod path; -pub mod query; -pub mod selector; - -#[cfg(test)] -mod tests; -mod util; - -use anyhow::{anyhow, Result}; -use kclvm_ast_pretty::print_ast_module; -use kclvm_error::diagnostic::Errors; -use kclvm_parser::parse_single_file; - -use kclvm_sema::pre_process::fix_config_expr_nest_attr; -pub use query::{get_schema_type, GetSchemaOption}; -pub use r#override::{apply_override_on_module, apply_overrides}; - -/// Override and rewrite a file with override specifications. Please note that this is an external user API, -/// and it can directly modify the KCL file in place. -/// -/// # Parameters -/// -/// `file`: [&str] -/// The File that need to be overridden -/// -/// `specs`: &\[[String]\] -/// List of specs that need to be overridden. -/// Each spec string satisfies the form: := or :- -/// When the pkgpath is '__main__', `:` can be omitted. -/// -/// `import_paths`: &\[[String]\] -/// List of import paths that are need to be added. -/// -/// # Returns -/// -/// result: [Result] -/// Whether the file has been modified. -/// -/// # Examples -/// -/// ```no_run -/// use kclvm_query::override_file; -/// -/// let result = override_file( -/// "test.k", -/// &["alice.age=18".to_string()], -/// &[] -/// ).unwrap(); -/// ``` -/// -/// - test.k (before override) -/// -/// ```kcl -/// schema Person: -/// age: int -/// -/// alice = Person { -/// age = 10 -/// } -/// ``` -/// -/// - test.k (after override) -/// -/// ```kcl -/// schema Person: -/// age: int -/// -/// alice = Person { -/// age = 18 -/// } -/// ``` -pub fn override_file( - file: &str, - specs: &[String], - import_paths: &[String], -) -> Result { - // Parse file to AST module. - let mut parse_result = match parse_single_file(file, None) { - Ok(module) => module, - Err(msg) => return Err(anyhow!("{}", msg)), - }; - let mut result = false; - // Override AST module. - for s in specs { - if apply_override_on_module(&mut parse_result.module, s, import_paths)? { - result = true; - } - } - - // Transform config expr to simplify the config path query and override. - fix_config_expr_nest_attr(&mut parse_result.module); - // Print AST module. - if result { - let code_str = print_ast_module(&parse_result.module); - std::fs::write(file, code_str)? - } - Ok(OverrideFileResult { - result, - parse_errors: parse_result.errors, - }) -} - -pub struct OverrideFileResult { - pub result: bool, - pub parse_errors: Errors, -} diff --git a/kclvm/query/src/node.rs b/kclvm/query/src/node.rs deleted file mode 100644 index 3439db732..000000000 --- a/kclvm/query/src/node.rs +++ /dev/null @@ -1,765 +0,0 @@ -use kclvm_ast::{ - ast::{self}, - walker::MutSelfMutWalker, -}; - -use kclvm_ast::walk_if_mut; -use kclvm_ast::walk_list_mut; - -/// `AstNodeMover` will move the AST node by offset -pub struct AstNodeMover { - pub line_offset: usize, -} - -impl<'ctx> MutSelfMutWalker<'ctx> for AstNodeMover { - fn walk_expr_stmt(&mut self, expr_stmt: &'ctx mut ast::ExprStmt) { - for expr in expr_stmt.exprs.iter_mut() { - expr.line += self.line_offset as u64; - expr.end_line += self.line_offset as u64; - } - - for expr in expr_stmt.exprs.iter_mut() { - self.walk_expr(&mut expr.node) - } - } - fn walk_type_alias_stmt(&mut self, type_alias_stmt: &'ctx mut ast::TypeAliasStmt) { - type_alias_stmt.type_name.line += self.line_offset as u64; - type_alias_stmt.type_name.end_line += self.line_offset as u64; - - type_alias_stmt.ty.line += self.line_offset as u64; - type_alias_stmt.ty.end_line += self.line_offset as u64; - - self.walk_identifier(&mut type_alias_stmt.type_name.node); - self.walk_type(&mut type_alias_stmt.ty.node); - } - fn walk_unification_stmt(&mut self, unification_stmt: &'ctx mut ast::UnificationStmt) { - unification_stmt.target.line += self.line_offset as u64; - unification_stmt.target.end_line += self.line_offset as u64; - - unification_stmt.value.line += self.line_offset as u64; - unification_stmt.value.end_line += self.line_offset as u64; - - self.walk_identifier(&mut unification_stmt.target.node); - self.walk_schema_expr(&mut unification_stmt.value.node); - } - fn walk_assign_stmt(&mut self, assign_stmt: &'ctx mut ast::AssignStmt) { - for target in assign_stmt.targets.iter_mut() { - target.line += self.line_offset as u64; - target.end_line += self.line_offset as u64; - } - - assign_stmt.value.line += self.line_offset as u64; - assign_stmt.value.end_line += self.line_offset as u64; - - match assign_stmt.ty.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - for target in assign_stmt.targets.iter_mut() { - self.walk_target(&mut target.node) - } - self.walk_expr(&mut assign_stmt.value.node); - walk_if_mut!(self, walk_type, assign_stmt.ty) - } - fn walk_aug_assign_stmt(&mut self, aug_assign_stmt: &'ctx mut ast::AugAssignStmt) { - aug_assign_stmt.target.line += self.line_offset as u64; - aug_assign_stmt.target.end_line += self.line_offset as u64; - - aug_assign_stmt.value.line += self.line_offset as u64; - aug_assign_stmt.value.end_line += self.line_offset as u64; - - self.walk_target(&mut aug_assign_stmt.target.node); - self.walk_expr(&mut aug_assign_stmt.value.node); - } - fn walk_assert_stmt(&mut self, assert_stmt: &'ctx mut ast::AssertStmt) { - assert_stmt.test.line += self.line_offset as u64; - assert_stmt.test.end_line += self.line_offset as u64; - - match assert_stmt.if_cond.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - match assert_stmt.msg.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - self.walk_expr(&mut assert_stmt.test.node); - walk_if_mut!(self, walk_expr, assert_stmt.if_cond); - walk_if_mut!(self, walk_expr, assert_stmt.msg); - } - fn walk_if_stmt(&mut self, if_stmt: &'ctx mut ast::IfStmt) { - if_stmt.cond.line += self.line_offset as u64; - if_stmt.cond.end_line += self.line_offset as u64; - - for stmt in if_stmt.body.iter_mut() { - stmt.line += self.line_offset as u64; - stmt.end_line += self.line_offset as u64; - } - - for stmt in if_stmt.orelse.iter_mut() { - stmt.line += self.line_offset as u64; - stmt.end_line += self.line_offset as u64; - } - - self.walk_expr(&mut if_stmt.cond.node); - walk_list_mut!(self, walk_stmt, if_stmt.body); - walk_list_mut!(self, walk_stmt, if_stmt.orelse); - } - fn walk_import_stmt(&mut self, _import_stmt: &'ctx mut ast::ImportStmt) { - // Nothing to do - } - fn walk_schema_attr(&mut self, schema_attr: &'ctx mut ast::SchemaAttr) { - schema_attr.name.line += self.line_offset as u64; - schema_attr.name.end_line += self.line_offset as u64; - - match schema_attr.value.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - schema_attr.decorators.iter_mut().for_each(|d| { - d.line += self.line_offset as u64; - d.end_line += self.line_offset as u64; - }); - - schema_attr.ty.line += self.line_offset as u64; - schema_attr.ty.end_line += self.line_offset as u64; - - walk_list_mut!(self, walk_call_expr, schema_attr.decorators); - walk_if_mut!(self, walk_expr, schema_attr.value); - self.walk_type(&mut schema_attr.ty.node); - } - - fn walk_type(&mut self, ty: &'ctx mut ast::Type) { - match ty { - ast::Type::Named(id) => self.walk_identifier(id), - ast::Type::List(list_ty) => { - if let Some(ty) = &mut list_ty.inner_type { - ty.line += self.line_offset as u64; - ty.end_line += self.line_offset as u64; - self.walk_type(&mut ty.node) - } - } - ast::Type::Dict(dict_ty) => { - if let Some(ty) = &mut dict_ty.key_type { - ty.line += self.line_offset as u64; - ty.end_line += self.line_offset as u64; - self.walk_type(&mut ty.node) - } - if let Some(ty) = &mut dict_ty.value_type { - ty.line += self.line_offset as u64; - ty.end_line += self.line_offset as u64; - self.walk_type(&mut ty.node) - } - } - ast::Type::Union(union_ty) => { - union_ty.type_elements.iter_mut().for_each(|ty| { - ty.line += self.line_offset as u64; - ty.end_line += self.line_offset as u64; - self.walk_type(&mut ty.node) - }); - } - _ => {} - } - } - fn walk_schema_stmt(&mut self, schema_stmt: &'ctx mut ast::SchemaStmt) { - schema_stmt.name.line += self.line_offset as u64; - schema_stmt.name.end_line += self.line_offset as u64; - - match schema_stmt.parent_name.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - match schema_stmt.for_host_name.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - for arg in schema_stmt.args.iter_mut() { - arg.line += self.line_offset as u64; - arg.end_line += self.line_offset as u64; - } - - if let Some(schema_index_signature) = schema_stmt.index_signature.as_deref_mut() { - let value = &mut schema_index_signature.node.value; - match value.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - } - - schema_stmt.mixins.iter_mut().for_each(|m| { - m.line += self.line_offset as u64; - m.end_line += self.line_offset as u64; - }); - - schema_stmt.decorators.iter_mut().for_each(|d| { - d.line += self.line_offset as u64; - d.end_line += self.line_offset as u64; - }); - - schema_stmt.checks.iter_mut().for_each(|c| { - c.line += self.line_offset as u64; - c.end_line += self.line_offset as u64; - }); - - schema_stmt.body.iter_mut().for_each(|s| { - s.line += self.line_offset as u64; - s.end_line += self.line_offset as u64; - }); - - walk_if_mut!(self, walk_identifier, schema_stmt.parent_name); - walk_if_mut!(self, walk_identifier, schema_stmt.for_host_name); - walk_if_mut!(self, walk_arguments, schema_stmt.args); - if let Some(schema_index_signature) = schema_stmt.index_signature.as_deref_mut() { - let value = &mut schema_index_signature.node.value; - walk_if_mut!(self, walk_expr, value); - } - walk_list_mut!(self, walk_identifier, schema_stmt.mixins); - walk_list_mut!(self, walk_call_expr, schema_stmt.decorators); - walk_list_mut!(self, walk_check_expr, schema_stmt.checks); - walk_list_mut!(self, walk_stmt, schema_stmt.body); - } - fn walk_rule_stmt(&mut self, rule_stmt: &'ctx mut ast::RuleStmt) { - rule_stmt.name.line += self.line_offset as u64; - rule_stmt.name.end_line += self.line_offset as u64; - - rule_stmt.parent_rules.iter_mut().for_each(|p| { - p.line += self.line_offset as u64; - p.end_line += self.line_offset as u64; - }); - - rule_stmt.decorators.iter_mut().for_each(|d| { - d.line += self.line_offset as u64; - d.end_line += self.line_offset as u64; - }); - - rule_stmt.checks.iter_mut().for_each(|c| { - c.line += self.line_offset as u64; - c.end_line += self.line_offset as u64; - }); - - rule_stmt.args.iter_mut().for_each(|a| { - a.line += self.line_offset as u64; - a.end_line += self.line_offset as u64; - }); - - match rule_stmt.for_host_name.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - walk_list_mut!(self, walk_identifier, rule_stmt.parent_rules); - walk_list_mut!(self, walk_call_expr, rule_stmt.decorators); - walk_list_mut!(self, walk_check_expr, rule_stmt.checks); - walk_if_mut!(self, walk_arguments, rule_stmt.args); - walk_if_mut!(self, walk_identifier, rule_stmt.for_host_name); - } - fn walk_quant_expr(&mut self, quant_expr: &'ctx mut ast::QuantExpr) { - quant_expr.target.line += self.line_offset as u64; - quant_expr.target.end_line += self.line_offset as u64; - - quant_expr.variables.iter_mut().for_each(|v| { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - }); - - quant_expr.test.line += self.line_offset as u64; - quant_expr.test.end_line += self.line_offset as u64; - - match quant_expr.if_cond.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - self.walk_expr(&mut quant_expr.target.node); - walk_list_mut!(self, walk_identifier, quant_expr.variables); - self.walk_expr(&mut quant_expr.test.node); - walk_if_mut!(self, walk_expr, quant_expr.if_cond); - } - fn walk_if_expr(&mut self, if_expr: &'ctx mut ast::IfExpr) { - if_expr.cond.line += self.line_offset as u64; - if_expr.cond.end_line += self.line_offset as u64; - - if_expr.body.line += self.line_offset as u64; - if_expr.body.end_line += self.line_offset as u64; - - if_expr.orelse.line += self.line_offset as u64; - if_expr.orelse.end_line += self.line_offset as u64; - - self.walk_expr(&mut if_expr.cond.node); - self.walk_expr(&mut if_expr.body.node); - self.walk_expr(&mut if_expr.orelse.node); - } - fn walk_unary_expr(&mut self, unary_expr: &'ctx mut ast::UnaryExpr) { - unary_expr.operand.line += self.line_offset as u64; - unary_expr.operand.end_line += self.line_offset as u64; - - self.walk_expr(&mut unary_expr.operand.node); - } - fn walk_binary_expr(&mut self, binary_expr: &'ctx mut ast::BinaryExpr) { - binary_expr.left.line += self.line_offset as u64; - binary_expr.left.end_line += self.line_offset as u64; - - self.walk_expr(&mut binary_expr.left.node); - self.walk_expr(&mut binary_expr.right.node); - } - fn walk_selector_expr(&mut self, selector_expr: &'ctx mut ast::SelectorExpr) { - selector_expr.value.line += self.line_offset as u64; - selector_expr.value.end_line += self.line_offset as u64; - - self.walk_expr(&mut selector_expr.value.node); - self.walk_identifier(&mut selector_expr.attr.node); - } - fn walk_call_expr(&mut self, call_expr: &'ctx mut ast::CallExpr) { - call_expr.func.line += self.line_offset as u64; - call_expr.func.end_line += self.line_offset as u64; - - call_expr.args.iter_mut().for_each(|a| { - a.line += self.line_offset as u64; - a.end_line += self.line_offset as u64; - }); - - call_expr.keywords.iter_mut().for_each(|k| { - k.line += self.line_offset as u64; - k.end_line += self.line_offset as u64; - }); - - self.walk_expr(&mut call_expr.func.node); - walk_list_mut!(self, walk_expr, call_expr.args); - walk_list_mut!(self, walk_keyword, call_expr.keywords); - } - fn walk_subscript(&mut self, subscript: &'ctx mut ast::Subscript) { - subscript.value.line += self.line_offset as u64; - subscript.value.end_line += self.line_offset as u64; - - match subscript.index.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - match subscript.lower.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - match subscript.upper.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - match subscript.step.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - self.walk_expr(&mut subscript.value.node); - walk_if_mut!(self, walk_expr, subscript.index); - walk_if_mut!(self, walk_expr, subscript.lower); - walk_if_mut!(self, walk_expr, subscript.upper); - walk_if_mut!(self, walk_expr, subscript.step); - } - fn walk_paren_expr(&mut self, paren_expr: &'ctx mut ast::ParenExpr) { - paren_expr.expr.line += self.line_offset as u64; - paren_expr.expr.end_line += self.line_offset as u64; - - self.walk_expr(&mut paren_expr.expr.node); - } - fn walk_list_expr(&mut self, list_expr: &'ctx mut ast::ListExpr) { - list_expr.elts.iter_mut().for_each(|e| { - e.line += self.line_offset as u64; - e.end_line += self.line_offset as u64; - }); - walk_list_mut!(self, walk_expr, list_expr.elts); - } - fn walk_list_comp(&mut self, list_comp: &'ctx mut ast::ListComp) { - list_comp.elt.line += self.line_offset as u64; - list_comp.elt.end_line += self.line_offset as u64; - - list_comp.generators.iter_mut().for_each(|g| { - g.line += self.line_offset as u64; - g.end_line += self.line_offset as u64; - }); - - self.walk_expr(&mut list_comp.elt.node); - walk_list_mut!(self, walk_comp_clause, list_comp.generators); - } - fn walk_list_if_item_expr(&mut self, list_if_item_expr: &'ctx mut ast::ListIfItemExpr) { - list_if_item_expr.if_cond.line += self.line_offset as u64; - list_if_item_expr.if_cond.end_line += self.line_offset as u64; - - list_if_item_expr.exprs.iter_mut().for_each(|e| { - e.line += self.line_offset as u64; - e.end_line += self.line_offset as u64; - }); - - match list_if_item_expr.orelse.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - self.walk_expr(&mut list_if_item_expr.if_cond.node); - walk_list_mut!(self, walk_expr, list_if_item_expr.exprs); - walk_if_mut!(self, walk_expr, list_if_item_expr.orelse); - } - fn walk_starred_expr(&mut self, starred_expr: &'ctx mut ast::StarredExpr) { - starred_expr.value.line += self.line_offset as u64; - starred_expr.value.end_line += self.line_offset as u64; - self.walk_expr(&mut starred_expr.value.node); - } - fn walk_dict_comp(&mut self, dict_comp: &'ctx mut ast::DictComp) { - if let Some(key) = &mut dict_comp.entry.key { - key.line += self.line_offset as u64; - key.end_line += self.line_offset as u64; - } - - dict_comp.entry.value.line += self.line_offset as u64; - dict_comp.entry.value.end_line += self.line_offset as u64; - - dict_comp.generators.iter_mut().for_each(|g| { - g.line += self.line_offset as u64; - g.end_line += self.line_offset as u64; - }); - - if let Some(key) = &mut dict_comp.entry.key { - self.walk_expr(&mut key.node); - } - self.walk_expr(&mut dict_comp.entry.value.node); - walk_list_mut!(self, walk_comp_clause, dict_comp.generators); - } - fn walk_config_if_entry_expr( - &mut self, - config_if_entry_expr: &'ctx mut ast::ConfigIfEntryExpr, - ) { - config_if_entry_expr.if_cond.line += self.line_offset as u64; - config_if_entry_expr.if_cond.end_line += self.line_offset as u64; - - for config_entry in config_if_entry_expr.items.iter_mut() { - match config_entry.node.key.as_deref_mut() { - Some(k) => { - k.line += self.line_offset as u64; - k.end_line += self.line_offset as u64; - } - None => (), - } - - config_entry.node.value.line += self.line_offset as u64; - } - - match config_if_entry_expr.orelse.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - self.walk_expr(&mut config_if_entry_expr.if_cond.node); - for config_entry in config_if_entry_expr.items.iter_mut() { - walk_if_mut!(self, walk_expr, config_entry.node.key); - self.walk_expr(&mut config_entry.node.value.node); - } - walk_if_mut!(self, walk_expr, config_if_entry_expr.orelse); - } - fn walk_comp_clause(&mut self, comp_clause: &'ctx mut ast::CompClause) { - comp_clause.iter.line += self.line_offset as u64; - comp_clause.iter.end_line += self.line_offset as u64; - - comp_clause.targets.iter_mut().for_each(|t| { - t.line += self.line_offset as u64; - t.end_line += self.line_offset as u64; - }); - - comp_clause.ifs.iter_mut().for_each(|i| { - i.line += self.line_offset as u64; - i.end_line += self.line_offset as u64; - }); - - walk_list_mut!(self, walk_identifier, comp_clause.targets); - self.walk_expr(&mut comp_clause.iter.node); - walk_list_mut!(self, walk_expr, comp_clause.ifs); - } - fn walk_schema_expr(&mut self, schema_expr: &'ctx mut ast::SchemaExpr) { - schema_expr.name.line += self.line_offset as u64; - schema_expr.name.end_line += self.line_offset as u64; - - schema_expr.args.iter_mut().for_each(|a| { - a.line += self.line_offset as u64; - a.end_line += self.line_offset as u64; - }); - - schema_expr.kwargs.iter_mut().for_each(|k| { - k.line += self.line_offset as u64; - k.end_line += self.line_offset as u64; - }); - - schema_expr.config.line += self.line_offset as u64; - schema_expr.config.end_line += self.line_offset as u64; - - self.walk_identifier(&mut schema_expr.name.node); - walk_list_mut!(self, walk_expr, schema_expr.args); - walk_list_mut!(self, walk_keyword, schema_expr.kwargs); - self.walk_expr(&mut schema_expr.config.node); - } - fn walk_config_expr(&mut self, config_expr: &'ctx mut ast::ConfigExpr) { - for config_entry in config_expr.items.iter_mut() { - match config_entry.node.key.as_deref_mut() { - Some(k) => { - k.line += self.line_offset as u64; - k.end_line += self.line_offset as u64; - } - None => (), - } - - config_entry.node.value.line += self.line_offset as u64; - } - - for config_entry in config_expr.items.iter_mut() { - walk_if_mut!(self, walk_expr, config_entry.node.key); - self.walk_expr(&mut config_entry.node.value.node); - } - } - fn walk_check_expr(&mut self, check_expr: &'ctx mut ast::CheckExpr) { - check_expr.test.line += self.line_offset as u64; - check_expr.test.end_line += self.line_offset as u64; - - match check_expr.if_cond.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - match check_expr.msg.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - self.walk_expr(&mut check_expr.test.node); - walk_if_mut!(self, walk_expr, check_expr.if_cond); - walk_if_mut!(self, walk_expr, check_expr.msg); - } - fn walk_lambda_expr(&mut self, lambda_expr: &'ctx mut ast::LambdaExpr) { - match lambda_expr.args.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - for stmt in lambda_expr.body.iter_mut() { - stmt.line += self.line_offset as u64; - stmt.end_line += self.line_offset as u64; - } - - match lambda_expr.return_ty.as_deref_mut() { - Some(v) => { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - None => (), - } - - walk_if_mut!(self, walk_arguments, lambda_expr.args); - walk_list_mut!(self, walk_stmt, lambda_expr.body); - walk_if_mut!(self, walk_type, lambda_expr.return_ty); - } - fn walk_keyword(&mut self, keyword: &'ctx mut ast::Keyword) { - keyword.arg.line += self.line_offset as u64; - keyword.arg.end_line += self.line_offset as u64; - - if let Some(v) = keyword.value.as_deref_mut() { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - } - - self.walk_identifier(&mut keyword.arg.node); - if let Some(v) = keyword.value.as_deref_mut() { - self.walk_expr(&mut v.node) - } - } - fn walk_arguments(&mut self, arguments: &'ctx mut ast::Arguments) { - arguments.args.iter_mut().for_each(|a| { - a.line += self.line_offset as u64; - a.end_line += self.line_offset as u64; - }); - - for default in arguments.defaults.iter_mut() { - if let Some(d) = default.as_deref_mut() { - d.line += self.line_offset as u64; - d.end_line += self.line_offset as u64; - } - } - for ty in arguments.ty_list.iter_mut() { - if let Some(ty) = ty.as_deref_mut() { - ty.line += self.line_offset as u64; - ty.end_line += self.line_offset as u64; - } - } - - walk_list_mut!(self, walk_identifier, arguments.args); - for default in arguments.defaults.iter_mut() { - if let Some(d) = default.as_deref_mut() { - self.walk_expr(&mut d.node) - } - } - for ty in arguments.ty_list.iter_mut() { - if let Some(ty) = ty.as_deref_mut() { - self.walk_type(&mut ty.node); - } - } - } - fn walk_compare(&mut self, compare: &'ctx mut ast::Compare) { - compare.left.line += self.line_offset as u64; - compare.left.end_line += self.line_offset as u64; - - for comparator in compare.comparators.iter_mut() { - comparator.line += self.line_offset as u64; - comparator.end_line += self.line_offset as u64; - } - - self.walk_expr(&mut compare.left.node); - walk_list_mut!(self, walk_expr, compare.comparators); - } - fn walk_joined_string(&mut self, joined_string: &'ctx mut ast::JoinedString) { - joined_string.values.iter_mut().for_each(|v| { - v.line += self.line_offset as u64; - v.end_line += self.line_offset as u64; - }); - - walk_list_mut!(self, walk_expr, joined_string.values); - } - fn walk_formatted_value(&mut self, formatted_value: &'ctx mut ast::FormattedValue) { - formatted_value.value.line += self.line_offset as u64; - formatted_value.value.end_line += self.line_offset as u64; - - self.walk_expr(&mut formatted_value.value.node); - } - fn walk_module(&mut self, module: &'ctx mut ast::Module) { - module.comments.iter_mut().for_each(|c| { - c.line += self.line_offset as u64; - c.end_line += self.line_offset as u64; - }); - - for stmt in module.body.iter_mut() { - if let ast::Stmt::Import(_) = stmt.node { - continue; - } - - stmt.line += self.line_offset as u64; - stmt.end_line += self.line_offset as u64; - - self.walk_stmt(&mut stmt.node) - } - } - fn walk_stmt(&mut self, stmt: &'ctx mut ast::Stmt) { - match stmt { - ast::Stmt::TypeAlias(type_alias) => self.walk_type_alias_stmt(type_alias), - ast::Stmt::Expr(expr_stmt) => self.walk_expr_stmt(expr_stmt), - ast::Stmt::Unification(unification_stmt) => { - self.walk_unification_stmt(unification_stmt) - } - ast::Stmt::Assign(assign_stmt) => self.walk_assign_stmt(assign_stmt), - ast::Stmt::AugAssign(aug_assign_stmt) => self.walk_aug_assign_stmt(aug_assign_stmt), - ast::Stmt::Assert(assert_stmt) => self.walk_assert_stmt(assert_stmt), - ast::Stmt::If(if_stmt) => self.walk_if_stmt(if_stmt), - ast::Stmt::Import(import_stmt) => self.walk_import_stmt(import_stmt), - ast::Stmt::SchemaAttr(schema_attr) => self.walk_schema_attr(schema_attr), - ast::Stmt::Schema(schema_stmt) => self.walk_schema_stmt(schema_stmt), - ast::Stmt::Rule(rule_stmt) => self.walk_rule_stmt(rule_stmt), - } - } - fn walk_expr(&mut self, expr: &'ctx mut ast::Expr) { - match expr { - ast::Expr::Target(target) => self.walk_target(target), - ast::Expr::Identifier(identifier) => self.walk_identifier(identifier), - ast::Expr::Unary(unary_expr) => self.walk_unary_expr(unary_expr), - ast::Expr::Binary(binary_expr) => self.walk_binary_expr(binary_expr), - ast::Expr::If(if_expr) => self.walk_if_expr(if_expr), - ast::Expr::Selector(selector_expr) => self.walk_selector_expr(selector_expr), - ast::Expr::Call(call_expr) => self.walk_call_expr(call_expr), - ast::Expr::Paren(paren_expr) => self.walk_paren_expr(paren_expr), - ast::Expr::Quant(quant_expr) => self.walk_quant_expr(quant_expr), - ast::Expr::List(list_expr) => self.walk_list_expr(list_expr), - ast::Expr::ListIfItem(list_if_item_expr) => { - self.walk_list_if_item_expr(list_if_item_expr) - } - ast::Expr::ListComp(list_comp) => self.walk_list_comp(list_comp), - ast::Expr::Starred(starred_expr) => self.walk_starred_expr(starred_expr), - ast::Expr::DictComp(dict_comp) => self.walk_dict_comp(dict_comp), - ast::Expr::ConfigIfEntry(config_if_entry_expr) => { - self.walk_config_if_entry_expr(config_if_entry_expr) - } - ast::Expr::CompClause(comp_clause) => self.walk_comp_clause(comp_clause), - ast::Expr::Schema(schema_expr) => self.walk_schema_expr(schema_expr), - ast::Expr::Config(config_expr) => self.walk_config_expr(config_expr), - ast::Expr::Check(check) => self.walk_check_expr(check), - ast::Expr::Lambda(lambda) => self.walk_lambda_expr(lambda), - ast::Expr::Subscript(subscript) => self.walk_subscript(subscript), - ast::Expr::Keyword(keyword) => self.walk_keyword(keyword), - ast::Expr::Arguments(arguments) => self.walk_arguments(arguments), - ast::Expr::Compare(compare) => self.walk_compare(compare), - ast::Expr::NumberLit(number_lit) => self.walk_number_lit(number_lit), - ast::Expr::StringLit(string_lit) => self.walk_string_lit(string_lit), - ast::Expr::NameConstantLit(name_constant_lit) => { - self.walk_name_constant_lit(name_constant_lit) - } - ast::Expr::JoinedString(joined_string) => self.walk_joined_string(joined_string), - ast::Expr::FormattedValue(formatted_value) => { - self.walk_formatted_value(formatted_value) - } - ast::Expr::Missing(missing_expr) => self.walk_missing_expr(missing_expr), - } - } -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-10.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-10.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-10.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-11.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-11.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-11.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-12.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-12.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-12.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-13.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-13.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-13.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-14.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-14.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-14.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-15.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-15.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-15.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-2.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-2.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-2.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-3.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-3.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-3.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-4.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-4.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-4.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-5.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-5.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-5.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-6.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-6.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-6.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-7.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-7.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-7.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-8.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-8.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-8.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-9.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-9.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables-9.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables.snap deleted file mode 100644 index 05312712c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_all_variables.snap +++ /dev/null @@ -1,734 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "_list0": [ - { - "name": "_list0", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_list1": [ - { - "name": "_list1", - "type_name": "", - "op_sym": "=", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "_part1": [ - { - "name": "_part1", - "type_name": "", - "op_sym": "=", - "value": "{\n a = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "_part2": [ - { - "name": "_part2", - "type_name": "", - "op_sym": "=", - "value": "{\n c = \"d\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": "=", - "value": "\"d\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ], - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ], - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ], - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ], - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ], - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ], - "c": [ - { - "name": "c", - "type_name": "C", - "op_sym": "=", - "value": "C {\n a: {name: \"Hello\"}\n a: {ids: [7, 8, 9]}\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - }, - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ], - "job": [ - { - "name": "job", - "type_name": "Job", - "op_sym": "=", - "value": "Job {\n name = \"{}-{}\".format(\"app\", \"test\").lower()\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ], - "select": [ - { - "name": "select", - "type_name": "a.b.c", - "op_sym": "=", - "value": "a.b.c {\n a: 1\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ], - "uconfa": [ - { - "name": "uconfa", - "type_name": "UnificationConf", - "op_sym": ":", - "value": "UnificationConf {\n name = \"b\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ], - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-10.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-10.snap deleted file mode 100644 index 6ff706a78..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-10.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "dict1.b": [ - { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-11.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-11.snap deleted file mode 100644 index 048543d0d..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-11.snap +++ /dev/null @@ -1,62 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "dict2": [ - { - "name": "dict2", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": {\n \"c\": 2\n \"d\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-12.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-12.snap deleted file mode 100644 index 463f534c6..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-12.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "dict2.a": [ - { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-13.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-13.snap deleted file mode 100644 index c805efc89..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-13.snap +++ /dev/null @@ -1,39 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "dict2.b": [ - { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n \"d\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-14.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-14.snap deleted file mode 100644 index 4e097554a..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-14.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "dict2.b.c": [ - { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-15.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-15.snap deleted file mode 100644 index 8e9e5cc3f..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-15.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "dict2.b.d": [ - { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-16.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-16.snap deleted file mode 100644 index 3619bf40f..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-16.snap +++ /dev/null @@ -1,111 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "sha": [ - { - "name": "sha", - "type_name": "A", - "op_sym": "=", - "value": "A {\n name: \"Hello\"\n ids: [1, 2, 3]\n data: {\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-17.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-17.snap deleted file mode 100644 index cdd2fea38..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-17.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "sha.name": [ - { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-18.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-18.snap deleted file mode 100644 index e52d3b673..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-18.snap +++ /dev/null @@ -1,41 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "sha.ids": [ - { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-19.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-19.snap deleted file mode 100644 index 80f490cc6..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-19.snap +++ /dev/null @@ -1,52 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "sha.data": [ - { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"a\": {\n \"b\": {\n \"c\": 2\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-2.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-2.snap deleted file mode 100644 index fd89b8a39..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-2.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "a1": [ - { - "name": "a1", - "type_name": "", - "op_sym": "=", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-20.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-20.snap deleted file mode 100644 index 738ea1425..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-20.snap +++ /dev/null @@ -1,40 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "sha.data.a": [ - { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n \"b\": {\n \"c\": 2\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-21.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-21.snap deleted file mode 100644 index 46979358e..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-21.snap +++ /dev/null @@ -1,28 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "sha.data.a.b": [ - { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "{\n \"c\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "c", - "value": { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-22.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-22.snap deleted file mode 100644 index 18d4fa819..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-22.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "sha.data.a.b.c": [ - { - "name": "c", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-23.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-23.snap deleted file mode 100644 index 7be559c7c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-23.snap +++ /dev/null @@ -1,123 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "shb": [ - { - "name": "shb", - "type_name": "B", - "op_sym": "=", - "value": "B {\n a: {\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-24.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-24.snap deleted file mode 100644 index adc4b5bf6..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-24.snap +++ /dev/null @@ -1,111 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "shb.a": [ - { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"HelloB\"\n ids: [4, 5, 6]\n data: {\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - }, - { - "key": "data", - "value": { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - } - ] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-25.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-25.snap deleted file mode 100644 index 07d17738c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-25.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "shb.a.name": [ - { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"HelloB\"", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-26.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-26.snap deleted file mode 100644 index e53fb1fa9..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-26.snap +++ /dev/null @@ -1,41 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "shb.a.ids": [ - { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 4\n 5\n 6\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "4", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "5", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "6", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-27.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-27.snap deleted file mode 100644 index 69664521c..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-27.snap +++ /dev/null @@ -1,52 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "shb.a.data": [ - { - "name": "data", - "type_name": "", - "op_sym": ":", - "value": "{\n \"d\": {\n \"e\": {\n \"f\": 3\n }\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "d", - "value": { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - } - ] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-28.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-28.snap deleted file mode 100644 index 01349d3d6..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-28.snap +++ /dev/null @@ -1,40 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "shb.a.data.d": [ - { - "name": "d", - "type_name": "", - "op_sym": ":", - "value": "{\n \"e\": {\n \"f\": 3\n }\n}", - "list_items": [], - "dict_entries": [ - { - "key": "e", - "value": { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - } - ] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-29.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-29.snap deleted file mode 100644 index cdf811de6..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-29.snap +++ /dev/null @@ -1,28 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "shb.a.data.d.e": [ - { - "name": "e", - "type_name": "", - "op_sym": ":", - "value": "{\n \"f\": 3\n}", - "list_items": [], - "dict_entries": [ - { - "key": "f", - "value": { - "name": "f", - "type_name": "", - "op_sym": ":", - "value": "3", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-3.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-3.snap deleted file mode 100644 index 1ee7ad1bc..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-3.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "a3": [ - { - "name": "a3", - "type_name": "", - "op_sym": "=", - "value": "3m", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-30.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-30.snap deleted file mode 100644 index ef96f3dce..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-30.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "uconfa.name": [ - { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"b\"", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-31.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-31.snap deleted file mode 100644 index 300f02879..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-31.snap +++ /dev/null @@ -1,73 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "c.a": [ - { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n name: \"Hello\"\n}", - "list_items": [], - "dict_entries": [ - { - "key": "name", - "value": { - "name": "name", - "type_name": "", - "op_sym": ":", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - } - ] - }, - { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "{\n ids: [7, 8, 9]\n}", - "list_items": [], - "dict_entries": [ - { - "key": "ids", - "value": { - "name": "ids", - "type_name": "", - "op_sym": ":", - "value": "[\n 7\n 8\n 9\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "7", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "8", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "9", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - } - ] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-32.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-32.snap deleted file mode 100644 index 8ff53eded..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-32.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "job.name": [ - { - "name": "name", - "type_name": "", - "op_sym": "=", - "value": "\"{}-{}\".format(\"app\", \"test\").lower()", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-33.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-33.snap deleted file mode 100644 index d89b02b12..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-33.snap +++ /dev/null @@ -1,33 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "union_list": [ - { - "name": "union_list", - "type_name": "", - "op_sym": "=", - "value": "[\n *_list0\n *_list1\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list0", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "*_list1", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-34.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-34.snap deleted file mode 100644 index f5e8f07ac..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-34.snap +++ /dev/null @@ -1,39 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "a_dict": [ - { - "name": "a_dict", - "type_name": "", - "op_sym": "=", - "value": "{\n **_part1\n **_part2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "", - "value": { - "name": "", - "type_name": "", - "op_sym": ":", - "value": "_part2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-4.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-4.snap deleted file mode 100644 index b8f33a1f4..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-4.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "b1": [ - { - "name": "b1", - "type_name": "", - "op_sym": "=", - "value": "True", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-5.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-5.snap deleted file mode 100644 index 0ad8ec0d3..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-5.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "b2": [ - { - "name": "b2", - "type_name": "", - "op_sym": "=", - "value": "False", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-6.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-6.snap deleted file mode 100644 index 289741857..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-6.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "s1": [ - { - "name": "s1", - "type_name": "", - "op_sym": "=", - "value": "\"Hello\"", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-7.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-7.snap deleted file mode 100644 index 588a63886..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-7.snap +++ /dev/null @@ -1,41 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "array1": [ - { - "name": "array1", - "type_name": "", - "op_sym": "=", - "value": "[\n 1\n 2\n 3\n]", - "list_items": [ - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "1", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "2", - "list_items": [], - "dict_entries": [] - }, - { - "name": "", - "type_name": "", - "op_sym": "", - "value": "3", - "list_items": [], - "dict_entries": [] - } - ], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-8.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-8.snap deleted file mode 100644 index 3c3a55dc0..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-8.snap +++ /dev/null @@ -1,39 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "dict1": [ - { - "name": "dict1", - "type_name": "", - "op_sym": "=", - "value": "{\n \"a\": 1\n \"b\": 2\n}", - "list_items": [], - "dict_entries": [ - { - "key": "a", - "value": { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - }, - { - "key": "b", - "value": { - "name": "b", - "type_name": "", - "op_sym": ":", - "value": "2", - "list_items": [], - "dict_entries": [] - } - } - ] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-9.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-9.snap deleted file mode 100644 index 1a0eecc18..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables-9.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "dict1.a": [ - { - "name": "a", - "type_name": "", - "op_sym": ":", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables.snap b/kclvm/query/src/snapshots/kclvm_query__tests__list_variables.snap deleted file mode 100644 index f8f69e330..000000000 --- a/kclvm/query/src/snapshots/kclvm_query__tests__list_variables.snap +++ /dev/null @@ -1,16 +0,0 @@ ---- -source: query/src/tests.rs -expression: got_json ---- -{ - "a": [ - { - "name": "a", - "type_name": "", - "op_sym": "=", - "value": "1", - "list_items": [], - "dict_entries": [] - } - ] -} diff --git a/kclvm/query/src/tests.rs b/kclvm/query/src/tests.rs deleted file mode 100644 index c1777d16b..000000000 --- a/kclvm/query/src/tests.rs +++ /dev/null @@ -1,1099 +0,0 @@ -use std::{fs, path::PathBuf}; - -use super::{r#override::apply_override_on_module, *}; -use crate::{ - path::parse_attribute_path, r#override::parse_override_spec, selector::list_variables, -}; -use kclvm_error::{DiagnosticId, ErrorKind, Level}; -use kclvm_parser::parse_file_force_errors; -use kclvm_utils::path::PathPrefix; -use pretty_assertions::assert_eq; -use selector::ListOptions; - -const CARGO_FILE_PATH: &str = env!("CARGO_MANIFEST_DIR"); - -fn get_test_dir(sub: String) -> PathBuf { - let mut cargo_file_path = PathBuf::from(CARGO_FILE_PATH); - cargo_file_path.push("src"); - cargo_file_path.push("test_data"); - // Split unix and windows path - for part in sub.split("/") { - for p in part.split("\\") { - cargo_file_path.push(p); - } - } - cargo_file_path -} - -/// Test override_file result. -#[test] -fn test_override_file_simple() { - let specs = vec![ - "config.image=image/image".to_string(), - "config.image=\"image/image:v1\"".to_string(), - "config.data={id=1,value=\"override_value\"}".to_string(), - "dict_config={\"image\": \"image/image:v2\" \"data\":{\"id\":2 \"value2\": \"override_value2\"}}".to_string(), - "envs=[{key=\"key1\" value=\"value1\"} {key=\"key2\" value=\"value2\"}]".to_string(), - "isfilter=False".to_string(), - "count=2".to_string(), - "msg=\"Hi World\"".to_string(), - "delete-".to_string(), - "dict_delete.image-".to_string(), - "dict_delete_whole-".to_string(), - "insert_config.key=1".to_string(), - "uni_config.labels.key1=1".to_string(), - "config_unification=Config {\"image\": \"image/image:v4\"}".to_string(), - "config_unification:Config {\"env\": {\"aaa\": \"aaa\"}}".to_string(), - "config_unification.env: {\"bbb\": \"bbb\"}}".to_string(), - "config_unification_delete-".to_string() - ]; - - let simple_path = get_test_dir("simple.k".to_string()); - let simple_bk_path = get_test_dir("simple.bk.k".to_string()); - let expect_path = get_test_dir("expect.k".to_string()); - fs::copy(simple_bk_path.clone(), simple_path.clone()).unwrap(); - if simple_path.exists() { - fs::remove_file(simple_path.clone()).unwrap(); - } - - fs::copy(simple_bk_path.clone(), simple_path.clone()).unwrap(); - - let import_paths = vec![]; - assert_eq!( - override_file(simple_path.clone().to_str().unwrap(), &specs, &import_paths) - .unwrap() - .result, - true - ); - - let simple_content = fs::read_to_string(simple_path.clone()).unwrap(); - let expect_content = fs::read_to_string(expect_path).unwrap(); - - let simple_content = simple_content.replace("\r\n", "\n"); - let expect_content = expect_content.replace("\r\n", "\n"); - - assert_eq!(simple_content, expect_content); - - fs::copy(simple_bk_path.clone(), simple_path.clone()).unwrap(); -} -/// Test override_file result. -#[test] -fn test_override_file_import_paths() { - let specs = vec!["data.value=\"override_value\"".to_string()]; - let import_paths = vec![ - "pkg".to_string(), - "pkg.pkg".to_string(), - "pkg.pkg as alias_pkg1".to_string(), - "pkg.pkg as alias_pkg2".to_string(), - ]; - - let mut cargo_file_path = PathBuf::from(CARGO_FILE_PATH); - cargo_file_path.push("src/test_data/import_paths.k"); - let abs_path = cargo_file_path.to_str().unwrap(); - - assert_eq!( - override_file(abs_path, &specs, &import_paths) - .unwrap() - .result, - true - ) -} - -/// Test override_file result with the expected modified AST. -#[test] -fn test_override_file_config() { - let specs = vec![ - "appConfiguration.image=\"kcl/kcl:{}\".format(version)".to_string(), - r#"appConfiguration.mainContainer.name="override_name""#.to_string(), - "appConfiguration.labels.key.key=\"override_value\"".to_string(), - "appConfiguration.labels.key.str-key=\"override_value\"".to_string(), - "appConfiguration.labels.key['dot.key']=\"override_value\"".to_string(), - "appConfiguration.overQuota=False".to_string(), - "appConfiguration.probe={periodSeconds=20}".to_string(), - "appConfiguration.resource-".to_string(), - "appConfiguration.svc=s.Service {}".to_string(), - "appConfigurationUnification.image=\"kcl/kcl:v0.1\"".to_string(), - r#"appConfigurationUnification.mainContainer.name="override_name""#.to_string(), - "appConfigurationUnification.labels.key.key=\"override_value\"".to_string(), - "appConfigurationUnification.overQuota=False".to_string(), - "appConfigurationUnification.resource.cpu-".to_string(), - "appConfigurationUnification.svc=s.Service {}".to_string(), - "appConfigurationUnification:{name=\"name\"}".to_string(), - "config.x:{a:1}".to_string(), - "config.x:{b:2}".to_string(), - "config.x:{b:3}".to_string(), - "config.x:{c.d:4}".to_string(), - "config.y=1".to_string(), - "config.z+=[1,2,3]".to_string(), - "config.z+=[4,5,6]".to_string(), - "var1:1".to_string(), - "var2=1".to_string(), - "var3+=[1,2,3]".to_string(), - "var3+=[4,5,6]".to_string(), - "var4:AppConfiguration {image:'image'}".to_string(), - ]; - let import_paths = vec!["service as s".to_string()]; - - let mut cargo_file_path = PathBuf::from(CARGO_FILE_PATH); - cargo_file_path.push("src/test_data/config.k"); - let abs_path = cargo_file_path.to_str().unwrap(); - - let mut module = parse_file_force_errors(abs_path, None).unwrap(); - for s in &specs { - apply_override_on_module(&mut module, s, &import_paths).unwrap(); - } - let expected_code = print_ast_module(&module); - assert_eq!( - expected_code, - r#"import service as s - -schema Main: - name?: str - env?: [{str:}] - -schema Probe: - initialDelaySeconds?: int - timeoutSeconds?: int - periodSeconds?: int = 10 - successThreshold?: int - failureThreshold?: int - -schema AppConfiguration: - appName: str - image: str - overQuota: bool = False - resource: {str:} - mainContainer?: Main - labels: {str:} - probe?: Probe - -appConfiguration = AppConfiguration { - appName: "kclvm" - image: "kcl/kcl:{}".format(version) - labels: { - key: { - key: "override_value" - "str-key" = "override_value" - "dot.key" = "override_value" - } - } - mainContainer: Main {name: "override_name"} - overQuota = False - overQuota = False - probe: { - periodSeconds = 20 - } - svc = s.Service {} -} - -appConfigurationUnification: AppConfiguration { - appName: "kclvm" - image: "kcl/kcl:v0.1" - resource: { - disk: "50Gi" - memory: "12Gi" - } - labels: { - key: {key: "override_value"} - } - mainContainer: Main {name: "override_name"} - overQuota: False - svc = s.Service {} - name = "name" -} -config = { - x: { - a: 1 - b: 3 - c: { - d: 4 - } - } - y = 1 - z += [ - 1 - 2 - 3 - 4 - 5 - 6 - ] -} -var1 = 1 -var2 = 1 -var3 += [ - 1 - 2 - 3 - 4 - 5 - 6 -] -var4: AppConfiguration { - image: 'image' -} -"# - ); -} - -/// Test override spec parser. -#[test] -fn test_parse_override_spec_invalid() { - let specs = vec![":a:", "=a=", ":a", "a-1"]; - for spec in specs { - assert!(parse_override_spec(spec).is_err(), "{spec} test failed"); - } -} - -#[test] -fn test_parse_property_path() { - assert_eq!(parse_attribute_path("a.b.c").unwrap(), vec!["a", "b", "c"]); - assert_eq!( - parse_attribute_path(r#"a["b"].c"#).unwrap(), - vec!["a", "b", "c"] - ); - assert_eq!( - parse_attribute_path(r#"a.["b"].c"#).unwrap(), - vec!["a", "b", "c"] - ); - assert_eq!( - parse_attribute_path(r#"a['b'].c"#).unwrap(), - vec!["a", "b", "c"] - ); - assert_eq!( - parse_attribute_path(r#"a.b['c.d']"#).unwrap(), - vec!["a", "b", "c.d"] - ); - assert_eq!( - parse_attribute_path(r#"a.b.['c.d']"#).unwrap(), - vec!["a", "b", "c.d"] - ); - assert_eq!( - parse_attribute_path(r#"a.b['c.d'].e"#).unwrap(), - vec!["a", "b", "c.d", "e"] - ); - assert_eq!( - parse_attribute_path(r#"a.b.['c.d'].e"#).unwrap(), - vec!["a", "b", "c.d", "e"] - ); - assert_eq!( - parse_attribute_path(r#"a.b.c-d.e"#).unwrap(), - vec!["a", "b", "c-d", "e"] - ); - assert!(parse_attribute_path(r#"a.[b.c-d.e"#).is_err(),); - assert!(parse_attribute_path(r#"a.[b.c]-d.e"#).is_err(),); -} - -#[test] -fn test_list_variables() { - let file = PathBuf::from("./src/test_data/test_list_variables/supported.k") - .canonicalize() - .unwrap() - .display() - .to_string(); - let test_cases = vec![ - ("a", "1", "", "="), - ("a1", "2", "", "="), - ("a3", "3m", "", "="), - ("b1", "True", "", "="), - ("b2", "False", "", "="), - ("s1", "\"Hello\"", "", "="), - ( - "array1", - r#"[ - 1 - 2 - 3 -]"#, - "", - "=", - ), - ( - "dict1", - r#"{ - "a": 1 - "b": 2 -}"#, - "", - "=", - ), - ("dict1.a", "1", "", ":"), - ("dict1.b", "2", "", ":"), - ( - "dict2", - r#"{ - "a": 1 - "b": { - "c": 2 - "d": 3 - } -}"#, - "", - "=", - ), - ("dict2.a", "1", "", ":"), - ( - "dict2.b", - r#"{ - "c": 2 - "d": 3 -}"#, - "", - ":", - ), - ("dict2.b.c", "2", "", ":"), - ("dict2.b.d", "3", "", ":"), - ( - "sha", - r#"A { - name: "Hello" - ids: [1, 2, 3] - data: { - "a": { - "b": { - "c": 2 - } - } - } -}"#, - "A", - "=", - ), - ("sha.name", "\"Hello\"", "", ":"), - ( - "sha.ids", - r#"[ - 1 - 2 - 3 -]"#, - "", - ":", - ), - ( - "sha.data", - r#"{ - "a": { - "b": { - "c": 2 - } - } -}"#, - "", - ":", - ), - ( - "sha.data.a", - r#"{ - "b": { - "c": 2 - } -}"#, - "", - ":", - ), - ( - "sha.data.a.b", - r#"{ - "c": 2 -}"#, - "", - ":", - ), - ("sha.data.a.b.c", "2", "", ":"), - ( - "shb", - r#"B { - a: { - name: "HelloB" - ids: [4, 5, 6] - data: { - "d": { - "e": { - "f": 3 - } - } - } - } -}"#, - "B", - "=", - ), - ( - "shb.a", - r#"{ - name: "HelloB" - ids: [4, 5, 6] - data: { - "d": { - "e": { - "f": 3 - } - } - } -}"#, - "", - ":", - ), - ("shb.a.name", "\"HelloB\"", "", ":"), - ( - "shb.a.ids", - r#"[ - 4 - 5 - 6 -]"#, - "", - ":", - ), - ( - "shb.a.data", - r#"{ - "d": { - "e": { - "f": 3 - } - } -}"#, - "", - ":", - ), - ( - "shb.a.data.d", - r#"{ - "e": { - "f": 3 - } -}"#, - "", - ":", - ), - ( - "shb.a.data.d.e", - r#"{ - "f": 3 -}"#, - "", - ":", - ), - ("uconfa.name", "\"b\"", "", "="), - ( - "c.a", - r#"{ - name: "Hello" -}"#, - "", - ":", - ), - ( - "job.name", - r#""{}-{}".format("app", "test").lower()"#, - "", - "=", - ), - ( - "union_list", - r#"[ - *_list0 - *_list1 -]"#, - "", - "=", - ), - ( - "a_dict", - r#"{ - **_part1 - **_part2 -}"#, - "", - "=", - ), - ]; - - for (spec, expected, expected_name, op_sym) in test_cases { - let specs = vec![spec.to_string()]; - let result = list_variables(vec![file.clone()], specs, None).unwrap(); - assert_eq!( - result.variables.get(spec).unwrap().get(0).unwrap().value, - expected, - "{spec}" - ); - assert_eq!( - result - .variables - .get(spec) - .unwrap() - .get(0) - .unwrap() - .type_name, - expected_name, - "{spec}" - ); - assert_eq!( - result.variables.get(spec).unwrap().get(0).unwrap().op_sym, - op_sym, - "{spec}" - ); - - let got_json = serde_json::to_string_pretty(&result.variables).unwrap(); - insta::assert_snapshot!(got_json); - } -} - -#[test] -fn test_list_all_variables() { - let file = PathBuf::from("./src/test_data/test_list_variables/supported.k") - .canonicalize() - .unwrap() - .display() - .to_string(); - let test_cases = vec![ - ("a", "1", "", "="), - ("a1", "2", "", "="), - ("a3", "3m", "", "="), - ("b1", "True", "", "="), - ("b2", "False", "", "="), - ("s1", "\"Hello\"", "", "="), - ( - "array1", - r#"[ - 1 - 2 - 3 -]"#, - "", - "=", - ), - ( - "dict1", - r#"{ - "a": 1 - "b": 2 -}"#, - "", - "=", - ), - ( - "dict2", - r#"{ - "a": 1 - "b": { - "c": 2 - "d": 3 - } -}"#, - "", - "=", - ), - ( - "sha", - r#"A { - name: "Hello" - ids: [1, 2, 3] - data: { - "a": { - "b": { - "c": 2 - } - } - } -}"#, - "A", - "=", - ), - ( - "shb", - r#"B { - a: { - name: "HelloB" - ids: [4, 5, 6] - data: { - "d": { - "e": { - "f": 3 - } - } - } - } -}"#, - "B", - "=", - ), - ( - "job", - r#"Job { - name = "{}-{}".format("app", "test").lower() -}"#, - "Job", - "=", - ), - ( - "select", - r#"a.b.c { - a: 1 -}"#, - "a.b.c", - "=", - ), - ( - "union_list", - r#"[ - *_list0 - *_list1 -]"#, - "", - "=", - ), - ( - "a_dict", - r#"{ - **_part1 - **_part2 -}"#, - "", - "=", - ), - ]; - - for (spec, expected, expected_name, op_sym) in test_cases { - println!("{:?}", spec); - let result = list_variables(vec![file.clone()], vec![], None).unwrap(); - assert_eq!( - result.variables.get(spec).unwrap().get(0).unwrap().value, - expected, - "{spec}" - ); - assert_eq!( - result - .variables - .get(spec) - .unwrap() - .get(0) - .unwrap() - .type_name, - expected_name, - "{spec}" - ); - assert_eq!( - result.variables.get(spec).unwrap().get(0).unwrap().op_sym, - op_sym, - "{spec}" - ); - assert_eq!(result.parse_errors.len(), 0); - - let got_json = serde_json::to_string_pretty(&result.variables).unwrap(); - insta::assert_snapshot!(got_json); - } -} - -#[test] -fn test_list_unsupported_variables() { - let file = PathBuf::from("./src/test_data/test_list_variables/unsupported.k") - .canonicalize() - .unwrap() - .display() - .to_string(); - - // test unsupport code - let test_cases = vec![ - ("list", "[_x for _x in range(20) if _x % 2 == 0]"), - ("list1", "[i if i > 2 else i + 1 for i in [1, 2, 3]]"), - ("dict", "{str(i): 2 * i for i in range(3)}"), - ( - "func", - r#"lambda x: int, y: int -> int { - x + y -}"#, - ), - ( - "if_schema.falseValue", - "if True:\n trueValue: 1\nelse:\n falseValue: 2", - ), - ( - "if_schema.trueValue", - "if True:\n trueValue: 1\nelse:\n falseValue: 2", - ), - ]; - - for (spec, expected_code) in test_cases { - let specs = vec![spec.to_string()]; - let result = list_variables(vec![file.clone()], specs, None).unwrap(); - assert_eq!(result.variables.get(spec), None); - assert_eq!(result.unsupported[0].code, expected_code); - assert_eq!(result.parse_errors.len(), 0); - } - - // test list variables from unsupported code - let test_cases = vec![ - ("if_schema.name", r#""name""#), - ("if_schema.age", "1"), - ( - "if_schema.inner", - r#"IfSchemaInner { - innerValue: 1 -}"#, - ), - ("if_schema.inner.innerValue", "1"), - ( - "if_schema.inner2", - r#"{ - innerValue: 2 -}"#, - ), - ("if_schema.inner2.innerValue", "2"), - ("if_schema1.name", r#""name""#), - ("if_schema1.age", "1"), - ( - "if_schema1.inner", - r#"IfSchemaInner { - innerValue: 1 -}"#, - ), - ("if_schema1.inner.innerValue", "1"), - ( - "if_schema1.inner2", - r#"{ - innerValue: 2 -}"#, - ), - ("if_schema1.inner2.innerValue", "2"), - ]; - - for (spec, expected_code) in test_cases { - let specs = vec![spec.to_string()]; - let result = list_variables(vec![file.clone()], specs, None).unwrap(); - assert_eq!( - result.variables.get(spec).unwrap().get(0).unwrap().value, - expected_code, - "{spec}", - ); - } -} - -#[test] -fn test_override_file_insert() { - let specs = vec![ - r#"b={ - "c": 2 - }"# - .to_string(), - r#"c.b={"a": "b"}"#.to_string(), - r#"d.e.f.g=3"#.to_string(), - r#"_access3=test.ServiceAccess { - iType = "kkkkkkk" - sType = dsType - TestStr = ["${test_str}"] - ports = [80, 443] - booltest = True -}"# - .to_string(), - r#"_access4=test.ServiceAccess { - iType = "kkkkkkk" - sType = dsType - TestStr = ["${test_str}"] - ports = [80, 443] - booltest = True -}"# - .to_string(), - r#"_access.iType="kkkkkkk""#.to_string(), - r#"_access5.iType="dddddd""#.to_string(), - r#"a=b"#.to_string(), - r#"_access6 ="a6""#.to_string(), - r#"_access.mergedattr=1"#.to_string(), - r#"_access.a.b.c=2"#.to_string(), - r#"_access.a.c.b=3"#.to_string(), - ]; - - let simple_path = get_test_dir("test_override_file/main.k".to_string()); - let simple_bk_path = get_test_dir("test_override_file/main.bk.k".to_string()); - let expect_path = get_test_dir("test_override_file/expect.k".to_string()); - fs::copy(simple_bk_path.clone(), simple_path.clone()).unwrap(); - let import_paths = vec![ - "base.pkg.kusion_models.app".to_string(), - "base.pkg.kusion_models.app.vip as vip".to_string(), - "base.pkg.kusion_models.app.container".to_string(), - "base.pkg.kusion_models.app.resource as res".to_string(), - "base.pkg.kusion_models.app.sidecar".to_string(), - ".values".to_string(), - ]; - - // test insert multiple times - for _ in 1..=5 { - assert_eq!( - override_file(&simple_path.display().to_string(), &specs, &import_paths) - .unwrap() - .result, - true - ); - - let simple_content = fs::read_to_string(simple_path.clone()).unwrap(); - let expect_content = fs::read_to_string(expect_path.clone()).unwrap(); - - let simple_content = simple_content.replace("\r\n", "\n"); - let expect_content = expect_content.replace("\r\n", "\n"); - - assert_eq!(simple_content, expect_content); - } - - fs::copy(simple_bk_path.clone(), simple_path.clone()).unwrap(); -} - -#[test] -fn test_list_variable_with_invalid_kcl() { - let file = PathBuf::from("./src/test_data/test_list_variables/invalid.k") - .canonicalize() - .unwrap() - .display() - .to_string(); - let specs = vec!["a".to_string()]; - let result = list_variables(vec![file.clone()], specs, None).unwrap(); - assert_eq!(result.variables.get("a"), None); - assert_eq!(result.parse_errors.len(), 2); - assert_eq!(result.parse_errors[0].level, Level::Error); - assert_eq!( - result.parse_errors[0].code, - Some(DiagnosticId::Error(ErrorKind::InvalidSyntax)) - ); - assert_eq!( - result.parse_errors[0].messages[0].message, - "expected one of [\"=\"] got eof", - ); - assert_eq!( - result.parse_errors[0].messages[0].range.0.filename, - file.adjust_canonicalization() - ); - assert_eq!(result.parse_errors[0].messages[0].range.0.line, 1); - assert_eq!(result.parse_errors[0].messages[0].range.0.column, Some(8)); -} - -#[test] -fn test_overridefile_with_invalid_kcl() { - let simple_path = get_test_dir("test_override_file/invalid.k".to_string()); - let simple_bk_path = get_test_dir("invalid.bk.k".to_string()); - fs::copy(simple_bk_path.clone(), simple_path.clone()).unwrap(); - - let result = override_file( - &simple_path.display().to_string(), - &vec!["a=b".to_string()], - &vec![], - ) - .unwrap(); - - fs::copy(simple_bk_path.clone(), simple_path.clone()).unwrap(); - assert_eq!(result.result, true); - assert_eq!(result.parse_errors.len(), 2); - assert_eq!(result.parse_errors[0].level, Level::Error); - assert_eq!( - result.parse_errors[0].code, - Some(DiagnosticId::Error(ErrorKind::InvalidSyntax)) - ); - assert_eq!( - result.parse_errors[0].messages[0].message, - "expected one of [\"=\"] got eof" - ); - assert_eq!( - result.parse_errors[0].messages[0] - .range - .0 - .filename - .adjust_canonicalization(), - simple_path.display().to_string().adjust_canonicalization() - ); - assert_eq!(result.parse_errors[0].messages[0].range.0.line, 1); - assert_eq!(result.parse_errors[0].messages[0].range.0.column, Some(8)); -} - -#[test] -fn test_list_variables_with_file_noexist() { - let file = PathBuf::from("./src/test_data/test_list_variables/noexist.k") - .display() - .to_string(); - let specs = vec!["a".to_string()]; - let result = list_variables(vec![file.clone()], specs, None); - assert!(result.is_err()); - let err = result.err().unwrap(); - assert_eq!(err.to_string(), "Cannot find the kcl file, please check the file path ./src/test_data/test_list_variables/noexist.k"); -} - -#[test] -fn test_override_file_with_invalid_spec() { - let specs = vec!["....".to_string()]; - let import_paths = vec![]; - let file = PathBuf::from("./src/test_data/test_override_file/main.k") - .canonicalize() - .unwrap() - .display() - .to_string(); - let result = override_file(&file, &specs, &import_paths); - assert!(result.is_err()); - let err = result.err().unwrap(); - assert_eq!(err.to_string(), "Invalid spec format '....', expected =, :, += or -"); -} - -#[test] -fn test_list_merged_variables() { - let file = PathBuf::from("./src/test_data/test_list_variables/test_list_merged_variables") - .canonicalize() - .unwrap(); - - file.join("path").display().to_string(); - - let test_cases = vec![ - ( - vec![ - file.join("merge_1/base.k").display().to_string(), - file.join("merge_1/main.k").display().to_string(), - ], - vec!["appConfiguration.resource".to_string()], - vec![r#"res.Resource {cpu = "2", disk = "35Gi", memory = "4Gi"}"#.to_string()], - ), - ( - vec![ - file.join("merge_2/base.k").display().to_string(), - file.join("merge_2/main.k").display().to_string(), - ], - vec!["appConfiguration.resource".to_string()], - vec![r#"res.Resource { - cpu = "2" - memory = "4Gi" -}"#.to_string()], - ), - ( - vec![ - file.join("merge_3/base.k").display().to_string(), - file.join("merge_3/main.k").display().to_string(), - ], - vec!["appConfiguration.resource".to_string()], - vec![r#"res.Resource {cpu = "2", disk = "35Gi", memory = "4Gi"}"#.to_string()], - ), - ( - vec![ - file.join("merge_4/base.k").display().to_string(), - file.join("merge_4/main.k").display().to_string(), - ], - vec!["appConfiguration.resource".to_string()], - vec![r#"res.Resource { - cpu = "2" - memory = "4Gi" -}"#.to_string()], - ), - ( - vec![ - file.join("merge_5/base.k").display().to_string(), - file.join("merge_5/main.k").display().to_string(), - ], - vec!["appConfiguration.resource".to_string()], - vec![r#"res.Resource {cpu = {limit: "200m", limit_plus: "20000m", request: "100m"}, disk = "35Gi", memory = "4Gi"}"#.to_string()], - ), - ( - vec![ - file.join("merge_6/main.k").display().to_string(), - file.join("merge_6/base.k").display().to_string(), - ], - vec!["config".to_string()], - vec![r#"Config { - name = "config2" - args: ["kcl", "main.k"] - labels: {key1: "value1"} -}"#.to_string()], - ), - ( - vec![ - file.join("merge_7/main.k").display().to_string(), - file.join("merge_7/base.k").display().to_string(), - ], - vec!["config".to_string()], - vec![r#"Config { - name = _NAME - args: ["kcl", "main.k"] - labels: {key1: "value1"} -}"#.to_string()], - ), - ( - vec![ - file.join("merge_8/main.k").display().to_string(), - ], - vec!["config".to_string()], - vec![r#"Config { - args: [ - "kcl" - "main.k" - ] - labels: { - key1: "value1" - } - labels: { - key2: "value2" - } - "labels": { - "key3": "value3" - } -}"#.to_string()], - ), - ( - vec![ - file.join("merge_9/main.k").display().to_string(), - ], - vec!["config".to_string()], - vec![r#"Config { - args: [ - "kcl" - "main.k" - ] - labels: { - key1: "value1" - } - labels: { - key2: "value2" - } - name: { - name: { - name: "name" - } - } - name: { - name: Name0 {data: 1} - } -}"#.to_string()], - ), - ( - vec![ - file.join("merge_10/main.k").display().to_string(), - ], - vec!["alice.hc".to_string()], - vec![r#"[ - 2 -]"#.to_string()], - ), - ( - vec![ - file.join("merge_11/main.k").display().to_string(), - ], - vec!["config.main".to_string()], - vec![r#"Main {args: ["1"], env: ["789", "456"]}"#.to_string()], - ), - ]; - - for (files, specs, expected_values) in test_cases { - println!("{:?}", files); - let result = list_variables( - files, - specs.clone(), - Some(&ListOptions { - merge_program: true, - }), - ) - .unwrap(); - for (i, expected_value) in expected_values.iter().enumerate() { - let variables = result - .variables - .get(&specs.get(i).unwrap().to_string()) - .unwrap(); - assert_eq!(variables.len(), 1); - for variable in variables { - assert_eq!(variable.value.to_string(), expected_value.to_string()); - } - } - } -} diff --git a/kclvm/query/src/util.rs b/kclvm/query/src/util.rs deleted file mode 100644 index 7b4b500f8..000000000 --- a/kclvm/query/src/util.rs +++ /dev/null @@ -1,38 +0,0 @@ -use anyhow::{anyhow, Result}; - -/// Get field package path and identifier name from the path. -/// (TODO: Needs to be a package related to the language specification -/// and move this function into it.) -/// -/// split_field_path("pkg.to.path:field") -> ("pkg.to.path", "field") -pub(crate) fn split_field_path(path: &str) -> Result<(String, String)> { - let err = Err(anyhow!("Invalid field path {:?}", path)); - let paths = path.splitn(2, ':').collect::>(); - let (pkgpath, field_path) = if paths.len() == 1 { - ("".to_string(), paths[0].to_string()) - } else if paths.len() == 2 { - (paths[0].to_string(), paths[1].to_string()) - } else { - return err; - }; - if field_path.is_empty() { - err - } else { - Ok((pkgpath, field_path)) - } -} - -/// Get the invalid spec error message. -#[inline] -pub(crate) fn invalid_spec_error(spec: &str) -> anyhow::Error { - anyhow!("Invalid spec format '{}', expected =, :, += or -", spec) -} - -/// Get the invalid symbol selector spec error message. -#[inline] -pub(crate) fn invalid_symbol_selector_spec_error(spec: &str) -> anyhow::Error { - anyhow!( - "Invalid spec format '{}', expected :", - spec - ) -} diff --git a/kclvm/runner/Cargo.toml b/kclvm/runner/Cargo.toml deleted file mode 100644 index 349f21661..000000000 --- a/kclvm/runner/Cargo.toml +++ /dev/null @@ -1,51 +0,0 @@ -[package] -name = "kclvm-runner" -version = "0.11.2" -edition = "2021" - -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - -[build-dependencies] -cc = "1.0" - -[dependencies] -serde_json = "1.0" -serde = { version = "1", features = ["derive"] } -glob = "0.3.0" -walkdir = "2" -libc = "0.2.112" -libloading = "0.7.3" -threadpool = "1.0" -chrono = "0.4.19" -tempfile = "3.5.0" -anyhow = "1.0" -once_cell = "1.10" -cc = "1.0" -uuid = "1.7.0" -compiler_base_session = "0.1.3" -compiler_base_macros = "0.1.1" - -kclvm-ast = { path = "../ast" } -kclvm-parser = { path = "../parser" } -kclvm-compiler = { path = "../compiler" } -kclvm-config = { path = "../config" } -kclvm-runtime = { path = "../runtime" } -kclvm-sema = { path = "../sema" } -kclvm-version = { path = "../version" } -kclvm-error = { path = "../error" } -kclvm-query = { path = "../query" } -kclvm-utils = { path = "../utils" } -kclvm-driver = { path = "../driver" } -kclvm-evaluator = { path = "../evaluator" } -kclvm-primitives = { path = "../primitives" } - -[dev-dependencies] -kclvm-parser = { path = "../parser" } -criterion = "0.5" - -[[bench]] -name = "bench_runner" -harness = false - -[features] -llvm = ["kclvm-compiler/llvm"] diff --git a/kclvm/runner/build.rs b/kclvm/runner/build.rs deleted file mode 100644 index 6e02103ba..000000000 --- a/kclvm/runner/build.rs +++ /dev/null @@ -1,11 +0,0 @@ -fn main() { - setup_target(); -} - -/// Set rustc TARGET to KCLVM_DEFAULT_TARGET -fn setup_target() { - println!( - "cargo:rustc-env=KCLVM_DEFAULT_TARGET={}", - std::env::var("TARGET").unwrap() - ); -} diff --git a/kclvm/runner/src/assembler.rs b/kclvm/runner/src/assembler.rs deleted file mode 100644 index 17b1866e2..000000000 --- a/kclvm/runner/src/assembler.rs +++ /dev/null @@ -1,420 +0,0 @@ -use anyhow::Result; -use compiler_base_macros::bug; -use kclvm_ast::ast::{self, Program}; -use kclvm_compiler::codegen::{emit_code, EmitOptions, OBJECT_FILE_SUFFIX}; -use kclvm_config::cache::{load_pkg_cache, save_pkg_cache, CacheOption, KCL_CACHE_PATH_ENV_VAR}; -use kclvm_primitives::IndexMap; -use kclvm_sema::resolver::scope::ProgramScope; -use kclvm_utils::fslock::open_lock_file; -use std::{ - collections::HashMap, - env, - path::{Path, PathBuf}, -}; - -use crate::ExecProgramArgs; - -/// IR code file suffix. -const DEFAULT_IR_FILE: &str = "_a.out"; - -/// LibAssembler trait is used to indicate the general interface -/// that must be implemented when different intermediate codes are assembled -/// into dynamic link libraries. -/// -/// Note: LibAssembler is only for single file kcl program. For multi-file kcl programs, -/// KclvmAssembler is provided to support for multi-file parallel compilation to improve -/// the performance of the compiler. -pub(crate) trait LibAssembler { - /// Add a suffix to the file name according to the file suffix of different intermediate code files. - /// e.g. LLVM IR -> code_file : "/test_dir/test_code_file" -> return : "/test_dir/test_code_file.o" - fn add_code_file_suffix(&self, code_file: &str) -> String; - - /// Return the file suffix of different intermediate code files. - /// e.g. LLVM IR -> return : ".o" - fn get_code_file_suffix(&self) -> String; - - /// Assemble different intermediate codes into object files for single file kcl program. - /// Returns the path of the object file. - /// - /// Inputs: - /// compile_prog: Reference of kcl program ast. - /// - /// "import_names" is import pkgpath and name of kcl program. - /// Type of import_names is "IndexMap>". - /// - /// "kcl_file_name" is the kcl file name string. - /// "import_name" is the name string of import stmt. - /// "import_path" is the path string of import stmt. - /// - /// e.g. "import test/main_pkg as main", "main" is an "import_name". - /// e.g. "import test/main_pkg as main", "test/main_pkg" is an import_path. - /// - /// "code_file" is the filename of the generated intermediate code file. - /// e.g. code_file : "/test_dir/test_code_file" - /// - /// "object_file_path" is the full filename of the generated intermediate code file with suffix. - /// e.g. code_file_path : "/test_dir/test_code_file.o" - /// - /// "arg" is the arguments of the kclvm runtime. - fn assemble( - &self, - compile_prog: &Program, - import_names: IndexMap>, - code_file: &str, - code_file_path: &str, - arg: &ExecProgramArgs, - ) -> Result; - - /// Clean cache lock files. - #[inline] - fn clean_lock_file(&self, path: &str) -> Result<()> { - let lock_path = &format!("{}.lock", self.add_code_file_suffix(path)); - clean_path(lock_path) - } -} - -/// This enum lists all the intermediate code assemblers currently supported by kclvm. -/// Currently only supports assemble llvm intermediate code into dynamic link library. -#[derive(Clone)] -pub(crate) enum KclvmLibAssembler { - LLVM, -} - -/// KclvmLibAssembler is a dispatcher, responsible for calling corresponding methods -/// according to different types of intermediate codes. -/// -/// KclvmLibAssembler implements the LibAssembler trait, -/// and calls the corresponding method according to different assembler. -impl LibAssembler for KclvmLibAssembler { - #[inline] - fn assemble( - &self, - compile_prog: &Program, - import_names: IndexMap>, - code_file: &str, - object_file_path: &str, - args: &ExecProgramArgs, - ) -> Result { - match &self { - KclvmLibAssembler::LLVM => LlvmLibAssembler.assemble( - compile_prog, - import_names, - code_file, - object_file_path, - args, - ), - } - } - - #[inline] - fn add_code_file_suffix(&self, code_file: &str) -> String { - match &self { - KclvmLibAssembler::LLVM => LlvmLibAssembler.add_code_file_suffix(code_file), - } - } - - #[inline] - fn get_code_file_suffix(&self) -> String { - match &self { - KclvmLibAssembler::LLVM => LlvmLibAssembler.get_code_file_suffix(), - } - } -} - -/// LlvmLibAssembler is mainly responsible for assembling the generated LLVM IR into a dynamic link library. -#[derive(Clone)] -pub(crate) struct LlvmLibAssembler; - -impl LlvmLibAssembler { - #[inline] - fn new() -> Self { - Self {} - } -} - -impl Default for LlvmLibAssembler { - #[inline] - fn default() -> Self { - Self::new() - } -} - -/// KclvmLibAssembler implements the LibAssembler trait, -impl LibAssembler for LlvmLibAssembler { - /// "assemble_lib" will call the [kclvm_compiler::codegen::emit_code] - /// to generate the `.o` object file. - #[inline] - fn assemble( - &self, - compile_prog: &Program, - import_names: IndexMap>, - code_file: &str, - object_file_path: &str, - arg: &ExecProgramArgs, - ) -> Result { - // Clean the existed "*.o" object file. - clean_path(object_file_path)?; - - // Compile KCL code into ".o" object file. - emit_code( - compile_prog, - arg.work_dir.clone().unwrap_or("".to_string()), - import_names, - &EmitOptions { - from_path: None, - emit_path: Some(code_file), - no_link: true, - }, - ) - .map_err(|e| { - anyhow::anyhow!( - "Internal error: compile KCL to LLVM error {}", - e.to_string() - ) - })?; - - Ok(object_file_path.to_string()) - } - - #[inline] - fn add_code_file_suffix(&self, code_file: &str) -> String { - format!("{}{}", code_file, OBJECT_FILE_SUFFIX) - } - - #[inline] - fn get_code_file_suffix(&self) -> String { - OBJECT_FILE_SUFFIX.to_string() - } -} - -/// KclvmAssembler is mainly responsible for assembling the generated bytecode -/// LLVM IR or other IR code into dynamic link libraries, for multi-file kcl programs, -/// and take the result of kclvm-parser, kclvm-sema and kclvm-compiler as input. -/// -/// KclvmAssembler improves the performance of kclvm by concurrently compiling kcl multi-file programs. -/// The member "thread_count" of KclvmAssembler is the number of threads in multi-file compilation. -/// -/// KclvmAssembler provides an atomic operation for generating a dynamic link library for a single file -/// through KclvmLibAssembler for each thread. -pub(crate) struct KclvmAssembler { - program: ast::Program, - scope: ProgramScope, - entry_file: String, - single_file_assembler: KclvmLibAssembler, - target: String, - external_pkgs: HashMap, -} - -impl KclvmAssembler { - /// Constructs an KclvmAssembler instance with a default value 4 - /// for the number of threads in multi-file compilation. - #[inline] - pub(crate) fn new( - program: ast::Program, - scope: ProgramScope, - entry_file: String, - single_file_assembler: KclvmLibAssembler, - external_pkgs: HashMap, - ) -> Self { - Self { - program, - scope, - entry_file, - single_file_assembler, - target: env!("KCLVM_DEFAULT_TARGET").to_string(), - external_pkgs, - } - } - - /// Clean up the path of the dynamic link libraries generated. - /// It will remove the file in "file_path" and all the files in file_path end with ir code file suffix. - #[inline] - pub(crate) fn clean_path_for_genlibs(&self, file_path: &str, suffix: &str) -> Result<()> { - let path = std::path::Path::new(file_path); - if path.exists() { - std::fs::remove_file(path)?; - } - for entry in glob::glob(&format!("{}*{}", file_path, suffix))? { - match entry { - Ok(path) => { - if path.exists() { - std::fs::remove_file(path)?; - } - } - Err(e) => bug!("{:?}", e), - }; - } - Ok(()) - } - - /// Generate cache dir from the program root path. - /// Create cache dir if it doesn't exist. - #[inline] - pub(crate) fn load_cache_dir(&self, root: &str) -> Result { - let cache_dir = self.construct_cache_dir(root); - if !cache_dir.exists() { - std::fs::create_dir_all(&cache_dir)?; - } - Ok(cache_dir) - } - - #[inline] - pub(crate) fn construct_cache_dir(&self, root: &str) -> PathBuf { - let root = std::env::var(KCL_CACHE_PATH_ENV_VAR).unwrap_or(root.to_string()); - Path::new(&root) - .join(".kclvm") - .join("cache") - .join(kclvm_version::get_version_string()) - .join(&self.target) - } - - /// Generate the dynamic link libraries and return file paths. - /// - /// In the method, multiple threads will be created to concurrently generate dynamic link libraries - /// under different package paths. - /// - /// This method will generate dynamic link library files (such as "*.dylib", "*.dll.lib", "*.so") - /// and ir code files, and return the file paths of the dynamic link library files in [Vec]. - /// - /// `gen_libs` will create multiple threads and call the method provided by [KclvmLibAssembler] in each thread - /// to generate the dynamic link library in parallel. - pub(crate) fn gen_libs(self, args: &ExecProgramArgs) -> Result> { - self.clean_path_for_genlibs( - DEFAULT_IR_FILE, - &self.single_file_assembler.get_code_file_suffix(), - )?; - let cache_dir = self.load_cache_dir(&self.program.root)?; - let mut compile_progs: IndexMap< - String, - ( - ast::Program, - IndexMap>, - PathBuf, - ), - > = Default::default(); - for (pkgpath, modules) in self.program.pkgs { - let mut pkgs = HashMap::new(); - pkgs.insert(pkgpath.clone(), modules); - let compile_prog = ast::Program { - root: self.program.root.clone(), - pkgs, - modules: self.program.modules.clone(), - pkgs_not_imported: HashMap::new(), - modules_not_imported: HashMap::new(), - }; - compile_progs.insert( - pkgpath, - ( - compile_prog, - self.scope.import_names.clone(), - cache_dir.clone(), - ), - ); - } - let mut lib_paths = vec![]; - for (pkgpath, (compile_prog, import_names, cache_dir)) in compile_progs { - // Clone a single file assembler for one thread. - let assembler = self.single_file_assembler.clone(); - // Generate paths for some intermediate files (*.o, *.lock). - let entry_file = self.entry_file.clone(); - let is_main_pkg = pkgpath == kclvm_ast::MAIN_PKG; - let file = if is_main_pkg { - // The path to the generated files(*.o or *.lock) when the main package is compiled. - PathBuf::from(entry_file) - } else { - // The path to the generated files(*.o or *.lock) when the non-main package is compiled. - cache_dir.join(&pkgpath) - }; - let code_file = file - .to_str() - .ok_or(anyhow::anyhow!("Internal error: get cache file failed"))? - .to_string(); - let code_file_path = assembler.add_code_file_suffix(&code_file); - let lock_file_path = format!("{}.lock", code_file_path); - let target = self.target.clone(); - { - // Locking file for parallel code generation. - let mut file_lock = open_lock_file(&lock_file_path)?; - file_lock.lock()?; - - let root = &compile_prog.root; - // The main package does not perform cache reading and writing, - // and other packages perform read and write caching. Because - // KCL supports multi-file compilation, it is impossible to - // specify a standard entry for these multi-files and cannot - // be shared, so the cache of the main package is not read and - // written. - let file_path = if is_main_pkg { - // generate dynamic link library for single file kcl program - assembler.assemble( - &compile_prog, - import_names, - &code_file, - &code_file_path, - args, - )? - } else { - // Read the lib path cache - let file_relative_path: Option = load_pkg_cache( - root, - &target, - &pkgpath, - CacheOption::default(), - &self.external_pkgs, - ); - let file_abs_path = match file_relative_path { - Some(file_relative_path) => { - let path = if file_relative_path.starts_with('.') { - file_relative_path.replacen('.', root, 1) - } else { - file_relative_path - }; - if Path::new(&path).exists() { - Some(path) - } else { - None - } - } - None => None, - }; - match file_abs_path { - Some(path) => path, - None => { - // Generate the object file for single file kcl program. - let file_path = assembler.assemble( - &compile_prog, - import_names, - &code_file, - &code_file_path, - args, - )?; - let lib_relative_path = file_path.replacen(root, ".", 1); - let _ = save_pkg_cache( - root, - &target, - &pkgpath, - lib_relative_path, - CacheOption::default(), - &self.external_pkgs, - ); - file_path - } - } - }; - file_lock.unlock()?; - lib_paths.push(file_path); - }; - } - self.single_file_assembler - .clean_lock_file(&self.entry_file)?; - Ok(lib_paths) - } -} - -#[inline] -pub(crate) fn clean_path(path: &str) -> Result<()> { - if Path::new(path).exists() { - std::fs::remove_file(path)?; - } - Ok(()) -} diff --git a/kclvm/runner/src/lib.rs b/kclvm/runner/src/lib.rs deleted file mode 100644 index 934438146..000000000 --- a/kclvm/runner/src/lib.rs +++ /dev/null @@ -1,415 +0,0 @@ -use std::{ - collections::HashMap, - ffi::OsStr, - path::Path, - sync::{Arc, RwLock}, -}; - -use anyhow::{anyhow, bail, Result}; -use assembler::KclvmLibAssembler; -use kclvm_ast::{ - ast::{Module, Program}, - MAIN_PKG, -}; -use kclvm_config::cache::KCL_CACHE_PATH_ENV_VAR; -use kclvm_parser::{load_program, KCLModuleCache, ParseSessionRef}; -use kclvm_query::apply_overrides; -use kclvm_sema::resolver::{ - resolve_program, resolve_program_with_opts, scope::ProgramScope, Options, -}; -use kclvm_utils::fslock::open_lock_file; -use linker::Command; -pub use runner::{Artifact, ExecProgramArgs, ExecProgramResult, MapErrorResult}; -use runner::{FastRunner, RunnerOptions}; -#[cfg(feature = "llvm")] -use runner::{LibRunner, ProgramRunner}; -use tempfile::tempdir; - -pub mod assembler; -pub mod linker; -pub mod runner; - -#[cfg(test)] -pub mod tests; - -pub const KCL_FAST_EVAL_ENV_VAR: &str = "KCL_FAST_EVAL"; - -/// After the kcl program passed through kclvm-parser in the compiler frontend, -/// KCL needs to resolve ast, generate corresponding LLVM IR, dynamic link library or -/// executable file for kcl program in the compiler backend. -/// -/// Method “execute” is the entry point for the compiler backend. -/// -/// It returns the KCL program executing result as Result, -/// and mainly takes "program" (ast.Program returned by kclvm-parser) as input. -/// -/// "args" is the items selected by the user in the KCL CLI. -/// -/// This method will first resolve “program” (ast.Program) and save the result to the "scope" (ProgramScope). -/// -/// Then, dynamic link libraries is generated by KclvmAssembler, and method "KclvmAssembler::gen_libs" -/// will return dynamic link library paths in a "Vec"; -/// -/// KclvmAssembler is mainly responsible for concurrent compilation of multiple files. -/// Single-file compilation in each thread in concurrent compilation is the responsibility of KclvmLibAssembler. -/// In the future, it may support the dynamic link library generation of multiple intermediate language. -/// KclvmLibAssembler currently only supports LLVM IR. -/// -/// After linking all dynamic link libraries by KclvmLinker, method "KclvmLinker::link_all_libs" will return a path -/// for dynamic link library after linking. -/// -/// At last, KclLibRunner will be constructed and call method "run" to execute the kcl program. -/// -/// **Note that it is not thread safe.** -/// -/// # Examples -/// -/// ``` -/// use kclvm_runner::{exec_program, ExecProgramArgs}; -/// use kclvm_parser::ParseSession; -/// use std::sync::Arc; -/// -/// // Create sessions -/// let sess = Arc::new(ParseSession::default()); -/// // Get default args -/// let mut args = ExecProgramArgs::default(); -/// args.k_filename_list = vec!["./src/test_datas/init_check_order_0/main.k".to_string()]; -/// -/// // Resolve ast, generate libs, link libs and execute. -/// // Result is the kcl in json format. -/// let result = exec_program(sess, &args).unwrap(); -/// ``` -pub fn exec_program(sess: ParseSessionRef, args: &ExecProgramArgs) -> Result { - // parse args from json string - let opts = args.get_load_program_options(); - let kcl_paths_str = args - .k_filename_list - .iter() - .map(|s| s.as_str()) - .collect::>(); - let module_cache = KCLModuleCache::default(); - let mut program = load_program( - sess.clone(), - kcl_paths_str.as_slice(), - Some(opts), - Some(module_cache), - )? - .program; - apply_overrides( - &mut program, - &args.overrides, - &[], - args.print_override_ast || args.debug > 0, - )?; - execute(sess, program, args) -} - -/// Execute the KCL artifact with args. -pub fn exec_artifact>( - path: P, - args: &ExecProgramArgs, -) -> Result { - #[cfg(feature = "llvm")] - { - Artifact::from_path(path)?.run(args) - } - #[cfg(not(feature = "llvm"))] - { - let _ = path; - let _ = args; - Err(anyhow::anyhow!("error: llvm feature is not enabled. Note: Set KCL_FAST_EVAL=1 or rebuild the crate with the llvm feature.")) - } -} - -/// After the kcl program passed through kclvm-parser in the compiler frontend, -/// KCL needs to resolve ast, generate corresponding LLVM IR, dynamic link library or -/// executable file for kcl program in the compiler backend. -/// -/// Method “execute” is the entry point for the compiler backend. -/// -/// It returns the KCL program executing result as Result, -/// and mainly takes "program" (ast.Program returned by kclvm-parser) as input. -/// -/// "args" is the items selected by the user in the KCL CLI. -/// -/// This method will first resolve “program” (ast.Program) and save the result to the "scope" (ProgramScope). -/// -/// Then, dynamic link libraries is generated by KclvmAssembler, and method "KclvmAssembler::gen_libs" -/// will return dynamic link library paths in a "Vec"; -/// -/// KclvmAssembler is mainly responsible for concurrent compilation of multiple files. -/// Single-file compilation in each thread in concurrent compilation is the responsibility of KclvmLibAssembler. -/// In the future, it may support the dynamic link library generation of multiple intermediate language. -/// KclvmLibAssembler currently only supports LLVM IR. -/// -/// After linking all dynamic link libraries by KclvmLinker, method "KclvmLinker::link_all_libs" will return a path -/// for dynamic link library after linking. -/// -/// At last, KclLibRunner will be constructed and call method "run" to execute the kcl program. -/// -/// **Note that it is not thread safe.** -/// -/// # Examples -/// -/// ``` -/// use kclvm_runner::{execute, runner::ExecProgramArgs}; -/// use kclvm_parser::{load_program, ParseSession}; -/// use kclvm_ast::ast::Program; -/// use std::sync::Arc; -/// -/// // Create sessions -/// let sess = Arc::new(ParseSession::default()); -/// // Get default args -/// let args = ExecProgramArgs::default(); -/// let opts = args.get_load_program_options(); -/// -/// // Parse kcl file -/// let kcl_path = "./src/test_datas/init_check_order_0/main.k"; -/// let prog = load_program(sess.clone(), &[kcl_path], Some(opts), None).unwrap().program; -/// -/// // Resolve ast, generate libs, link libs and execute. -/// // Result is the kcl in json format. -/// let result = execute(sess, prog, &args).unwrap(); -/// ``` -pub fn execute( - sess: ParseSessionRef, - mut program: Program, - args: &ExecProgramArgs, -) -> Result { - // If the user only wants to compile the kcl program, the following code will only resolve ast. - if args.compile_only { - let mut resolve_opts = Options::default(); - resolve_opts.merge_program = false; - // Resolve ast - let scope = resolve_program_with_opts(&mut program, resolve_opts, None); - emit_compile_diag_to_string(sess, &scope, args.compile_only)?; - return Ok(ExecProgramResult::default()); - } - // Resolve ast - let scope = resolve_program(&mut program); - // Emit parse and resolve errors if exists. - emit_compile_diag_to_string(sess, &scope, false)?; - Ok( - // Use the fast evaluator to run the kcl program. - if args.fast_eval || std::env::var(KCL_FAST_EVAL_ENV_VAR).is_ok() { - FastRunner::new(Some(RunnerOptions { - plugin_agent_ptr: args.plugin_agent, - })) - .run(&program, args)? - } else { - // Compile the kcl program to native lib and run it. - #[cfg(feature = "llvm")] - { - // Create a temp entry file and the temp dir will be delete automatically - let temp_dir = tempdir()?; - let temp_dir_path = temp_dir.path().to_str().ok_or(anyhow!( - "Internal error: {}: No such file or directory", - temp_dir.path().display() - ))?; - let temp_entry_file = temp_file(temp_dir_path)?; - - // Generate libs - let lib_paths = assembler::KclvmAssembler::new( - program, - scope, - temp_entry_file.clone(), - KclvmLibAssembler::LLVM, - args.get_package_maps_from_external_pkg(), - ) - .gen_libs(args)?; - - // Link libs into one library - let lib_suffix = Command::get_lib_suffix(); - let temp_out_lib_file = format!("{}{}", temp_entry_file, lib_suffix); - let lib_path = linker::KclvmLinker::link_all_libs(lib_paths, temp_out_lib_file)?; - - // Run the library - let runner = LibRunner::new(Some(RunnerOptions { - plugin_agent_ptr: args.plugin_agent, - })); - let result = runner.run(&lib_path, args)?; - - remove_file(&lib_path)?; - clean_tmp_files(&temp_entry_file, &lib_suffix)?; - result - } - // If we don't enable llvm feature, the default running path is through the evaluator. - #[cfg(not(feature = "llvm"))] - { - FastRunner::new(Some(RunnerOptions { - plugin_agent_ptr: args.plugin_agent, - })) - .run(&program, args)? - } - }, - ) -} - -/// `execute_module` can directly execute the ast `Module`. -/// `execute_module` constructs `Program` with default pkg name `MAIN_PKG`, -/// and calls method `execute` with default `plugin_agent` and `ExecProgramArgs`. -/// For more information, see doc above method `execute`. -/// -/// **Note that it is not thread safe.** -pub fn execute_module(m: Module) -> Result { - let mut pkgs = HashMap::new(); - let mut modules = HashMap::new(); - pkgs.insert(MAIN_PKG.to_string(), vec![m.filename.clone()]); - modules.insert(m.filename.clone(), Arc::new(RwLock::new(m))); - - let prog = Program { - root: MAIN_PKG.to_string(), - pkgs, - modules, - pkgs_not_imported: HashMap::new(), - modules_not_imported: HashMap::new(), - }; - - execute( - ParseSessionRef::default(), - prog, - &ExecProgramArgs::default(), - ) -} - -/// Build a KCL program and generate a library artifact. -pub fn build_program>( - sess: ParseSessionRef, - args: &ExecProgramArgs, - output: Option